(baseUrl: string, credentials: { readonly email: string; readonly password: string })
| 52 | // then POST the same `/api/auth/oauth2/consent` grant the Allow button fires. |
| 53 | export const forcedMcpConsent = |
| 54 | (baseUrl: string, credentials: { readonly email: string; readonly password: string }) => |
| 55 | async ({ authorizationUrl }: { authorizationUrl: string }): Promise<{ code: string }> => { |
| 56 | const origin = new URL(baseUrl).origin; |
| 57 | const { cookieHeader } = await signInSession(baseUrl, credentials); |
| 58 | |
| 59 | const authorize = await fetch(authorizationUrl, { |
| 60 | headers: { cookie: cookieHeader }, |
| 61 | redirect: "manual", |
| 62 | }); |
| 63 | const location = authorize.headers.get("location"); |
| 64 | if (!location) { |
| 65 | throw new Error(`forcedMcpConsent: authorize did not redirect (status ${authorize.status})`); |
| 66 | } |
| 67 | // The consent redirect is relative (`/mcp-consent?...`) — resolve it against |
| 68 | // the instance origin. If the server issued a code directly (consent not |
| 69 | // forced), use it; otherwise complete the forced approval below. |
| 70 | const redirect = new URL(location, baseUrl); |
| 71 | const direct = redirect.searchParams.get("code"); |
| 72 | if (direct) return { code: direct }; |
| 73 | const consentCode = redirect.searchParams.get("consent_code"); |
| 74 | if (!consentCode) { |
| 75 | throw new Error(`forcedMcpConsent: no consent_code in authorize redirect: ${location}`); |
| 76 | } |
| 77 | |
| 78 | const decision = await fetch(new URL("/api/auth/oauth2/consent", baseUrl), { |
| 79 | method: "POST", |
| 80 | headers: { "content-type": "application/json", origin, cookie: cookieHeader }, |
| 81 | body: JSON.stringify({ accept: true, consent_code: consentCode }), |
| 82 | }); |
| 83 | if (!decision.ok) { |
| 84 | throw new Error(`forcedMcpConsent: consent grant failed (status ${decision.status})`); |
| 85 | } |
| 86 | const decisionText = await decision.text(); |
| 87 | if (!decisionText) { |
| 88 | throw new Error( |
| 89 | `forcedMcpConsent: consent grant returned an empty body (status ${decision.status})`, |
| 90 | ); |
| 91 | } |
| 92 | const body = JSON.parse(decisionText) as { redirectURI?: string }; |
| 93 | const code = body.redirectURI ? new URL(body.redirectURI).searchParams.get("code") : null; |
| 94 | if (!code) { |
| 95 | throw new Error( |
| 96 | `forcedMcpConsent: no code in consent redirect: ${body.redirectURI ?? "(none)"}`, |
| 97 | ); |
| 98 | } |
| 99 | return { code }; |
| 100 | }; |
| 101 | |
| 102 | export const selfhostTarget = (): Target => ({ |
| 103 | name: "selfhost", |
no test coverage detected