@softistx/alxia-react-router 0.89.5 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +30 -1
  2. package/dist/chunks/{index-1nw5yeek.js → index-qkyt0bka.js} +3 -3
  3. package/dist/chunks/{index-1nw5yeek.js.map → index-qkyt0bka.js.map} +1 -1
  4. package/dist/chunks/index-w61bjnkw.js +1019 -0
  5. package/dist/chunks/index-w61bjnkw.js.map +27 -0
  6. package/dist/clavix/api-url.d.ts +43 -0
  7. package/dist/clavix/api-url.d.ts.map +1 -0
  8. package/dist/clavix/client.d.ts +22 -0
  9. package/dist/clavix/client.d.ts.map +1 -0
  10. package/dist/clavix/core.d.ts +39 -0
  11. package/dist/clavix/core.d.ts.map +1 -0
  12. package/dist/clavix/env.d.ts +26 -0
  13. package/dist/clavix/env.d.ts.map +1 -0
  14. package/dist/clavix/index.d.ts +19 -0
  15. package/dist/clavix/index.d.ts.map +1 -0
  16. package/dist/clavix/index.js +673 -0
  17. package/dist/clavix/index.js.map +22 -0
  18. package/dist/clavix/landing.d.ts +67 -0
  19. package/dist/clavix/landing.d.ts.map +1 -0
  20. package/dist/clavix/messages.d.ts +53 -0
  21. package/dist/clavix/messages.d.ts.map +1 -0
  22. package/dist/clavix/notice.d.ts +32 -0
  23. package/dist/clavix/notice.d.ts.map +1 -0
  24. package/dist/clavix/refusal.d.ts +29 -0
  25. package/dist/clavix/refusal.d.ts.map +1 -0
  26. package/dist/clavix/relay.d.ts +41 -0
  27. package/dist/clavix/relay.d.ts.map +1 -0
  28. package/dist/clavix/routes.d.ts +5 -0
  29. package/dist/clavix/routes.d.ts.map +1 -0
  30. package/dist/clavix/send.d.ts +32 -0
  31. package/dist/clavix/send.d.ts.map +1 -0
  32. package/dist/clavix/state.d.ts +20 -0
  33. package/dist/clavix/state.d.ts.map +1 -0
  34. package/dist/clavix/types.d.ts +97 -0
  35. package/dist/clavix/types.d.ts.map +1 -0
  36. package/dist/clavix/viewer.d.ts +12 -0
  37. package/dist/clavix/viewer.d.ts.map +1 -0
  38. package/dist/oidc/index.js +23 -1025
  39. package/dist/oidc/index.js.map +3 -21
  40. package/dist/session/index.js +1 -1
  41. package/docs/README.md +2 -1
  42. package/docs/guide/clavix.md +332 -0
  43. package/docs/guide/oidc.md +3 -0
  44. package/docs/roadmap.md +6 -0
  45. package/docs/troubleshooting.md +41 -0
  46. package/package.json +8 -2
@@ -1,27 +1,9 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/oidc/errors.ts", "../src/oidc/flow.ts", "../src/oidc/dpop.ts", "../src/oidc/seal.ts", "../src/oidc/stored.ts", "../src/oidc/tokens.ts", "../src/oidc/callback.ts", "../src/oidc/context.ts", "../src/oidc/revoke.ts", "../src/oidc/logout.ts", "../src/oidc/user.ts", "../src/oidc/refresh.ts", "../src/oidc/session.ts", "../src/oidc/signin.ts", "../src/oidc/client.ts", "../src/oidc/dpop-fetch.ts", "../src/oidc/env.ts", "../src/oidc/routes.ts"],
3
+ "sources": [],
4
4
  "sourcesContent": [
5
- "/** Why a relying-party step refused. */\nexport type OidcErrorCode =\n\t| 'discovery-failed'\n\t| 'missing-challenge'\n\t| 'challenge-expired'\n\t| 'provider-error'\n\t| 'issuer-mismatch'\n\t| 'state-mismatch'\n\t| 'missing-code'\n\t| 'token-exchange-failed'\n\t| 'invalid-id-token'\n\t| 'nonce-mismatch'\n\t| 'refresh-failed'\n\t| 'par-failed'\n\t| 'revoke-failed'\n\t| 'token-cookie-too-large';\n\n/**\n * What `callback` throws. `headers` holds the `Set-Cookie` that clears the\n * spent challenge: pass it when the route answers the failure, e.g.\n * `redirect('/sign-in?error=' + error.code, { headers: error.headers })`.\n */\nexport class OidcError extends Error {\n\toverride readonly name = 'OidcError';\n\tconstructor(\n\t\treadonly code: OidcErrorCode,\n\t\tmessage: string,\n\t\treadonly headers: Headers = new Headers(),\n\t\toptions?: { readonly cause?: unknown },\n\t) {\n\t\tsuper(message, options);\n\t}\n}\n",
6
- "import {\n\tcreateLocalJWKSet,\n\tdecodeJwt,\n\ttype JSONWebKeySet,\n\ttype JWTPayload,\n\terrors as joseErrors,\n\tjwtVerify,\n} from 'jose';\nimport {\n\ttype DpopKey,\n\ttype NonceMemory,\n\tsignDpopProof,\n\twantsNonce,\n} from './dpop';\nimport { OidcError, type OidcErrorCode } from './errors';\n\n/** The fields of the issuer's discovery document the flow reads. */\nexport interface DiscoveryDocument {\n\treadonly issuer: string;\n\treadonly authorization_endpoint: string;\n\treadonly token_endpoint: string;\n\treadonly jwks_uri: string;\n\treadonly end_session_endpoint?: string;\n\treadonly revocation_endpoint?: string;\n\treadonly pushed_authorization_request_endpoint?: string;\n\treadonly require_pushed_authorization_requests?: boolean;\n}\n\n/** What the issuer's token endpoint answers. */\nexport interface TokenResponse {\n\treadonly access_token: string;\n\treadonly id_token?: string;\n\treadonly refresh_token?: string;\n\treadonly expires_in?: number;\n\treadonly token_type?: string;\n}\n\nexport type Fetcher = (input: string, init?: RequestInit) => Promise<Response>;\n\nconst DISCOVERY_TTL = 60 * 60 * 1000;\nconst JWKS_TTL = 10 * 60 * 1000;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null;\n\nconst text = (value: unknown): value is string =>\n\ttypeof value === 'string' && value !== '';\n\n/** Discovery and the issuer's keys, cached; one per relying party. */\nexport function issuerClient(config: {\n\treadonly issuer: string;\n\treadonly fetch: Fetcher;\n\treadonly now: () => number;\n\treadonly algorithms: string[];\n\treadonly clockToleranceSeconds: number;\n}) {\n\tconst { issuer, now } = config;\n\tlet discovery: { at: number; value: Promise<DiscoveryDocument> } | undefined;\n\tlet keys: { at: number; value: Promise<JSONWebKeySet> } | undefined;\n\n\tasync function getJson(url: string, code: OidcErrorCode): Promise<unknown> {\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await config.fetch(url, {\n\t\t\t\theaders: { accept: 'application/json' },\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\tthrow new OidcError(code, `Could not reach ${url}.`, undefined, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new OidcError(code, `${url} answered ${response.status}.`);\n\t\t}\n\t\treturn response.json().catch(() => {\n\t\t\tthrow new OidcError(code, `${url} did not answer JSON.`);\n\t\t});\n\t}\n\n\tasync function loadDiscovery(): Promise<DiscoveryDocument> {\n\t\tconst url = `${issuer.replace(/\\/$/, '')}/.well-known/openid-configuration`;\n\t\tconst body = await getJson(url, 'discovery-failed');\n\t\tif (\n\t\t\t!isRecord(body) ||\n\t\t\t!text(body['authorization_endpoint']) ||\n\t\t\t!text(body['token_endpoint']) ||\n\t\t\t!text(body['jwks_uri'])\n\t\t) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'discovery-failed',\n\t\t\t\t`${url} lacks authorization_endpoint, token_endpoint or jwks_uri.`,\n\t\t\t);\n\t\t}\n\t\tfor (const key of [\n\t\t\t'authorization_endpoint',\n\t\t\t'token_endpoint',\n\t\t\t'jwks_uri',\n\t\t]) {\n\t\t\tconst endpoint = new URL(String(body[key]));\n\t\t\tconst loopback = ['localhost', '127.0.0.1', '[::1]'].includes(\n\t\t\t\tendpoint.hostname,\n\t\t\t);\n\t\t\tif (\n\t\t\t\tendpoint.protocol !== 'https:' &&\n\t\t\t\t!(loopback && endpoint.protocol === 'http:')\n\t\t\t) {\n\t\t\t\tthrow new OidcError(\n\t\t\t\t\t'discovery-failed',\n\t\t\t\t\t`${url} gives a ${key} that is not https.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (body['issuer'] !== issuer) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'issuer-mismatch',\n\t\t\t\t`${url} names the issuer ${JSON.stringify(body['issuer'])}, not ${JSON.stringify(issuer)}.`,\n\t\t\t);\n\t\t}\n\t\treturn body as unknown as DiscoveryDocument;\n\t}\n\n\tconst discover = (): Promise<DiscoveryDocument> => {\n\t\tif (!discovery || now() - discovery.at > DISCOVERY_TTL) {\n\t\t\tconst value = loadDiscovery();\n\t\t\tconst entry = { at: now(), value };\n\t\t\tdiscovery = entry;\n\t\t\tvalue.catch(() => {\n\t\t\t\tif (discovery === entry) discovery = undefined;\n\t\t\t});\n\t\t}\n\t\treturn discovery.value;\n\t};\n\n\tasync function jwks(force: boolean): Promise<JSONWebKeySet> {\n\t\tif (force || !keys || now() - keys.at > JWKS_TTL) {\n\t\t\tconst value = discover().then(\n\t\t\t\tasync (document) =>\n\t\t\t\t\t(await getJson(\n\t\t\t\t\t\tdocument.jwks_uri,\n\t\t\t\t\t\t'invalid-id-token',\n\t\t\t\t\t)) as JSONWebKeySet,\n\t\t\t);\n\t\t\tconst entry = { at: now(), value };\n\t\t\tkeys = entry;\n\t\t\tvalue.catch(() => {\n\t\t\t\tif (keys === entry) keys = undefined;\n\t\t\t});\n\t\t}\n\t\treturn keys.value;\n\t}\n\n\t/**\n\t * Verify an id token: signature against the issuer's keys (refetched once\n\t * when the `kid` is unknown), `iss`, `aud` (and `azp` when several), `exp`.\n\t * `nonce` is checked when given (the code exchange, not a refresh).\n\t */\n\tasync function verifyIdToken(\n\t\tidToken: string,\n\t\tclientId: string,\n\t\tnonce?: string,\n\t): Promise<JWTPayload> {\n\t\tconst document = await discover();\n\t\tconst check = async (force: boolean) =>\n\t\t\tjwtVerify(idToken, createLocalJWKSet(await jwks(force)), {\n\t\t\t\tissuer: document.issuer,\n\t\t\t\taudience: clientId,\n\t\t\t\talgorithms: config.algorithms,\n\t\t\t\tclockTolerance: config.clockToleranceSeconds,\n\t\t\t\tcurrentDate: new Date(now()),\n\t\t\t\trequiredClaims: ['exp', 'iat', 'sub'],\n\t\t\t});\n\t\tlet payload: JWTPayload;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\t({ payload } = await check(false));\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof joseErrors.JWKSNoMatchingKey)) throw error;\n\t\t\t\t({ payload } = await check(true));\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\tif (cause instanceof OidcError) throw cause;\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid-id-token',\n\t\t\t\t`The id token was refused: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t\tundefined,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tArray.isArray(payload.aud) &&\n\t\t\tpayload.aud.length > 1 &&\n\t\t\tpayload['azp'] !== clientId\n\t\t) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid-id-token',\n\t\t\t\t'The id token has several audiences and its azp is not this client.',\n\t\t\t);\n\t\t}\n\t\tif (nonce !== undefined && payload['nonce'] !== nonce) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'nonce-mismatch',\n\t\t\t\t'The id token nonce is not the one this sign-in sent.',\n\t\t\t);\n\t\t}\n\t\treturn payload;\n\t}\n\n\treturn { discover, verifyIdToken };\n}\n\n/** What a request to the issuer needs to carry a DPoP proof: the session's key and the nonces seen. */\nexport interface DpopSigning {\n\treadonly key: DpopKey;\n\treadonly nonces: NonceMemory;\n\treadonly now: () => number;\n}\n\ntype Client = { readonly id: string; readonly secret?: string | undefined };\n\n/**\n * POST a form to the issuer with the client's authentication (basic for a\n * confidential client, `client_id` in the body for a public one) and, with\n * `dpop`, a DPoP proof; a `use_dpop_nonce` answer is retried once with the\n * nonce the issuer sent, which is remembered for the next call.\n */\nasync function postForm(\n\tfetcher: Fetcher,\n\tendpoint: string,\n\tclient: Client,\n\tparams: Record<string, string>,\n\tcode: OidcErrorCode,\n\twhat: string,\n\tdpop?: DpopSigning,\n\tsignal?: AbortSignal,\n): Promise<{ response: Response; answer: unknown }> {\n\tconst body = new URLSearchParams(params);\n\tconst headers: Record<string, string> = {\n\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\taccept: 'application/json',\n\t};\n\tif (client.secret === undefined) {\n\t\tbody.set('client_id', client.id);\n\t} else {\n\t\t// client_secret_basic: both parts form-urlencoded first (RFC 6749 2.3.1).\n\t\tconst pair = `${encodeURIComponent(client.id)}:${encodeURIComponent(client.secret)}`;\n\t\theaders['authorization'] = `Basic ${btoa(pair)}`;\n\t}\n\tconst send = async (nonce: string | undefined): Promise<Response> => {\n\t\tconst sent = dpop\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tdpop: await signDpopProof(dpop.key, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\turl: endpoint,\n\t\t\t\t\t\tnonce,\n\t\t\t\t\t\tnow: dpop.now,\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: headers;\n\t\ttry {\n\t\t\tconst response = await fetcher(endpoint, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: sent,\n\t\t\t\tbody,\n\t\t\t\t...(signal && { signal }),\n\t\t\t});\n\t\t\tconst given = response.headers.get('dpop-nonce');\n\t\t\tif (dpop && given) dpop.nonces.set(endpoint, given);\n\t\t\treturn response;\n\t\t} catch (cause) {\n\t\t\tthrow new OidcError(\n\t\t\t\tcode,\n\t\t\t\t`The ${what} could not be reached.`,\n\t\t\t\tundefined,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t};\n\tlet response = await send(dpop?.nonces.get(endpoint));\n\tif (dpop && (await wantsNonce(response))) {\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\tresponse = await send(response.headers.get('dpop-nonce') ?? undefined);\n\t}\n\tconst answer: unknown = await response.json().catch(() => null);\n\treturn { response, answer };\n}\n\nconst detailOf = (answer: unknown): string =>\n\tisRecord(answer)\n\t\t? [answer['error'], answer['error_description']].filter(text).join(': ')\n\t\t: '';\n\n/** POST to the token endpoint; `error` and `description` come from the issuer. */\nexport async function tokenRequest(\n\tfetcher: Fetcher,\n\tendpoint: string,\n\tclient: Client,\n\tparams: Record<string, string>,\n\tcode: OidcErrorCode,\n\tdpop?: DpopSigning,\n): Promise<TokenResponse> {\n\tconst { response, answer } = await postForm(\n\t\tfetcher,\n\t\tendpoint,\n\t\tclient,\n\t\tparams,\n\t\tcode,\n\t\t'token endpoint',\n\t\tdpop,\n\t);\n\tif (!response.ok || !isRecord(answer) || !text(answer['access_token'])) {\n\t\tconst detail = detailOf(answer);\n\t\tthrow new OidcError(\n\t\t\tcode,\n\t\t\t`The token endpoint answered ${response.status}${detail ? ` (${detail})` : ''}.`,\n\t\t);\n\t}\n\tconst type = String(answer['token_type'] ?? 'bearer').toLowerCase();\n\tif (type !== 'bearer' && !(dpop && type === 'dpop')) {\n\t\tthrow new OidcError(\n\t\t\tcode,\n\t\t\t'The token endpoint did not issue a bearer token.',\n\t\t);\n\t}\n\treturn answer as unknown as TokenResponse;\n}\n\n/**\n * POST one token to the revocation endpoint (RFC 7009), with the client's authentication\n * and the DPoP proof when the tokens are bound. Throws `OidcError('revoke-failed')` on a\n * network error or a non-2xx answer.\n */\nexport async function revokeRequest(\n\tfetcher: Fetcher,\n\tendpoint: string,\n\tclient: Client,\n\tparams: { readonly token: string; readonly token_type_hint: string },\n\tdpop?: DpopSigning,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tconst { response, answer } = await postForm(\n\t\tfetcher,\n\t\tendpoint,\n\t\tclient,\n\t\tparams,\n\t\t'revoke-failed',\n\t\t'revocation endpoint',\n\t\tdpop,\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tconst detail = detailOf(answer);\n\t\tthrow new OidcError(\n\t\t\t'revoke-failed',\n\t\t\t`The revocation endpoint answered ${response.status}${detail ? ` (${detail})` : ''}.`,\n\t\t);\n\t}\n}\n\n/** POST the authorization request to the pushed authorization request endpoint (RFC 9126): the `request_uri` to redirect with. */\nexport async function pushRequest(\n\tfetcher: Fetcher,\n\tendpoint: string,\n\tclient: Client,\n\tparams: Record<string, string>,\n\tdpop?: DpopSigning,\n): Promise<string> {\n\tconst { response, answer } = await postForm(\n\t\tfetcher,\n\t\tendpoint,\n\t\tclient,\n\t\tparams,\n\t\t'par-failed',\n\t\t'pushed authorization request endpoint',\n\t\tdpop,\n\t);\n\tif (!response.ok || !isRecord(answer) || !text(answer['request_uri'])) {\n\t\tconst detail = detailOf(answer);\n\t\tthrow new OidcError(\n\t\t\t'par-failed',\n\t\t\t`The pushed authorization request endpoint answered ${response.status}${detail ? ` (${detail})` : ''}.`,\n\t\t);\n\t}\n\treturn answer['request_uri'];\n}\n\nexport { decodeJwt };\n",
7
- "import {\n\tcalculateJwkThumbprint,\n\texportJWK,\n\tgenerateKeyPair,\n\timportJWK,\n\ttype JWK,\n\tSignJWT,\n} from 'jose';\nimport { randomToken, toBase64Url } from './seal';\n\n/** The signature algorithms of a DPoP key (RFC 9449). */\nexport type DpopAlgorithm = 'ES256' | 'EdDSA';\n\n/** A DPoP key pair as it is stored with the session: the private JWK and its algorithm. */\nexport interface DpopKey {\n\treadonly alg: DpopAlgorithm;\n\treadonly jwk: JWK;\n}\n\n/** What a proof is signed for. */\nexport interface DpopProofInput {\n\t/** The HTTP method of the request the proof goes with. */\n\treadonly method: string;\n\t/** The request's URL; its query and fragment are dropped (`htu`). */\n\treadonly url: string | URL;\n\t/** The access token the proof is bound to (`ath`), for a call to a resource. */\n\treadonly accessToken?: string | undefined;\n\t/** The server's last `DPoP-Nonce`. */\n\treadonly nonce?: string | undefined;\n\t/** The clock, in ms; `Date.now` by default. */\n\treadonly now?: (() => number) | undefined;\n}\n\nconst encoder = new TextEncoder();\n\n/** A fresh DPoP key pair (ES256 by default), the private half as a JWK. */\nexport async function generateDpopKey(\n\talg: DpopAlgorithm = 'ES256',\n): Promise<DpopKey> {\n\tconst { privateKey } = await generateKeyPair(alg, { extractable: true });\n\treturn {\n\t\talg,\n\t\tjwk: pick(await exportJWK(privateKey), ['kty', 'crv', 'x', 'y', 'd']),\n\t};\n}\n\n/** Only the named members of a JWK that are set. */\nconst pick = (jwk: JWK, names: readonly (keyof JWK)[]): JWK =>\n\tObject.fromEntries(\n\t\tnames.flatMap((name) =>\n\t\t\tjwk[name] === undefined ? [] : [[name, jwk[name]]],\n\t\t),\n\t) as JWK;\n\nconst publicOf = (jwk: JWK): JWK => pick(jwk, ['kty', 'crv', 'x', 'y']);\n\n/** The RFC 7638 thumbprint of the key's public half (the `jkt` a server binds a token to). */\nexport const dpopThumbprint = (key: DpopKey): Promise<string> =>\n\tcalculateJwkThumbprint(publicOf(key.jwk), 'sha256');\n\n/** The URL a proof names: no query, no fragment. */\nexport function dpopTarget(url: string | URL): string {\n\tconst target = new URL(url);\n\ttarget.search = '';\n\ttarget.hash = '';\n\treturn target.toString();\n}\n\n/**\n * A DPoP proof (RFC 9449 section 4): a JWT of type `dpop+jwt` carrying the\n * key's public half, signed for one method and URL, with `ath` when it goes\n * with an access token and `nonce` when the server asked for one.\n */\nexport async function signDpopProof(\n\tkey: DpopKey,\n\tinput: DpopProofInput,\n): Promise<string> {\n\tconst signer = await importJWK(key.jwk, key.alg);\n\tconst iat = Math.floor((input.now ?? Date.now)() / 1000);\n\tconst ath =\n\t\tinput.accessToken === undefined\n\t\t\t? undefined\n\t\t\t: toBase64Url(\n\t\t\t\t\tnew Uint8Array(\n\t\t\t\t\t\tawait crypto.subtle.digest(\n\t\t\t\t\t\t\t'SHA-256',\n\t\t\t\t\t\t\tencoder.encode(input.accessToken),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\treturn new SignJWT({\n\t\thtm: input.method.toUpperCase(),\n\t\thtu: dpopTarget(input.url),\n\t\tjti: randomToken(16),\n\t\tiat,\n\t\t...(input.nonce !== undefined && { nonce: input.nonce }),\n\t\t...(ath !== undefined && { ath }),\n\t})\n\t\t.setProtectedHeader({\n\t\t\ttyp: 'dpop+jwt',\n\t\t\talg: key.alg,\n\t\t\tjwk: publicOf(key.jwk),\n\t\t})\n\t\t.sign(signer);\n}\n\n/** The last `DPoP-Nonce` each server sent, by origin (RFC 9449 section 8: a nonce belongs to one server). */\nexport interface NonceMemory {\n\tget(url: string | URL): string | undefined;\n\tset(url: string | URL, nonce: string): void;\n}\n\nexport function nonceMemory(): NonceMemory {\n\tconst nonces = new Map<string, string>();\n\treturn {\n\t\tget: (url) => nonces.get(new URL(url).origin),\n\t\tset: (url, nonce) => void nonces.set(new URL(url).origin, nonce),\n\t};\n}\n\n/** Whether a response asks for a (new) nonce: 400 `use_dpop_nonce` at an endpoint, 401 `WWW-Authenticate` at a resource. */\nexport async function wantsNonce(response: Response): Promise<boolean> {\n\tif (!response.headers.get('dpop-nonce')) return false;\n\tif (response.status === 401) {\n\t\treturn /use_dpop_nonce/.test(\n\t\t\tresponse.headers.get('www-authenticate') ?? '',\n\t\t);\n\t}\n\tif (response.status !== 400) return false;\n\tconst body: unknown = await response\n\t\t.clone()\n\t\t.json()\n\t\t.catch(() => null);\n\treturn (\n\t\ttypeof body === 'object' &&\n\t\tbody !== null &&\n\t\t(body as Record<string, unknown>)['error'] === 'use_dpop_nonce'\n\t);\n}\n\n/**\n * The DPoP side of a signed-in user: signs proofs for calls to a resource with\n * the session's key, bound to its access token.\n */\nexport interface DpopBinding {\n\t/** The key's thumbprint (`jkt`). */\n\treadonly thumbprint: string;\n\t/** A proof for one call (`htm`, `htu`, `ath`), with the nonce the server last sent unless one is given. */\n\tproof(input: {\n\t\treadonly method: string;\n\t\treadonly url: string | URL;\n\t\treadonly nonce?: string | undefined;\n\t}): Promise<string>;\n\t/** The two headers of a call: `Authorization: DPoP <token>` and `DPoP: <proof>`. */\n\theaders(input: {\n\t\treadonly method: string;\n\t\treadonly url: string | URL;\n\t\treadonly nonce?: string | undefined;\n\t}): Promise<{ readonly authorization: string; readonly dpop: string }>;\n\t/**\n\t * `fetch` with both headers set and the nonce retry: on `401` with\n\t * `WWW-Authenticate: DPoP error=\"use_dpop_nonce\"` it signs again with the\n\t * `DPoP-Nonce` header and retries once. Give a string or bytes as `body`,\n\t * since a stream cannot be sent twice.\n\t */\n\tfetch(input: string | URL, init?: RequestInit): Promise<Response>;\n}\n\nexport function dpopBinding(config: {\n\treadonly key: DpopKey;\n\treadonly thumbprint: string;\n\treadonly accessToken: string;\n\treadonly nonces: NonceMemory;\n\treadonly fetch: (input: string, init?: RequestInit) => Promise<Response>;\n\treadonly now: () => number;\n}): DpopBinding {\n\tconst { key, accessToken, nonces } = config;\n\tconst proof: DpopBinding['proof'] = ({ method, url, nonce }) =>\n\t\tsignDpopProof(key, {\n\t\t\tmethod,\n\t\t\turl,\n\t\t\taccessToken,\n\t\t\tnonce: nonce ?? nonces.get(url),\n\t\t\tnow: config.now,\n\t\t});\n\treturn {\n\t\tthumbprint: config.thumbprint,\n\t\tproof,\n\t\tasync headers(input) {\n\t\t\treturn {\n\t\t\t\tauthorization: `DPoP ${accessToken}`,\n\t\t\t\tdpop: await proof(input),\n\t\t\t};\n\t\t},\n\t\tasync fetch(input, init) {\n\t\t\tconst url = String(input);\n\t\t\tconst method = init?.method ?? 'GET';\n\t\t\tconst send = async (nonce?: string) => {\n\t\t\t\tconst headers = new Headers(init?.headers);\n\t\t\t\theaders.set('authorization', `DPoP ${accessToken}`);\n\t\t\t\theaders.set('dpop', await proof({ method, url, nonce }));\n\t\t\t\tconst response = await config.fetch(url, { ...init, headers });\n\t\t\t\tconst sent = response.headers.get('dpop-nonce');\n\t\t\t\tif (sent) nonces.set(url, sent);\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst first = await send();\n\t\t\tif (!(await wantsNonce(first))) return first;\n\t\t\treturn send(first.headers.get('dpop-nonce') ?? undefined);\n\t\t},\n\t};\n}\n",
8
- "const encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** Bytes as unpadded base64url. */\nexport const toBase64Url = (bytes: Uint8Array): string => {\n\tlet binary = '';\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary)\n\t\t.replaceAll('+', '-')\n\t\t.replaceAll('/', '_')\n\t\t.replaceAll('=', '');\n};\n\nconst fromBase64Url = (text: string): Uint8Array<ArrayBuffer> => {\n\tconst padded = text.replaceAll('-', '+').replaceAll('_', '/');\n\tconst binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));\n\treturn Uint8Array.from(binary, (char) => char.charCodeAt(0));\n};\n\n/** `bytes` random bytes as base64url. */\nexport const randomToken = (bytes = 32): string =>\n\ttoBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));\n\n/** Whether two strings are equal, comparing every byte whatever the first difference. */\nexport function sameText(a: string, b: string): boolean {\n\tconst left = encoder.encode(a);\n\tconst right = encoder.encode(b);\n\tlet difference = left.length ^ right.length;\n\tfor (let index = 0; index < Math.max(left.length, right.length); index++) {\n\t\tdifference |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn difference === 0;\n}\n\n/** The base64url S256 challenge of a PKCE verifier. */\nexport async function s256(verifier: string): Promise<string> {\n\treturn toBase64Url(\n\t\tnew Uint8Array(\n\t\t\tawait crypto.subtle.digest('SHA-256', encoder.encode(verifier)),\n\t\t),\n\t);\n}\n\n/**\n * An AES-256-GCM sealer keyed from the session secret and a purpose, so a\n * challenge cookie cannot be replayed as a token cookie: the value is\n * encrypted (the tokens stay unreadable) and authenticated (nobody can forge\n * or edit it).\n */\nexport function sealer(secret: string, purpose: string) {\n\tconst key = crypto.subtle\n\t\t.digest('SHA-256', encoder.encode(`alxia-oidc/${purpose}/${secret}`))\n\t\t.then((raw) =>\n\t\t\tcrypto.subtle.importKey('raw', raw, 'AES-GCM', false, [\n\t\t\t\t'encrypt',\n\t\t\t\t'decrypt',\n\t\t\t]),\n\t\t);\n\tconst additionalData = encoder.encode(purpose);\n\treturn {\n\t\tasync seal(value: unknown): Promise<string> {\n\t\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\t\t\tconst data = new Uint8Array(\n\t\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t\t{ name: 'AES-GCM', iv, additionalData },\n\t\t\t\t\tawait key,\n\t\t\t\t\tencoder.encode(JSON.stringify(value)),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst out = new Uint8Array(iv.length + data.length);\n\t\t\tout.set(iv);\n\t\t\tout.set(data, iv.length);\n\t\t\treturn toBase64Url(out);\n\t\t},\n\t\t/** The value, or `null` when the text was not sealed with this secret and purpose. */\n\t\tasync open(text: string): Promise<unknown> {\n\t\t\ttry {\n\t\t\t\tconst bytes = fromBase64Url(text);\n\t\t\t\tif (bytes.length < 29) return null;\n\t\t\t\tconst plain = await crypto.subtle.decrypt(\n\t\t\t\t\t{ name: 'AES-GCM', iv: bytes.slice(0, 12), additionalData },\n\t\t\t\t\tawait key,\n\t\t\t\t\tbytes.slice(12),\n\t\t\t\t);\n\t\t\t\treturn JSON.parse(decoder.decode(plain));\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n}\n",
9
- "import type { DpopKey } from './dpop';\n\n/** The sign-in challenge sealed in the short-lived flow cookie. */\nexport interface Flow {\n\treadonly state: string;\n\treadonly nonce: string;\n\treadonly verifier: string;\n\treadonly next: string;\n\treadonly exp: number;\n\treadonly dpop?: DpopKey | undefined;\n}\n\n/** The tokens sealed in the session cookie. */\nexport interface Stored {\n\treadonly idToken: string;\n\treadonly accessToken: string;\n\treadonly refreshToken?: string | undefined;\n\treadonly expiresAt: number;\n\treadonly dpop?: DpopKey | undefined;\n}\n\nconst isKey = (value: unknown): value is DpopKey =>\n\ttypeof value === 'object' &&\n\tvalue !== null &&\n\t['ES256', 'EdDSA'].includes(\n\t\t(value as Record<string, unknown>)['alg'] as string,\n\t) &&\n\ttypeof (value as Record<string, unknown>)['jwk'] === 'object';\n\nexport const isFlow = (value: unknown): value is Flow =>\n\ttypeof value === 'object' &&\n\tvalue !== null &&\n\t['state', 'nonce', 'verifier', 'next'].every(\n\t\t(key) => typeof (value as Record<string, unknown>)[key] === 'string',\n\t) &&\n\ttypeof (value as Record<string, unknown>)['exp'] === 'number' &&\n\t((value as Record<string, unknown>)['dpop'] === undefined ||\n\t\tisKey((value as Record<string, unknown>)['dpop']));\n\nexport const isStored = (value: unknown): value is Stored =>\n\ttypeof value === 'object' &&\n\tvalue !== null &&\n\ttypeof (value as Record<string, unknown>)['idToken'] === 'string' &&\n\ttypeof (value as Record<string, unknown>)['accessToken'] === 'string' &&\n\ttypeof (value as Record<string, unknown>)['expiresAt'] === 'number' &&\n\t((value as Record<string, unknown>)['dpop'] === undefined ||\n\t\tisKey((value as Record<string, unknown>)['dpop']));\n",
10
- "import type { JWTPayload } from 'jose';\nimport type { OidcContext } from './context';\nimport type { DpopKey } from './dpop';\nimport { OidcError } from './errors';\nimport { decodeJwt, type TokenResponse } from './flow';\nimport type { Stored } from './stored';\n\n/** The tokens of a token endpoint answer, as the session keeps them, with the id token's claims. */\nexport async function toStored(\n\tctx: OidcContext,\n\tresponse: TokenResponse,\n\tnonce: string | undefined,\n\tprevious?: Stored,\n\tkey?: DpopKey,\n): Promise<{ stored: Stored; claims: JWTPayload }> {\n\tconst { now } = ctx;\n\t// Only a token the issuer says is DPoP-bound keeps the key.\n\tconst dpop =\n\t\tkey &&\n\t\t(String(response.token_type).toLowerCase() === 'dpop' ||\n\t\t\t(previous?.dpop !== undefined && response.token_type === undefined))\n\t\t\t? key\n\t\t\t: undefined;\n\tif (!response.id_token && previous) {\n\t\t// A refresh may omit the id token (OIDC Core 12.2): keep the one verified\n\t\t// at sign-in, in the sealed cookie, though it has expired since.\n\t\tconst kept = decodeJwt(previous.idToken);\n\t\treturn {\n\t\t\tclaims: kept,\n\t\t\tstored: {\n\t\t\t\tidToken: previous.idToken,\n\t\t\t\tdpop,\n\t\t\t\taccessToken: response.access_token,\n\t\t\t\trefreshToken: response.refresh_token ?? previous.refreshToken,\n\t\t\t\texpiresAt:\n\t\t\t\t\ttypeof response.expires_in === 'number'\n\t\t\t\t\t\t? now() + response.expires_in * 1000\n\t\t\t\t\t\t: now() + 300_000,\n\t\t\t},\n\t\t};\n\t}\n\tconst idToken = response.id_token;\n\tif (!idToken) {\n\t\tthrow new OidcError(\n\t\t\t'invalid-id-token',\n\t\t\t'The token endpoint sent no id token.',\n\t\t);\n\t}\n\tconst claims = await ctx.issuerApi.verifyIdToken(\n\t\tidToken,\n\t\tctx.clientId,\n\t\tnonce,\n\t);\n\tif (previous && decodeJwt(previous.idToken).sub !== claims.sub) {\n\t\tthrow new OidcError('invalid-id-token', 'A refresh changed the user.');\n\t}\n\tconst expiresAt =\n\t\ttypeof response.expires_in === 'number'\n\t\t\t? now() + response.expires_in * 1000\n\t\t\t: (claims['exp'] ?? 0) * 1000;\n\treturn {\n\t\tclaims,\n\t\tstored: {\n\t\t\tidToken,\n\t\t\tdpop,\n\t\t\taccessToken: response.access_token,\n\t\t\trefreshToken: response.refresh_token ?? previous?.refreshToken,\n\t\t\texpiresAt,\n\t\t},\n\t};\n}\n\n/** Seals `stored` into the token cookie and appends it to `headers`. */\nexport async function commit(\n\tctx: OidcContext,\n\theaders: Headers,\n\tstored: Stored,\n): Promise<void> {\n\tconst { now } = ctx;\n\tconst lifetime = stored.refreshToken\n\t\t? ctx.sessionSeconds\n\t\t: Math.max(0, (stored.expiresAt - now()) / 1000);\n\tconst cookie = ctx.cookies.commit(\n\t\tawait ctx.tokenSeal.seal(stored),\n\t\tnew Date(now() + lifetime * 1000),\n\t\tnow(),\n\t);\n\t// A browser silently drops a cookie over 4096 bytes: fail loudly instead.\n\tif (cookie.length > 4096) {\n\t\tthrow new OidcError(\n\t\t\t'token-cookie-too-large',\n\t\t\t`The token cookie is ${cookie.length} bytes, over the 4096 a browser keeps. Ask the issuer for fewer claims or a shorter access token.`,\n\t\t);\n\t}\n\theaders.append('Set-Cookie', cookie);\n}\n",
11
- "import { safeNext } from '../session/model/safe-next';\nimport type { OidcContext } from './context';\nimport { OidcError } from './errors';\nimport { tokenRequest } from './flow';\nimport { sameText } from './seal';\nimport { type Flow, isFlow } from './stored';\nimport { commit, toStored } from './tokens';\n\ntype Failure = (\n\tcode: ConstructorParameters<typeof OidcError>[0],\n\tmessage: string,\n) => OidcError;\n\n/** The challenge of the request, checked against what the issuer sent back. */\nasync function checkedFlow(\n\tctx: OidcContext,\n\trequest: Request,\n\tfail: Failure,\n): Promise<{ flow: Flow; code: string }> {\n\tconst url = new URL(request.url);\n\tconst sealed = ctx.cookies.challengeOf(request);\n\tconst flow = sealed ? await ctx.flowSeal.open(sealed) : null;\n\tif (!isFlow(flow)) {\n\t\tthrow fail(\n\t\t\t'missing-challenge',\n\t\t\t'The sign-in challenge cookie is missing or unreadable (a second tab, an expired page or a blocked cookie).',\n\t\t);\n\t}\n\tif (flow.exp <= ctx.now()) {\n\t\tthrow fail('challenge-expired', 'The sign-in took too long; start again.');\n\t}\n\tconst returned = url.searchParams.get('state');\n\tif (returned === null || !sameText(returned, flow.state)) {\n\t\tthrow fail(\n\t\t\t'state-mismatch',\n\t\t\t'The returned state is not the one this sign-in sent.',\n\t\t);\n\t}\n\tconst failure = url.searchParams.get('error');\n\tif (failure) {\n\t\tconst description = url.searchParams.get('error_description');\n\t\tthrow fail(\n\t\t\t'provider-error',\n\t\t\t`The issuer refused: ${failure}${description ? ` (${description})` : ''}.`,\n\t\t);\n\t}\n\tconst claimedIssuer = url.searchParams.get('iss');\n\tif (claimedIssuer !== null && claimedIssuer !== ctx.issuer) {\n\t\tthrow fail('issuer-mismatch', 'The callback names another issuer.');\n\t}\n\tconst code = url.searchParams.get('code');\n\tif (!code) throw fail('missing-code', 'The callback carries no code.');\n\treturn { flow, code };\n}\n\n/** `OidcClient.callback`: state, code exchange, id token, token cookie, redirect to `next`. */\nexport async function callback(\n\tctx: OidcContext,\n\trequest: Request,\n): Promise<Response> {\n\tconst cleared = () => {\n\t\tconst headers = new Headers();\n\t\theaders.append('Set-Cookie', ctx.cookies.destroyChallenge());\n\t\treturn headers;\n\t};\n\tconst fail: Failure = (code, message) =>\n\t\tnew OidcError(code, message, cleared());\n\tconst { flow, code } = await checkedFlow(ctx, request, fail);\n\ttry {\n\t\tconst document = await ctx.issuerApi.discover();\n\t\tconst answer = await tokenRequest(\n\t\t\tctx.fetcher,\n\t\t\tdocument.token_endpoint,\n\t\t\tctx.client,\n\t\t\t{\n\t\t\t\t...ctx.extraTokenParams,\n\t\t\t\tgrant_type: 'authorization_code',\n\t\t\t\tcode,\n\t\t\t\tredirect_uri: ctx.redirectUri,\n\t\t\t\tcode_verifier: flow.verifier,\n\t\t\t},\n\t\t\t'token-exchange-failed',\n\t\t\tctx.signing(flow.dpop),\n\t\t);\n\t\tconst { stored } = await toStored(\n\t\t\tctx,\n\t\t\tanswer,\n\t\t\tflow.nonce,\n\t\t\tundefined,\n\t\t\tflow.dpop,\n\t\t);\n\t\tconst headers = cleared();\n\t\tawait commit(ctx, headers, stored);\n\t\theaders.set('Location', safeNext(flow.next));\n\t\theaders.set('Cache-Control', 'no-store');\n\t\treturn new Response(null, { status: 302, headers });\n\t} catch (error) {\n\t\tif (error instanceof OidcError) {\n\t\t\tfor (const value of cleared().getSetCookie()) {\n\t\t\t\terror.headers.append('Set-Cookie', value);\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n}\n",
12
- "import { type SessionCookies, sessionCookies } from '../session/cookies';\nimport { type DpopKey, type NonceMemory, nonceMemory } from './dpop';\nimport { type DpopSigning, type Fetcher, issuerClient } from './flow';\nimport { sealer } from './seal';\nimport type { Stored } from './stored';\nimport type { OidcOptions, OidcUser } from './types';\n\nconst DEFAULT_ALGORITHMS = ['RS256', 'PS256', 'ES256', 'EdDSA'];\nexport const CHALLENGE_SECONDS = 600;\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/** What every concern of the client reads: the options resolved once, and the state they share. */\nexport interface OidcContext {\n\treadonly options: OidcOptions;\n\treadonly issuer: string;\n\treadonly clientId: string;\n\treadonly redirectUri: string;\n\treadonly signInPath: string;\n\treadonly sessionSeconds: number;\n\treadonly refreshSkewSeconds: number;\n\treadonly refreshFlightMs: number;\n\treadonly scopes: readonly string[];\n\t/** The token request's extra parameters, without the client's credentials. */\n\treadonly extraTokenParams: Readonly<Record<string, string>>;\n\treadonly now: () => number;\n\treadonly cookies: SessionCookies;\n\treadonly flowSeal: ReturnType<typeof sealer>;\n\treadonly tokenSeal: ReturnType<typeof sealer>;\n\treadonly issuerApi: ReturnType<typeof issuerClient>;\n\treadonly fetcher: Fetcher;\n\treadonly client: {\n\t\treadonly id: string;\n\t\treadonly secret: string | undefined;\n\t};\n\treadonly par: 'auto' | 'always' | 'never';\n\treadonly dpopAlg: 'ES256' | 'EdDSA' | undefined;\n\treadonly nonces: NonceMemory;\n\treadonly signing: (key: DpopKey | undefined) => DpopSigning | undefined;\n\t/** Refreshes in flight (or just done), by refresh token. */\n\treadonly flights: Map<string, Promise<Stored>>;\n\t/** The tokens behind each user this client returned. */\n\treadonly stores: WeakMap<OidcUser, Stored>;\n}\n\nfunction checkRequired(options: OidcOptions): void {\n\tfor (const [label, value] of [\n\t\t['issuer', options.issuer],\n\t\t['clientId', options.clientId],\n\t\t['redirectUri', options.redirectUri],\n\t] as const) {\n\t\tif (!value) throw new TypeError(`oidcClient(): ${label} is required.`);\n\t}\n\tconst { secret } = options;\n\tif (typeof secret !== 'string' || secret.length < 32) {\n\t\tthrow new TypeError(\n\t\t\t'oidcClient(): secret must be a string of at least 32 characters.',\n\t\t);\n\t}\n}\n\nfunction checkTuning(\n\toptions: OidcOptions,\n\tpar: string,\n\tdpopAlg: string | undefined,\n\trefreshFlightMs: number,\n): void {\n\tif (!['auto', 'always', 'never'].includes(par)) {\n\t\tthrow new TypeError(\n\t\t\t\"oidcClient(): par must be 'auto', 'always' or 'never'.\",\n\t\t);\n\t}\n\tif (dpopAlg !== undefined && !['ES256', 'EdDSA'].includes(dpopAlg)) {\n\t\tthrow new TypeError(\"oidcClient(): dpop.alg must be 'ES256' or 'EdDSA'.\");\n\t}\n\tif (\n\t\toptions.revokeTimeoutMs !== undefined &&\n\t\t!(Number.isFinite(options.revokeTimeoutMs) && options.revokeTimeoutMs > 0)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'oidcClient(): revokeTimeoutMs must be a positive finite number of milliseconds.',\n\t\t);\n\t}\n\tif (\n\t\t!(\n\t\t\tNumber.isFinite(refreshFlightMs) &&\n\t\t\trefreshFlightMs >= 0 &&\n\t\t\trefreshFlightMs <= MAX_TIMER_MS\n\t\t)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.',\n\t\t);\n\t}\n}\n\n/** Validates the options and resolves them once. Throws `TypeError` on a bad option. */\nexport function createContext(options: OidcOptions): OidcContext {\n\tcheckRequired(options);\n\tconst {\n\t\tissuer,\n\t\tclientId,\n\t\tclientSecret,\n\t\tredirectUri,\n\t\tsecret,\n\t\tsignInPath = '/sign-in',\n\t\tsessionSeconds = 30 * 24 * 3600,\n\t\trefreshSkewSeconds = 60,\n\t\trefreshFlightMs = 10_000,\n\t\tclockToleranceSeconds = 30,\n\t} = options;\n\t// Client credentials travel by the client's authentication method, never as extras.\n\tconst {\n\t\tclient_id: _id,\n\t\tclient_secret: _secret,\n\t\t...extraTokenParams\n\t} = options.tokenParams ?? {};\n\tconst now = options.now ?? Date.now;\n\tconst scopes = [\n\t\t...new Set(['openid', ...(options.scopes ?? ['profile', 'email'])]),\n\t];\n\tconst cookies = sessionCookies({\n\t\tsession: options.name,\n\t\tchallenge: `${options.name}_flow`,\n\t\tchallengePath: '/',\n\t\tchallengeHostPrefix: true,\n\t\tchallengeSeconds: CHALLENGE_SECONDS,\n\t\tsecure: options.secure,\n\t\tsameSite: 'lax',\n\t});\n\tconst flowSeal = sealer(secret, 'flow');\n\tconst tokenSeal = sealer(secret, 'tokens');\n\tconst fetcher: Fetcher =\n\t\toptions.fetch ?? ((input, init) => fetch(input, init));\n\tconst issuerApi = issuerClient({\n\t\tissuer,\n\t\tfetch: fetcher,\n\t\tnow,\n\t\talgorithms: [...(options.algorithms ?? DEFAULT_ALGORITHMS)],\n\t\tclockToleranceSeconds,\n\t});\n\tconst par = options.par ?? 'auto';\n\tconst dpopAlg = options.dpop ? (options.dpop.alg ?? 'ES256') : undefined;\n\tcheckTuning(options, par, dpopAlg, refreshFlightMs);\n\tconst nonces = nonceMemory();\n\treturn {\n\t\toptions,\n\t\tissuer,\n\t\tclientId,\n\t\tredirectUri,\n\t\tsignInPath,\n\t\tsessionSeconds,\n\t\trefreshSkewSeconds,\n\t\trefreshFlightMs,\n\t\tscopes,\n\t\textraTokenParams,\n\t\tnow,\n\t\tcookies,\n\t\tflowSeal,\n\t\ttokenSeal,\n\t\tissuerApi,\n\t\tfetcher,\n\t\tclient: { id: clientId, secret: clientSecret },\n\t\tpar,\n\t\tdpopAlg,\n\t\tnonces,\n\t\tsigning: (key) => (key ? { key, nonces, now } : undefined),\n\t\tflights: new Map(),\n\t\tstores: new WeakMap(),\n\t};\n}\n",
13
- "import type { DpopKey } from './dpop';\nimport { OidcError } from './errors';\nimport type { DpopSigning, Fetcher } from './flow';\nimport { revokeRequest } from './flow';\n\n/** What `revokeTokens` needs: the sealed session's tokens and, when bound, its DPoP key. */\ninterface Revocable {\n\treadonly accessToken: string;\n\treadonly refreshToken?: string | undefined;\n\treadonly dpop?: DpopKey | undefined;\n}\n\n/**\n * Revoke the refresh token, then the access token (RFC 7009). Each failure is passed to\n * `report`, none is thrown. `timeoutMs` bounds both calls together: past it, the pending\n * call is aborted and reported as `revoke-failed`, and the other is not attempted.\n */\nexport async function revokeTokens(input: {\n\treadonly fetcher: Fetcher;\n\treadonly client: {\n\t\treadonly id: string;\n\t\treadonly secret?: string | undefined;\n\t};\n\treadonly endpoint: string;\n\treadonly stored: Revocable;\n\treadonly signing: (key: DpopKey | undefined) => DpopSigning | undefined;\n\treadonly timeoutMs: number;\n\treadonly report: (error: OidcError) => void;\n}): Promise<void> {\n\tconst { stored } = input;\n\tconst signal = AbortSignal.timeout(input.timeoutMs);\n\tconst timedOut = new Promise<never>((_, reject) => {\n\t\tsignal.addEventListener(\n\t\t\t'abort',\n\t\t\t() =>\n\t\t\t\treject(\n\t\t\t\t\tnew OidcError(\n\t\t\t\t\t\t'revoke-failed',\n\t\t\t\t\t\t`The revocation endpoint did not answer within ${input.timeoutMs} ms.`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ once: true },\n\t\t);\n\t});\n\ttimedOut.catch(() => undefined);\n\tconst tokens = [\n\t\t...(stored.refreshToken\n\t\t\t? ([[stored.refreshToken, 'refresh_token']] as const)\n\t\t\t: []),\n\t\t[stored.accessToken, 'access_token'] as const,\n\t];\n\tfor (const [token, hint] of tokens) {\n\t\ttry {\n\t\t\t// The race also ends a fetcher that ignores the signal.\n\t\t\tawait Promise.race([\n\t\t\t\trevokeRequest(\n\t\t\t\t\tinput.fetcher,\n\t\t\t\t\tinput.endpoint,\n\t\t\t\t\tinput.client,\n\t\t\t\t\t{ token, token_type_hint: hint },\n\t\t\t\t\tinput.signing(stored.dpop),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\ttimedOut,\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tinput.report(\n\t\t\t\terror instanceof OidcError\n\t\t\t\t\t? error\n\t\t\t\t\t: new OidcError('revoke-failed', 'Revocation failed.', undefined, {\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t}),\n\t\t\t);\n\t\t\tif (signal.aborted) return;\n\t\t}\n\t}\n}\n",
14
- "import type { OidcContext } from './context';\nimport { OidcError } from './errors';\nimport { revokeTokens } from './revoke';\nimport { isStored } from './stored';\n\n/** `OidcClient.logout`: revokes the tokens (when on), clears the cookie, redirects to the issuer or home. */\nexport async function logout(\n\tctx: OidcContext,\n\trequest: Request,\n): Promise<Response> {\n\tconst { options } = ctx;\n\tconst report = (error: OidcError): void => {\n\t\ttry {\n\t\t\toptions.onRevokeError?.(error);\n\t\t} catch {\n\t\t\t// A failing hook never blocks the logout.\n\t\t}\n\t};\n\tconst headers = new Headers({ 'Cache-Control': 'no-store' });\n\theaders.append('Set-Cookie', ctx.cookies.destroy());\n\tconst sealed = ctx.cookies.token(request);\n\tconst opened = sealed ? await ctx.tokenSeal.open(sealed) : null;\n\tconst document = await ctx.issuerApi.discover().catch((cause) => {\n\t\tif (options.revokeOnLogout) {\n\t\t\treport(\n\t\t\t\tnew OidcError(\n\t\t\t\t\t'discovery-failed',\n\t\t\t\t\t'Discovery failed at logout, so the tokens were not revoked.',\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ cause },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t});\n\tif (\n\t\toptions.revokeOnLogout &&\n\t\tdocument?.revocation_endpoint &&\n\t\tisStored(opened)\n\t) {\n\t\tawait revokeTokens({\n\t\t\tfetcher: ctx.fetcher,\n\t\t\tclient: ctx.client,\n\t\t\tendpoint: document.revocation_endpoint,\n\t\t\tstored: opened,\n\t\t\tsigning: ctx.signing,\n\t\t\ttimeoutMs: options.revokeTimeoutMs ?? 3000,\n\t\t\treport,\n\t\t});\n\t}\n\tconst endpoint = document?.end_session_endpoint;\n\tif (!endpoint) {\n\t\theaders.set('Location', options.postLogoutRedirectUri ?? '/');\n\t\treturn new Response(null, { status: 302, headers });\n\t}\n\tconst target = new URL(endpoint);\n\tif (isStored(opened))\n\t\ttarget.searchParams.set('id_token_hint', opened.idToken);\n\ttarget.searchParams.set('client_id', ctx.clientId);\n\tif (options.postLogoutRedirectUri) {\n\t\ttarget.searchParams.set(\n\t\t\t'post_logout_redirect_uri',\n\t\t\toptions.postLogoutRedirectUri,\n\t\t);\n\t}\n\theaders.set('Location', target.toString());\n\treturn new Response(null, { status: 302, headers });\n}\n",
15
- "import type { OidcContext } from './context';\nimport { dpopBinding, dpopThumbprint } from './dpop';\nimport { decodeJwt } from './flow';\nimport type { Stored } from './stored';\nimport type { OidcUser } from './types';\n\n/** The user a loader reads, from the session's tokens; remembers them for `refresh`. */\nexport async function toUser(\n\tctx: OidcContext,\n\tstored: Stored,\n\theaders: Headers,\n): Promise<OidcUser> {\n\tconst user: OidcUser = {\n\t\tclaims: decodeJwt(stored.idToken),\n\t\taccessToken: stored.accessToken,\n\t\tidToken: stored.idToken,\n\t\texpiresAt: stored.expiresAt,\n\t\theaders,\n\t\tdpop: stored.dpop\n\t\t\t? dpopBinding({\n\t\t\t\t\tkey: stored.dpop,\n\t\t\t\t\tthumbprint: await dpopThumbprint(stored.dpop),\n\t\t\t\t\taccessToken: stored.accessToken,\n\t\t\t\t\tnonces: ctx.nonces,\n\t\t\t\t\tfetch: ctx.fetcher,\n\t\t\t\t\tnow: ctx.now,\n\t\t\t\t})\n\t\t\t: null,\n\t\tfetch: ctx.fetcher,\n\t};\n\tctx.stores.set(user, stored);\n\treturn user;\n}\n",
16
- "import type { OidcContext } from './context';\nimport { OidcError } from './errors';\nimport { tokenRequest } from './flow';\nimport type { Stored } from './stored';\nimport { commit, toStored } from './tokens';\nimport type { OidcUser } from './types';\nimport { toUser } from './user';\n\n/** One refresh per refresh token: parallel callers share the flight. */\nexport function refreshing(\n\tctx: OidcContext,\n\tstored: Stored,\n\tkey: string,\n): Promise<Stored> {\n\tconst { flights } = ctx;\n\tconst flying = flights.get(key);\n\tif (flying) return flying;\n\tconst flight = (async () => {\n\t\tconst document = await ctx.issuerApi.discover();\n\t\tconst answer = await tokenRequest(\n\t\t\tctx.fetcher,\n\t\t\tdocument.token_endpoint,\n\t\t\tctx.client,\n\t\t\t{\n\t\t\t\t...ctx.extraTokenParams,\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\trefresh_token: key,\n\t\t\t\tscope: ctx.scopes.join(' '),\n\t\t\t},\n\t\t\t'refresh-failed',\n\t\t\tctx.signing(stored.dpop),\n\t\t);\n\t\treturn (await toStored(ctx, answer, undefined, stored, stored.dpop)).stored;\n\t})();\n\tflights.set(key, flight);\n\t// Rotation: parallel requests still carry the spent refresh token for a moment.\n\tconst forget = () => {\n\t\tconst timer = setTimeout(() => flights.delete(key), ctx.refreshFlightMs);\n\t\t// A pending forget never keeps the process alive.\n\t\tif (typeof timer === 'object') timer.unref();\n\t};\n\tflight.then(forget, () => flights.delete(key));\n\treturn flight;\n}\n\n/** `OidcClient.refresh`: a new user from the tokens of `user`, when due or forced. */\nexport async function refresh(\n\tctx: OidcContext,\n\tuser: OidcUser,\n\trefreshOptions: { readonly force?: boolean | undefined } = {},\n): Promise<OidcUser> {\n\tconst stored = ctx.stores.get(user);\n\tif (!stored) {\n\t\tthrow new TypeError(\n\t\t\t'oidc.refresh(): the user was not returned by this client.',\n\t\t);\n\t}\n\tif (\n\t\t!refreshOptions.force &&\n\t\tstored.expiresAt - ctx.refreshSkewSeconds * 1000 > ctx.now()\n\t) {\n\t\treturn user;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tif (!stored.refreshToken) throw new Error('no refresh token');\n\t\tconst next = await refreshing(ctx, stored, stored.refreshToken);\n\t\tawait commit(ctx, headers, next);\n\t\treturn toUser(ctx, next, headers);\n\t} catch (cause) {\n\t\t// A transient failure keeps a still-valid access token going.\n\t\tif (stored.expiresAt > ctx.now()) return user;\n\t\tthrow cause instanceof OidcError\n\t\t\t? cause\n\t\t\t: new OidcError('refresh-failed', 'The refresh failed.', undefined, {\n\t\t\t\t\tcause,\n\t\t\t\t});\n\t}\n}\n",
17
- "import { redirect } from 'react-router';\nimport { safeNext } from '../session/model/safe-next';\nimport type { OidcContext } from './context';\nimport { refreshing } from './refresh';\nimport { isStored, type Stored } from './stored';\nimport { commit } from './tokens';\nimport type { OidcUser } from './types';\nimport { toUser } from './user';\n\n/** `OidcClient.oidcUser`: the signed-in user (refreshed if due), or `null`. */\nexport async function oidcUser(\n\tctx: OidcContext,\n\trequest: Request,\n): Promise<OidcUser | null> {\n\tconst headers = new Headers();\n\tconst sealed = ctx.cookies.token(request);\n\tif (!sealed) return null;\n\tconst opened = await ctx.tokenSeal.open(sealed);\n\tif (!isStored(opened)) {\n\t\theaders.append('Set-Cookie', ctx.cookies.destroy());\n\t\treturn null;\n\t}\n\tlet stored: Stored = opened;\n\tif (stored.expiresAt - ctx.refreshSkewSeconds * 1000 <= ctx.now()) {\n\t\ttry {\n\t\t\tif (!stored.refreshToken) throw new Error('no refresh token');\n\t\t\tstored = await refreshing(ctx, stored, stored.refreshToken);\n\t\t\tawait commit(ctx, headers, stored);\n\t\t} catch {\n\t\t\t// A transient failure keeps a still-valid access token going.\n\t\t\tif (stored.expiresAt <= ctx.now()) return null;\n\t\t}\n\t}\n\treturn toUser(ctx, stored, headers);\n}\n\nconst toSignIn = (\n\tctx: OidcContext,\n\trequest: Request,\n\theaders: Headers,\n): never => {\n\tconst url = new URL(request.url);\n\tconst next = safeNext(`${url.pathname}${url.search}`);\n\tconst target = new URL(ctx.signInPath, url);\n\ttarget.searchParams.set('next', next);\n\tthrow redirect(`${target.pathname}${target.search}`, { headers });\n};\n\n/** `OidcClient.requireOidcUser`: the user, else a thrown redirect to the sign-in route. */\nexport async function requireOidcUser(\n\tctx: OidcContext,\n\trequest: Request,\n): Promise<OidcUser> {\n\tconst user = await oidcUser(ctx, request);\n\tif (user) return user;\n\tconst headers = new Headers();\n\tif (ctx.cookies.token(request)) {\n\t\theaders.append('Set-Cookie', ctx.cookies.destroy());\n\t}\n\treturn toSignIn(ctx, request, headers);\n}\n",
18
- "import { safeNext } from '../session/model/safe-next';\nimport { CHALLENGE_SECONDS, type OidcContext } from './context';\nimport { dpopThumbprint, generateDpopKey } from './dpop';\nimport { OidcError } from './errors';\nimport { pushRequest } from './flow';\nimport { randomToken, s256 } from './seal';\nimport type { Flow } from './stored';\n\n/** `OidcClient.signIn`: a redirect to the issuer, the challenge sealed in its cookie. */\nexport async function signIn(\n\tctx: OidcContext,\n\trequest: Request,\n): Promise<Response> {\n\tconst { clientId, now } = ctx;\n\tconst document = await ctx.issuerApi.discover();\n\tconst url = new URL(request.url);\n\tconst flow: Flow = {\n\t\tstate: randomToken(),\n\t\tnonce: randomToken(),\n\t\tverifier: randomToken(48),\n\t\tnext: safeNext(url.searchParams.get('next')),\n\t\texp: now() + CHALLENGE_SECONDS * 1000,\n\t\tdpop: ctx.dpopAlg ? await generateDpopKey(ctx.dpopAlg) : undefined,\n\t};\n\tconst authRequest: Record<string, string> = {\n\t\t...ctx.options.authorizationParams,\n\t\tresponse_type: 'code',\n\t\tclient_id: clientId,\n\t\tredirect_uri: ctx.redirectUri,\n\t\tscope: ctx.scopes.join(' '),\n\t\tstate: flow.state,\n\t\tnonce: flow.nonce,\n\t\tcode_challenge: await s256(flow.verifier),\n\t\tcode_challenge_method: 'S256',\n\t\t...(flow.dpop && { dpop_jkt: await dpopThumbprint(flow.dpop) }),\n\t};\n\tconst endpoint = document.pushed_authorization_request_endpoint;\n\tconst push =\n\t\tctx.par === 'always' ||\n\t\t(ctx.par === 'auto' &&\n\t\t\tdocument.require_pushed_authorization_requests === true);\n\tconst target = new URL(document.authorization_endpoint);\n\tif (push) {\n\t\tif (!endpoint) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'par-failed',\n\t\t\t\t'Pushed authorization requests are required but the issuer publishes no pushed_authorization_request_endpoint.',\n\t\t\t);\n\t\t}\n\t\tconst requestUri = await pushRequest(\n\t\t\tctx.fetcher,\n\t\t\tendpoint,\n\t\t\tctx.client,\n\t\t\tauthRequest,\n\t\t\tctx.signing(flow.dpop),\n\t\t);\n\t\ttarget.searchParams.set('client_id', clientId);\n\t\ttarget.searchParams.set('request_uri', requestUri);\n\t} else {\n\t\tfor (const [key, value] of Object.entries(authRequest)) {\n\t\t\ttarget.searchParams.set(key, value);\n\t\t}\n\t}\n\tconst headers = new Headers({ 'Cache-Control': 'no-store' });\n\theaders.append(\n\t\t'Set-Cookie',\n\t\tctx.cookies.commitChallenge(await ctx.flowSeal.seal(flow), null, now()),\n\t);\n\theaders.set('Location', target.toString());\n\treturn new Response(null, { status: 302, headers });\n}\n",
19
- "import { callback } from './callback';\nimport { createContext } from './context';\nimport { logout } from './logout';\nimport { refresh } from './refresh';\nimport { oidcUser, requireOidcUser } from './session';\nimport { signIn } from './signin';\nimport type { OidcOptions, OidcUser } from './types';\n\n/** The relying party `oidcClient` returns. */\nexport interface OidcClient {\n\t/** The route action or loader that starts the sign-in: a redirect to the issuer. `?next=` is kept, through `safeNext`. */\n\tsignIn(request: Request): Promise<Response>;\n\t/** The redirect route: checks state, exchanges the code, validates the id token, sets the token cookie and redirects to `next`. Throws `OidcError`. */\n\tcallback(request: Request): Promise<Response>;\n\t/** The signed-in user (refreshed if due), or `null`. */\n\toidcUser(request: Request): Promise<OidcUser | null>;\n\t/**\n\t * Refreshes `user` from its own tokens (not the request's cookie, which a rotation\n\t * leaves behind) when its access token ends within `refreshSkewSeconds`, and returns\n\t * the new user, whose `headers` hold the `Set-Cookie` to send; `user` itself when\n\t * nothing is due, or with `{ force: true }` always. A forced refresh inside the\n\t * flight window of `refreshFlightMs` shares that flight's tokens; with no refresh\n\t * token it returns `user` while its access token is valid. A refresh that fails\n\t * throws `OidcError` (`refresh-failed`) when the access token has ended, else\n\t * returns `user`. Only a user this client returned can be refreshed (else\n\t * `TypeError`).\n\t */\n\trefresh(\n\t\tuser: OidcUser,\n\t\toptions?: { readonly force?: boolean | undefined },\n\t): Promise<OidcUser>;\n\t/** Like `oidcUser`, but throws a redirect to the sign-in route (with a safe `next`) when there is none. */\n\trequireOidcUser(request: Request): Promise<OidcUser>;\n\t/** Clears the token cookie (after revoking the tokens with `revokeOnLogout`) and redirects to the issuer's `end_session_endpoint` (with `id_token_hint`), else to `postLogoutRedirectUri` or `/`. Call it from an action. */\n\tlogout(request: Request): Promise<Response>;\n\t/** The cookie names as sent, prefixes included. */\n\treadonly names: { readonly session: string; readonly challenge: string };\n}\n\n/**\n * A BFF as the relying party of an external OpenID Connect issuer:\n * authorization code with PKCE (S256), state and nonce in a short-lived\n * `__Host-` challenge cookie, discovery (cached), the code exchange, the id\n * token validated against the issuer's keys (`jose`, an optional peer), the\n * tokens in a sealed `__Host-` cookie, a single-flight refresh and\n * RP-initiated logout.\n *\n * @example\n * export const oidc = oidcClient({\n * issuer: 'https://id.example.com',\n * clientId: 'my-app',\n * clientSecret: process.env.OIDC_CLIENT_SECRET,\n * redirectUri: 'https://app.example.com/auth/callback',\n * scopes: ['openid', 'profile', 'email', 'offline_access'],\n * secret: process.env.SESSION_SECRET!,\n * name: 'my-app_oidc',\n * secure: !import.meta.env.DEV,\n * });\n * // routes/auth.callback.ts: export const loader = ({ request }) => oidc.callback(request);\n * // any loader: const { claims, headers } = await oidc.requireOidcUser(request);\n */\nexport function oidcClient(options: OidcOptions): OidcClient {\n\tconst ctx = createContext(options);\n\treturn {\n\t\tnames: ctx.cookies.names,\n\t\toidcUser: (request) => oidcUser(ctx, request),\n\t\trefresh: (user, refreshOptions) => refresh(ctx, user, refreshOptions),\n\t\trequireOidcUser: (request) => requireOidcUser(ctx, request),\n\t\tsignIn: (request) => signIn(ctx, request),\n\t\tcallback: (request) => callback(ctx, request),\n\t\tlogout: (request) => logout(ctx, request),\n\t};\n}\n",
20
- "import type { OidcClient } from './client';\nimport type { OidcUser } from './types';\n\n/** A `fetch` that calls a resource as one signed-in user. */\nexport type DpopFetch = (\n\tinput: string | URL,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\n/** The part of the relying party `dpopFetch` needs. */\nexport type DpopRefresher = Pick<OidcClient, 'refresh'>;\n\n/** Options of {@link dpopFetch}. */\nexport interface DpopFetchOptions {\n\t/**\n\t * Called with the new user each time the access token or its expiry changes\n\t * (parallel calls sharing one refresh report it once). Its `headers` hold the\n\t * `Set-Cookie` to pass with the route's answer (the last one wins: each refresh\n\t * starts from the previous user, so the cookie it sets replaces the older one).\n\t */\n\treadonly onUser?: ((user: OidcUser) => void) | undefined;\n}\n\n/**\n * `fetch` for the calls a loader or an action makes to an API as the signed-in\n * user. On a DPoP-bound session (`oidcClient`'s `dpop` option) each call carries\n * `Authorization: DPoP <token>` and a fresh proof (`htm`, `htu` without its\n * query, `ath`, `jti`), and a `401` with `WWW-Authenticate: DPoP\n * error=\"use_dpop_nonce\"` is signed again with the `DPoP-Nonce` sent and\n * retried once; the nonce is remembered per server. On a bearer session it\n * sends `Authorization: Bearer <token>` through the client's own `fetch`.\n *\n * It keeps the last user it got. Before each call it asks `oidc.refresh` for a\n * fresh one, which refreshes from that user's own tokens (never the request's\n * cookie, whose refresh token a rotation spends) only when the access token\n * ends within `refreshSkewSeconds`. A body must be a string or bytes, since a\n * stream cannot be sent twice.\n *\n * @example\n * const user = await oidc.requireOidcUser(request);\n * let latest = user;\n * const api = dpopFetch(oidc, user, { onUser: (next) => (latest = next) });\n * const orders = await (await api('https://api.example.com/orders?page=2')).json();\n * return data({ orders }, { headers: latest.headers });\n */\nexport function dpopFetch(\n\toidc: DpopRefresher,\n\tuser: OidcUser,\n\toptions: DpopFetchOptions = {},\n): DpopFetch {\n\tlet last = user;\n\treturn async (input, init) => {\n\t\tconst next = await oidc.refresh(last);\n\t\tif (\n\t\t\tnext.accessToken !== last.accessToken ||\n\t\t\tnext.expiresAt !== last.expiresAt\n\t\t) {\n\t\t\tlast = next;\n\t\t\toptions.onUser?.(next);\n\t\t}\n\t\tif (last.dpop) return last.dpop.fetch(input, init);\n\t\tconst headers = new Headers(init?.headers);\n\t\theaders.set('authorization', `Bearer ${last.accessToken}`);\n\t\treturn last.fetch(String(input), { ...init, headers });\n\t};\n}\n",
21
- "import type { OidcOptions } from './types';\n\n/** Every start-up problem of the environment, in one error. */\nexport class OidcEnvError extends Error {\n\toverride readonly name = 'OidcEnvError';\n\tconstructor(readonly problems: readonly string[]) {\n\t\tsuper(\n\t\t\t`The OIDC environment is not usable:\\n${problems.map((p) => `- ${p}`).join('\\n')}`,\n\t\t);\n\t}\n}\n\n/** What {@link oidcFromEnv} reads. */\nexport interface OidcEnvSource {\n\t/** The variables' prefix. `'OIDC'` by default (`OIDC_ISSUER`, …). */\n\treadonly prefix?: string | undefined;\n\t/** The environment; `process.env` by default. */\n\treadonly env?: Readonly<Record<string, string | undefined>> | undefined;\n\t/** Reads a secret file; `Bun.file(path).text()` by default. */\n\treadonly readFile?: ((path: string) => Promise<string>) | undefined;\n\t/** Gives a secret file's `mode`, to refuse one that group or others can read; `Bun.file(path).stat()` by default. */\n\treadonly statFile?:\n\t\t| ((path: string) => Promise<{ readonly mode: number }>)\n\t\t| undefined;\n}\n\n/** What {@link oidcFromEnv} gives: spread it into `oidcClient`, with `secure`. */\nexport type OidcEnvOptions = Pick<\n\tOidcOptions,\n\t| 'issuer'\n\t| 'clientId'\n\t| 'clientSecret'\n\t| 'redirectUri'\n\t| 'secret'\n\t| 'name'\n\t| 'postLogoutRedirectUri'\n>;\n\n/** What the readers share: data only. */\ninterface Context {\n\treadonly env: Readonly<Record<string, string | undefined>>;\n\treadonly prefix: string;\n\treadonly problems: string[];\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly statFile: (path: string) => Promise<{ readonly mode: number }>;\n}\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nconst named = (context: Context, suffix: string) =>\n\t`${context.prefix}_${suffix}`;\n\nfunction plain(context: Context, suffix: string): string | undefined {\n\tconst value = context.env[named(context, suffix)]?.trim();\n\treturn value ? value : undefined;\n}\n\n/** A required plain value. */\nfunction required(context: Context, suffix: string): string | undefined {\n\tconst value = plain(context, suffix);\n\tif (value === undefined) {\n\t\tcontext.problems.push(`${named(context, suffix)} is not set.`);\n\t}\n\treturn value;\n}\n\n/** An absolute `https:` URL, `http:` on loopback only. */\nfunction url(\n\tcontext: Context,\n\tsuffix: string,\n\tmandatory: boolean,\n): string | undefined {\n\tconst value = mandatory ? required(context, suffix) : plain(context, suffix);\n\tif (value === undefined) return undefined;\n\tconst variable = named(context, suffix);\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(value);\n\t} catch {\n\t\tcontext.problems.push(`${variable} is not an absolute URL.`);\n\t\treturn undefined;\n\t}\n\tif (\n\t\tparsed.protocol !== 'https:' &&\n\t\t!(parsed.protocol === 'http:' && LOOPBACK.has(parsed.hostname))\n\t) {\n\t\tcontext.problems.push(`${variable} must be an https: URL.`);\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\n/** A value given directly or through a `_FILE` variable, named by the one it came from. */\nasync function secret(\n\tcontext: Context,\n\tsuffix: string,\n\tmandatory: boolean,\n): Promise<{ value: string; variable: string } | undefined> {\n\tconst direct = plain(context, suffix);\n\tconst fileSuffix = `${suffix}_FILE`;\n\tconst path = plain(context, fileSuffix);\n\tif (direct !== undefined && path !== undefined) {\n\t\tcontext.problems.push(\n\t\t\t`Set ${named(context, suffix)} or ${named(context, fileSuffix)}, not both.`,\n\t\t);\n\t\treturn undefined;\n\t}\n\tif (path === undefined) {\n\t\tif (direct !== undefined) {\n\t\t\treturn { value: direct, variable: named(context, suffix) };\n\t\t}\n\t\tif (mandatory) {\n\t\t\tcontext.problems.push(\n\t\t\t\t`${named(context, fileSuffix)} (or ${named(context, suffix)}) is not set.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst variable = named(context, fileSuffix);\n\tlet text: string;\n\ttry {\n\t\tconst { mode } = await context.statFile(path);\n\t\tif ((mode & 0o077) !== 0) {\n\t\t\tcontext.problems.push(\n\t\t\t\t`${variable} names a file readable by group or others (mode ${(mode & 0o777).toString(8)}); restrict it to its owner, such as chmod 600.`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\ttext = await context.readFile(path);\n\t} catch {\n\t\tcontext.problems.push(\n\t\t\t`${variable} names a file that cannot be read: check the path and its permissions.`,\n\t\t);\n\t\treturn undefined;\n\t}\n\tconst value = text.trim();\n\tif (value === '') {\n\t\tcontext.problems.push(`${variable} names an empty file.`);\n\t\treturn undefined;\n\t}\n\tif (/\\s/.test(value)) {\n\t\tcontext.problems.push(\n\t\t\t`${variable} names a file with whitespace inside: it must hold one value.`,\n\t\t);\n\t\treturn undefined;\n\t}\n\treturn { value, variable };\n}\n\n/**\n * The relying party's settings from the environment, checked once at start-up:\n * every missing or malformed variable is listed in one `OidcEnvError`, never a\n * secret's value. `secure` is not read from the environment: give it to\n * `oidcClient` yourself (`secure: !import.meta.env.DEV`).\n *\n * | variable (prefix `OIDC`) | |\n * | --- | --- |\n * | `OIDC_ISSUER` | required, an `https:` URL (`http:` on loopback) |\n * | `OIDC_CLIENT_ID` | required |\n * | `OIDC_CLIENT_SECRET_FILE` or `OIDC_CLIENT_SECRET` | the secret of a confidential client; none for a public one |\n * | `OIDC_REDIRECT_URI` | required, an `https:` URL (`http:` on loopback) |\n * | `OIDC_SESSION_SECRET_FILE` or `OIDC_SESSION_SECRET` | required, 32 characters or more |\n * | `OIDC_COOKIE_NAME` | `'oidc'` by default |\n * | `OIDC_POST_LOGOUT_REDIRECT_URI` | optional, an `https:` URL (`http:` on loopback) |\n *\n * A `_FILE` variable names a file whose trimmed content is the value, and\n * that only its owner can read (no group or other permission bit), with no\n * whitespace inside; a message never prints the path. Prefer it to the plain\n * variable for a secret.\n *\n * @example\n * export const oidc = oidcClient({\n * ...(await oidcFromEnv()),\n * secure: !import.meta.env.DEV,\n * scopes: ['profile', 'email', 'offline_access'],\n * });\n */\nexport async function oidcFromEnv(\n\tsource: OidcEnvSource = {},\n): Promise<OidcEnvOptions> {\n\tconst context: Context = {\n\t\tenv: source.env ?? process.env,\n\t\tprefix: source.prefix ?? 'OIDC',\n\t\tproblems: [],\n\t\treadFile: source.readFile ?? ((path) => Bun.file(path).text()),\n\t\tstatFile: source.statFile ?? ((path) => Bun.file(path).stat()),\n\t};\n\tconst issuer = url(context, 'ISSUER', true);\n\tconst clientId = required(context, 'CLIENT_ID');\n\tconst clientSecret = await secret(context, 'CLIENT_SECRET', false);\n\tconst redirectUri = url(context, 'REDIRECT_URI', true);\n\tconst postLogoutRedirectUri = url(context, 'POST_LOGOUT_REDIRECT_URI', false);\n\tconst session = await secret(context, 'SESSION_SECRET', true);\n\tif (session !== undefined && session.value.length < 32) {\n\t\tcontext.problems.push(\n\t\t\t`The session secret must be 32 characters or more (${session.variable}).`,\n\t\t);\n\t}\n\tif (\n\t\tcontext.problems.length > 0 ||\n\t\tissuer === undefined ||\n\t\tclientId === undefined ||\n\t\tredirectUri === undefined ||\n\t\tsession === undefined\n\t) {\n\t\tthrow new OidcEnvError(context.problems);\n\t}\n\treturn {\n\t\tissuer,\n\t\tclientId,\n\t\tclientSecret: clientSecret?.value,\n\t\tredirectUri,\n\t\tsecret: session.value,\n\t\tname: plain(context, 'COOKIE_NAME') ?? 'oidc',\n\t\tpostLogoutRedirectUri,\n\t};\n}\n",
22
- "import { redirect } from 'react-router';\nimport { siteCheck } from '../errors/same-site';\nimport { sitePath } from '../session/model/site-path';\nimport type { OidcClient } from './client';\nimport { OidcError } from './errors';\n\ntype Args = { readonly request: Request };\n\n/** Runs before a route does its work: throw a `Response` or `data()` to refuse. */\ntype Guard = (request: Request) => void | Promise<void>;\n\n/** Options of {@link signInRoute}. */\nexport interface SignInRouteOptions {\n\t/** Runs first, e.g. to refuse a host the sign-in must not be served on. */\n\treadonly guard?: Guard | undefined;\n}\n\n/**\n * The sign-in route module: a `loader` that redirects to the issuer (`?next=`\n * is kept, through `safeNext`).\n *\n * @example\n * // app/routes/sign-in.ts\n * export const { loader } = signInRoute(oidc);\n */\nexport function signInRoute(\n\toidc: Pick<OidcClient, 'signIn'>,\n\toptions: SignInRouteOptions = {},\n): { loader: (args: Args) => Promise<Response> } {\n\treturn {\n\t\tasync loader({ request }) {\n\t\t\tawait options.guard?.(request);\n\t\t\treturn oidc.signIn(request);\n\t\t},\n\t};\n}\n\n/** Options of {@link callbackRoute}. */\nexport interface CallbackRouteOptions {\n\t/** Runs first. */\n\treadonly guard?: Guard | undefined;\n\t/**\n\t * Answers a refused sign-in. It gets the `OidcError` and must put its\n\t * `headers` on the response (they clear the spent challenge cookie).\n\t * By default the browser is redirected to `errorPath` with `?sign-in-error=<code>`.\n\t */\n\treadonly onError?:\n\t\t| ((error: OidcError) => Response | Promise<Response>)\n\t\t| undefined;\n\t/** Where the default answer redirects: a path of this site with no query or fragment (`TypeError` otherwise). `'/'` by default. */\n\treadonly errorPath?: string | undefined;\n}\n\n/**\n * The redirect route: a `loader` that finishes the sign-in (302 to `next`, token\n * cookie set). An `OidcError` is answered, never thrown, with the cookie that\n * clears the spent challenge; any other error is thrown.\n *\n * @example\n * // app/routes/auth.callback.ts\n * export const { loader } = callbackRoute(oidc, { errorPath: '/sign-in/failed' });\n */\nexport function callbackRoute(\n\toidc: Pick<OidcClient, 'callback'>,\n\toptions: CallbackRouteOptions = {},\n): { loader: (args: Args) => Promise<Response> } {\n\tconst errorPath = sitePath(options.errorPath ?? '/', {\n\t\tlabel: 'callbackRoute(): errorPath',\n\t});\n\treturn {\n\t\tasync loader({ request }) {\n\t\t\tawait options.guard?.(request);\n\t\t\ttry {\n\t\t\t\treturn await oidc.callback(request);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OidcError)) throw error;\n\t\t\t\tif (options.onError) return options.onError(error);\n\t\t\t\treturn redirect(\n\t\t\t\t\t`${errorPath}?${new URLSearchParams({ 'sign-in-error': error.code })}`,\n\t\t\t\t\t{ headers: error.headers },\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** Options of {@link signOutRoute}. */\nexport interface SignOutRouteOptions {\n\t/** Runs first, on the action and on the loader. */\n\treadonly guard?: Guard | undefined;\n\t/** The app's own origin, required behind a TLS-terminating proxy (see `requireSameSite`). */\n\treadonly origin?: string | (() => string | undefined) | undefined;\n\t/** Where a GET on the route goes: a path of this site (`TypeError` otherwise). `'/'` by default. */\n\treadonly redirectTo?: string | undefined;\n}\n\n/**\n * The sign-out route module: an `action` that refuses a cross-site request,\n * then calls `logout`: the cookie is cleared (and the tokens revoked with\n * `revokeOnLogout`), then the browser goes to the issuer's\n * `end_session_endpoint` (with `id_token_hint` and `post_logout_redirect_uri`)\n * when discovery announces one, else to `postLogoutRedirectUri` or `/`: the\n * local session alone ends. A GET only redirects, so a link or an image cannot\n * sign the user out.\n *\n * @example\n * // app/routes/sign-out.ts\n * export const { action, loader } = signOutRoute(oidc);\n */\nexport function signOutRoute(\n\toidc: Pick<OidcClient, 'logout'>,\n\toptions: SignOutRouteOptions = {},\n): {\n\taction: (args: Args) => Promise<Response>;\n\tloader: (args: Args) => Promise<Response>;\n} {\n\tconst sameSite = siteCheck(options.origin);\n\tconst redirectTo = sitePath(options.redirectTo ?? '/', {\n\t\tlabel: 'signOutRoute(): redirectTo',\n\t\tquery: true,\n\t});\n\treturn {\n\t\tasync action({ request }) {\n\t\t\tawait options.guard?.(request);\n\t\t\tsameSite(request);\n\t\t\treturn oidc.logout(request);\n\t\t},\n\t\tasync loader({ request }) {\n\t\t\tawait options.guard?.(request);\n\t\t\treturn redirect(redirectTo);\n\t\t},\n\t};\n}\n"
23
5
  ],
24
- "mappings": ";;;;;;;;;;;;AAsBO,MAAM,kBAAkB,MAAM;AAAA,EAG1B;AAAA,EAEA;AAAA,EAJQ,OAAO;AAAA,EACzB,WAAW,CACD,MACT,SACS,UAAmB,IAAI,SAChC,SACC;AAAA,IACD,MAAM,SAAS,OAAO;AAAA,IALb;AAAA,IAEA;AAAA;AAKX;;;AChCA;AAAA;AAAA;AAAA,YAKC;AAAA;AAAA;;;ACLD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,UAAU,IAAI;AACpB,IAAM,UAAU,IAAI;AAGb,IAAM,cAAc,CAAC,UAA8B;AAAA,EACzD,IAAI,SAAS;AAAA,EACb,WAAW,QAAQ;AAAA,IAAO,UAAU,OAAO,aAAa,IAAI;AAAA,EAC5D,OAAO,KAAK,MAAM,EAChB,WAAW,KAAK,GAAG,EACnB,WAAW,KAAK,GAAG,EACnB,WAAW,KAAK,EAAE;AAAA;AAGrB,IAAM,gBAAgB,CAAC,SAA0C;AAAA,EAChE,MAAM,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE,WAAW,KAAK,GAAG;AAAA,EAC5D,MAAM,SAAS,KAAK,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAAC,CAAC;AAAA,EACtE,OAAO,WAAW,KAAK,QAAQ,CAAC,SAAS,KAAK,WAAW,CAAC,CAAC;AAAA;AAIrD,IAAM,cAAc,CAAC,QAAQ,OACnC,YAAY,OAAO,gBAAgB,IAAI,WAAW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D,OAAO,UACN,GAAG,aAAa,IAAI,gBAAgB,EAAE,iBAAiB,MAAM,KAAK,CAAC,KACnE,EAAE,SAAS,MAAM,QAAQ,CAC1B;AAAA;AAAA;AAAA,EAGH;AAAA;AA0BM,SAAS,YAAY,CAC3B,MACA,UAA+B,CAAC,GAI/B;AAAA,EACD,MAAM,WAAW,UAAU,QAAQ,MAAM;AAAA,EACzC,MAAM,aAAa,SAAS,QAAQ,cAAc,KAAK;AAAA,IACtD,OAAO;AAAA,IACP,OAAO;AAAA,EACR,CAAC;AAAA,EACD,OAAO;AAAA,UACA,MAAM,GAAG,WAAW;AAAA,MACzB,MAAM,QAAQ,QAAQ,OAAO;AAAA,MAC7B,SAAS,OAAO;AAAA,MAChB,OAAO,KAAK,OAAO,OAAO;AAAA;AAAA,UAErB,MAAM,GAAG,WAAW;AAAA,MACzB,MAAM,QAAQ,QAAQ,OAAO;AAAA,MAC7B,OAAO,UAAS,UAAU;AAAA;AAAA,EAE5B;AAAA;",
25
- "debugId": "C1E1692B5010A35F64756E2164756E21",
6
+ "mappings": "",
7
+ "debugId": "464051438A2604CB64756E2164756E21",
26
8
  "names": []
27
9
  }
@@ -32,7 +32,7 @@ import {
32
32
  secondsUntil2,
33
33
  sessionCookies2,
34
34
  challengeCleared
35
- } from "../chunks/index-1nw5yeek.js";
35
+ } from "../chunks/index-qkyt0bka.js";
36
36
  import {
37
37
  nextOf2
38
38
  } from "../chunks/index-njfh26ez.js";
package/docs/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  The [package README](../README.md) is the short version. This folder is
4
4
  the long one: the setup, the Vite plugin and its default server, the build for Bun,
5
5
  customising the server, the typed context, the client's files, making the app
6
- installable and usable offline, wording an API's refusals, the BFF session, a GraphQL subscription relayed to the browser (`/subscription`), an API's MCP and OAuth endpoints relayed on the app's origin (`/mcp`), an API's media files read and uploaded through the app (`/media`) and uploaded from the page with progress (`/media/client`), the consent screen of an OAuth server (`/oauth`), a user's API keys (`/api-keys`), a relying party of an external OpenID Connect issuer (`/oidc`), and what to do with each message.
6
+ installable and usable offline, wording an API's refusals, the BFF session, a GraphQL subscription relayed to the browser (`/subscription`), an API's MCP and OAuth endpoints relayed on the app's origin (`/mcp`), an API's media files read and uploaded through the app (`/media`) and uploaded from the page with progress (`/media/client`), the consent screen of an OAuth server (`/oauth`), a user's API keys (`/api-keys`), a relying party of an external OpenID Connect issuer (`/oidc`), a BFF signing in with Clavix (`/clavix`), and what to do with each message.
7
7
 
8
8
  | Page | Read it when |
9
9
  | --- | --- |
@@ -26,6 +26,7 @@ installable and usable offline, wording an API's refusals, the BFF session, a Gr
26
26
  | [Lists whose state is the URL](guide/lists.md) | a search and filters in the address bar that drop the cursor (`useSearchChange`), a skeleton while the same page reloads (`useSameRouteLoading`), and a load-more button that appends pages by cursor and keeps the rows when one fails (`usePagedRows`), numbered pages over a cursor-paged connection (`connectionPage`), a connection's nodes as an array (`nodesOf`); `@softistx/alxia-react-router/lists` |
27
27
  | [Per-role flow docs and a help panel](guide/help.md) | documenting each role's flows screen by screen in `docs/flows/<name>.<lang>.md` (the front-matter format, steps, the four WebP captures), loading them at build time (`loadHelpFlows`), the flows of the current screen and the user's roles in the shape of `HelpSheet` (`useHelpFlows`), and the coverage check of routes, flows and captures (`alxia-react-router help check`); `@softistx/alxia-react-router/help`, `/help/check` |
28
28
  | [The consent screen of an OAuth server](guide/oauth.md) | letting a viewer allow or deny an OAuth client: `oauthConsent` (the route's loader and action over the janus-oauth GraphQL, passed in as functions), `useConsent` (the decision, the step-up replay, the callback) `oauthGrants` (an account's connected apps: the list newest first, the revoke) and the pure helpers; `@softistx/alxia-react-router/oauth` |
29
+ | [A BFF signing in with Clavix](guide/clavix.md) | `clavixRoutes`: the sign-in, callback and sign-out routes over `/oidc` (PAR, DPoP, `offline_access`, a resource), provider-only by default, env read at start-up with named errors, the sign-in page's landing and notices (signed out, refused with a support reference, expired session), refusal wording in English and French, an internal-origin client with the public `htu`, and the `/media` and `/live` relays; `@softistx/alxia-react-router/clavix` |
29
30
  | [A relying party of an OpenID Connect issuer](guide/oidc.md) | signing users in with an external issuer: `oidcClient` (authorization code + PKCE S256, state and nonce in a `__Host-` challenge cookie, discovery, the code exchange, the id token validated against the issuer's JWKS with `jose`, a sealed `__Host-` token cookie, a single-flight refresh, `requireOidcUser`, RP-initiated logout, pushed authorization requests, DPoP), `oidcFromEnv`, the route helpers (`signInRoute`, `callbackRoute`, `signOutRoute`) and `dpopFetch`, its options and limits; `@softistx/alxia-react-router/oidc` |
30
31
  | [Media through the BFF](guide/media.md) | serving and uploading an API's `@softistx/alxia-media` files on the app's own origin: `proxyMediaRead` and `proxyMediaWrite` in a `/media/*` resource route, the kinds and their limits, the same-site check, the 413 before the API, streaming both ways, Range and ETag passed through, the no-store exemption (`@softistx/alxia-react-router/media`), and the page's `uploadMedia` with progress, abort and typed refusals (`@softistx/alxia-react-router/media/client`) |
31
32
  | [A user's API keys](guide/api-keys.md) | listing a user's API keys, creating one behind a step-up with its secret shown once, and revoking one: `apiKeys` and the page's `useStepUpReplay` (`@softistx/alxia-react-router/api-keys`) |
@@ -0,0 +1,332 @@
1
+ # Signing in with Clavix
2
+
3
+ A BFF that signs its users in with Clavix is an [OpenID Connect relying
4
+ party](oidc.md) with a fixed profile: pushed authorization requests, DPoP-bound
5
+ tokens, a sealed `__Host-` cookie, the API as the token's resource, and
6
+ Clavix's own refusals to word. `@softistx/alxia-react-router/clavix` is that
7
+ profile, so the UI side of an app is a few lines of wiring.
8
+
9
+ | subpath | holds | imports |
10
+ | --- | --- | --- |
11
+ | `@softistx/alxia-react-router/clavix` | `clavixRoutes`, `SessionExpired`, `isExpiredAnswer` (recognises the `answer` of a `SessionExpired`, not the error), `ClavixOriginError`, `appendSetCookies`, `rewritingFetch`, `clavixRefusalOf`, `needsReference`, `supportReference`, `isSupportReference`, `clavixNoticeOf`, `clavixToneOf`, `clavixNoticeText`, `clavixMessages`, `CLAVIX_PARAMS`, `CLAVIX_REFUSALS`, and the types `ClavixRoutesOptions`, `ClavixRoutes`, `ClavixPaths`, `ClavixLanding`, `LandingOptions`, `ClavixNotice`, `ClavixTone`, `ClavixRefusal`, `ClavixMessages`, `ClavixRelay`, `ApiUrls`, `Send` | `react-router`, `/session`'s cookie helpers, `jose` (optional peer) |
12
+
13
+ Install the peer: `bun add jose`. The subpath sits on [`/oidc`](oidc.md) and
14
+ shares its `OidcError`; it does not need `@softistx/alxia-clavix`, which is the
15
+ API side.
16
+
17
+ ## What it does
18
+
19
+ - **The routes.** `/auth/clavix` starts the sign-in (PAR, PKCE, DPoP),
20
+ `/auth/clavix/callback` finishes it, `/sign-out` revokes the tokens, clears
21
+ the cookie and goes to Clavix's `end_session_endpoint`.
22
+ - **Provider-only by default.** When Clavix is the app's only way in, every
23
+ "Sign in" goes straight to it: no page showing a lone button. The sign-in
24
+ page shows only when it has something to say (below).
25
+ - **The API called as the user.** A `fetch` that signs each call with a DPoP
26
+ proof for the API's *public* URL while the call goes to its *internal*
27
+ address, refreshes the token before it ends, retries once on a 401 and turns
28
+ an ended session into a `SessionExpired`.
29
+ - **Refusals worded.** The issuer's refusals become a bounded set of notices
30
+ (cancelled, suspended, expired, down, provider, generic), each with a tone,
31
+ an English and a French sentence, and a support reference when the visitor
32
+ cannot fix it alone.
33
+ - **The relays.** `/media` and `/live` forwarded with `Authorization: DPoP`.
34
+
35
+ ## Set it up
36
+
37
+ ```ts
38
+ // app/clavix.server.ts
39
+ import { clavixRoutes } from '@softistx/alxia-react-router/clavix';
40
+
41
+ export const clavix = clavixRoutes({
42
+ secure: !import.meta.env.DEV,
43
+ api: {
44
+ publicUrl: process.env.API_PUBLIC_URL ?? 'https://api.example.com',
45
+ internalUrl: process.env.API_URL,
46
+ },
47
+ appOrigin: process.env.APP_ORIGIN,
48
+ scopes: ['example:api'],
49
+ });
50
+
51
+ // Boot: a bad environment stops here, with every variable named.
52
+ await clavix.ready();
53
+ ```
54
+
55
+ The routes are three files:
56
+
57
+ ```ts
58
+ // app/routes/auth.clavix.ts
59
+ import { clavix } from '../clavix.server';
60
+
61
+ export const { loader } = clavix.routes.start;
62
+ ```
63
+
64
+ ```ts
65
+ // app/routes/auth.clavix.callback.ts
66
+ import { clavix } from '../clavix.server';
67
+
68
+ export const { loader } = clavix.routes.callback;
69
+ ```
70
+
71
+ ```ts
72
+ // app/routes/sign-out.ts
73
+ import { clavix } from '../clavix.server';
74
+
75
+ export const { action, loader } = clavix.routes.signOut;
76
+ ```
77
+
78
+ Register `https://<app>/auth/clavix/callback` (and `https://<app>/sign-in` as
79
+ the post-logout address) with the Clavix client. Both default from
80
+ `appOrigin`.
81
+
82
+ ### Environment
83
+
84
+ `ready()` reads and checks the environment once. A missing or malformed
85
+ variable is listed by name, never by value, in one `OidcEnvError`; a failure is
86
+ not cached, so a fixed environment is read again at the next request.
87
+
88
+ | variable | |
89
+ | --- | --- |
90
+ | `CLAVIX_ISSUER` | required, Clavix's `https:` URL (`http:` on loopback) |
91
+ | `CLAVIX_CLIENT_ID` | required |
92
+ | `CLAVIX_CLIENT_SECRET_FILE` or `CLAVIX_CLIENT_SECRET` | the secret of a confidential client |
93
+ | `CLAVIX_SESSION_SECRET_FILE` or `CLAVIX_SESSION_SECRET` | required, 32 characters or more; seals the cookie |
94
+ | `CLAVIX_REDIRECT_URI` | `<appOrigin>/auth/clavix/callback` by default |
95
+ | `CLAVIX_POST_LOGOUT_REDIRECT_URI` | `<appOrigin>/sign-in` by default |
96
+ | `CLAVIX_COOKIE_NAME` | `clavix` by default |
97
+ | `CLAVIX_AUDIENCE` | the resource (RFC 8707) the token is for; the API's `<publicUrl>/graphql` by default |
98
+
99
+ A `_FILE` variable names a file only its owner can read (`chmod 600`); see
100
+ [`oidcFromEnv`](oidc.md#oidcfromenv).
101
+
102
+ ### Options
103
+
104
+ | option | |
105
+ | --- | --- |
106
+ | `secure` | required. `Secure` and `__Host-` cookies: `!import.meta.env.DEV`. It is not read from the environment, since a built `dist` has no `import.meta.env` |
107
+ | `api.publicUrl` | the API's public address, what a proof's `htu` names |
108
+ | `api.internalUrl` | what this server calls instead; omit it when the API is reached at its public address |
109
+ | `api.graphqlPath` | `/graphql`; the default resource is `publicUrl + graphqlPath` |
110
+ | `appOrigin` | a string or a function; the registered addresses default from it and sign-out checks the request against it |
111
+ | `scopes` | beside `openid`, `profile`, `email` and `offline_access`, such as the API's own scope |
112
+ | `paths` | `{ start, callback, signIn }`: `/auth/clavix`, `/auth/clavix/callback`, `/sign-in` |
113
+ | `env`, `readFile`, `statFile` | for tests |
114
+ | `fetch` | every call to Clavix and the API; the global `fetch` by default |
115
+ | `log` | `console` by default; a refusal is logged there under its reference |
116
+ | `onRevokeError` | a failed revocation at sign-out; the sign-out goes on |
117
+
118
+ The client is fixed to `par: 'always'`, `dpop: {}` and `revokeOnLogout: true`.
119
+
120
+ ## The sign-in page
121
+
122
+ ```ts
123
+ // app/routes/sign-in.tsx
124
+ import { data } from 'react-router';
125
+ import type { Route } from './+types/sign-in';
126
+ import { clavix } from '../clavix.server';
127
+
128
+ export async function loader({ request }: Route.LoaderArgs) {
129
+ // Throws the redirect when the page is not shown.
130
+ const { headers, ...page } = await clavix.landing(request);
131
+ return data(page, { headers });
132
+ }
133
+ ```
134
+
135
+ `landing` decides, in this order:
136
+
137
+ 1. A signed-in visitor goes to `next` (a path of this site; anything else is
138
+ `/`).
139
+ 2. A session cookie that no longer opens (its refresh token is gone) is
140
+ cleared, so `/` stops sending the visitor back.
141
+ 3. The signed-out cookie that sign-out sets (the end-session redirect cannot
142
+ carry a query) becomes `?signed-out=1`: a reload keeps the page instead of
143
+ sending the visitor to Clavix, whose single sign-on would sign them straight
144
+ back in.
145
+ 4. With nothing to say, a document redirect (`redirectDocument`) to
146
+ `/auth/clavix?next=…`.
147
+
148
+ The page stays, and `landing` returns what to show, when:
149
+
150
+ | it has to say | URL | `notice.kind` |
151
+ | --- | --- | --- |
152
+ | the visitor signed out | `?signed-out=1` | `signed-out`, with `endSessionUrl` for an "also sign out of Clavix" link |
153
+ | the session ended | `?expired=1` | `session-expired` |
154
+ | a sign-in was refused | `?clavix-error=<kind>[&ref=XXXX-XXXX]` | `cancelled`, `suspended`, `expired`, `down`, `provider` or `generic`, with a `reference` for the last three |
155
+ | other methods exist | | none: pass `{ otherMethods: true }` |
156
+ | the app's own state | | none: pass `{ speakingParams: ['spent'] }` |
157
+
158
+ Only the bounded set is read from the URL: a crafted `clavix-error` or `ref`
159
+ shows nothing. A refusal is never redirected away, since a loop would hide the
160
+ error.
161
+
162
+ The page itself stays in the app, because it is the app's UI and i18n.
163
+ `clavixNoticeText` words a notice in English or French, the tone says how loud:
164
+
165
+ ```tsx no-check
166
+ // app/routes/sign-in.tsx, the component
167
+ import {
168
+ clavixMessages,
169
+ clavixNoticeText,
170
+ clavixToneOf,
171
+ } from '@softistx/alxia-react-router/clavix';
172
+ import { AuthCard } from '@softistx/material/auth';
173
+ import type { Route } from './+types/sign-in';
174
+
175
+ export default function SignIn({ loaderData }: Route.ComponentProps) {
176
+ const { notice, startHref, endSessionUrl } = loaderData;
177
+ const words = clavixMessages.en;
178
+ const said = notice ? clavixNoticeText(notice, words) : null;
179
+ return (
180
+ <AuthCard icon={<ClavixMark />} title={words.continue}>
181
+ {said ? (
182
+ <p role="alert" data-tone={clavixToneOf(notice!)}>
183
+ {said.text} {said.reference}
184
+ </p>
185
+ ) : null}
186
+ <a href={startHref}>{words.continue}</a>
187
+ {endSessionUrl ? <a href={endSessionUrl}>{words.signOutOfProvider}</a> : null}
188
+ </AuthCard>
189
+ );
190
+ }
191
+ ```
192
+
193
+ The sign-in button is a link (a GET), since a content security policy's
194
+ `form-action` may refuse a form posting to Clavix. `AuthCard`'s `icon` prop
195
+ (`@softistx/material` 3.353.0 and later) carries the provider's mark.
196
+
197
+ ## Calling the API as the user
198
+
199
+ ```ts
200
+ // app/routes/orders.tsx
201
+ import { SessionExpired } from '@softistx/alxia-react-router/clavix';
202
+ import { clavix } from '../clavix.server';
203
+ import type { Route } from './+types/orders';
204
+
205
+ export async function loader({ request }: Route.LoaderArgs) {
206
+ const send = clavix.sendOf(request);
207
+ try {
208
+ const response = await send(clavix.apiUrl(), {
209
+ method: 'POST',
210
+ headers: { 'content-type': 'application/json' },
211
+ body: JSON.stringify({ query: '{ viewer { id } }' }),
212
+ });
213
+ return await clavix.withRefreshedCookies(request, response);
214
+ } catch (error) {
215
+ // A GET goes to /sign-in?next=…&expired=1, any other method gets a 401 `session-expired`.
216
+ if (error instanceof SessionExpired) return error.answer;
217
+ throw error;
218
+ }
219
+ }
220
+ ```
221
+
222
+ `sendOf(request)` is a `fetch` for one request's calls:
223
+
224
+ - Pass it the **public** URL (`clavix.apiUrl()`); the call is signed for it and
225
+ sent to `api.internalUrl`. A proof for the internal address would not match
226
+ the `htu` the API checks.
227
+ - It refreshes the token before it ends, signs again on `use_dpop_nonce`, and
228
+ on a 401 that remains forces one refresh and retries once.
229
+ - A refresh that fails, or no session, throws `SessionExpired`, whose `answer`
230
+ is a redirect to the sign-in page (a GET) or a 401 JSON (anything else);
231
+ `sendOf(request, { expired })` gives another answer. Any other answer, a 503
232
+ included, is returned as it is: an unreachable API is never a sign-out.
233
+ - The refreshed cookie rides on the response: `withRefreshedCookies(request,
234
+ response)`, or `refreshedCookies(request)` for the raw `Set-Cookie` lines.
235
+
236
+ A call to any address other than `api.publicUrl` or `api.internalUrl` (a
237
+ lookalike host, a `user@host` trick, another port or scheme) throws
238
+ `ClavixOriginError` before anything is signed: a DPoP-bound token never goes to
239
+ another origin. `sendOf` does not follow a redirect either (`redirect: 'manual'`: a 3xx comes back as is). The relays' `fetch` checks the origin the same way; the upstream the app passes it must not follow redirects to another origin.
240
+
241
+ ### The viewer, without the plumbing
242
+
243
+ A GraphQL client that turns every error from `fetch` into a 503 hides the
244
+ `SessionExpired`. `clavix.viewer(request, load)` takes the plumbing: you write
245
+ only the query, as `load(send)`.
246
+
247
+ ```ts
248
+ // app/session.server.ts, in the middleware or a loader
249
+ import { clavix } from './clavix.server';
250
+ import { viewerOf } from './viewer.server'; // the app's own query: (send) => Promise<Viewer | null>
251
+
252
+ export const viewer = (request: Request) => clavix.viewer(request, viewerOf);
253
+ ```
254
+
255
+ It returns `null` without a session (`load` does not run), runs `load` once per
256
+ request (a second call with the same `load` gets the same answer; another `load` runs), and, when the session ended,
257
+ throws the request's answer, a redirect to sign-in for a GET, **even when your
258
+ client swallowed the `SessionExpired`** into an error of its own. Any other
259
+ error is rethrown and not kept. Put `withRefreshedCookies` on the response as
260
+ usual.
261
+
262
+ `userOf(request)` gives the signed-in user (`claims`, `accessToken`, …) or
263
+ `null`, read once per request. `hasSession(request)` only looks at the cookie
264
+ header. `clearCookie()` is the `Set-Cookie` that ends a cookie that no longer
265
+ opens.
266
+
267
+ ## Relays for `/media` and `/live`
268
+
269
+ The relay libraries put the session's access token in `Authorization: Bearer`;
270
+ `clavix.relay.fetch` turns that into `Authorization: DPoP` with a proof for the
271
+ public URL, and signs again once on `use_dpop_nonce` when the call has no body
272
+ to replay. A call whose user is not found is answered 401, never forwarded with
273
+ a bare bearer token.
274
+
275
+ ```ts
276
+ // app/routes/media.ts
277
+ import { proxyMediaRead, proxyMediaWrite, type MediaProxyOptions } from '@softistx/alxia-react-router/media';
278
+ import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router';
279
+ import { clavix } from '../clavix.server';
280
+
281
+ const optionsOf = (request: Request): MediaProxyOptions => ({
282
+ api: 'https://api.internal:3000', // the same address as `api.internalUrl`, so the proof's `htu` is rewritten
283
+ kinds: { avatars: { maxBytes: 512 * 1024 } },
284
+ getToken: (incoming) => clavix.relay.tokenOf(incoming),
285
+ // signs each upstream call with DPoP; `request` finds the user
286
+ fetch: clavix.relay.fetch((upstream) => fetch(upstream), request),
287
+ });
288
+
289
+ export const loader = (args: LoaderFunctionArgs) => proxyMediaRead(args, optionsOf(args.request));
290
+ export const action = (args: ActionFunctionArgs) => proxyMediaWrite(args, optionsOf(args.request));
291
+ ```
292
+
293
+ A relay built once for every call (`/live`) is not given the request: take its
294
+ token with `liveTokenOf(request)`, which remembers the request under the
295
+ token's hash, and call `forget(request)` when the relay has answered.
296
+
297
+ ## The user is `(issuer, subject)`
298
+
299
+ `ClavixPrincipal.issuer` and `subject` (on the API, with
300
+ [`@softistx/alxia-clavix`](https://github.com/softistx/alxia/blob/develop/packages/clavix/docs/guide/principal-and-scopes.md))
301
+ are the identity key, and `@softistx/notify` keys its push subscriptions and
302
+ notices on exactly `(principal.issuer, principal.subject)`. On the BFF the same
303
+ pair is `userOf(request)`'s `claims.iss` and `claims.sub`.
304
+
305
+ ## What stays in the app
306
+
307
+ - The sign-in page and its button, with the app's i18n and design system
308
+ (this guide's snippets are the starting point).
309
+ - The viewer's GraphQL query, `(send) => Promise<Viewer | null>`, which needs
310
+ the app's document and client; `clavix.viewer` runs it.
311
+ - Linking an existing account, or any other sign-in method the app keeps
312
+ (pass `otherMethods: true`).
313
+ - Forwarding webhooks and a machine client.
314
+
315
+ ## Limits
316
+
317
+ - `api.internalUrl` rewrites the *client's* calls. The API verifying a proof
318
+ against its public address behind its own proxy is the API's setting
319
+ (the `CLAVIX_API_ORIGIN` variable of `clavixEnv` in `@softistx/alxia-clavix`),
320
+ not this package's.
321
+ - The sign-out action leaves for Clavix's `end_session_endpoint` with the
322
+ session's `id_token_hint`, so Clavix ends its own session without asking. The
323
+ « also sign out of Clavix » link of the signed-out page (`endSessionUrl`) has no
324
+ token left to send: Clavix then shows its confirmation page and ends nothing
325
+ until the visitor confirms.
326
+ - The messages cover English and French; any other language words the
327
+ `notice.kind` itself.
328
+ - The relays hash the token with `Bun.CryptoHasher`, so `/clavix` runs on Bun,
329
+ as the rest of the stack does.
330
+
331
+ See also: [A relying party of an OpenID Connect issuer](oidc.md), and the
332
+ [troubleshooting](../troubleshooting.md).
@@ -1,5 +1,8 @@
1
1
  # A relying party of an external OpenID Connect issuer
2
2
 
3
+ > Signing in with Clavix? [`clavixRoutes`](clavix.md) is this client with PAR, DPoP, the
4
+ > sign-in, callback and sign-out routes and the refusal pages already set.
5
+
3
6
  A BFF that signs its users in with an issuer it does not own (Keycloak,
4
7
  Authentik, Google, Microsoft Entra, an in-house provider) is an OpenID
5
8
  Connect *relying party*. The API's own sessions (`/session`) and a social