@plasgos/oidc-client 0.1.0-next.1 → 0.1.0-next.3

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 (62) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +4 -3
  3. package/README.md +27 -14
  4. package/dist/index.cjs +2 -2
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +2 -2
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/service.cjs +1 -1
  11. package/dist/service.cjs.map +1 -1
  12. package/dist/service.d.cts +3 -3
  13. package/dist/service.d.ts +3 -3
  14. package/dist/service.js +1 -1
  15. package/dist/service.js.map +1 -1
  16. package/dist/session.cjs +71 -20
  17. package/dist/session.cjs.map +1 -1
  18. package/dist/session.d.cts +57 -6
  19. package/dist/session.d.ts +57 -6
  20. package/dist/session.js +63 -13
  21. package/dist/session.js.map +1 -1
  22. package/dist/{types-Cncksfeo.d.cts → types-JE0OMyoi.d.cts} +1 -1
  23. package/dist/{types-Cncksfeo.d.ts → types-JE0OMyoi.d.ts} +1 -1
  24. package/docs/bff-express.md +1314 -0
  25. package/docs/consumers.md +98 -0
  26. package/docs/contoh-hitungcuan.md +255 -0
  27. package/docs/contoh-plaslink.md +244 -0
  28. package/docs/error.md +613 -0
  29. package/docs/examples/auth-verify-readme.ts +42 -0
  30. package/docs/examples/bff-express.ts +370 -0
  31. package/docs/examples/bff-proxy.ts +335 -0
  32. package/docs/examples/bff-redis-lock.ts +187 -0
  33. package/docs/examples/bff-revocation.ts +136 -0
  34. package/docs/examples/config-error.ts +24 -0
  35. package/docs/examples/env.ts +150 -0
  36. package/docs/examples/failure-log.ts +18 -0
  37. package/docs/examples/login-client.ts +46 -0
  38. package/docs/examples/login-flow.ts +186 -0
  39. package/docs/examples/plaslink-connect.ts +48 -0
  40. package/docs/examples/readme.ts +60 -0
  41. package/docs/examples/service-client.ts +105 -0
  42. package/docs/examples/session-store.ts +53 -0
  43. package/docs/examples/token-commonjs.cjs +95 -0
  44. package/docs/examples/token-express.ts +56 -0
  45. package/docs/examples/token-fetch.ts +24 -0
  46. package/docs/examples/token-nestjs-jest.ts +77 -0
  47. package/docs/examples/token-nestjs.ts +127 -0
  48. package/docs/examples/token-socket.ts +59 -0
  49. package/docs/examples/token-testing.ts +100 -0
  50. package/docs/examples/token-verifier.ts +132 -0
  51. package/docs/examples/user-events.ts +110 -0
  52. package/docs/examples/webhook-express.ts +46 -0
  53. package/docs/examples/webhook-fetch.ts +60 -0
  54. package/docs/examples/webhook-nestjs.ts +59 -0
  55. package/docs/examples/webhook-testing.ts +60 -0
  56. package/docs/examples/webhook-verifier.ts +197 -0
  57. package/docs/login-web.md +650 -0
  58. package/docs/memulai.md +419 -0
  59. package/docs/server-ke-server.md +287 -0
  60. package/docs/verifikasi-token.md +1219 -0
  61. package/docs/webhook.md +810 -0
  62. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/service/client.ts","../src/core/config.ts","../src/core/failure.ts","../src/core/token.ts","../src/core/http.ts","../src/service/index.ts"],"sourcesContent":["import {\n ConfigError,\n DEFAULT_AUDIENCES,\n OidcError,\n PRODUCTION_ISSUER,\n environmentProblems,\n parseAudience,\n parseIssuer,\n serviceScopeProblems,\n} from \"@plasgos/auth-shared\";\nimport type { Environment, ServiceScope } from \"@plasgos/auth-shared\";\n\nimport { distinctScopes, globalFetch, isBlank, isObject, parsed, timeoutsOf } from \"../core/config.js\";\nimport { report } from \"../core/failure.js\";\nimport type { OidcFailureEvent } from \"../core/failure.js\";\nimport type { UpstreamCall } from \"../core/http.js\";\nimport { tokenEndpointRequest } from \"../core/token.js\";\nimport type { TokenEndpoint } from \"../core/token.js\";\nimport type { OidcFetch } from \"../core/types.js\";\n\n/**\n * Options of `createServiceClient`. Values usually come from `process.env`; every problem is\n * reported at once in one `ConfigError`, by field name and never by value.\n *\n * @example\n * const options: ServiceClientOptions = {\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * apiUrl: \"https://api.plasgos.co.id\",\n * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? \"\",\n * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? \"\",\n * scopes: [\"platform:self.read\", \"payments:read\", \"payments:write\"],\n * };\n */\nexport interface ServiceClientOptions {\n /** `\"sandbox\"` or `\"production\"`; checked against `issuer`, `resource`, `backchannelUrl` and `apiUrl`. */\n environment: Environment;\n /** Bare origin of the provider. */\n issuer: string;\n /** Origin `/oidc/token` is called on; `http:` allowed (internal network). Default: `issuer`. */\n backchannelUrl?: string | undefined;\n /** Bare origin `client.fetch` calls: the API host, or the internal api-main origin; `http:` allowed. */\n apiUrl: string;\n /** Client id of the app's service client. */\n clientId: string;\n /** Sent only as `client_secret_basic`, to the token endpoint. */\n clientSecret: string;\n /** Service scopes, at least one; a user scope is refused. */\n scopes: readonly ServiceScope[];\n /** Audience of the token. Default: `DEFAULT_AUDIENCES.platform`. */\n resource?: string | undefined;\n /** Sandbox only: `http:` for the issuer. */\n allowInsecureHttp?: boolean | undefined;\n /** Milliseconds, 1 to 60 000 each. Defaults: `tokenMs` 10 000 (token call), `requestMs` 10 000 (each `fetch` attempt). */\n timeouts?: { tokenMs?: number | undefined; requestMs?: number | undefined } | undefined;\n /** Default: the global `fetch`. */\n fetch?: OidcFetch | undefined;\n /** Receives one event per failure (`service_token`, `service_request`); safe to log. */\n onFailure?: ((event: OidcFailureEvent) => void) | undefined;\n}\n\n/**\n * What `createServiceClient` returns.\n *\n * @example\n * const res = await plasgos.fetch(\"/v5/service/payments\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(payment),\n * });\n * if (!res.ok) throw new Error(`payments answered ${String(res.status)}`);\n */\nexport interface ServiceClient {\n /** The `environment` the client was created with. */\n readonly environment: Environment;\n /** The client id the client was created with. */\n readonly clientId: string;\n /** A cached access token; a new one is requested 60 s before expiry. */\n getToken(): Promise<string>;\n /** `fetch(apiUrl + path)` with `Authorization: Bearer`; one retry on 401 invalid_token; `redirect: \"manual\"` unless the caller sets `redirect`. */\n fetch(path: string, init?: RequestInit): Promise<Response>;\n}\n\n/** The validated options of a service client, with every default filled in. Frozen. */\nexport interface ResolvedServiceConfig {\n readonly environment: Environment;\n /** Canonical origin of the provider. */\n readonly issuer: string;\n /** Canonical origin for the token call, or null to use `issuer`. */\n readonly backchannelUrl: string | null;\n /** Canonical origin `client.fetch` calls. */\n readonly apiUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n readonly scopes: readonly string[];\n readonly resource: string;\n readonly timeouts: Readonly<{ tokenMs: number; requestMs: number }>;\n readonly fetch: OidcFetch;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n}\n\nconst DEFAULT_TOKEN_MS = 10_000;\nconst DEFAULT_REQUEST_MS = 10_000;\n/** A token is replaced this long before it expires, or at half its life when that is shorter. */\nconst EXPIRY_MARGIN_SECONDS = 60;\n/** One leading \"/\", not followed by a second \"/\" or a \"\\\" (which a URL parser reads as one). */\nconst SINGLE_SLASH_PATH = /^\\/(?![/\\\\])/;\nconst PATH_PROBLEM = \"serviceClient.fetch: path must start with a single /\";\n\nconst ignore = (): void => undefined;\n\n/** RFC 6750 `WWW-Authenticate: Bearer error=\"invalid_token\"` on a 401, as api-main's service token guard answers. */\nconst isInvalidToken = (res: Response): boolean => {\n if (res.status !== 401) return false;\n const challenge = res.headers.get(\"www-authenticate\") ?? \"\";\n return /^\\s*Bearer\\b/i.test(challenge) && /\\berror\\s*=\\s*\"?invalid_token\"?/i.test(challenge);\n};\n\n/**\n * Checks the untyped options of `createServiceClient` (plan decisions 2, 3 and 17); one\n * ConfigError lists every problem, by field name only.\n */\nexport function resolveServiceConfig(raw: unknown): ResolvedServiceConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n const given = (field: string): boolean => raw[field] !== undefined;\n /** For an optional string option: a blank string counts as not given. */\n const present = (field: string): boolean => given(field) && !isBlank(raw[field]);\n const required = (field: string): string | undefined => {\n const value = text(field);\n const blank = isBlank(value);\n if (blank || !given(field)) problems.push(`${field} is required`);\n return blank ? undefined : value;\n };\n /** A bare origin; a non-string already has its problem and is never handed to the parser. */\n const origin = (field: string, allowInsecureHttp: boolean, optional: boolean): string | undefined => {\n if (optional && !present(field)) return undefined;\n const value = text(field);\n if (value === undefined && given(field)) return undefined;\n return parsed(problems, () => parseIssuer(value, { field, allowInsecureHttp }));\n };\n\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuer = origin(\"issuer\", allowInsecureHttp, false);\n // Both may be internal network addresses, so `http:` is accepted in either environment.\n const backchannelUrl = origin(\"backchannelUrl\", true, true);\n const apiUrl = origin(\"apiUrl\", true, false);\n\n const clientId = required(\"clientId\");\n const clientSecret = required(\"clientSecret\");\n\n const scopesRaw = raw[\"scopes\"];\n problems.push(...serviceScopeProblems(scopesRaw));\n\n const resourceRaw = present(\"resource\") ? text(\"resource\") : undefined;\n const resource = present(\"resource\")\n ? resourceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(resourceRaw, { field: \"resource\", allowInsecureHttp }))\n : DEFAULT_AUDIENCES.platform;\n\n if (raw[\"allowInsecureHttp\"] !== undefined && typeof raw[\"allowInsecureHttp\"] !== \"boolean\") {\n problems.push(\"allowInsecureHttp must be a boolean\");\n }\n\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"], { tokenMs: DEFAULT_TOKEN_MS, requestMs: DEFAULT_REQUEST_MS });\n\n const { fetch, onFailure } = raw;\n if (fetch !== undefined && typeof fetch !== \"function\") problems.push(\"fetch must be a function\");\n if (onFailure !== undefined && typeof onFailure !== \"function\") problems.push(\"onFailure must be a function\");\n\n // An issuer that did not parse already has its problem, so the guard gets a value it has nothing\n // to say about and still judges the other fields.\n const environment = raw[\"environment\"];\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(resource !== undefined ? { audiences: [resource] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n });\n\n if (guard.length > 0 || problems.length > 0) throw new ConfigError([...guard, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n backchannelUrl: backchannelUrl ?? null,\n apiUrl: apiUrl as string,\n clientId: clientId as string,\n clientSecret: clientSecret as string,\n scopes: distinctScopes(scopesRaw),\n resource: resource as string,\n timeouts: Object.freeze(timeouts),\n fetch: (fetch as OidcFetch | undefined) ?? globalFetch,\n onFailure: onFailure as ResolvedServiceConfig[\"onFailure\"],\n });\n}\n\n/**\n * A server-to-server client: `client_credentials` tokens of a service client, cached, and a\n * `fetch` that carries the token to the Plasgos API.\n *\n * @example\n * const plasgos = createServiceClient({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * apiUrl: \"https://api.plasgos.co.id\",\n * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? \"\",\n * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? \"\",\n * scopes: [\"platform:self.read\"],\n * });\n * const res = await plasgos.fetch(\"/v5/service/me\");\n */\nexport function createServiceClient(options: ServiceClientOptions): ServiceClient {\n const config = resolveServiceConfig(options);\n const endpoint: TokenEndpoint = {\n environment: config.environment,\n origin: config.backchannelUrl ?? config.issuer,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n resource: config.resource,\n timeoutMs: config.timeouts.tokenMs,\n fetch: config.fetch,\n onFailure: config.onFailure,\n refreshTokenRequired: false,\n };\n const scope = config.scopes.join(\" \");\n\n // The cache and the request in flight belong to this client; the module keeps no state.\n let cached: { token: string; freshUntil: number } | null = null;\n let pending: Promise<string> | null = null;\n\n const mint = async (): Promise<string> => {\n // Counted from before the request, so the cached token is never thought younger than it is.\n const obtainedAt = Date.now();\n const tokens = await tokenEndpointRequest(endpoint, \"service_token\", { grant_type: \"client_credentials\", scope });\n const margin = Math.min(EXPIRY_MARGIN_SECONDS, Math.floor(tokens.expires_in / 2));\n cached = { token: tokens.access_token, freshUntil: obtainedAt + (tokens.expires_in - margin) * 1000 };\n return tokens.access_token;\n };\n\n const getToken = (): Promise<string> => {\n if (cached !== null && Date.now() < cached.freshUntil) return Promise.resolve(cached.token);\n // Single flight: callers that arrive while a request runs share it; a failure is not kept.\n pending ??= mint().finally(() => {\n pending = null;\n });\n return pending;\n };\n\n /** One attempt, bounded by `requestMs`. A failure is reported and thrown as `unavailable`. */\n const attempt = async (url: string, init: RequestInit, token: string, call: UpstreamCall): Promise<Response> => {\n const controller = new AbortController();\n // Not cleared when the headers arrive: it bounds the caller's read of the body too.\n const timer = setTimeout(() => {\n controller.abort();\n }, config.timeouts.requestMs);\n timer.unref();\n const callerSignal = init.signal ?? null;\n try {\n // Inside the try: `Headers` throws a TypeError that quotes the name or the value it refuses,\n // which may be the caller's secret header (the token itself is header-safe by the parser).\n const headers = new Headers(init.headers);\n headers.set(\"Authorization\", `Bearer ${token}`);\n return await config.fetch(url, {\n ...init,\n headers,\n // The bearer token would follow a redirect to another host (plan decision 11).\n redirect: init.redirect ?? \"manual\",\n signal: callerSignal === null ? controller.signal : AbortSignal.any([callerSignal, controller.signal]),\n });\n } catch {\n // Deliberately untyped: whatever `Headers` or `fetch` threw is dropped, because its message,\n // `input` and `cause` may hold a header or the URL with its query.\n clearTimeout(timer);\n // The caller's own abort is the caller's to handle, with the reason it gave.\n callerSignal?.throwIfAborted();\n report(config.onFailure, {\n environment: config.environment,\n operation: \"service_request\",\n reason: \"unavailable\",\n method: call.method,\n path: call.path,\n status: null,\n requestId: null,\n providerError: null,\n });\n throw new OidcError(\"unavailable\", { method: call.method, path: call.path, status: null, requestId: null });\n }\n };\n\n const fetch = async (path: string, init: RequestInit = {}): Promise<Response> => {\n if (typeof path !== \"string\" || !SINGLE_SLASH_PATH.test(path)) throw new TypeError(PATH_PROBLEM);\n // `init` comes from untyped JavaScript as well.\n const given: unknown = init;\n if (!isObject(given)) throw new TypeError(\"serviceClient.fetch: init must be an object\");\n const url = `${config.apiUrl}${path}`;\n // Checked here, so that neither `new URL` nor `fetch` gets to throw an error that carries the path.\n if (!URL.canParse(url) || new URL(url).origin !== config.apiUrl) throw new TypeError(PATH_PROBLEM);\n init.signal?.throwIfAborted();\n const call: UpstreamCall = {\n method: typeof init.method === \"string\" ? init.method.toUpperCase() : \"GET\",\n path: path.split(/[?#]/, 1)[0] ?? \"\",\n };\n\n const token = await getToken();\n const res = await attempt(url, init, token, call);\n if (!isInvalidToken(res)) return res;\n // api-main refused the token (expired early, key rotated, client state changed): it is dropped,\n // unless another request already replaced it.\n if (cached?.token === token) cached = null;\n // A stream was consumed by the first attempt and cannot be sent again.\n if (init.body instanceof ReadableStream) return res;\n // The refused answer is replaced by the retry's; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n return attempt(url, init, await getToken(), call);\n };\n\n return Object.freeze({ environment: config.environment, clientId: config.clientId, getToken, fetch });\n}\n","import {\n ConfigError,\n PRODUCTION_ISSUER,\n environmentProblems,\n parseAudience,\n parseIssuer,\n userScopeProblems,\n} from \"@plasgos/auth-shared\";\nimport type { ClientProfile, Environment } from \"@plasgos/auth-shared\";\n\nimport type { OidcFailureEvent } from \"./failure.js\";\nimport { memoryLockStore } from \"./refresh-lock.js\";\nimport type { RefreshLockStore } from \"./refresh-lock.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * Validation of the `createOidcClient` options (plan decision 3). Options come from untyped\n * JavaScript and from env parsing, so nothing is trusted to have its declared type. Every problem\n * is collected and thrown as one ConfigError; a problem names the field, never its value.\n */\n\n/** The validated options of a client, with every default filled in. Frozen. */\nexport interface ResolvedConfig {\n readonly environment: Environment;\n /** Canonical origin: browser URLs and the exact `iss` value. */\n readonly issuer: string;\n /** Canonical origin for the back-channel calls, or null to use `issuer`. */\n readonly backchannelUrl: string | null;\n readonly clientId: string;\n readonly clientSecret: string;\n readonly redirectUri: string;\n readonly postLogoutRedirectUri: string | null;\n readonly scopes: readonly string[];\n readonly profile: ClientProfile;\n readonly resource: string | null;\n readonly logoutTicket: boolean;\n readonly endSession: \"redirect\" | \"form-post\";\n readonly extraClaims: readonly string[];\n readonly timeouts: Readonly<{ tokenMs: number; logoutMs: number }>;\n readonly fetch: OidcFetch;\n readonly refreshLock: RefreshLockStore;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n}\n\nconst DEFAULT_TOKEN_MS = 10_000;\nconst DEFAULT_LOGOUT_MS = 3_000;\nconst MAX_TIMEOUT_MS = 60_000;\nconst CLAIM_NAME = /^[A-Za-z0-9_:.-]{1,64}$/;\n/** Claims the SDK checks or already returns, and the names that would reach the prototype. */\nconst RESERVED_CLAIMS: ReadonlySet<string> = new Set([\n \"iss\",\n \"sub\",\n \"aud\",\n \"azp\",\n \"exp\",\n \"iat\",\n \"nbf\",\n \"jti\",\n \"nonce\",\n \"auth_time\",\n \"at_hash\",\n \"c_hash\",\n \"s_hash\",\n \"name\",\n \"picture\",\n \"email\",\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/** True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\". */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * The scope list that is sent: each scope once, in the order given. Called after the shared scope\n * check found no problem, so every entry is a valid scope token.\n */\nexport const distinctScopes = (scopes: unknown): readonly string[] =>\n Object.freeze([...new Set(Array.isArray(scopes) ? scopes.filter((scope) => typeof scope === \"string\") : [])]);\n\n/** Resolved at call time, so a `globalThis.fetch` replaced later (a test spy, an instrumentation) is used. */\nexport const globalFetch: OidcFetch = (input, init) => globalThis.fetch(input, init);\n\n/** Runs a single-problem parser of auth-shared; its problem is collected, not thrown. */\nexport function parsed(problems: string[], parse: () => string): string | undefined {\n try {\n return parse();\n } catch (error) {\n if (!(error instanceof ConfigError)) throw error;\n problems.push(...error.problems);\n return undefined;\n }\n}\n\n/**\n * The `timeouts` option with its defaults filled in: each named budget is an integer from 1 to\n * 60 000 ms (plan decision 12). A problem is collected and the default kept.\n */\nexport function timeoutsOf<Name extends string>(\n problems: string[],\n raw: unknown,\n defaults: Readonly<Record<Name, number>>,\n): Record<Name, number> {\n const given = raw ?? {};\n if (!isObject(given)) problems.push(\"timeouts must be an object\");\n const resolved: Record<Name, number> = { ...defaults };\n for (const name of Object.keys(defaults) as Name[]) {\n const value = isObject(given) ? given[name] : undefined;\n if (value === undefined) continue;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS) {\n resolved[name] = value;\n } else {\n problems.push(`timeouts.${name} must be an integer from 1 to ${String(MAX_TIMEOUT_MS)}`);\n }\n }\n return resolved;\n}\n\n/**\n * Validates `redirectUri` or `postLogoutRedirectUri` by the rule api-main applies when the URI is\n * registered (API:src/modules/auth/oauth-clients/client-registration-rules.ts:59-85): an absolute\n * http(s) URL that may carry a query; a wildcard, a fragment (an empty \"#\" too) and credentials are\n * refused, and `http:` needs `allowInsecureHttp`. The provider compares the value exactly with the\n * registered one, so it is returned as written (trimmed), and what the URL parser would silently\n * strip or rewrite is refused. The problem names the field, never the value.\n */\nfunction redirectUriProblem(value: string, field: string, allowInsecureHttp: boolean): string | undefined {\n if (value === \"\") return `${field} is required`;\n if (value.includes(\"*\")) return `${field} must not contain a wildcard`;\n if (!URL.canParse(value)) return `${field} must be an absolute URL`;\n // eslint-disable-next-line no-control-regex -- control characters are what this check looks for\n if (/[\\u0000- \\u007f\\\\]/.test(value)) {\n return `${field} must not contain whitespace, control characters or a backslash`;\n }\n const url = new URL(value);\n // The raw value is checked too: the URL parser drops an empty \"#\" and an empty userinfo.\n if (url.hash || value.includes(\"#\")) return `${field} must not contain a fragment`;\n const authority = /^[a-z][a-z0-9+.-]*:\\/\\/([^/?]*)/i.exec(value)?.[1] ?? \"\";\n if (url.username || url.password || authority.includes(\"@\")) return `${field} must not contain credentials`;\n if (url.protocol !== \"https:\" && !(allowInsecureHttp && url.protocol === \"http:\")) return `${field} must use https`;\n if (!/^https?:\\/\\//i.test(value)) return `${field} must be an absolute URL`;\n return undefined;\n}\n\n/** The trimmed redirect or post-logout URI, or undefined after its problem was collected. */\nfunction redirectUriOf(\n problems: string[],\n raw: string | undefined,\n field: string,\n allowInsecureHttp: boolean,\n): string | undefined {\n const value = raw?.trim() ?? \"\";\n const problem = redirectUriProblem(value, field, allowInsecureHttp);\n if (problem === undefined) return value;\n problems.push(problem);\n return undefined;\n}\n\n/** Checks the untyped options; one ConfigError lists every problem, by field name only. */\nexport function resolveConfig(raw: unknown): ResolvedConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n /** True when the option was given, usable or not. */\n const given = (field: string): boolean => raw[field] !== undefined;\n /** For an optional string option: a blank string counts as not given. */\n const present = (field: string): boolean => given(field) && !isBlank(raw[field]);\n const optional = (field: string): string | undefined => (present(field) ? text(field) : undefined);\n const required = (field: string): string | undefined => {\n const value = text(field);\n const blank = isBlank(value);\n if (blank || !given(field)) problems.push(`${field} is required`);\n return blank ? undefined : value;\n };\n\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuerRaw = text(\"issuer\");\n const issuer =\n given(\"issuer\") && issuerRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(issuerRaw, { field: \"issuer\", allowInsecureHttp }));\n\n const backchannelRaw = optional(\"backchannelUrl\");\n const backchannelUrl =\n backchannelRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(backchannelRaw, { field: \"backchannelUrl\", allowInsecureHttp: true }));\n\n const clientId = required(\"clientId\");\n const clientSecret = required(\"clientSecret\");\n\n const redirectRaw = text(\"redirectUri\");\n const redirectUri =\n given(\"redirectUri\") && redirectRaw === undefined\n ? undefined\n : redirectUriOf(problems, redirectRaw, \"redirectUri\", allowInsecureHttp);\n\n const postLogoutRaw = optional(\"postLogoutRedirectUri\");\n const postLogoutRedirectUri =\n postLogoutRaw === undefined\n ? undefined\n : redirectUriOf(problems, postLogoutRaw, \"postLogoutRedirectUri\", allowInsecureHttp);\n\n const profileRaw = text(\"profile\");\n const profile = profileRaw === \"first-party\" || profileRaw === \"third-party\" ? profileRaw : undefined;\n\n // With an unusable profile the scopes are judged as first-party, so only the profile is reported;\n // a resource that was given but is malformed still counts as given.\n const scopesRaw = raw[\"scopes\"];\n problems.push(...userScopeProblems(scopesRaw, { profile: profile ?? \"first-party\", resource: present(\"resource\") }));\n if (profile === undefined && !(given(\"profile\") && profileRaw === undefined)) {\n problems.push('profile must be \"first-party\" or \"third-party\"');\n }\n\n const resourceRaw = optional(\"resource\");\n const resource =\n resourceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(resourceRaw, { field: \"resource\", allowInsecureHttp }));\n if (present(\"resource\") && profile === \"third-party\") {\n problems.push('resource is not allowed for profile \"third-party\"');\n }\n\n const endSessionRaw = text(\"endSession\");\n const endSession = endSessionRaw ?? (given(\"endSession\") ? undefined : \"redirect\");\n const endSessionKnown = endSession === \"redirect\" || endSession === \"form-post\";\n\n const logoutTicketRaw = raw[\"logoutTicket\"];\n if (logoutTicketRaw !== undefined && typeof logoutTicketRaw !== \"boolean\") {\n problems.push(\"logoutTicket must be a boolean\");\n } else if (logoutTicketRaw === true) {\n if (profile === \"third-party\") {\n problems.push('logoutTicket is not allowed for profile \"third-party\"');\n } else if (endSession === \"form-post\") {\n problems.push('logoutTicket is not used with endSession \"form-post\"');\n } else if (!present(\"backchannelUrl\")) {\n problems.push(\"logoutTicket requires backchannelUrl (the internal api-main URL)\");\n }\n }\n // The ticket endpoint is internal-only (plan decision 14), so the default needs a backchannelUrl.\n const logoutTicket =\n logoutTicketRaw === true ||\n (logoutTicketRaw === undefined &&\n profile === \"first-party\" &&\n endSession === \"redirect\" &&\n backchannelUrl !== undefined);\n\n if (endSession !== undefined && !endSessionKnown) {\n problems.push('endSession must be \"redirect\" or \"form-post\"');\n } else if (\n // Sandbox is left alone: local development runs the app and the issuer on two ports. The\n // provider still answers a cross-origin form POST with 403 (plan decision 14).\n raw[\"environment\"] === \"production\" &&\n endSession === \"form-post\" &&\n issuer !== undefined &&\n redirectUri !== undefined &&\n new URL(redirectUri).origin !== issuer\n ) {\n problems.push('endSession \"form-post\" requires redirectUri on the issuer origin');\n }\n\n // Absent only when undefined: null is refused like any other value that is not a list.\n const extraClaimsRaw: unknown = raw[\"extraClaims\"] === undefined ? [] : raw[\"extraClaims\"];\n const extraClaims =\n Array.isArray(extraClaimsRaw) &&\n extraClaimsRaw.every(\n (name): name is string => typeof name === \"string\" && CLAIM_NAME.test(name) && !RESERVED_CLAIMS.has(name),\n )\n ? [...new Set(extraClaimsRaw)]\n : undefined;\n if (extraClaims === undefined) problems.push(\"extraClaims contains an invalid claim name\");\n\n if (raw[\"allowInsecureHttp\"] !== undefined && typeof raw[\"allowInsecureHttp\"] !== \"boolean\") {\n problems.push(\"allowInsecureHttp must be a boolean\");\n }\n\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"], { tokenMs: DEFAULT_TOKEN_MS, logoutMs: DEFAULT_LOGOUT_MS });\n\n const { fetch, refreshLock, onFailure } = raw;\n if (fetch !== undefined && typeof fetch !== \"function\") problems.push(\"fetch must be a function\");\n if (refreshLock !== undefined && !(isObject(refreshLock) && typeof refreshLock[\"run\"] === \"function\")) {\n problems.push(\"refreshLock must have a run function\");\n }\n if (onFailure !== undefined && typeof onFailure !== \"function\") problems.push(\"onFailure must be a function\");\n\n // The guard compares parsed values. An issuer that did not parse already has its problem, so the\n // guard gets a value it has nothing to say about and still judges the other fields.\n const environment = raw[\"environment\"];\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(resource !== undefined ? { audiences: [resource] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n });\n\n if (guard.length > 0 || problems.length > 0) throw new ConfigError([...guard, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n backchannelUrl: backchannelUrl ?? null,\n clientId: clientId as string,\n clientSecret: clientSecret as string,\n redirectUri: redirectUri as string,\n postLogoutRedirectUri: postLogoutRedirectUri ?? null,\n scopes: distinctScopes(scopesRaw),\n profile: profile as ClientProfile,\n resource: resource ?? null,\n logoutTicket,\n endSession: endSession as \"redirect\" | \"form-post\",\n extraClaims: Object.freeze(extraClaims as string[]),\n timeouts: Object.freeze(timeouts),\n fetch: (fetch as OidcFetch | undefined) ?? globalFetch,\n refreshLock: (refreshLock as RefreshLockStore | undefined) ?? memoryLockStore(),\n onFailure: onFailure as ResolvedConfig[\"onFailure\"],\n });\n}\n","import type { Environment, OidcErrorReason } from \"@plasgos/auth-shared\";\n\n/*\n * The failure event of the SDK (plan decision 10). The SDK never logs: every failure, thrown or\n * swallowed, is handed to the app's `onFailure` hook as one event that is safe to write to a log.\n * Ported from the failure lines of plasgos-shipping-v2 (`failure-log.server.ts`): the path loses\n * its query string, and a field that is not a plain identifier becomes null, because the request\n * id and the error code come from the provider's answer and are not trusted.\n */\n\n/**\n * The step of the SDK that failed.\n *\n * @example\n * if (event.operation === \"refresh\" && event.reason === \"config_invalid\") alertOps(event);\n */\nexport type OidcOperation =\n | \"callback\"\n | \"token\"\n | \"refresh\"\n | \"revocation\"\n | \"logout_ticket\"\n | \"service_token\"\n | \"service_request\";\n\n/**\n * One failure, as the `onFailure` hook receives it. It never holds a token, code, secret, body or\n * query string.\n *\n * @example\n * const onFailure = (event: OidcFailureEvent) => {\n * logger.error(`login failed: ${event.operation} ${event.reason} request_id=${event.requestId ?? \"-\"}`);\n * };\n */\nexport interface OidcFailureEvent {\n /** The `environment` of the client that failed. */\n environment: Environment;\n /** The step that failed. */\n operation: OidcOperation;\n /** The same reason an `OidcError` of this failure carries. */\n reason: OidcErrorReason;\n /** HTTP method of the call that failed, or null. */\n method: string | null;\n /** Path of the call that failed, without query string or fragment, or null. */\n path: string | null;\n /** HTTP status of the provider's answer; null when there was none. */\n status: number | null;\n /** `x-request-id` of the provider's answer, or null. */\n requestId: string | null;\n /** The `error` code the provider answered with, or null. */\n providerError: string | null;\n}\n\nconst PLAIN = /^[\\w.:-]{1,128}$/;\nconst PLAIN_PATH = /^\\/[\\w./~-]{0,255}$/;\n\n/** `value` when it is a plain identifier (word characters, \".\", \":\" and \"-\", at most 128), else null. */\nexport const plain = (value: string | null): string | null => (value !== null && PLAIN.test(value) ? value : null);\n\nconst pathOnly = (path: string | null): string | null => {\n if (path === null) return null;\n const bare = path.split(/[?#]/, 1)[0] ?? \"\";\n return PLAIN_PATH.test(bare) ? bare : null;\n};\n\n/** A copy of `event` in which every field that is not a plain identifier or a plain path is null. */\nexport function sanitizeEvent(event: OidcFailureEvent): OidcFailureEvent {\n return {\n environment: event.environment,\n operation: event.operation,\n reason: event.reason,\n method: plain(event.method),\n path: pathOnly(event.path),\n status: Number.isInteger(event.status) ? event.status : null,\n requestId: plain(event.requestId),\n providerError: plain(event.providerError),\n };\n}\n\nconst ignore = (): void => undefined;\n\n/**\n * Hands the sanitised event to the app's hook. A hook that throws, or whose promise rejects, never\n * changes what the SDK does next.\n */\nexport function report(hook: ((event: OidcFailureEvent) => void) | undefined, event: OidcFailureEvent): void {\n if (hook === undefined) return;\n try {\n // The hook is typed to return nothing, but an async function is assignable to it.\n const run: (event: OidcFailureEvent) => unknown = hook;\n const result = run(sanitizeEvent(event));\n if (result instanceof Promise) result.catch(ignore);\n } catch {\n // The hook is the app's code; its failure must not turn into a second failure here.\n }\n}\n","import { OIDC_PATHS, OidcError, basicAuthHeader } from \"@plasgos/auth-shared\";\nimport type { Environment, OidcErrorReason, TokenSet } from \"@plasgos/auth-shared\";\n\nimport type { ResolvedConfig } from \"./config.js\";\nimport { report } from \"./failure.js\";\nimport type { OidcFailureEvent } from \"./failure.js\";\nimport { failOnStatus, requestJson } from \"./http.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * The token endpoint: one form POST with `client_secret_basic`, and the checks on its answer.\n * Ported from plasgos-shipping-v2 (`oidc.server.ts` tokenRequest, `oidc-response.server.ts`\n * tokenSetSchema). The secret travels in the Authorization header only; no code, verifier, token\n * or response body reaches an error or an event.\n */\n\n/** The step a token request belongs to, as the failure event names it. */\nexport type TokenOperation = \"token\" | \"refresh\" | \"service_token\";\n\nconst TOKEN_CALL = { method: \"POST\", path: OIDC_PATHS.token } as const;\n\n/** `error` codes that say the client's own configuration is wrong (plan decision 5). */\nconst CONFIG_ERRORS: ReadonlySet<string> = new Set([\n \"invalid_client\",\n \"unauthorized_client\",\n \"invalid_scope\",\n \"unsupported_grant_type\",\n]);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst own = (record: Record<string, unknown>, key: string): unknown =>\n Object.hasOwn(record, key) ? record[key] : undefined;\n\n/**\n * Visible ASCII only. A token travels in a header (`Authorization: Bearer`), and `Headers` refuses\n * a value with a line break or a character outside Latin-1 by throwing a TypeError that quotes it.\n * Every token api-main issues is base64url or a JWT, so nothing real is refused.\n */\nconst HEADER_SAFE = /^[\\x21-\\x7e]+$/;\n\nconst isToken = (value: unknown): value is string => typeof value === \"string\" && HEADER_SAFE.test(value);\n\n/** The token set of a 200 answer, or null when the answer is not one. Unknown fields are dropped. */\nfunction tokenSetOf(body: unknown, refreshTokenRequired: boolean): TokenSet | null {\n if (!isRecord(body)) return null;\n const accessToken = own(body, \"access_token\");\n const refreshToken = own(body, \"refresh_token\");\n const idToken = own(body, \"id_token\");\n const expiresIn = own(body, \"expires_in\");\n const tokenType = own(body, \"token_type\");\n const scope = own(body, \"scope\");\n if (!isToken(accessToken)) return null;\n if (refreshToken === undefined && refreshTokenRequired) return null;\n if (refreshToken !== undefined && !isToken(refreshToken)) return null;\n if (idToken !== undefined && !isToken(idToken)) return null;\n if (typeof expiresIn !== \"number\" || !Number.isSafeInteger(expiresIn) || expiresIn <= 0) return null;\n // Only bearer tokens are usable by the apps; a DPoP-bound token would be sent without its proof.\n if (typeof tokenType !== \"string\" || tokenType.toLowerCase() !== \"bearer\") return null;\n if (scope !== undefined && typeof scope !== \"string\") return null;\n return {\n access_token: accessToken,\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...(idToken !== undefined ? { id_token: idToken } : {}),\n expires_in: expiresIn,\n token_type: \"Bearer\",\n ...(scope !== undefined ? { scope } : {}),\n };\n}\n\nconst reasonOf = (code: string | null): OidcErrorReason => {\n if (code === \"invalid_grant\" || code === \"invalid_target\") return code;\n return code !== null && CONFIG_ERRORS.has(code) ? \"config_invalid\" : \"provider_error\";\n};\n\n/** Where and as whom a token request is made, and how its answer and its failures are judged. */\nexport interface TokenEndpoint {\n readonly environment: Environment;\n /** Origin the token endpoint is called on: `backchannelUrl ?? issuer`. */\n readonly origin: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Sent as the last form field, or left out when null. */\n readonly resource: string | null;\n readonly timeoutMs: number;\n readonly fetch: OidcFetch;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n /** A 200 answer without a refresh token is `provider_error`. */\n readonly refreshTokenRequired: boolean;\n}\n\n/**\n * One request to `${origin}/oidc/token`. `params` are sent in the order given, followed by\n * `resource` when there is one. Every failure is reported once through `onFailure` under\n * `operation` and thrown as an `OidcError` with the upstream.\n *\n * @example\n * const tokens = await tokenEndpointRequest(endpoint, \"service_token\", { grant_type: \"client_credentials\", scope });\n */\nexport async function tokenEndpointRequest(\n endpoint: TokenEndpoint,\n operation: TokenOperation,\n params: Readonly<Record<string, string>>,\n): Promise<TokenSet> {\n // The `error` code of a refusal, kept for the event; the sanitiser drops anything but a plain code.\n let providerError: string | null = null;\n try {\n const form = new URLSearchParams({ ...params, ...(endpoint.resource !== null ? { resource: endpoint.resource } : {}) });\n const { res, body, at } = await requestJson(\n `${endpoint.origin}${TOKEN_CALL.path}`,\n {\n method: TOKEN_CALL.method,\n headers: {\n Authorization: basicAuthHeader(endpoint.clientId, endpoint.clientSecret),\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: form.toString(),\n },\n { timeoutMs: endpoint.timeoutMs, fetch: endpoint.fetch, call: TOKEN_CALL },\n );\n if (!res.ok && isRecord(body)) {\n const code = own(body, \"error\");\n if (typeof code === \"string\") providerError = code;\n }\n failOnStatus(res, body, at);\n if (!res.ok) throw new OidcError(reasonOf(providerError), at);\n const tokens = tokenSetOf(body, endpoint.refreshTokenRequired);\n if (tokens === null) throw new OidcError(\"provider_error\", at);\n return tokens;\n } catch (error) {\n // `send` turns every rejection of `fetch` into an OidcError, so anything else is a bug to surface.\n if (error instanceof OidcError) {\n report(endpoint.onFailure, {\n environment: endpoint.environment,\n operation,\n reason: error.reason,\n method: TOKEN_CALL.method,\n path: TOKEN_CALL.path,\n status: error.upstream?.status ?? null,\n requestId: error.upstream?.requestId ?? null,\n providerError,\n });\n }\n throw error;\n }\n}\n\n/**\n * One token request of a login client, to `${backchannelUrl ?? issuer}/oidc/token`; see\n * {@link tokenEndpointRequest}. A first-party client must be given a refresh token.\n *\n * @example\n * const tokens = await tokenRequest(config, \"refresh\", { grant_type: \"refresh_token\", refresh_token });\n */\nexport function tokenRequest(\n config: ResolvedConfig,\n operation: \"token\" | \"refresh\",\n params: Readonly<Record<string, string>>,\n): Promise<TokenSet> {\n return tokenEndpointRequest(\n {\n environment: config.environment,\n origin: config.backchannelUrl ?? config.issuer,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n resource: config.resource,\n timeoutMs: config.timeouts.tokenMs,\n fetch: config.fetch,\n onFailure: config.onFailure,\n refreshTokenRequired: config.profile === \"first-party\",\n },\n operation,\n params,\n );\n}\n","import { OidcError } from \"@plasgos/auth-shared\";\nimport type { OidcUpstream } from \"@plasgos/auth-shared\";\n\nimport { plain } from \"./failure.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * The transport of every back-channel call (token, revocation, logout ticket): one timed `fetch`\n * that never follows a redirect, and a body read under a size cap. Ported from plasgos-shipping-v2\n * (`oidc.server.ts` send, `capped-body.server.ts`, `oidc-response.server.ts`). Nothing here puts a\n * URL, a header or a body into an error: an `OidcError` carries the reason, the method, the path,\n * the status and the provider's request id only.\n */\n\n/** Largest accepted provider response body (plan decision 13). */\nexport const MAX_RESPONSE_BYTES = 16_384;\n\n/** The method and path a failure is reported under. */\nexport interface UpstreamCall {\n readonly method: string;\n readonly path: string;\n}\n\n/** How one call is made: its time budget, the `fetch` to use, and what to name it in a failure. */\nexport interface SendOptions {\n readonly timeoutMs: number;\n readonly fetch: OidcFetch;\n readonly call: UpstreamCall;\n}\n\n/** An answer whose body is still unread. `done` stops the timer; `timedOut` tells whether it fired. */\nexport interface Sent {\n res: Response;\n done: () => void;\n timedOut: () => boolean;\n}\n\n/** The body's bytes, or why there are none: over the cap (declared or streamed) or a failed read. */\nexport type CappedBody = { kind: \"bytes\"; bytes: Buffer } | { kind: \"too_large\" } | { kind: \"unreadable\" };\n\n/** What {@link requestJson} answers. */\nexport interface JsonAnswer {\n res: Response;\n /** Parsed JSON, `null` for a body that is not JSON, `undefined` for one over the cap. */\n body: unknown;\n at: OidcUpstream;\n}\n\nconst ignore = (): void => undefined;\n\nconst isRedirect = (res: Response): boolean =>\n res.type === \"opaqueredirect\" || (res.status >= 300 && res.status < 400);\n\n/**\n * One call, aborted after `timeoutMs`. The timer keeps running while the caller reads the body, so\n * the caller calls `done` once it has finished. A redirect is never followed (the Basic credentials\n * and the form body must not be replayed to another host): a 3xx answer is `provider_error`.\n * Whatever `fetch` rejects with (a network error, the timeout, a non-Error) is `unavailable`.\n *\n * @example\n * const { res, done } = await send(url, { method: \"POST\", body }, { timeoutMs: 10_000, fetch, call });\n * const body = await readJson(res).finally(done);\n */\nexport async function send(url: string, init: RequestInit, options: SendOptions): Promise<Sent> {\n const { method, path } = options.call;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, options.timeoutMs);\n const done = (): void => {\n clearTimeout(timer);\n };\n let res: Response;\n try {\n res = await options.fetch(url, { ...init, redirect: \"manual\", signal: controller.signal });\n } catch {\n done();\n // Deliberately untyped: fetch rejects with a TypeError (network) or the abort's DOMException\n // (timeout), and an injected fetch with anything at all (a non-Error, an Error of another\n // realm). Each one is an outage, and each is dropped: its message and `cause` may hold the URL.\n throw new OidcError(\"unavailable\", { method, path, status: null, requestId: null });\n }\n if (isRedirect(res)) {\n done();\n // The answer is refused either way; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n const at = upstreamOf(method, path, res);\n // An opaque redirect has status 0, which is no HTTP status.\n throw new OidcError(\"provider_error\", res.status === 0 ? { ...at, status: null } : at);\n }\n return { res, done, timedOut: () => controller.signal.aborted };\n}\n\n/** Reads at most `maxBytes`; past the cap it cancels the body and stops reading. */\nexport async function readCappedBody(res: Response, maxBytes: number): Promise<CappedBody> {\n const declared = Number(res.headers.get(\"content-length\") ?? \"0\");\n if (declared > maxBytes) {\n // The answer is refused either way; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n return { kind: \"too_large\" };\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n const reader = res.body?.getReader();\n while (reader !== undefined) {\n const chunk = (await reader.read()) as { done: boolean; value?: Uint8Array };\n const value = chunk.value;\n if (chunk.done || value === undefined) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel().catch(ignore);\n return { kind: \"too_large\" };\n }\n chunks.push(value);\n }\n } catch {\n // Deliberately untyped: a stream can be errored with any reason (a reset connection, the call's\n // timeout abort), and each one means the same unusable body.\n return { kind: \"unreadable\" };\n }\n return { kind: \"bytes\", bytes: Buffer.concat(chunks) };\n}\n\n/** Parsed JSON, `null` for an unreadable or non-JSON body, `undefined` when it exceeds the cap. */\nexport async function readJson(res: Response): Promise<unknown> {\n const body = await readCappedBody(res, MAX_RESPONSE_BYTES);\n if (body.kind === \"too_large\") return undefined;\n if (body.kind === \"unreadable\") return null;\n try {\n return JSON.parse(body.bytes.toString(\"utf8\")) as unknown;\n } catch (error) {\n if (error instanceof SyntaxError) return null;\n throw error;\n }\n}\n\n/**\n * Where an answer came from: method, path, status and the provider's request id. The id is the\n * provider's text and ends up in logs, so one that is not a plain identifier is null, by the rule\n * the failure event applies.\n */\nexport function upstreamOf(method: string, path: string, res: Response): OidcUpstream {\n return { method, path, status: res.status, requestId: plain(res.headers.get(\"x-request-id\")) };\n}\n\n/** 5xx and 429 are retryable (`unavailable`), whatever the body; an oversized body is `provider_error`. */\nexport function failOnStatus(res: Response, body: unknown, at: OidcUpstream): void {\n if (res.status >= 500 || res.status === 429) throw new OidcError(\"unavailable\", at);\n if (body === undefined) throw new OidcError(\"provider_error\", at);\n}\n\n/**\n * {@link send}, then the JSON body under the cap, with the timer stopped afterwards. A body the\n * timeout cut short is `unavailable`, not a malformed answer.\n */\nexport async function requestJson(url: string, init: RequestInit, options: SendOptions): Promise<JsonAnswer> {\n const { res, done, timedOut } = await send(url, init, options);\n const body = await readJson(res).finally(done);\n const at = upstreamOf(options.call.method, options.call.path, res);\n if (timedOut()) throw new OidcError(\"unavailable\", at);\n return { res, body, at };\n}\n","export { createServiceClient } from \"./client.js\";\nexport type { ServiceClient, ServiceClientOptions } from \"./client.js\";\nexport type { OidcFailureEvent, OidcOperation } from \"../core/failure.js\";\nexport type { OidcFetch } from \"../core/types.js\";\nexport { ConfigError, OidcError } from \"@plasgos/auth-shared\";\nexport type { Environment, OidcErrorReason, OidcUpstream, ServiceScope } from \"@plasgos/auth-shared\";\n"],"mappings":";AAAA;AAAA,EACE,eAAAA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,uBAAAC;AAAA,EACA,iBAAAC;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,OACK;;;ACTP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCP,IAAM,iBAAiB;AAyBhB,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAG9D,IAAM,UAAU,CAAC,UAA4B,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM;AAM3F,IAAM,iBAAiB,CAAC,WAC7B,OAAO,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,MAAM,IAAI,OAAO,OAAO,CAAC,UAAU,OAAO,UAAU,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC;AAGvG,IAAM,cAAyB,CAAC,OAAO,SAAS,WAAW,MAAM,OAAO,IAAI;AAG5E,SAAS,OAAO,UAAoB,OAAyC;AAClF,MAAI;AACF,WAAO,MAAM;AAAA,EACf,SAAS,OAAO;AACd,QAAI,EAAE,iBAAiB,aAAc,OAAM;AAC3C,aAAS,KAAK,GAAG,MAAM,QAAQ;AAC/B,WAAO;AAAA,EACT;AACF;AAMO,SAAS,WACd,UACA,KACA,UACsB;AACtB,QAAM,QAAQ,OAAO,CAAC;AACtB,MAAI,CAAC,SAAS,KAAK,EAAG,UAAS,KAAK,4BAA4B;AAChE,QAAM,WAAiC,EAAE,GAAG,SAAS;AACrD,aAAW,QAAQ,OAAO,KAAK,QAAQ,GAAa;A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_ISSUER","environmentProblems","parseAudience","parseIssuer","OidcError","ignore","OidcError","ignore","ConfigError","allowInsecureHttp","parseIssuer","parseAudience","environmentProblems","PRODUCTION_ISSUER","OidcError","ConfigError","OidcError"]}
1
+ {"version":3,"sources":["../src/service/client.ts","../src/core/config.ts","../src/core/failure.ts","../src/core/token.ts","../src/core/http.ts","../src/service/index.ts"],"sourcesContent":["import {\n ConfigError,\n DEFAULT_AUDIENCES,\n OidcError,\n PRODUCTION_ISSUER,\n environmentProblems,\n parseAudience,\n parseIssuer,\n serviceScopeProblems,\n} from \"@plasgos/auth-shared\";\nimport type { Environment, ServiceScope } from \"@plasgos/auth-shared\";\n\nimport { distinctScopes, globalFetch, isBlank, isObject, parsed, timeoutsOf } from \"../core/config.js\";\nimport { report } from \"../core/failure.js\";\nimport type { OidcFailureEvent } from \"../core/failure.js\";\nimport type { UpstreamCall } from \"../core/http.js\";\nimport { tokenEndpointRequest } from \"../core/token.js\";\nimport type { TokenEndpoint } from \"../core/token.js\";\nimport type { OidcFetch } from \"../core/types.js\";\n\n/**\n * Options of `createServiceClient`. Values usually come from `process.env`; every problem is\n * reported at once in one `ConfigError`, by field name and never by value.\n *\n * @example\n * const options: ServiceClientOptions = {\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * apiUrl: \"https://api.plasgos.co.id\",\n * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? \"\",\n * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? \"\",\n * scopes: [\"platform:self.read\", \"payments:read\", \"payments:write\"],\n * };\n */\nexport interface ServiceClientOptions {\n /** `\"sandbox\"` or `\"production\"`; checked against `issuer`, `resource`, `backchannelUrl` and `apiUrl`. */\n environment: Environment;\n /** Bare origin of the provider. */\n issuer: string;\n /** Origin `/oidc/token` is called on; `http:` allowed (internal network). Default: `issuer`. */\n backchannelUrl?: string | undefined;\n /** Bare origin `client.fetch` calls: the API host, or the internal Plasgos server origin; `http:` allowed. */\n apiUrl: string;\n /** Client id of the app's service client. */\n clientId: string;\n /** Sent only as `client_secret_basic`, to the token endpoint. */\n clientSecret: string;\n /** Service scopes, at least one; a user scope is refused. */\n scopes: readonly ServiceScope[];\n /** Audience of the token. Default: `DEFAULT_AUDIENCES.platform`. */\n resource?: string | undefined;\n /** Sandbox only: `http:` for the issuer. */\n allowInsecureHttp?: boolean | undefined;\n /** Milliseconds, 1 to 60 000 each. Defaults: `tokenMs` 10 000 (token call), `requestMs` 10 000 (each `fetch` attempt). */\n timeouts?: { tokenMs?: number | undefined; requestMs?: number | undefined } | undefined;\n /** Default: the global `fetch`. */\n fetch?: OidcFetch | undefined;\n /** Receives one event per failure (`service_token`, `service_request`); safe to log. */\n onFailure?: ((event: OidcFailureEvent) => void) | undefined;\n}\n\n/**\n * What `createServiceClient` returns.\n *\n * @example\n * const res = await plasgos.fetch(\"/v5/service/payments\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(payment),\n * });\n * if (!res.ok) throw new Error(`payments answered ${String(res.status)}`);\n */\nexport interface ServiceClient {\n /** The `environment` the client was created with. */\n readonly environment: Environment;\n /** The client id the client was created with. */\n readonly clientId: string;\n /** A cached access token; a new one is requested 60 s before expiry. */\n getToken(): Promise<string>;\n /** `fetch(apiUrl + path)` with `Authorization: Bearer`; one retry on 401 invalid_token; `redirect: \"manual\"` unless the caller sets `redirect`. */\n fetch(path: string, init?: RequestInit): Promise<Response>;\n}\n\n/** The validated options of a service client, with every default filled in. Frozen. */\nexport interface ResolvedServiceConfig {\n readonly environment: Environment;\n /** Canonical origin of the provider. */\n readonly issuer: string;\n /** Canonical origin for the token call, or null to use `issuer`. */\n readonly backchannelUrl: string | null;\n /** Canonical origin `client.fetch` calls. */\n readonly apiUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n readonly scopes: readonly string[];\n readonly resource: string;\n readonly timeouts: Readonly<{ tokenMs: number; requestMs: number }>;\n readonly fetch: OidcFetch;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n}\n\nconst DEFAULT_TOKEN_MS = 10_000;\nconst DEFAULT_REQUEST_MS = 10_000;\n/** A token is replaced this long before it expires, or at half its life when that is shorter. */\nconst EXPIRY_MARGIN_SECONDS = 60;\n/** One leading \"/\", not followed by a second \"/\" or a \"\\\" (which a URL parser reads as one). */\nconst SINGLE_SLASH_PATH = /^\\/(?![/\\\\])/;\nconst PATH_PROBLEM = \"serviceClient.fetch: path must start with a single /\";\n\nconst ignore = (): void => undefined;\n\n/** RFC 6750 `WWW-Authenticate: Bearer error=\"invalid_token\"` on a 401, as the Plasgos API answers a refused service token. */\nconst isInvalidToken = (res: Response): boolean => {\n if (res.status !== 401) return false;\n const challenge = res.headers.get(\"www-authenticate\") ?? \"\";\n return /^\\s*Bearer\\b/i.test(challenge) && /\\berror\\s*=\\s*\"?invalid_token\"?/i.test(challenge);\n};\n\n/**\n * Checks the untyped options of `createServiceClient`; one\n * ConfigError lists every problem, by field name only.\n */\nexport function resolveServiceConfig(raw: unknown): ResolvedServiceConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n const given = (field: string): boolean => raw[field] !== undefined;\n /** For an optional string option: a blank string counts as not given. */\n const present = (field: string): boolean => given(field) && !isBlank(raw[field]);\n const required = (field: string): string | undefined => {\n const value = text(field);\n const blank = isBlank(value);\n if (blank || !given(field)) problems.push(`${field} is required`);\n return blank ? undefined : value;\n };\n /** A bare origin; a non-string already has its problem and is never handed to the parser. */\n const origin = (field: string, allowInsecureHttp: boolean, optional: boolean): string | undefined => {\n if (optional && !present(field)) return undefined;\n const value = text(field);\n if (value === undefined && given(field)) return undefined;\n return parsed(problems, () => parseIssuer(value, { field, allowInsecureHttp }));\n };\n\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuer = origin(\"issuer\", allowInsecureHttp, false);\n // Both may be internal network addresses, so `http:` is accepted in either environment.\n const backchannelUrl = origin(\"backchannelUrl\", true, true);\n const apiUrl = origin(\"apiUrl\", true, false);\n\n const clientId = required(\"clientId\");\n const clientSecret = required(\"clientSecret\");\n\n const scopesRaw = raw[\"scopes\"];\n problems.push(...serviceScopeProblems(scopesRaw));\n\n const resourceRaw = present(\"resource\") ? text(\"resource\") : undefined;\n const resource = present(\"resource\")\n ? resourceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(resourceRaw, { field: \"resource\", allowInsecureHttp }))\n : DEFAULT_AUDIENCES.platform;\n\n if (raw[\"allowInsecureHttp\"] !== undefined && typeof raw[\"allowInsecureHttp\"] !== \"boolean\") {\n problems.push(\"allowInsecureHttp must be a boolean\");\n }\n\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"], { tokenMs: DEFAULT_TOKEN_MS, requestMs: DEFAULT_REQUEST_MS });\n\n const { fetch, onFailure } = raw;\n if (fetch !== undefined && typeof fetch !== \"function\") problems.push(\"fetch must be a function\");\n if (onFailure !== undefined && typeof onFailure !== \"function\") problems.push(\"onFailure must be a function\");\n\n // An issuer that did not parse already has its problem, so the guard gets a value it has nothing\n // to say about and still judges the other fields.\n const environment = raw[\"environment\"];\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(resource !== undefined ? { audiences: [resource] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n });\n\n if (guard.length > 0 || problems.length > 0) throw new ConfigError([...guard, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n backchannelUrl: backchannelUrl ?? null,\n apiUrl: apiUrl as string,\n clientId: clientId as string,\n clientSecret: clientSecret as string,\n scopes: distinctScopes(scopesRaw),\n resource: resource as string,\n timeouts: Object.freeze(timeouts),\n fetch: (fetch as OidcFetch | undefined) ?? globalFetch,\n onFailure: onFailure as ResolvedServiceConfig[\"onFailure\"],\n });\n}\n\n/**\n * A server-to-server client: `client_credentials` tokens of a service client, cached, and a\n * `fetch` that carries the token to the Plasgos API.\n *\n * @example\n * const plasgos = createServiceClient({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * apiUrl: \"https://api.plasgos.co.id\",\n * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? \"\",\n * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? \"\",\n * scopes: [\"platform:self.read\"],\n * });\n * const res = await plasgos.fetch(\"/v5/service/me\");\n */\nexport function createServiceClient(options: ServiceClientOptions): ServiceClient {\n const config = resolveServiceConfig(options);\n const endpoint: TokenEndpoint = {\n environment: config.environment,\n origin: config.backchannelUrl ?? config.issuer,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n resource: config.resource,\n timeoutMs: config.timeouts.tokenMs,\n fetch: config.fetch,\n onFailure: config.onFailure,\n refreshTokenRequired: false,\n };\n const scope = config.scopes.join(\" \");\n\n // The cache and the request in flight belong to this client; the module keeps no state.\n let cached: { token: string; freshUntil: number } | null = null;\n let pending: Promise<string> | null = null;\n\n const mint = async (): Promise<string> => {\n // Counted from before the request, so the cached token is never thought younger than it is.\n const obtainedAt = Date.now();\n const tokens = await tokenEndpointRequest(endpoint, \"service_token\", { grant_type: \"client_credentials\", scope });\n const margin = Math.min(EXPIRY_MARGIN_SECONDS, Math.floor(tokens.expires_in / 2));\n cached = { token: tokens.access_token, freshUntil: obtainedAt + (tokens.expires_in - margin) * 1000 };\n return tokens.access_token;\n };\n\n const getToken = (): Promise<string> => {\n if (cached !== null && Date.now() < cached.freshUntil) return Promise.resolve(cached.token);\n // Single flight: callers that arrive while a request runs share it; a failure is not kept.\n pending ??= mint().finally(() => {\n pending = null;\n });\n return pending;\n };\n\n /** One attempt, bounded by `requestMs`. A failure is reported and thrown as `unavailable`. */\n const attempt = async (url: string, init: RequestInit, token: string, call: UpstreamCall): Promise<Response> => {\n const controller = new AbortController();\n // Not cleared when the headers arrive: it bounds the caller's read of the body too.\n const timer = setTimeout(() => {\n controller.abort();\n }, config.timeouts.requestMs);\n timer.unref();\n const callerSignal = init.signal ?? null;\n try {\n // Inside the try: `Headers` throws a TypeError that quotes the name or the value it refuses,\n // which may be the caller's secret header (the token itself is header-safe by the parser).\n const headers = new Headers(init.headers);\n headers.set(\"Authorization\", `Bearer ${token}`);\n return await config.fetch(url, {\n ...init,\n headers,\n // The bearer token would follow a redirect to another host.\n redirect: init.redirect ?? \"manual\",\n signal: callerSignal === null ? controller.signal : AbortSignal.any([callerSignal, controller.signal]),\n });\n } catch {\n // Deliberately untyped: whatever `Headers` or `fetch` threw is dropped, because its message,\n // `input` and `cause` may hold a header or the URL with its query.\n clearTimeout(timer);\n // The caller's own abort is the caller's to handle, with the reason it gave.\n callerSignal?.throwIfAborted();\n report(config.onFailure, {\n environment: config.environment,\n operation: \"service_request\",\n reason: \"unavailable\",\n method: call.method,\n path: call.path,\n status: null,\n requestId: null,\n providerError: null,\n });\n throw new OidcError(\"unavailable\", { method: call.method, path: call.path, status: null, requestId: null });\n }\n };\n\n const fetch = async (path: string, init: RequestInit = {}): Promise<Response> => {\n if (typeof path !== \"string\" || !SINGLE_SLASH_PATH.test(path)) throw new TypeError(PATH_PROBLEM);\n // `init` comes from untyped JavaScript as well.\n const given: unknown = init;\n if (!isObject(given)) throw new TypeError(\"serviceClient.fetch: init must be an object\");\n const url = `${config.apiUrl}${path}`;\n // Checked here, so that neither `new URL` nor `fetch` gets to throw an error that carries the path.\n if (!URL.canParse(url) || new URL(url).origin !== config.apiUrl) throw new TypeError(PATH_PROBLEM);\n init.signal?.throwIfAborted();\n const call: UpstreamCall = {\n method: typeof init.method === \"string\" ? init.method.toUpperCase() : \"GET\",\n path: path.split(/[?#]/, 1)[0] ?? \"\",\n };\n\n const token = await getToken();\n const res = await attempt(url, init, token, call);\n if (!isInvalidToken(res)) return res;\n // The API refused the token (expired early, key rotated, client state changed): it is dropped,\n // unless another request already replaced it.\n if (cached?.token === token) cached = null;\n // A stream was consumed by the first attempt and cannot be sent again.\n if (init.body instanceof ReadableStream) return res;\n // The refused answer is replaced by the retry's; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n return attempt(url, init, await getToken(), call);\n };\n\n return Object.freeze({ environment: config.environment, clientId: config.clientId, getToken, fetch });\n}\n","import {\n ConfigError,\n PRODUCTION_ISSUER,\n environmentProblems,\n parseAudience,\n parseIssuer,\n userScopeProblems,\n} from \"@plasgos/auth-shared\";\nimport type { ClientProfile, Environment } from \"@plasgos/auth-shared\";\n\nimport type { OidcFailureEvent } from \"./failure.js\";\nimport { memoryLockStore } from \"./refresh-lock.js\";\nimport type { RefreshLockStore } from \"./refresh-lock.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * Validation of the `createOidcClient` options. Options come from untyped\n * JavaScript and from env parsing, so nothing is trusted to have its declared type. Every problem\n * is collected and thrown as one ConfigError; a problem names the field, never its value.\n */\n\n/** The validated options of a client, with every default filled in. Frozen. */\nexport interface ResolvedConfig {\n readonly environment: Environment;\n /** Canonical origin: browser URLs and the exact `iss` value. */\n readonly issuer: string;\n /** Canonical origin for the back-channel calls, or null to use `issuer`. */\n readonly backchannelUrl: string | null;\n readonly clientId: string;\n readonly clientSecret: string;\n readonly redirectUri: string;\n readonly postLogoutRedirectUri: string | null;\n readonly scopes: readonly string[];\n readonly profile: ClientProfile;\n readonly resource: string | null;\n readonly logoutTicket: boolean;\n readonly endSession: \"redirect\" | \"form-post\";\n readonly extraClaims: readonly string[];\n readonly timeouts: Readonly<{ tokenMs: number; logoutMs: number }>;\n readonly fetch: OidcFetch;\n readonly refreshLock: RefreshLockStore;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n}\n\nconst DEFAULT_TOKEN_MS = 10_000;\nconst DEFAULT_LOGOUT_MS = 3_000;\nconst MAX_TIMEOUT_MS = 60_000;\nconst CLAIM_NAME = /^[A-Za-z0-9_:.-]{1,64}$/;\n/** Claims the SDK checks or already returns, and the names that would reach the prototype. */\nconst RESERVED_CLAIMS: ReadonlySet<string> = new Set([\n \"iss\",\n \"sub\",\n \"aud\",\n \"azp\",\n \"exp\",\n \"iat\",\n \"nbf\",\n \"jti\",\n \"nonce\",\n \"auth_time\",\n \"at_hash\",\n \"c_hash\",\n \"s_hash\",\n \"name\",\n \"picture\",\n \"email\",\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/** True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\". */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * The scope list that is sent: each scope once, in the order given. Called after the shared scope\n * check found no problem, so every entry is a valid scope token.\n */\nexport const distinctScopes = (scopes: unknown): readonly string[] =>\n Object.freeze([...new Set(Array.isArray(scopes) ? scopes.filter((scope) => typeof scope === \"string\") : [])]);\n\n/** Resolved at call time, so a `globalThis.fetch` replaced later (a test spy, an instrumentation) is used. */\nexport const globalFetch: OidcFetch = (input, init) => globalThis.fetch(input, init);\n\n/** Runs a single-problem parser of auth-shared; its problem is collected, not thrown. */\nexport function parsed(problems: string[], parse: () => string): string | undefined {\n try {\n return parse();\n } catch (error) {\n if (!(error instanceof ConfigError)) throw error;\n problems.push(...error.problems);\n return undefined;\n }\n}\n\n/**\n * The `timeouts` option with its defaults filled in: each named budget is an integer from 1 to\n * 60 000 ms. A problem is collected and the default kept.\n */\nexport function timeoutsOf<Name extends string>(\n problems: string[],\n raw: unknown,\n defaults: Readonly<Record<Name, number>>,\n): Record<Name, number> {\n const given = raw ?? {};\n if (!isObject(given)) problems.push(\"timeouts must be an object\");\n const resolved: Record<Name, number> = { ...defaults };\n for (const name of Object.keys(defaults) as Name[]) {\n const value = isObject(given) ? given[name] : undefined;\n if (value === undefined) continue;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS) {\n resolved[name] = value;\n } else {\n problems.push(`timeouts.${name} must be an integer from 1 to ${String(MAX_TIMEOUT_MS)}`);\n }\n }\n return resolved;\n}\n\n/**\n * Validates `redirectUri` or `postLogoutRedirectUri` by the rule Plasgos applies when the URI is\n * registered: an absolute\n * http(s) URL that may carry a query; a wildcard, a fragment (an empty \"#\" too) and credentials are\n * refused, and `http:` needs `allowInsecureHttp`. The provider compares the value exactly with the\n * registered one, so it is returned as written (trimmed), and what the URL parser would silently\n * strip or rewrite is refused. The problem names the field, never the value.\n */\nfunction redirectUriProblem(value: string, field: string, allowInsecureHttp: boolean): string | undefined {\n if (value === \"\") return `${field} is required`;\n if (value.includes(\"*\")) return `${field} must not contain a wildcard`;\n if (!URL.canParse(value)) return `${field} must be an absolute URL`;\n // eslint-disable-next-line no-control-regex -- control characters are what this check looks for\n if (/[\\u0000- \\u007f\\\\]/.test(value)) {\n return `${field} must not contain whitespace, control characters or a backslash`;\n }\n const url = new URL(value);\n // The raw value is checked too: the URL parser drops an empty \"#\" and an empty userinfo.\n if (url.hash || value.includes(\"#\")) return `${field} must not contain a fragment`;\n const authority = /^[a-z][a-z0-9+.-]*:\\/\\/([^/?]*)/i.exec(value)?.[1] ?? \"\";\n if (url.username || url.password || authority.includes(\"@\")) return `${field} must not contain credentials`;\n if (url.protocol !== \"https:\" && !(allowInsecureHttp && url.protocol === \"http:\")) return `${field} must use https`;\n if (!/^https?:\\/\\//i.test(value)) return `${field} must be an absolute URL`;\n return undefined;\n}\n\n/** The trimmed redirect or post-logout URI, or undefined after its problem was collected. */\nfunction redirectUriOf(\n problems: string[],\n raw: string | undefined,\n field: string,\n allowInsecureHttp: boolean,\n): string | undefined {\n const value = raw?.trim() ?? \"\";\n const problem = redirectUriProblem(value, field, allowInsecureHttp);\n if (problem === undefined) return value;\n problems.push(problem);\n return undefined;\n}\n\n/** Checks the untyped options; one ConfigError lists every problem, by field name only. */\nexport function resolveConfig(raw: unknown): ResolvedConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n /** True when the option was given, usable or not. */\n const given = (field: string): boolean => raw[field] !== undefined;\n /** For an optional string option: a blank string counts as not given. */\n const present = (field: string): boolean => given(field) && !isBlank(raw[field]);\n const optional = (field: string): string | undefined => (present(field) ? text(field) : undefined);\n const required = (field: string): string | undefined => {\n const value = text(field);\n const blank = isBlank(value);\n if (blank || !given(field)) problems.push(`${field} is required`);\n return blank ? undefined : value;\n };\n\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuerRaw = text(\"issuer\");\n const issuer =\n given(\"issuer\") && issuerRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(issuerRaw, { field: \"issuer\", allowInsecureHttp }));\n\n const backchannelRaw = optional(\"backchannelUrl\");\n const backchannelUrl =\n backchannelRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(backchannelRaw, { field: \"backchannelUrl\", allowInsecureHttp: true }));\n\n const clientId = required(\"clientId\");\n const clientSecret = required(\"clientSecret\");\n\n const redirectRaw = text(\"redirectUri\");\n const redirectUri =\n given(\"redirectUri\") && redirectRaw === undefined\n ? undefined\n : redirectUriOf(problems, redirectRaw, \"redirectUri\", allowInsecureHttp);\n\n const postLogoutRaw = optional(\"postLogoutRedirectUri\");\n const postLogoutRedirectUri =\n postLogoutRaw === undefined\n ? undefined\n : redirectUriOf(problems, postLogoutRaw, \"postLogoutRedirectUri\", allowInsecureHttp);\n\n const profileRaw = text(\"profile\");\n const profile = profileRaw === \"first-party\" || profileRaw === \"third-party\" ? profileRaw : undefined;\n\n // With an unusable profile the scopes are judged as first-party, so only the profile is reported;\n // a resource that was given but is malformed still counts as given.\n const scopesRaw = raw[\"scopes\"];\n problems.push(...userScopeProblems(scopesRaw, { profile: profile ?? \"first-party\", resource: present(\"resource\") }));\n if (profile === undefined && !(given(\"profile\") && profileRaw === undefined)) {\n problems.push('profile must be \"first-party\" or \"third-party\"');\n }\n\n const resourceRaw = optional(\"resource\");\n const resource =\n resourceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(resourceRaw, { field: \"resource\", allowInsecureHttp }));\n if (present(\"resource\") && profile === \"third-party\") {\n problems.push('resource is not allowed for profile \"third-party\"');\n }\n\n const endSessionRaw = text(\"endSession\");\n const endSession = endSessionRaw ?? (given(\"endSession\") ? undefined : \"redirect\");\n const endSessionKnown = endSession === \"redirect\" || endSession === \"form-post\";\n\n const logoutTicketRaw = raw[\"logoutTicket\"];\n if (logoutTicketRaw !== undefined && typeof logoutTicketRaw !== \"boolean\") {\n problems.push(\"logoutTicket must be a boolean\");\n } else if (logoutTicketRaw === true) {\n if (profile === \"third-party\") {\n problems.push('logoutTicket is not allowed for profile \"third-party\"');\n } else if (endSession === \"form-post\") {\n problems.push('logoutTicket is not used with endSession \"form-post\"');\n } else if (!present(\"backchannelUrl\")) {\n problems.push(\"logoutTicket requires backchannelUrl (the internal Plasgos server URL)\");\n }\n }\n // The ticket endpoint is internal-only, so the default needs a backchannelUrl.\n const logoutTicket =\n logoutTicketRaw === true ||\n (logoutTicketRaw === undefined &&\n profile === \"first-party\" &&\n endSession === \"redirect\" &&\n backchannelUrl !== undefined);\n\n if (endSession !== undefined && !endSessionKnown) {\n problems.push('endSession must be \"redirect\" or \"form-post\"');\n } else if (\n // Sandbox is left alone: local development runs the app and the issuer on two ports. The\n // provider still answers a cross-origin form POST with 403.\n raw[\"environment\"] === \"production\" &&\n endSession === \"form-post\" &&\n issuer !== undefined &&\n redirectUri !== undefined &&\n new URL(redirectUri).origin !== issuer\n ) {\n problems.push('endSession \"form-post\" requires redirectUri on the issuer origin');\n }\n\n // Absent only when undefined: null is refused like any other value that is not a list.\n const extraClaimsRaw: unknown = raw[\"extraClaims\"] === undefined ? [] : raw[\"extraClaims\"];\n const extraClaims =\n Array.isArray(extraClaimsRaw) &&\n extraClaimsRaw.every(\n (name): name is string => typeof name === \"string\" && CLAIM_NAME.test(name) && !RESERVED_CLAIMS.has(name),\n )\n ? [...new Set(extraClaimsRaw)]\n : undefined;\n if (extraClaims === undefined) problems.push(\"extraClaims contains an invalid claim name\");\n\n if (raw[\"allowInsecureHttp\"] !== undefined && typeof raw[\"allowInsecureHttp\"] !== \"boolean\") {\n problems.push(\"allowInsecureHttp must be a boolean\");\n }\n\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"], { tokenMs: DEFAULT_TOKEN_MS, logoutMs: DEFAULT_LOGOUT_MS });\n\n const { fetch, refreshLock, onFailure } = raw;\n if (fetch !== undefined && typeof fetch !== \"function\") problems.push(\"fetch must be a function\");\n if (refreshLock !== undefined && !(isObject(refreshLock) && typeof refreshLock[\"run\"] === \"function\")) {\n problems.push(\"refreshLock must have a run function\");\n }\n if (onFailure !== undefined && typeof onFailure !== \"function\") problems.push(\"onFailure must be a function\");\n\n // The guard compares parsed values. An issuer that did not parse already has its problem, so the\n // guard gets a value it has nothing to say about and still judges the other fields.\n const environment = raw[\"environment\"];\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(resource !== undefined ? { audiences: [resource] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n });\n\n if (guard.length > 0 || problems.length > 0) throw new ConfigError([...guard, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n backchannelUrl: backchannelUrl ?? null,\n clientId: clientId as string,\n clientSecret: clientSecret as string,\n redirectUri: redirectUri as string,\n postLogoutRedirectUri: postLogoutRedirectUri ?? null,\n scopes: distinctScopes(scopesRaw),\n profile: profile as ClientProfile,\n resource: resource ?? null,\n logoutTicket,\n endSession: endSession as \"redirect\" | \"form-post\",\n extraClaims: Object.freeze(extraClaims as string[]),\n timeouts: Object.freeze(timeouts),\n fetch: (fetch as OidcFetch | undefined) ?? globalFetch,\n refreshLock: (refreshLock as RefreshLockStore | undefined) ?? memoryLockStore(),\n onFailure: onFailure as ResolvedConfig[\"onFailure\"],\n });\n}\n","import type { Environment, OidcErrorReason } from \"@plasgos/auth-shared\";\n\n/*\n * The failure event of the SDK. The SDK never logs: every failure, thrown or\n * swallowed, is handed to the app's `onFailure` hook as one event that is safe to write to a log.\n * Ported from the failure log lines of plasgos-shipping-v2: the path loses\n * its query string, and a field that is not a plain identifier becomes null, because the request\n * id and the error code come from the provider's answer and are not trusted.\n */\n\n/**\n * The step of the SDK that failed.\n *\n * @example\n * if (event.operation === \"refresh\" && event.reason === \"config_invalid\") alertOps(event);\n */\nexport type OidcOperation =\n | \"callback\"\n | \"token\"\n | \"refresh\"\n | \"revocation\"\n | \"logout_ticket\"\n | \"service_token\"\n | \"service_request\";\n\n/**\n * One failure, as the `onFailure` hook receives it. It never holds a token, code, secret, body or\n * query string.\n *\n * @example\n * const onFailure = (event: OidcFailureEvent) => {\n * logger.error(`login failed: ${event.operation} ${event.reason} request_id=${event.requestId ?? \"-\"}`);\n * };\n */\nexport interface OidcFailureEvent {\n /** The `environment` of the client that failed. */\n environment: Environment;\n /** The step that failed. */\n operation: OidcOperation;\n /** The same reason an `OidcError` of this failure carries. */\n reason: OidcErrorReason;\n /** HTTP method of the call that failed, or null. */\n method: string | null;\n /** Path of the call that failed, without query string or fragment, or null. */\n path: string | null;\n /** HTTP status of the provider's answer; null when there was none. */\n status: number | null;\n /** `x-request-id` of the provider's answer, or null. */\n requestId: string | null;\n /** The `error` code the provider answered with, or null. */\n providerError: string | null;\n}\n\nconst PLAIN = /^[\\w.:-]{1,128}$/;\nconst PLAIN_PATH = /^\\/[\\w./~-]{0,255}$/;\n\n/** `value` when it is a plain identifier (word characters, \".\", \":\" and \"-\", at most 128), else null. */\nexport const plain = (value: string | null): string | null => (value !== null && PLAIN.test(value) ? value : null);\n\nconst pathOnly = (path: string | null): string | null => {\n if (path === null) return null;\n const bare = path.split(/[?#]/, 1)[0] ?? \"\";\n return PLAIN_PATH.test(bare) ? bare : null;\n};\n\n/** A copy of `event` in which every field that is not a plain identifier or a plain path is null. */\nexport function sanitizeEvent(event: OidcFailureEvent): OidcFailureEvent {\n return {\n environment: event.environment,\n operation: event.operation,\n reason: event.reason,\n method: plain(event.method),\n path: pathOnly(event.path),\n status: Number.isInteger(event.status) ? event.status : null,\n requestId: plain(event.requestId),\n providerError: plain(event.providerError),\n };\n}\n\nconst ignore = (): void => undefined;\n\n/**\n * Hands the sanitised event to the app's hook. A hook that throws, or whose promise rejects, never\n * changes what the SDK does next.\n */\nexport function report(hook: ((event: OidcFailureEvent) => void) | undefined, event: OidcFailureEvent): void {\n if (hook === undefined) return;\n try {\n // The hook is typed to return nothing, but an async function is assignable to it.\n const run: (event: OidcFailureEvent) => unknown = hook;\n const result = run(sanitizeEvent(event));\n if (result instanceof Promise) result.catch(ignore);\n } catch {\n // The hook is the app's code; its failure must not turn into a second failure here.\n }\n}\n","import { OIDC_PATHS, OidcError, basicAuthHeader } from \"@plasgos/auth-shared\";\nimport type { Environment, OidcErrorReason, TokenSet } from \"@plasgos/auth-shared\";\n\nimport type { ResolvedConfig } from \"./config.js\";\nimport { report } from \"./failure.js\";\nimport type { OidcFailureEvent } from \"./failure.js\";\nimport { failOnStatus, requestJson } from \"./http.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * The token endpoint: one form POST with `client_secret_basic`, and the checks on its answer.\n * Ported from the token request and token set checks of plasgos-shipping-v2. The secret travels in the Authorization header only; no code, verifier, token\n * or response body reaches an error or an event.\n */\n\n/** The step a token request belongs to, as the failure event names it. */\nexport type TokenOperation = \"token\" | \"refresh\" | \"service_token\";\n\nconst TOKEN_CALL = { method: \"POST\", path: OIDC_PATHS.token } as const;\n\n/** `error` codes that say the client's own configuration is wrong. */\nconst CONFIG_ERRORS: ReadonlySet<string> = new Set([\n \"invalid_client\",\n \"unauthorized_client\",\n \"invalid_scope\",\n \"unsupported_grant_type\",\n]);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst own = (record: Record<string, unknown>, key: string): unknown =>\n Object.hasOwn(record, key) ? record[key] : undefined;\n\n/**\n * Visible ASCII only. A token travels in a header (`Authorization: Bearer`), and `Headers` refuses\n * a value with a line break or a character outside Latin-1 by throwing a TypeError that quotes it.\n * Every token Plasgos issues is base64url or a JWT, so nothing real is refused.\n */\nconst HEADER_SAFE = /^[\\x21-\\x7e]+$/;\n\nconst isToken = (value: unknown): value is string => typeof value === \"string\" && HEADER_SAFE.test(value);\n\n/** The token set of a 200 answer, or null when the answer is not one. Unknown fields are dropped. */\nfunction tokenSetOf(body: unknown, refreshTokenRequired: boolean): TokenSet | null {\n if (!isRecord(body)) return null;\n const accessToken = own(body, \"access_token\");\n const refreshToken = own(body, \"refresh_token\");\n const idToken = own(body, \"id_token\");\n const expiresIn = own(body, \"expires_in\");\n const tokenType = own(body, \"token_type\");\n const scope = own(body, \"scope\");\n if (!isToken(accessToken)) return null;\n if (refreshToken === undefined && refreshTokenRequired) return null;\n if (refreshToken !== undefined && !isToken(refreshToken)) return null;\n if (idToken !== undefined && !isToken(idToken)) return null;\n if (typeof expiresIn !== \"number\" || !Number.isSafeInteger(expiresIn) || expiresIn <= 0) return null;\n // Only bearer tokens are usable by the apps; a DPoP-bound token would be sent without its proof.\n if (typeof tokenType !== \"string\" || tokenType.toLowerCase() !== \"bearer\") return null;\n if (scope !== undefined && typeof scope !== \"string\") return null;\n return {\n access_token: accessToken,\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...(idToken !== undefined ? { id_token: idToken } : {}),\n expires_in: expiresIn,\n token_type: \"Bearer\",\n ...(scope !== undefined ? { scope } : {}),\n };\n}\n\nconst reasonOf = (code: string | null): OidcErrorReason => {\n if (code === \"invalid_grant\" || code === \"invalid_target\") return code;\n return code !== null && CONFIG_ERRORS.has(code) ? \"config_invalid\" : \"provider_error\";\n};\n\n/** Where and as whom a token request is made, and how its answer and its failures are judged. */\nexport interface TokenEndpoint {\n readonly environment: Environment;\n /** Origin the token endpoint is called on: `backchannelUrl ?? issuer`. */\n readonly origin: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Sent as the last form field, or left out when null. */\n readonly resource: string | null;\n readonly timeoutMs: number;\n readonly fetch: OidcFetch;\n readonly onFailure: ((event: OidcFailureEvent) => void) | undefined;\n /** A 200 answer without a refresh token is `provider_error`. */\n readonly refreshTokenRequired: boolean;\n}\n\n/**\n * One request to `${origin}/oidc/token`. `params` are sent in the order given, followed by\n * `resource` when there is one. Every failure is reported once through `onFailure` under\n * `operation` and thrown as an `OidcError` with the upstream.\n *\n * @example\n * const tokens = await tokenEndpointRequest(endpoint, \"service_token\", { grant_type: \"client_credentials\", scope });\n */\nexport async function tokenEndpointRequest(\n endpoint: TokenEndpoint,\n operation: TokenOperation,\n params: Readonly<Record<string, string>>,\n): Promise<TokenSet> {\n // The `error` code of a refusal, kept for the event; the sanitiser drops anything but a plain code.\n let providerError: string | null = null;\n try {\n const form = new URLSearchParams({ ...params, ...(endpoint.resource !== null ? { resource: endpoint.resource } : {}) });\n const { res, body, at } = await requestJson(\n `${endpoint.origin}${TOKEN_CALL.path}`,\n {\n method: TOKEN_CALL.method,\n headers: {\n Authorization: basicAuthHeader(endpoint.clientId, endpoint.clientSecret),\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: form.toString(),\n },\n { timeoutMs: endpoint.timeoutMs, fetch: endpoint.fetch, call: TOKEN_CALL },\n );\n if (!res.ok && isRecord(body)) {\n const code = own(body, \"error\");\n if (typeof code === \"string\") providerError = code;\n }\n failOnStatus(res, body, at);\n if (!res.ok) throw new OidcError(reasonOf(providerError), at);\n const tokens = tokenSetOf(body, endpoint.refreshTokenRequired);\n if (tokens === null) throw new OidcError(\"provider_error\", at);\n return tokens;\n } catch (error) {\n // `send` turns every rejection of `fetch` into an OidcError, so anything else is a bug to surface.\n if (error instanceof OidcError) {\n report(endpoint.onFailure, {\n environment: endpoint.environment,\n operation,\n reason: error.reason,\n method: TOKEN_CALL.method,\n path: TOKEN_CALL.path,\n status: error.upstream?.status ?? null,\n requestId: error.upstream?.requestId ?? null,\n providerError,\n });\n }\n throw error;\n }\n}\n\n/**\n * One token request of a login client, to `${backchannelUrl ?? issuer}/oidc/token`; see\n * {@link tokenEndpointRequest}. A first-party client must be given a refresh token.\n *\n * @example\n * const tokens = await tokenRequest(config, \"refresh\", { grant_type: \"refresh_token\", refresh_token });\n */\nexport function tokenRequest(\n config: ResolvedConfig,\n operation: \"token\" | \"refresh\",\n params: Readonly<Record<string, string>>,\n): Promise<TokenSet> {\n return tokenEndpointRequest(\n {\n environment: config.environment,\n origin: config.backchannelUrl ?? config.issuer,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n resource: config.resource,\n timeoutMs: config.timeouts.tokenMs,\n fetch: config.fetch,\n onFailure: config.onFailure,\n refreshTokenRequired: config.profile === \"first-party\",\n },\n operation,\n params,\n );\n}\n","import { OidcError } from \"@plasgos/auth-shared\";\nimport type { OidcUpstream } from \"@plasgos/auth-shared\";\n\nimport { plain } from \"./failure.js\";\nimport type { OidcFetch } from \"./types.js\";\n\n/*\n * The transport of every back-channel call (token, revocation, logout ticket): one timed `fetch`\n * that never follows a redirect, and a body read under a size cap. Ported from the back-channel\n * transport of plasgos-shipping-v2. Nothing here puts a\n * URL, a header or a body into an error: an `OidcError` carries the reason, the method, the path,\n * the status and the provider's request id only.\n */\n\n/** Largest accepted provider response body. */\nexport const MAX_RESPONSE_BYTES = 16_384;\n\n/** The method and path a failure is reported under. */\nexport interface UpstreamCall {\n readonly method: string;\n readonly path: string;\n}\n\n/** How one call is made: its time budget, the `fetch` to use, and what to name it in a failure. */\nexport interface SendOptions {\n readonly timeoutMs: number;\n readonly fetch: OidcFetch;\n readonly call: UpstreamCall;\n}\n\n/** An answer whose body is still unread. `done` stops the timer; `timedOut` tells whether it fired. */\nexport interface Sent {\n res: Response;\n done: () => void;\n timedOut: () => boolean;\n}\n\n/** The body's bytes, or why there are none: over the cap (declared or streamed) or a failed read. */\nexport type CappedBody = { kind: \"bytes\"; bytes: Buffer } | { kind: \"too_large\" } | { kind: \"unreadable\" };\n\n/** What {@link requestJson} answers. */\nexport interface JsonAnswer {\n res: Response;\n /** Parsed JSON, `null` for a body that is not JSON, `undefined` for one over the cap. */\n body: unknown;\n at: OidcUpstream;\n}\n\nconst ignore = (): void => undefined;\n\nconst isRedirect = (res: Response): boolean =>\n res.type === \"opaqueredirect\" || (res.status >= 300 && res.status < 400);\n\n/**\n * One call, aborted after `timeoutMs`. The timer keeps running while the caller reads the body, so\n * the caller calls `done` once it has finished. A redirect is never followed (the Basic credentials\n * and the form body must not be replayed to another host): a 3xx answer is `provider_error`.\n * Whatever `fetch` rejects with (a network error, the timeout, a non-Error) is `unavailable`.\n *\n * @example\n * const { res, done } = await send(url, { method: \"POST\", body }, { timeoutMs: 10_000, fetch, call });\n * const body = await readJson(res).finally(done);\n */\nexport async function send(url: string, init: RequestInit, options: SendOptions): Promise<Sent> {\n const { method, path } = options.call;\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, options.timeoutMs);\n const done = (): void => {\n clearTimeout(timer);\n };\n let res: Response;\n try {\n res = await options.fetch(url, { ...init, redirect: \"manual\", signal: controller.signal });\n } catch {\n done();\n // Deliberately untyped: fetch rejects with a TypeError (network) or the abort's DOMException\n // (timeout), and an injected fetch with anything at all (a non-Error, an Error of another\n // realm). Each one is an outage, and each is dropped: its message and `cause` may hold the URL.\n throw new OidcError(\"unavailable\", { method, path, status: null, requestId: null });\n }\n if (isRedirect(res)) {\n done();\n // The answer is refused either way; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n const at = upstreamOf(method, path, res);\n // An opaque redirect has status 0, which is no HTTP status.\n throw new OidcError(\"provider_error\", res.status === 0 ? { ...at, status: null } : at);\n }\n return { res, done, timedOut: () => controller.signal.aborted };\n}\n\n/** Reads at most `maxBytes`; past the cap it cancels the body and stops reading. */\nexport async function readCappedBody(res: Response, maxBytes: number): Promise<CappedBody> {\n const declared = Number(res.headers.get(\"content-length\") ?? \"0\");\n if (declared > maxBytes) {\n // The answer is refused either way; a cancel that fails changes nothing.\n await res.body?.cancel().catch(ignore);\n return { kind: \"too_large\" };\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n const reader = res.body?.getReader();\n while (reader !== undefined) {\n const chunk = (await reader.read()) as { done: boolean; value?: Uint8Array };\n const value = chunk.value;\n if (chunk.done || value === undefined) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel().catch(ignore);\n return { kind: \"too_large\" };\n }\n chunks.push(value);\n }\n } catch {\n // Deliberately untyped: a stream can be errored with any reason (a reset connection, the call's\n // timeout abort), and each one means the same unusable body.\n return { kind: \"unreadable\" };\n }\n return { kind: \"bytes\", bytes: Buffer.concat(chunks) };\n}\n\n/** Parsed JSON, `null` for an unreadable or non-JSON body, `undefined` when it exceeds the cap. */\nexport async function readJson(res: Response): Promise<unknown> {\n const body = await readCappedBody(res, MAX_RESPONSE_BYTES);\n if (body.kind === \"too_large\") return undefined;\n if (body.kind === \"unreadable\") return null;\n try {\n return JSON.parse(body.bytes.toString(\"utf8\")) as unknown;\n } catch (error) {\n if (error instanceof SyntaxError) return null;\n throw error;\n }\n}\n\n/**\n * Where an answer came from: method, path, status and the provider's request id. The id is the\n * provider's text and ends up in logs, so one that is not a plain identifier is null, by the rule\n * the failure event applies.\n */\nexport function upstreamOf(method: string, path: string, res: Response): OidcUpstream {\n return { method, path, status: res.status, requestId: plain(res.headers.get(\"x-request-id\")) };\n}\n\n/** 5xx and 429 are retryable (`unavailable`), whatever the body; an oversized body is `provider_error`. */\nexport function failOnStatus(res: Response, body: unknown, at: OidcUpstream): void {\n if (res.status >= 500 || res.status === 429) throw new OidcError(\"unavailable\", at);\n if (body === undefined) throw new OidcError(\"provider_error\", at);\n}\n\n/**\n * {@link send}, then the JSON body under the cap, with the timer stopped afterwards. A body the\n * timeout cut short is `unavailable`, not a malformed answer.\n */\nexport async function requestJson(url: string, init: RequestInit, options: SendOptions): Promise<JsonAnswer> {\n const { res, done, timedOut } = await send(url, init, options);\n const body = await readJson(res).finally(done);\n const at = upstreamOf(options.call.method, options.call.path, res);\n if (timedOut()) throw new OidcError(\"unavailable\", at);\n return { res, body, at };\n}\n","export { createServiceClient } from \"./client.js\";\nexport type { ServiceClient, ServiceClientOptions } from \"./client.js\";\nexport type { OidcFailureEvent, OidcOperation } from \"../core/failure.js\";\nexport type { OidcFetch } from \"../core/types.js\";\nexport { ConfigError, OidcError } from \"@plasgos/auth-shared\";\nexport type { Environment, OidcErrorReason, OidcUpstream, ServiceScope } from \"@plasgos/auth-shared\";\n"],"mappings":";AAAA;AAAA,EACE,eAAAA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,uBAAAC;AAAA,EACA,iBAAAC;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,OACK;;;ACTP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCP,IAAM,iBAAiB;AAyBhB,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAG9D,IAAM,UAAU,CAAC,UAA4B,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM;AAM3F,IAAM,iBAAiB,CAAC,WAC7B,OAAO,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM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AAM,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC,KAAK;AAAA,IACpC;AAEA,UAAM,QAAQ,MAAM,SAAS;AAC7B,UAAM,MAAM,MAAM,QAAQ,KAAK,MAAM,OAAO,IAAI;AAChD,QAAI,CAAC,eAAe,GAAG,EAAG,QAAO;AAGjC,QAAI,QAAQ,UAAU,MAAO,UAAS;AAEtC,QAAI,KAAK,gBAAgB,eAAgB,QAAO;AAEhD,UAAM,IAAI,MAAM,OAAO,EAAE,MAAMP,OAAM;AACrC,WAAO,QAAQ,KAAK,MAAM,MAAM,SAAS,GAAG,IAAI;AAAA,EAClD;AAEA,SAAO,OAAO,OAAO,EAAE,aAAa,OAAO,aAAa,UAAU,OAAO,UAAU,UAAU,MAAM,CAAC;AACtG;;;AKtUA,SAAS,eAAAQ,cAAa,aAAAC,kBAAiB;","names":["ConfigError","OidcError","PRODUCTION_ISSUER","environmentProblems","parseAudience","parseIssuer","OidcError","ignore","OidcError","ignore","ConfigError","allowInsecureHttp","parseIssuer","parseAudience","environmentProblems","PRODUCTION_ISSUER","OidcError","ConfigError","OidcError"]}
package/dist/session.cjs CHANGED
@@ -20,16 +20,48 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/session/index.ts
21
21
  var session_exports = {};
22
22
  __export(session_exports, {
23
- ConfigError: () => import_auth_shared2.ConfigError,
23
+ ConfigError: () => import_auth_shared3.ConfigError,
24
24
  SessionTooLargeError: () => SessionTooLargeError,
25
25
  createSessionStore: () => createSessionStore,
26
26
  deriveKeyRing: () => deriveKeyRing,
27
27
  memoryLockStore: () => memoryLockStore,
28
28
  openCookie: () => openCookie,
29
+ readAccessTokenClaims: () => readAccessTokenClaims,
29
30
  sealCookie: () => sealCookie
30
31
  });
31
32
  module.exports = __toCommonJS(session_exports);
32
33
 
34
+ // src/session/access-token-claims.ts
35
+ var import_auth_shared = require("@plasgos/auth-shared");
36
+ var SEGMENT = /^[A-Za-z0-9_-]+$/;
37
+ var MAX_PUBLIC_ID_LENGTH = 128;
38
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39
+ function readAccessTokenClaims(accessToken) {
40
+ const raw = accessToken;
41
+ if (typeof raw !== "string" || raw.length > import_auth_shared.MAX_JWT_LENGTH) return null;
42
+ const parts = raw.split(".");
43
+ if (parts.length !== 3) return null;
44
+ const [header = "", payload = ""] = parts;
45
+ if (!SEGMENT.test(header) || !SEGMENT.test(payload)) return null;
46
+ let claims;
47
+ try {
48
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(payload, "base64url"));
49
+ claims = JSON.parse(text);
50
+ } catch {
51
+ return null;
52
+ }
53
+ if (!isRecord(claims)) return null;
54
+ const own2 = (name) => Object.hasOwn(claims, name) ? claims[name] : void 0;
55
+ const sid = own2("sid");
56
+ const cv = own2("cv");
57
+ const publicId = own2("plasgos_public_id");
58
+ return Object.freeze({
59
+ sid: typeof sid === "string" && sid !== "" ? sid : null,
60
+ cv: typeof cv === "number" && Number.isSafeInteger(cv) ? cv : null,
61
+ plasgos_public_id: typeof publicId === "string" && publicId !== "" && publicId.length <= MAX_PUBLIC_ID_LENGTH ? publicId : null
62
+ });
63
+ }
64
+
33
65
  // src/session/cookie-crypto.ts
34
66
  var import_node_crypto = require("crypto");
35
67
  var VERSION = "v1";
@@ -96,7 +128,7 @@ function openCookie(cookie, sealed, ring) {
96
128
  }
97
129
 
98
130
  // src/session/store.ts
99
- var import_auth_shared = require("@plasgos/auth-shared");
131
+ var import_auth_shared2 = require("@plasgos/auth-shared");
100
132
 
101
133
  // src/session/compact-keys.ts
102
134
  var CORE_COMPACT_KEYS = Object.freeze({
@@ -184,10 +216,10 @@ function cookieValue(header, name) {
184
216
  }
185
217
  return null;
186
218
  }
187
- function serialize(name, value, maxAge, secure) {
219
+ function serialize(name, value, maxAge, secure, path = "/") {
188
220
  const attrs = [`${name}=${value}`];
189
221
  if (maxAge !== void 0) attrs.push(`Max-Age=${String(maxAge)}`);
190
- attrs.push("Path=/", "HttpOnly");
222
+ attrs.push(`Path=${path}`, "HttpOnly");
191
223
  if (secure) attrs.push("Secure");
192
224
  attrs.push("SameSite=Lax");
193
225
  return attrs.join("; ");
@@ -237,7 +269,7 @@ function createSessionHandle(data, authDirty, restDirty) {
237
269
  // src/session/parsers.ts
238
270
  var TOKEN_MAX = 4096;
239
271
  var TEXT_MAX = 512;
240
- function isRecord(value) {
272
+ function isRecord2(value) {
241
273
  return value !== null && typeof value === "object" && !Array.isArray(value);
242
274
  }
243
275
  var own = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
@@ -246,7 +278,7 @@ var isText = (value) => typeof value === "string" && value.length <= TEXT_MAX;
246
278
  var isRequiredText = (value) => isText(value) && value.length >= 1;
247
279
  var isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
248
280
  function parseUser(input) {
249
- if (!isRecord(input)) return null;
281
+ if (!isRecord2(input)) return null;
250
282
  const id = own(input, "id");
251
283
  const name = own(input, "name");
252
284
  const email = own(input, "email");
@@ -257,7 +289,7 @@ function parseUser(input) {
257
289
  return { id, name, ...email !== void 0 ? { email } : {}, avatar_url: avatar };
258
290
  }
259
291
  function parseAuthState(input) {
260
- if (!isRecord(input)) return null;
292
+ if (!isRecord2(input)) return null;
261
293
  const accessToken = own(input, "access_token");
262
294
  const refreshToken = own(input, "refresh_token");
263
295
  const expiresAt = own(input, "expires_at");
@@ -278,19 +310,19 @@ function parseAuthState(input) {
278
310
  };
279
311
  }
280
312
  function parseAuthPart(input) {
281
- if (!isRecord(input)) return null;
313
+ if (!isRecord2(input)) return null;
282
314
  const raw = own(input, "auth");
283
315
  if (raw === void 0) return {};
284
316
  const auth = parseAuthState(raw);
285
317
  return auth === null ? null : { auth };
286
318
  }
287
319
  function parseIdTokenPart(input) {
288
- if (!isRecord(input)) return null;
320
+ if (!isRecord2(input)) return null;
289
321
  const idToken = own(input, "id_token");
290
322
  return isToken(idToken) ? { id_token: idToken } : null;
291
323
  }
292
324
  function parseTransaction(input) {
293
- if (!isRecord(input)) return null;
325
+ if (!isRecord2(input)) return null;
294
326
  const state = own(input, "state");
295
327
  const nonce = own(input, "nonce");
296
328
  const codeVerifier = own(input, "code_verifier");
@@ -319,6 +351,8 @@ var TRANSACTION_MAX_AGE_SECONDS = 600;
319
351
  var CLOCK_SKEW_MS = 5e3;
320
352
  var MIN_SECRET_BYTES = 32;
321
353
  var COOKIE_NAME = /^[a-z0-9-]{1,32}$/;
354
+ var COOKIE_PATH = /^\/(?:[\x21-\x7E]*\/)?$/;
355
+ var PATH_PROBLEM = 'path must start and end with "/" and contain only printable ASCII without ";", ",", "%", ".." or "//"';
322
356
  var ROLES = ["app", "auth", "idToken", "transaction"];
323
357
  var SessionTooLargeError = class extends Error {
324
358
  /** Length of the refused `Set-Cookie` value, in characters. */
@@ -332,12 +366,25 @@ var SessionTooLargeError = class extends Error {
332
366
  };
333
367
  var isPositiveInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
334
368
  var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
369
+ function readPath(problems, raw) {
370
+ if (raw === void 0) return "/";
371
+ if (typeof raw !== "string") {
372
+ problems.push("path must be a string");
373
+ return "/";
374
+ }
375
+ if (raw.trim() === "") return "/";
376
+ if (!COOKIE_PATH.test(raw) || /[;,%]/.test(raw) || raw.includes("..") || raw.includes("//")) {
377
+ problems.push(PATH_PROBLEM);
378
+ return "/";
379
+ }
380
+ return raw;
381
+ }
335
382
  function readOptions(raw) {
336
- if (!isObject(raw)) throw new import_auth_shared.ConfigError(["options must be an object"]);
383
+ if (!isObject(raw)) throw new import_auth_shared2.ConfigError(["options must be an object"]);
337
384
  const problems = [];
338
385
  const { environment, hostPrefix, hkdfSalt, secrets, cookies, authMaxAgeSeconds } = raw;
339
- const { appSchema, compactKeys, onFailure } = raw;
340
- if (typeof environment !== "string" || !import_auth_shared.ENVIRONMENTS.includes(environment)) {
386
+ const { appSchema, compactKeys, onFailure, path } = raw;
387
+ if (typeof environment !== "string" || !import_auth_shared2.ENVIRONMENTS.includes(environment)) {
341
388
  problems.push('environment must be "sandbox" or "production"');
342
389
  }
343
390
  if (hostPrefix !== void 0 && typeof hostPrefix !== "boolean") {
@@ -345,6 +392,7 @@ function readOptions(raw) {
345
392
  } else if (hostPrefix === false && environment === "production") {
346
393
  problems.push('hostPrefix: false is not allowed when environment is "production"');
347
394
  }
395
+ const cookiePath = readPath(problems, path);
348
396
  if (hkdfSalt === void 0 || hkdfSalt === null || hkdfSalt === "") {
349
397
  problems.push("hkdfSalt is required");
350
398
  } else if (typeof hkdfSalt !== "string") {
@@ -376,12 +424,13 @@ function readOptions(raw) {
376
424
  if (onFailure !== void 0 && typeof onFailure !== "function") {
377
425
  problems.push("onFailure must be a function");
378
426
  }
379
- if (problems.length > 0) throw new import_auth_shared.ConfigError(problems);
427
+ if (problems.length > 0) throw new import_auth_shared2.ConfigError(problems);
380
428
  return {
381
429
  secrets: secretList,
382
430
  hkdfSalt,
383
431
  cookies: names,
384
432
  secure: hostPrefix !== false,
433
+ path: cookiePath,
385
434
  authMaxAge: authMaxAgeSeconds,
386
435
  parseApp: (input) => appSchema.parse(input),
387
436
  compactKeys,
@@ -404,7 +453,7 @@ function withFallback(cookie, commit, drop, report) {
404
453
  }
405
454
  function createSessionStore(options) {
406
455
  const settings = readOptions(options);
407
- const { cookies, secure } = settings;
456
+ const { cookies, secure, path } = settings;
408
457
  const codec = createKeyCodec(settings.compactKeys);
409
458
  const ring = (role) => rings[role];
410
459
  const rings = {
@@ -413,7 +462,8 @@ function createSessionStore(options) {
413
462
  idToken: deriveKeyRing(settings.secrets, cookies.idToken, settings.hkdfSalt),
414
463
  transaction: deriveKeyRing(settings.secrets, cookies.transaction, settings.hkdfSalt)
415
464
  };
416
- const wireName = (role) => secure ? `__Host-${cookies[role]}` : cookies[role];
465
+ const prefix = !secure ? "" : path === "/" ? "__Host-" : "__Secure-";
466
+ const wireName = (role) => `${prefix}${cookies[role]}`;
417
467
  const cookieNames = Object.freeze({
418
468
  app: wireName("app"),
419
469
  auth: wireName("auth"),
@@ -426,8 +476,8 @@ function createSessionStore(options) {
426
476
  if (raw === null || raw === "") return null;
427
477
  return openCookie(cookies[role], raw, ring(role));
428
478
  };
429
- const seal = (role, value, maxAge) => serialize(cookieNames[role], sealCookie(cookies[role], value, ring(role)), maxAge, secure);
430
- const expire = (role) => serialize(cookieNames[role], "", 0, secure);
479
+ const seal = (role, value, maxAge) => serialize(cookieNames[role], sealCookie(cookies[role], value, ring(role)), maxAge, secure, path);
480
+ const expire = (role) => serialize(cookieNames[role], "", 0, secure, path);
431
481
  const parseApp = (value) => {
432
482
  let parsed;
433
483
  try {
@@ -443,7 +493,7 @@ function createSessionStore(options) {
443
493
  if (typeof setting === "number") return setting;
444
494
  const seconds = setting(auth);
445
495
  if (!isPositiveInteger(seconds)) {
446
- throw new import_auth_shared.ConfigError(["authMaxAgeSeconds must return a positive integer"]);
496
+ throw new import_auth_shared2.ConfigError(["authMaxAgeSeconds must return a positive integer"]);
447
497
  }
448
498
  return seconds;
449
499
  };
@@ -587,7 +637,7 @@ function memoryLockStore(options = {}) {
587
637
  }
588
638
 
589
639
  // src/session/index.ts
590
- var import_auth_shared2 = require("@plasgos/auth-shared");
640
+ var import_auth_shared3 = require("@plasgos/auth-shared");
591
641
  // Annotate the CommonJS export names for ESM import in node:
592
642
  0 && (module.exports = {
593
643
  ConfigError,
@@ -596,6 +646,7 @@ var import_auth_shared2 = require("@plasgos/auth-shared");
596
646
  deriveKeyRing,
597
647
  memoryLockStore,
598
648
  openCookie,
649
+ readAccessTokenClaims,
599
650
  sealCookie
600
651
  });
601
652
  //# sourceMappingURL=session.cjs.map