wcz-layout
Version:
1 lines • 14.1 kB
Source Map (JSON)
{"version":3,"file":"tokens-DNe_Qifk.mjs","names":["definedScopes"],"sources":["../src/lib/auth/oidc.ts","../src/lib/auth/tokens.ts"],"sourcesContent":["import { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport type { Provider } from \"./providers\";\n\n/**\n * The whole OAuth2/OIDC surface this app needs, as plain form POSTs. Both Entra\n * and Cognito are ordinary OIDC servers, so a second provider is a config object\n * (see `providers.ts`) rather than a second integration.\n */\n\n/** The refresh token is expired/revoked — the user must sign in interactively. */\nexport class SessionExpiredError extends Error {}\n\nexport interface TokenResponse {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n expires_in: number;\n}\n\nconst base64url = (bytes: Buffer): string => bytes.toString(\"base64url\");\n\n/** PKCE verifier + S256 challenge for the authorization-code flow. */\nexport const createPkce = (): { verifier: string; challenge: string } => {\n const verifier = base64url(randomBytes(32));\n return { verifier, challenge: base64url(createHash(\"sha256\").update(verifier).digest()) };\n};\n\nexport const createState = (): string => randomUUID();\n\n/**\n * Revocation, inactivity expiry and Conditional Access sign-in frequency all\n * surface as `invalid_grant` or `interaction_required` — the session is dead and\n * only an interactive login helps. Missing consent (Entra AADSTS65001) looks the\n * same but is a configuration bug, so it is left to surface as-is.\n */\nconst isSessionDead = (error: { error?: string; suberror?: string }): boolean =>\n (error.error === \"invalid_grant\" || error.error === \"interaction_required\") &&\n error.suberror !== \"consent_required\";\n\nasync function requestToken(\n provider: Provider,\n body: Record<string, string>,\n): Promise<TokenResponse> {\n const credentials = Buffer.from(`${provider.clientId}:${provider.clientSecret}`).toString(\n \"base64\",\n );\n const response = await fetch(provider.tokenEndpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n // Both providers accept client_secret_basic; it keeps the secret out of the body.\n authorization: `Basic ${credentials}`,\n },\n body: new URLSearchParams({ client_id: provider.clientId, ...body }),\n });\n\n const payload = (await response.json()) as TokenResponse &\n Record<\"error\" | \"error_description\" | \"suberror\", string | undefined>;\n if (response.ok) return payload;\n\n const message = payload.error_description ?? payload.error ?? `HTTP ${response.status}`;\n if (isSessionDead(payload)) throw new SessionExpiredError(message);\n throw new Error(`[${provider.id}] ${message}`);\n}\n\n/** First leg of the auth-code flow: the URL to redirect the browser to. */\nexport function buildAuthUrl(\n provider: Provider,\n opts: { redirectUri: string; state: string; challenge: string },\n): string {\n const url = new URL(provider.authorizeEndpoint);\n url.search = new URLSearchParams({\n client_id: provider.clientId,\n response_type: \"code\",\n redirect_uri: opts.redirectUri,\n state: opts.state,\n scope: provider.loginScopes.join(\" \"),\n code_challenge: opts.challenge,\n code_challenge_method: \"S256\",\n }).toString();\n return url.toString();\n}\n\n/** Second leg: exchange the code for tokens. The refresh token is in the body. */\nexport const exchangeCode = (\n provider: Provider,\n opts: { code: string; redirectUri: string; codeVerifier: string },\n): Promise<TokenResponse> =>\n requestToken(provider, {\n grant_type: \"authorization_code\",\n code: opts.code,\n redirect_uri: opts.redirectUri,\n code_verifier: opts.codeVerifier,\n });\n\n/**\n * Delegated token for `scope`. Entra mints a token for any resource from its\n * multi-resource refresh token; Cognito can only narrow within the scopes already\n * registered on the app client, and ignores the rest.\n */\nexport const refreshTokens = (\n provider: Provider,\n opts: { refreshToken: string; scope: string },\n): Promise<TokenResponse> =>\n requestToken(provider, {\n grant_type: \"refresh_token\",\n refresh_token: opts.refreshToken,\n scope: opts.scope,\n });\n\n/**\n * Entra on-behalf-of: a delegated token for `scope` in exchange for a user token\n * another app sent to this one. Entra checks that `assertion` was issued to this app.\n */\nexport const onBehalfOf = (\n provider: Provider,\n opts: { assertion: string; scope: string },\n): Promise<TokenResponse> =>\n requestToken(provider, {\n grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n requested_token_use: \"on_behalf_of\",\n assertion: opts.assertion,\n scope: opts.scope,\n });\n\n/** App-only token: no user context, for background jobs. */\nexport const clientCredentials = (\n provider: Provider,\n opts: { scope: string },\n): Promise<TokenResponse> =>\n requestToken(provider, { grant_type: \"client_credentials\", scope: opts.scope });\n","import { createServerOnlyFn } from \"@tanstack/react-start\";\nimport * as jose from \"jose\";\nimport { scopes as definedScopes } from \"virtual:wcz-layout\";\nimport type { Scope } from \"~/models/Scopes\";\nimport type { ProviderId } from \"~/models/User\";\nimport { SessionExpiredError, clientCredentials, onBehalfOf, refreshTokens } from \"./oidc\";\nimport { getProvider } from \"./providers\";\nimport { getAppSession } from \"./session\";\nimport { getSessionUser } from \"./user\";\n\nexport type ScopeKey = keyof typeof definedScopes;\n\n/**\n * A scope entry is either a bare string (Entra) or `{ entra, aws }`. Throwing on a\n * missing entry fails at the call site instead of sending a token the API rejects.\n */\nexport const resolveScope = (key: ScopeKey, provider: ProviderId): string => {\n const entry: Scope = definedScopes[key];\n const scope =\n typeof entry === \"string\" ? (provider === \"entra\" ? entry : undefined) : entry[provider];\n\n if (!scope) throw new Error(`No \"${key}\" scope is configured for the \"${provider}\" provider.`);\n return scope;\n};\n\n/**\n * The request's Bearer token when it is an Entra user token: a sibling service calling for a\n * user. Entra checks its signature and audience in the on-behalf-of exchange. `undefined`\n * outside a request and for a malformed token.\n */\nasync function getBearerUserToken(): Promise<string | undefined> {\n try {\n const { getRequestHeader } = await import(\"@tanstack/react-start/server\");\n const token = getRequestHeader(\"authorization\")?.match(/^Bearer (.+)$/)?.[1];\n if (!token) return undefined;\n const { iss, scp } = jose.decodeJwt(token);\n return iss === getProvider(\"entra\").issuer && scp ? token : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Entra only: Cognito has no on-behalf-of grant, so an AWS Bearer caller counts as no user.\n * shortcut: one Entra round trip per call, no cache; cache by assertion and scope if a request\n * ever calls the same API many times.\n */\nasync function getOnBehalfOfToken(assertion: string, scopeKey: ScopeKey): Promise<string> {\n try {\n const result = await onBehalfOf(getProvider(\"entra\"), {\n assertion,\n scope: resolveScope(scopeKey, \"entra\"),\n });\n return result.access_token;\n } catch (error) {\n if (error instanceof SessionExpiredError)\n throw Response.json({ message: \"Unauthorized: Access token expired\" }, { status: 401 });\n throw error;\n }\n}\n\n/** Whether a user is behind the request: a session, or a sibling service's Bearer user token. */\nexport const hasUser = createServerOnlyFn(async (): Promise<boolean> =>\n Boolean((await getSessionUser()) ?? (await getBearerUserToken())),\n);\n\n/**\n * Delegated access token for the user behind the request. From a session it is minted from\n * the session refresh token; providers that rotate the refresh token return a new one, which\n * is persisted back. For a sibling service's Bearer user token it is exchanged on behalf of\n * that user. Server-only — stripped from the client bundle.\n */\nexport const getAccessToken = createServerOnlyFn(async (scopeKey: ScopeKey): Promise<string> => {\n const session = await getAppSession();\n const { provider: providerId, refreshToken } = session;\n if (!providerId || !refreshToken) {\n const assertion = await getBearerUserToken();\n if (!assertion) throw new Error(\"No active session. User not signed in.\");\n return getOnBehalfOfToken(assertion, scopeKey);\n }\n\n try {\n const result = await refreshTokens(getProvider(providerId), {\n refreshToken,\n scope: resolveScope(scopeKey, providerId),\n });\n if (result.refresh_token && result.refresh_token !== refreshToken) {\n session.refreshToken = result.refresh_token;\n await session.save();\n }\n return result.access_token;\n } catch (error) {\n // Revoked/expired refresh token: clear the dead session and answer 401 so the\n // client can redirect to /login, instead of surfacing a 500.\n if (error instanceof SessionExpiredError) {\n session.destroy();\n throw Response.json(\n { message: \"Unauthorized: Session expired, sign in again\" },\n { status: 401 },\n );\n }\n throw error;\n }\n});\n\n// MSAL used to cache these in memory; without it, a small TTL map keeps parity.\nconst appTokens = new Map<ScopeKey, { token: string; expiresAt: number }>();\n\n/**\n * Client-credentials (app-only) token, for background jobs with no user.\n * Entra-only: the AWS population signs in interactively, so a Cognito app client\n * for M2M has no caller yet (and Cognito bills M2M per token request).\n */\nexport const getAppToken = createServerOnlyFn(async (scopeKey: ScopeKey): Promise<string> => {\n const cached = appTokens.get(scopeKey);\n if (cached && cached.expiresAt > Date.now()) return cached.token;\n\n // Entra client credentials only accept `<resource>/.default`, not user scopes.\n const scope = resolveScope(scopeKey, \"entra\");\n const defaultScope = `${scope.slice(0, scope.lastIndexOf(\"/\"))}/.default`;\n\n const result = await clientCredentials(getProvider(\"entra\"), { scope: defaultScope });\n appTokens.set(scopeKey, {\n token: result.access_token,\n expiresAt: Date.now() + (result.expires_in - 60) * 1000,\n });\n return result.access_token;\n});\n\n/** The user's token when a user is behind the request (see `hasUser`), else the app token. */\nexport const getApiToken = createServerOnlyFn(async (scopeKey: ScopeKey): Promise<string> =>\n (await hasUser()) ? await getAccessToken(scopeKey) : await getAppToken(scopeKey),\n);\n"],"mappings":";;;;;;;;;;;;;;AAUA,IAAa,sBAAb,cAAyC,MAAM,CAAC;AAShD,MAAM,aAAa,UAA0B,MAAM,SAAS,WAAW;;AAGvE,MAAa,mBAA4D;CACvE,MAAM,WAAW,UAAU,YAAY,EAAE,CAAC;CAC1C,OAAO;EAAE;EAAU,WAAW,UAAU,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO,CAAC;CAAE;AAC1F;AAEA,MAAa,oBAA4B,WAAW;;;;;;;AAQpD,MAAM,iBAAiB,WACpB,MAAM,UAAU,mBAAmB,MAAM,UAAU,2BACpD,MAAM,aAAa;AAErB,eAAe,aACb,UACA,MACwB;CACxB,MAAM,cAAc,OAAO,KAAK,GAAG,SAAS,SAAS,GAAG,SAAS,cAAc,CAAC,CAAC,SAC/E,QACF;CACA,MAAM,WAAW,MAAM,MAAM,SAAS,eAAe;EACnD,QAAQ;EACR,SAAS;GACP,gBAAgB;GAEhB,eAAe,SAAS;EAC1B;EACA,MAAM,IAAI,gBAAgB;GAAE,WAAW,SAAS;GAAU,GAAG;EAAK,CAAC;CACrE,CAAC;CAED,MAAM,UAAW,MAAM,SAAS,KAAK;CAErC,IAAI,SAAS,IAAI,OAAO;CAExB,MAAM,UAAU,QAAQ,qBAAqB,QAAQ,SAAS,QAAQ,SAAS;CAC/E,IAAI,cAAc,OAAO,GAAG,MAAM,IAAI,oBAAoB,OAAO;CACjE,MAAM,IAAI,MAAM,IAAI,SAA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