@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.2

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 (47) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +15 -0
  3. package/README.md +145 -2
  4. package/dist/index.cjs +884 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +33 -0
  7. package/dist/index.d.ts +33 -0
  8. package/dist/index.js +860 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/service.cjs +432 -0
  11. package/dist/service.cjs.map +1 -0
  12. package/dist/service.d.cts +88 -0
  13. package/dist/service.d.ts +88 -0
  14. package/dist/service.js +419 -0
  15. package/dist/service.js.map +1 -0
  16. package/dist/session.cjs +601 -0
  17. package/dist/session.cjs.map +1 -0
  18. package/dist/session.d.cts +289 -0
  19. package/dist/session.d.ts +289 -0
  20. package/dist/session.js +568 -0
  21. package/dist/session.js.map +1 -0
  22. package/dist/types-JE0OMyoi.d.cts +375 -0
  23. package/dist/types-JE0OMyoi.d.ts +375 -0
  24. package/docs/consumers.md +90 -0
  25. package/docs/contoh-hitungcuan.md +255 -0
  26. package/docs/contoh-plaslink.md +244 -0
  27. package/docs/error.md +428 -0
  28. package/docs/examples/auth-verify-readme.ts +18 -0
  29. package/docs/examples/config-error.ts +24 -0
  30. package/docs/examples/env.ts +99 -0
  31. package/docs/examples/failure-log.ts +18 -0
  32. package/docs/examples/login-client.ts +46 -0
  33. package/docs/examples/login-flow.ts +186 -0
  34. package/docs/examples/plaslink-connect.ts +48 -0
  35. package/docs/examples/readme.ts +60 -0
  36. package/docs/examples/service-client.ts +105 -0
  37. package/docs/examples/session-store.ts +53 -0
  38. package/docs/examples/webhook-express.ts +46 -0
  39. package/docs/examples/webhook-fetch.ts +60 -0
  40. package/docs/examples/webhook-nestjs.ts +59 -0
  41. package/docs/examples/webhook-testing.ts +60 -0
  42. package/docs/examples/webhook-verifier.ts +143 -0
  43. package/docs/login-web.md +618 -0
  44. package/docs/memulai.md +339 -0
  45. package/docs/server-ke-server.md +275 -0
  46. package/docs/webhook.md +625 -0
  47. package/package.json +67 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/session/cookie-crypto.ts","../src/session/store.ts","../src/session/compact-keys.ts","../src/session/cookie-header.ts","../src/session/handle.ts","../src/session/parsers.ts","../src/core/refresh-lock.ts","../src/session/index.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from \"node:crypto\";\n\n/*\n * Cookie sealing, wire format v1. AES-256-GCM with one HKDF key per cookie name and the cookie name\n * bound as AAD; a sealed value is `v1.<kid>.<iv>.<ct>.<tag>` (base64url). The format is the one\n * plasgos-shipping-v2 and plasgos-accounts-v2 already use, so a change here logs every user out.\n * Anything that fails to open is null: this module never throws on a sealed input and never puts\n * cookie contents in an error.\n */\n\nconst VERSION = \"v1\";\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst B64URL = /^[A-Za-z0-9_-]*$/;\n\n/**\n * The keys of one cookie: `current` seals, every key in `all` (by kid) opens.\n *\n * @example\n * const ring: KeyRing = deriveKeyRing([process.env.SESSION_SECRET ?? \"\"], \"kp\", \"plasgos-shipping-v2\");\n * ring.all.has(ring.current.kid); // true\n */\nexport interface KeyRing {\n /** The key that seals: derived from the first secret. */\n readonly current: { readonly kid: string; readonly key: Buffer };\n /** Every key that opens, by kid. */\n readonly all: ReadonlyMap<string, Buffer>;\n}\n\n/** AAD binds the format version and the cookie name: a v2 format cannot accept relabelled v1 data. */\nfunction aad(cookie: string): Buffer {\n return Buffer.from(`${VERSION}.${cookie}`, \"utf8\");\n}\n\n/**\n * Derives the key ring of one cookie: HKDF-SHA256(secret, hkdfSalt, \"cookie:<cookie>:v1\", 32) per\n * secret. The first secret seals, all of them open; the kid is the first 8 base64url characters of\n * the key's SHA-256. Throws when `secrets` is empty.\n *\n * @example\n * // Rotation: the new secret first, the old one kept until its cookies have expired.\n * const ring = deriveKeyRing([newSecret, oldSecret], \"kp-auth\", \"plasgos-shipping-v2\");\n */\nexport function deriveKeyRing(\n secrets: readonly string[],\n cookie: string,\n hkdfSalt: string,\n): KeyRing {\n const all = new Map<string, Buffer>();\n let current: KeyRing[\"current\"] | undefined;\n for (const secret of secrets) {\n const key = Buffer.from(\n hkdfSync(\"sha256\", Buffer.from(secret, \"utf8\"), hkdfSalt, `cookie:${cookie}:v1`, 32),\n );\n const kid = createHash(\"sha256\").update(key).digest(\"base64url\").slice(0, 8);\n current ??= { kid, key };\n if (!all.has(kid)) all.set(kid, key);\n }\n if (current === undefined) throw new Error(\"deriveKeyRing: at least one secret is required\");\n return { current, all };\n}\n\n/**\n * Seals `value` (as JSON) for the cookie named `cookie` with `ring.current`: AES-256-GCM, a fresh\n * random 96-bit IV, AAD `v1.<cookie>`, wire format `v1.<kid>.<iv>.<ct>.<tag>` (base64url).\n *\n * @example\n * const sealed = sealCookie(\"kp\", { theme: \"dark\" }, ring);\n * // \"v1.<kid>.<iv>.<ct>.<tag>\"\n */\nexport function sealCookie(cookie: string, value: unknown, ring: KeyRing): string {\n const iv = randomBytes(IV_BYTES);\n const cipher = createCipheriv(\"aes-256-gcm\", ring.current.key, iv);\n cipher.setAAD(aad(cookie));\n const ct = Buffer.concat([cipher.update(JSON.stringify(value), \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return [\n VERSION,\n ring.current.kid,\n iv.toString(\"base64url\"),\n ct.toString(\"base64url\"),\n tag.toString(\"base64url\"),\n ].join(\".\");\n}\n\n/** Strict base64url: only the canonical spelling (no padding, no slack bits, no other characters). */\nfunction decode(part: string): Buffer | null {\n if (!B64URL.test(part)) return null;\n const decoded = Buffer.from(part, \"base64url\");\n return decoded.toString(\"base64url\") === part ? decoded : null;\n}\n\n/**\n * Opens a value sealed by {@link sealCookie} for the same cookie name. Returns the value and the kid\n * of the key that opened it (compare with `ring.current.kid` to re-seal after a rotation), or null\n * for anything that does not open: malformed, tampered, another key, another cookie name. Never\n * throws on input.\n *\n * @example\n * const opened = openCookie(\"kp\", sealed, ring);\n * if (opened === null) return null; // no session\n * const needsReseal = opened.kid !== ring.current.kid;\n */\nexport function openCookie(\n cookie: string,\n sealed: string,\n ring: KeyRing,\n): { value: unknown; kid: string } | null {\n try {\n const parts = sealed.split(\".\");\n if (parts.length !== 5) return null;\n const [version, kid, ivPart, ctPart, tagPart] = parts as [string, string, string, string, string];\n if (version !== VERSION) return null;\n const key = ring.all.get(kid);\n if (key === undefined) return null;\n const iv = decode(ivPart);\n const ct = decode(ctPart);\n const tag = decode(tagPart);\n if (iv === null || ct === null || tag === null) return null;\n if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) return null;\n const decipher = createDecipheriv(\"aes-256-gcm\", key, iv, { authTagLength: TAG_BYTES });\n decipher.setAAD(aad(cookie));\n decipher.setAuthTag(tag);\n const plain = Buffer.concat([decipher.update(ct), decipher.final()]).toString(\"utf8\");\n return { value: JSON.parse(plain) as unknown, kid };\n } catch {\n // A tampered or foreign value fails in node:crypto (auth tag) or in JSON.parse: never a session.\n return null;\n }\n}\n","import { ConfigError, ENVIRONMENTS } from \"@plasgos/auth-shared\";\nimport type { Environment } from \"@plasgos/auth-shared\";\n\nimport type { OidcTransaction } from \"../core/types.js\";\nimport { compactKeyProblems, createKeyCodec } from \"./compact-keys.js\";\nimport { deriveKeyRing, openCookie, sealCookie } from \"./cookie-crypto.js\";\nimport type { KeyRing } from \"./cookie-crypto.js\";\nimport { cookieValue, serialize } from \"./cookie-header.js\";\nimport { createSessionHandle } from \"./handle.js\";\nimport type { SessionData, SessionHandle, SessionSchema } from \"./handle.js\";\nimport { parseAuthPart, parseIdTokenPart, parseTransaction } from \"./parsers.js\";\nimport type { AuthState } from \"./parsers.js\";\n\n/*\n * Sealed session cookies: the app cookie (everything but auth), the auth cookie (tokens and user),\n * the idToken cookie (the ID token, kept for the logout; never in a URL) and the OIDC transaction\n * cookie. Ported from plasgos-shipping-v2 and plasgos-accounts-v2; names, salt and key table are\n * options so each app keeps opening the cookies it already sent. Anything that fails to open is\n * \"no session\": nothing here throws on a cookie or reports its contents.\n */\n\n/** Largest Set-Cookie value a commit emits; browsers drop name plus value above 4096. */\nconst MAX_SET_COOKIE_CHARS = 4000;\n/** Lifetime of the transaction cookie and of the transaction itself. */\nconst TRANSACTION_MAX_AGE_SECONDS = 600;\n/** Tolerated future `created_at` on a transaction (clock skew between instances). */\nconst CLOCK_SKEW_MS = 5000;\nconst MIN_SECRET_BYTES = 32;\nconst COOKIE_NAME = /^[a-z0-9-]{1,32}$/;\nconst ROLES = [\"app\", \"auth\", \"idToken\", \"transaction\"] as const;\n\ntype Role = (typeof ROLES)[number];\ntype CookieNames = Record<Role, string>;\ntype CookieInput = Request | string | null | undefined;\n\n/**\n * What `commit()` reports when a cookie did not fit and was expired instead. Sizes only.\n *\n * @example\n * createSessionStore({\n * ...options,\n * onFailure: (event) => logger.warn(`session cookie ${event.cookie} dropped: ${String(event.size)} chars`),\n * });\n */\nexport type SessionFailureEvent = {\n /** The only kind so far. */\n kind: \"session_too_large\";\n /** The cookie that did not fit. */\n cookie: \"app\" | \"auth\" | \"idToken\";\n /** Length of the refused `Set-Cookie` value, in characters. */\n size: number;\n};\n\n/**\n * A cookie would not fit in a browser. Thrown by `commitApp`, `commitAuth` and `commitIdToken`;\n * `commit()` handles it itself.\n *\n * @example\n * try {\n * headers.append(\"Set-Cookie\", store.commitAuth(session));\n * } catch (error) {\n * if (error instanceof SessionTooLargeError) return loginFailed();\n * throw error;\n * }\n */\nexport class SessionTooLargeError extends Error {\n /** Length of the refused `Set-Cookie` value, in characters. */\n readonly size: number;\n\n /** Message \"Session cookie too large: <size> chars (limit 4000)\"; never the cookie value. */\n constructor(size: number) {\n super(`Session cookie too large: ${String(size)} chars (limit ${String(MAX_SET_COOKIE_CHARS)})`);\n this.name = \"SessionTooLargeError\";\n this.size = size;\n }\n}\n\n/**\n * Options of {@link createSessionStore}. For an app that already has sessions, `hkdfSalt`,\n * `cookies` and `compactKeys` must stay exactly what the app uses today.\n *\n * @example\n * const options: SessionStoreOptions<{ flash?: string }> = {\n * environment: \"production\",\n * secrets: [process.env.SESSION_SECRET ?? \"\"],\n * hkdfSalt: \"my-app\",\n * cookies: { app: \"my\", auth: \"my-auth\", idToken: \"my-idt\", transaction: \"my-oidc\" },\n * authMaxAgeSeconds: 2_592_000,\n * appSchema,\n * };\n */\nexport interface SessionStoreOptions<App extends object> {\n /** The same value the app gives its client. `\"production\"` refuses `hostPrefix: false`. */\n environment: Environment;\n /** One or two secrets, each at least 32 bytes; the first seals, all open. */\n secrets: readonly string[];\n /** HKDF salt, for example `\"plasgos-shipping-v2\"`. */\n hkdfSalt: string;\n /** Logical cookie names (`/^[a-z0-9-]{1,32}$/`, distinct); they feed the key and the AAD. */\n cookies: { app: string; auth: string; idToken: string; transaction: string };\n /** `true` (default): wire name `__Host-<name>` plus `Secure`. `false` only for local http. */\n hostPrefix?: boolean | undefined;\n /** Max-Age of the auth and idToken cookies: a positive integer, or a function of the auth. */\n authMaxAgeSeconds: number | ((auth: AuthState) => number);\n /** Validates the app cookie. Every app field must be optional. */\n appSchema: SessionSchema<Omit<App, \"auth\">>;\n /** The app's compact key table, merged with the core table; omitted means no renaming. */\n compactKeys?: Readonly<Record<string, string>> | undefined;\n /** Receives the overflow fallbacks of `commit()`. Exceptions are swallowed. */\n onFailure?: ((event: SessionFailureEvent) => void) | undefined;\n}\n\n/**\n * What {@link createSessionStore} returns.\n *\n * @example\n * const session = store.read(request);\n * session.update({ auth });\n * for (const cookie of store.commit(session)) headers.append(\"Set-Cookie\", cookie);\n */\nexport interface SessionStore<App extends object> {\n /** Opens the session cookies of a request (or of a raw Cookie header). Never throws on input. */\n read(input: Request | string | null | undefined): SessionHandle<App>;\n /**\n * Every `Set-Cookie` value a dirty session needs (none when clean): the app cookie when the rest\n * changed, then auth and idToken when auth changed. A cookie that does not fit is expired, its\n * data removed from the session, and reported through `onFailure`.\n */\n commit(session: SessionHandle<App>): string[];\n /** The app cookie (everything but auth), a browser-session cookie. Throws SessionTooLargeError. */\n commitApp(session: SessionHandle<App>): string;\n /** The auth cookie: tokens and user, never `id_token`. Throws SessionTooLargeError. */\n commitAuth(session: SessionHandle<App>): string;\n /** The idToken cookie: `auth.id_token` alone. Throws SessionTooLargeError. */\n commitIdToken(session: SessionHandle<App>): string;\n /** Whether the cookies of `auth` would fit, checked before a login is stored. */\n fits(auth: AuthState): { auth: boolean; idToken: boolean };\n /** The transaction, or null when missing, invalid, older than 600 s or over 5 s in the future. */\n readTransaction(input: Request | string | null | undefined, now?: number): OidcTransaction | null;\n /** The `Set-Cookie` value of the transaction cookie (Max-Age 600). */\n commitTransaction(tx: OidcTransaction): string;\n /** The `Set-Cookie` value that expires the transaction cookie. */\n clearTransaction(): string;\n /** Wire names (with __Host- when hostPrefix). */\n readonly cookieNames: Readonly<{ app: string; auth: string; idToken: string; transaction: string }>;\n}\n\ninterface Settings {\n secrets: readonly string[];\n hkdfSalt: string;\n cookies: CookieNames;\n secure: boolean;\n authMaxAge: number | ((auth: AuthState) => number);\n parseApp: (input: unknown) => unknown;\n compactKeys: Readonly<Record<string, string>> | undefined;\n onFailure: ((event: SessionFailureEvent) => void) | undefined;\n}\n\nconst isPositiveInteger = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/** Checks the untyped options; one ConfigError lists every problem, by field name only. */\nfunction readOptions(raw: unknown): Settings {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n const { environment, hostPrefix, hkdfSalt, secrets, cookies, authMaxAgeSeconds } = raw;\n const { appSchema, compactKeys, onFailure } = raw;\n\n if (typeof environment !== \"string\" || !(ENVIRONMENTS as readonly string[]).includes(environment)) {\n problems.push('environment must be \"sandbox\" or \"production\"');\n }\n if (hostPrefix !== undefined && typeof hostPrefix !== \"boolean\") {\n problems.push(\"hostPrefix must be a boolean\");\n } else if (hostPrefix === false && environment === \"production\") {\n problems.push('hostPrefix: false is not allowed when environment is \"production\"');\n }\n\n if (hkdfSalt === undefined || hkdfSalt === null || hkdfSalt === \"\") {\n problems.push(\"hkdfSalt is required\");\n } else if (typeof hkdfSalt !== \"string\") {\n problems.push(\"hkdfSalt must be a string\");\n }\n\n const secretList =\n Array.isArray(secrets) && secrets.every((secret) => typeof secret === \"string\")\n ? secrets\n : [];\n if (secretList.length < 1 || secretList.length > 2) {\n problems.push(\"secrets must hold one or two values\");\n } else if (secretList.some((secret) => Buffer.byteLength(secret, \"utf8\") < MIN_SECRET_BYTES)) {\n problems.push(\"secrets values must each be at least 32 bytes\");\n }\n\n const names: Partial<CookieNames> = {};\n const given = isObject(cookies) ? cookies : {};\n for (const role of ROLES) {\n const name = Object.hasOwn(given, role) ? given[role] : undefined;\n if (typeof name === \"string\" && COOKIE_NAME.test(name)) names[role] = name;\n else problems.push(`cookies.${role} must match /^[a-z0-9-]{1,32}$/`);\n }\n const nameList = Object.values(names);\n if (nameList.length === ROLES.length && new Set(nameList).size !== ROLES.length) {\n problems.push(\"cookies names must be distinct\");\n }\n\n if (!isPositiveInteger(authMaxAgeSeconds) && typeof authMaxAgeSeconds !== \"function\") {\n problems.push(\"authMaxAgeSeconds must be a positive integer or a function\");\n }\n const parse = isObject(appSchema) ? appSchema[\"parse\"] : undefined;\n if (typeof parse !== \"function\") problems.push(\"appSchema must have a parse function\");\n if (compactKeys !== undefined) problems.push(...compactKeyProblems(compactKeys));\n if (onFailure !== undefined && typeof onFailure !== \"function\") {\n problems.push(\"onFailure must be a function\");\n }\n\n if (problems.length > 0) throw new ConfigError(problems);\n return {\n secrets: secretList,\n hkdfSalt: hkdfSalt as string,\n cookies: names as CookieNames,\n secure: hostPrefix !== false,\n authMaxAge: authMaxAgeSeconds as Settings[\"authMaxAge\"],\n parseApp: (input) => (appSchema as SessionSchema<unknown>).parse(input),\n compactKeys: compactKeys as Settings[\"compactKeys\"],\n onFailure: onFailure as Settings[\"onFailure\"],\n };\n}\n\nfunction checkSize(header: string): string {\n if (header.length > MAX_SET_COOKIE_CHARS) throw new SessionTooLargeError(header.length);\n return header;\n}\n\n/** Runs `commit`; on a size overflow reports it, lets `drop` shrink the session and commits again. */\nfunction withFallback(\n cookie: SessionFailureEvent[\"cookie\"],\n commit: () => string,\n drop: () => void,\n report: (event: SessionFailureEvent) => void,\n): string {\n try {\n return commit();\n } catch (error) {\n if (!(error instanceof SessionTooLargeError)) throw error;\n report({ kind: \"session_too_large\", cookie, size: error.size });\n drop();\n return commit();\n }\n}\n\n/**\n * Creates the session store of an app. Throws one `ConfigError` naming every invalid option.\n *\n * @example\n * const store = createSessionStore<{ flash?: Flash }>({\n * environment: \"sandbox\",\n * secrets: [process.env.SESSION_SECRET ?? \"\"],\n * hkdfSalt: \"my-app\",\n * cookies: { app: \"my\", auth: \"my-auth\", idToken: \"my-idt\", transaction: \"my-oidc\" },\n * authMaxAgeSeconds: 2_592_000,\n * appSchema: { parse: (input) => parseAppCookie(input) },\n * });\n * const session = store.read(request);\n * for (const cookie of store.commit(session)) headers.append(\"Set-Cookie\", cookie);\n */\nexport function createSessionStore<App extends object>(\n options: SessionStoreOptions<App>,\n): SessionStore<App> {\n const settings = readOptions(options);\n const { cookies, secure } = settings;\n const codec = createKeyCodec(settings.compactKeys);\n const ring = (role: Role): KeyRing => rings[role];\n const rings: Record<Role, KeyRing> = {\n app: deriveKeyRing(settings.secrets, cookies.app, settings.hkdfSalt),\n auth: deriveKeyRing(settings.secrets, cookies.auth, settings.hkdfSalt),\n idToken: deriveKeyRing(settings.secrets, cookies.idToken, settings.hkdfSalt),\n transaction: deriveKeyRing(settings.secrets, cookies.transaction, settings.hkdfSalt),\n };\n const wireName = (role: Role): string => (secure ? `__Host-${cookies[role]}` : cookies[role]);\n const cookieNames = Object.freeze({\n app: wireName(\"app\"),\n auth: wireName(\"auth\"),\n idToken: wireName(\"idToken\"),\n transaction: wireName(\"transaction\"),\n });\n\n const headerOf = (input: CookieInput): string | null =>\n typeof input === \"string\" ? input : (input?.headers.get(\"cookie\") ?? null);\n\n /** The opened value of one cookie and the kid that opened it, or null. */\n const open = (header: string | null, role: Role): { value: unknown; kid: string } | null => {\n const raw = cookieValue(header, cookieNames[role]);\n if (raw === null || raw === \"\") return null;\n return openCookie(cookies[role], raw, ring(role));\n };\n\n const seal = (role: Role, value: unknown, maxAge: number | undefined): string =>\n serialize(cookieNames[role], sealCookie(cookies[role], value, ring(role)), maxAge, secure);\n\n const expire = (role: Role): string => serialize(cookieNames[role], \"\", 0, secure);\n\n /** The app part: the schema's result without `auth`, or `{}` when it refuses, throws or is no object. */\n const parseApp = (value: unknown): Record<string, unknown> | null => {\n let parsed: unknown;\n try {\n parsed = settings.parseApp(value);\n } catch {\n // A schema that throws (zod's `parse`) means the same as one that returns null.\n return null;\n }\n if (!isObject(parsed)) return null;\n return Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== \"auth\"));\n };\n\n const authMaxAge = (auth: AuthState): number => {\n const { authMaxAge: setting } = settings;\n if (typeof setting === \"number\") return setting;\n const seconds: unknown = setting(auth);\n if (!isPositiveInteger(seconds)) {\n throw new ConfigError([\"authMaxAgeSeconds must return a positive integer\"]);\n }\n return seconds;\n };\n\n const authCookie = (auth: AuthState): string => {\n const maxAge = authMaxAge(auth);\n const sealed = Object.fromEntries(Object.entries(auth).filter(([key]) => key !== \"id_token\"));\n return seal(\"auth\", codec.compact({ auth: sealed }), maxAge);\n };\n\n const idTokenCookie = (auth: AuthState, idToken: string): string =>\n seal(\"idToken\", codec.compact({ id_token: idToken }), authMaxAge(auth));\n\n const report = (event: SessionFailureEvent): void => {\n try {\n settings.onFailure?.(event);\n } catch {\n // The hook is the app's; its failure must not lose the response's cookies.\n }\n };\n\n const store: SessionStore<App> = {\n cookieNames,\n\n read(input) {\n const header = headerOf(input);\n const appOpened = open(header, \"app\");\n const rest = appOpened === null ? null : parseApp(codec.expand(appOpened.value));\n const authOpened = open(header, \"auth\");\n let auth = authOpened === null ? undefined : parseAuthPart(codec.expand(authOpened.value))?.auth;\n if (auth !== undefined) {\n const idOpened = open(header, \"idToken\");\n const idPart = idOpened === null ? null : parseIdTokenPart(codec.expand(idOpened.value));\n if (idPart !== null) auth = { ...auth, id_token: idPart.id_token };\n }\n const data = { ...rest, ...(auth !== undefined ? { auth } : {}) } as SessionData<App>;\n // Key migration never marks auth dirty: rewriting tokens that were only read could roll back\n // a concurrent refresh. An old-key auth cookie is re-sealed when auth really changes.\n const migrate = rest !== null && appOpened?.kid !== ring(\"app\").current.kid;\n return createSessionHandle<App>(data, false, migrate);\n },\n\n commitApp(session) {\n const rest = Object.fromEntries(\n Object.entries(session.data).filter(([key, value]) => key !== \"auth\" && value !== undefined),\n );\n if (Object.keys(rest).length === 0) return expire(\"app\");\n return checkSize(seal(\"app\", codec.compact(rest), undefined));\n },\n\n commitAuth(session) {\n const { auth } = session.data;\n if (auth === undefined) return expire(\"auth\");\n return checkSize(authCookie(auth));\n },\n\n commitIdToken(session) {\n const { auth } = session.data;\n if (auth?.id_token === undefined || auth.id_token === \"\") return expire(\"idToken\");\n return checkSize(idTokenCookie(auth, auth.id_token));\n },\n\n fits(auth) {\n const idToken = auth.id_token;\n return {\n auth: authCookie(auth).length <= MAX_SET_COOKIE_CHARS,\n idToken:\n idToken === undefined ||\n idToken === \"\" ||\n idTokenCookie(auth, idToken).length <= MAX_SET_COOKIE_CHARS,\n };\n },\n\n commit(session) {\n const out: string[] = [];\n if (session.restDirty) {\n out.push(\n withFallback(\n \"app\",\n () => store.commitApp(session),\n () => {\n // Only the app cookie overflowed: drop its keys, never the tokens.\n for (const key of Object.keys(session.data)) {\n if (key !== \"auth\") session.unset(key as keyof SessionData<App>);\n }\n },\n report,\n ),\n );\n }\n if (!session.authDirty) return out;\n // Auth before idToken: an auth that is dropped here expires both.\n out.push(\n withFallback(\n \"auth\",\n () => store.commitAuth(session),\n () => {\n session.unset(\"auth\");\n },\n report,\n ),\n );\n out.push(\n withFallback(\n \"idToken\",\n () => store.commitIdToken(session),\n () => {\n // The ID token alone is dropped (the logout then has no ticket); the tokens stay.\n const { auth } = session.data;\n if (auth === undefined) return;\n const kept = Object.fromEntries(Object.entries(auth).filter(([key]) => key !== \"id_token\"));\n session.update({ auth: kept } as Parameters<SessionHandle<App>[\"update\"]>[0]);\n },\n report,\n ),\n );\n return out;\n },\n\n readTransaction(input, now = Date.now()) {\n // Long keys: the transaction is never compacted.\n const tx = parseTransaction(open(headerOf(input), \"transaction\")?.value);\n if (tx === null) return null;\n const age = now - tx.created_at;\n // Written as the accepted range, so a clock that is not a number opens nothing.\n if (!(age >= -CLOCK_SKEW_MS && age <= TRANSACTION_MAX_AGE_SECONDS * 1000)) return null;\n return tx;\n },\n\n commitTransaction(tx) {\n return seal(\"transaction\", tx, TRANSACTION_MAX_AGE_SECONDS);\n },\n\n clearTransaction() {\n return expire(\"transaction\");\n },\n };\n return store;\n}\n","/*\n * Compact keys: the session plaintext uses short keys so the largest realistic session stays under\n * the cookie budget. A table is bijective and strict: a key it does not name is dropped in both\n * directions, so an unmapped field can never be written or read back. The core table is what\n * plasgos-shipping-v2 and plasgos-accounts-v2 already seal; changing a pair logs every user out.\n */\n\n/**\n * The pairs of the SDK-owned auth shape: the 11 keys both apps share plus accounts' `remember`.\n * An app's table is merged with it and must agree with it.\n *\n * @example\n * createSessionStore({ ..., compactKeys: { flash: \"fl\", kind: \"k\", message: \"msg\" } });\n * // `auth`, `access_token`, … come from CORE_COMPACT_KEYS\n */\nexport const CORE_COMPACT_KEYS = Object.freeze({\n auth: \"a\",\n access_token: \"at\",\n refresh_token: \"rt\",\n expires_at: \"e\",\n remember: \"r\",\n user: \"u\",\n id: \"i\",\n name: \"n\",\n avatar_url: \"av\",\n email: \"em\",\n id_token: \"idt\",\n auth_time: \"atm\",\n} as const);\n\nconst KEY_PATTERN = /^[A-Za-z0-9_]{1,32}$/;\nconst RESERVED = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst isKey = (value: unknown): value is string =>\n typeof value === \"string\" && KEY_PATTERN.test(value) && !RESERVED.has(value);\n\n/** Own entries of the core table followed by the app's (the app's may repeat a core pair). */\nfunction mergedEntries(table: object): [string, unknown][] {\n const merged = new Map<string, unknown>(Object.entries(CORE_COMPACT_KEYS));\n for (const [long, short] of Object.entries(table)) merged.set(long, short);\n return [...merged];\n}\n\n/**\n * Problems of an app's compact key table (empty when it can be merged with the core table). A key\n * is echoed only after it passed the syntax check, so a message never carries an arbitrary string.\n *\n * @example\n * compactKeyProblems({ auth: \"x\" }); // ['compactKeys: \"auth\" must map to \"a\"']\n */\nexport function compactKeyProblems(table: unknown): string[] {\n if (table === null || typeof table !== \"object\" || Array.isArray(table)) {\n return [\"compactKeys must be an object\"];\n }\n const entries = Object.entries(table);\n if (entries.some(([long, short]) => !isKey(long) || !isKey(short))) {\n return [\"compactKeys: keys must match /^[A-Za-z0-9_]{1,32}$/ and must not be a reserved name\"];\n }\n\n const problems: string[] = [];\n const core = new Map<string, string>(Object.entries(CORE_COMPACT_KEYS));\n for (const [long, short] of entries) {\n const expected = core.get(long);\n if (expected !== undefined && short !== expected) {\n problems.push(`compactKeys: \"${long}\" must map to \"${expected}\"`);\n }\n }\n if (problems.length > 0) return problems;\n\n const merged = mergedEntries(table) as [string, string][];\n const longs = new Set(merged.map(([long]) => long));\n const seen = new Set<string>();\n const reported = new Set<string>();\n for (const [, short] of merged) {\n if (seen.has(short) && !reported.has(short)) {\n reported.add(short);\n problems.push(`compactKeys: short key \"${short}\" is used twice`);\n }\n seen.add(short);\n if (longs.has(short)) problems.push(`compactKeys: short key \"${short}\" is also a long key`);\n }\n return problems;\n}\n\n/** Renames keys in both directions; see {@link createKeyCodec}. */\nexport interface KeyCodec {\n /** Long keys to short keys, for the plaintext a cookie seals. */\n compact(value: unknown): unknown;\n /** Short keys back to long keys, for an opened cookie. */\n expand(value: unknown): unknown;\n}\n\n/**\n * Renames own keys at every depth (arrays included) and drops a key the table does not name. The\n * table is a Map, so a key such as `constructor` or `__proto__` is looked up as plain data and\n * never through a prototype; a validated table has no reserved name as a target either.\n */\nfunction renameKeys(value: unknown, table: ReadonlyMap<string, string>): unknown {\n if (Array.isArray(value)) return value.map((item) => renameKeys(item, table));\n if (value === null || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n const mapped = table.get(key);\n if (mapped !== undefined) out[mapped] = renameKeys(item, table);\n }\n return out;\n}\n\nconst IDENTITY: KeyCodec = { compact: (value) => value, expand: (value) => value };\n\n/**\n * The codec of a store. With a table (already checked by {@link compactKeyProblems}) it renames by\n * the core table merged with the app's; without one it is the identity: nothing is renamed and\n * nothing is dropped.\n *\n * @example\n * const codec = createKeyCodec({ flash: \"fl\", kind: \"k\", message: \"msg\" });\n * codec.compact({ flash: { kind: \"info\", message: \"Halo\" }, other: 1 });\n * // { fl: { k: \"info\", msg: \"Halo\" } }\n */\nexport function createKeyCodec(table: Readonly<Record<string, string>> | undefined): KeyCodec {\n if (table === undefined) return IDENTITY;\n const merged = mergedEntries(table) as [string, string][];\n const shorts = new Map(merged);\n const longs = new Map(merged.map(([long, short]) => [short, long]));\n return {\n compact: (value) => renameKeys(value, shorts),\n expand: (value) => renameKeys(value, longs),\n };\n}\n","/*\n * Cookie header plumbing: the one Cookie-header parser and the Set-Cookie serialiser of the session\n * cookies. A sealed value is base64url with dots, so it is never encoded or decoded here.\n */\n\n/**\n * The first value of `name` in a Cookie header, or null. Names and values are trimmed; a pair\n * without `=` is skipped; the value is never decoded.\n *\n * @example\n * cookieValue(\"theme=dark; kp=v1.abc\", \"kp\"); // \"v1.abc\"\n * cookieValue(\"xkp=1\", \"kp\"); // null\n */\nexport function cookieValue(header: string | null | undefined, name: string): string | null {\n if (header === null || header === undefined || header === \"\") return null;\n for (const pair of header.split(\";\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n if (pair.slice(0, eq).trim() === name) return pair.slice(eq + 1).trim();\n }\n return null;\n}\n\n/**\n * Serialises `name=value` with the fixed attributes, in the order both apps already send:\n * `Max-Age` (only when defined), `Path=/`, `HttpOnly`, `Secure` (only when `secure`),\n * `SameSite=Lax`. Never `Domain` or `Expires`, as the `__Host-` prefix requires.\n *\n * @example\n * serialize(\"__Host-kp\", sealed, 600, true);\n * // \"__Host-kp=<sealed>; Max-Age=600; Path=/; HttpOnly; Secure; SameSite=Lax\"\n */\nexport function serialize(\n name: string,\n value: string,\n maxAge: number | undefined,\n secure: boolean,\n): string {\n const attrs = [`${name}=${value}`];\n if (maxAge !== undefined) attrs.push(`Max-Age=${String(maxAge)}`);\n attrs.push(\"Path=/\", \"HttpOnly\");\n if (secure) attrs.push(\"Secure\");\n attrs.push(\"SameSite=Lax\");\n return attrs.join(\"; \");\n}\n","import type { AuthState } from \"./parsers.js\";\n\n/*\n * The request's session handle. Loaders, actions and the api client only mutate it; the server\n * layer commits it once through the store. `auth` and everything else are tracked apart because\n * they live in different cookies: a response that only takes a flash must never rewrite the tokens.\n */\n\n/**\n * Validates the app cookie; `null` means \"no app data\". The app's zod schema fits behind it.\n *\n * @example\n * const appSchema: SessionSchema<{ theme?: string }> = {\n * parse: (input) => (isThemeObject(input) ? input : null),\n * };\n */\nexport interface SessionSchema<T> {\n /** Returns the validated app data, or null when `input` is not what the app stored. May throw: that counts as null. */\n parse(input: unknown): T | null;\n}\n\n/**\n * The app's own session fields plus the SDK-owned `auth`.\n *\n * @example\n * type App = { flash?: string };\n * const data: SessionData<App> = store.read(request).data;\n * data.flash; data.auth?.user.id;\n */\nexport type SessionData<App extends object> = Omit<App, \"auth\"> & { auth?: AuthState | undefined };\n\n/**\n * One request's session.\n *\n * @example\n * const session = store.read(request);\n * session.update({ flash: { kind: \"success\", message: \"Tersimpan\" } });\n * session.update({ auth: undefined }); // sign out, the app data stays\n * const setCookies = store.commit(session);\n */\nexport interface SessionHandle<App extends object> {\n /** The current session: the app's fields and `auth` when signed in. */\n readonly data: Readonly<SessionData<App>>;\n /** True when anything has to be written back. */\n readonly dirty: boolean;\n /** Auth changed (login, refresh, logout, destroy). Never set by a key migration alone. */\n readonly authDirty: boolean;\n /** Anything but auth changed, or the app cookie was opened with a retiring secret. */\n readonly restDirty: boolean;\n /** A key given as `undefined` is deleted (works under exactOptionalPropertyTypes). */\n update(patch: { [K in keyof SessionData<App>]?: SessionData<App>[K] | undefined }): void;\n /** Deletes one key; nothing happens when it is absent. */\n unset(key: keyof SessionData<App>): void;\n /** Empties the session; the next commit expires its cookies. */\n destroy(): void;\n}\n\ntype Bag = Record<string, unknown>;\n\n/** `bag` without the keys `drop` selects, as a new object. */\nconst without = (bag: Bag, drop: (key: string, value: unknown) => boolean): Bag =>\n Object.fromEntries(Object.entries(bag).filter(([key, value]) => !drop(key, value)));\n\n/**\n * Opens a handle over `data` (never mutated) with its initial dirty flags.\n *\n * @example\n * const session = createSessionHandle<{ flash?: string }>({}, false, false);\n * session.update({ flash: \"hi\" });\n * session.restDirty; // true\n */\nexport function createSessionHandle<App extends object>(\n data: SessionData<App>,\n authDirty: boolean,\n restDirty: boolean,\n): SessionHandle<App> {\n let bag: Bag = { ...data };\n let auth = authDirty;\n let rest = restDirty;\n return {\n get data() {\n return bag as Readonly<SessionData<App>>;\n },\n get dirty() {\n return auth || rest;\n },\n get authDirty() {\n return auth;\n },\n get restDirty() {\n return rest;\n },\n update(patch) {\n const changes: Bag = { ...patch };\n // Compared by value: storing the tokens that were only read must not rewrite the auth cookie.\n if (\n Object.hasOwn(changes, \"auth\") &&\n JSON.stringify(changes[\"auth\"]) !== JSON.stringify(bag[\"auth\"])\n ) {\n auth = true;\n }\n if (Object.keys(changes).some((key) => key !== \"auth\")) rest = true;\n bag = without({ ...bag, ...changes }, (_key, value) => value === undefined);\n },\n unset(key) {\n if (!Object.hasOwn(bag, key)) return;\n bag = without(bag, (candidate) => candidate === key);\n if (key === \"auth\") auth = true;\n else rest = true;\n },\n destroy() {\n bag = {};\n auth = true;\n rest = true;\n },\n };\n}\n","import type { OidcTransaction } from \"../core/types.js\";\n\n/*\n * What a session cookie may hold, checked on every read. Hand-written equivalents of the zod\n * schemas both apps use (no zod dependency): unknown keys are stripped, a wrong-shaped value is\n * null, and nothing here throws or reports the value it refused. Caps: tokens 4096 chars, other\n * strings 512.\n */\n\n/**\n * The signed-in user as the session keeps it.\n *\n * @example\n * const user: SessionUser = { id: claims.sub, name: claims.name ?? \"\", email: claims.email ?? null, avatar_url: null };\n */\nexport interface SessionUser {\n /** The app's id of the user, usually the ID token `sub`. 1 to 512 characters. */\n id: string;\n /** Display name, at most 512 characters; may be empty. */\n name: string;\n /** Stored by plasgos-shipping-v2 (`null` when unknown); absent in plasgos-accounts-v2. */\n email?: string | null | undefined;\n /** Picture URL, or null. */\n avatar_url: string | null;\n}\n\n/**\n * The tokens and the user of a signed-in session.\n *\n * @example\n * session.update({\n * auth: {\n * access_token: tokens.access_token,\n * refresh_token: tokens.refresh_token,\n * expires_at: accessTokenExpiry(tokens, Date.now()),\n * user: { id: claims.sub, name: \"Budi\", email: null, avatar_url: null },\n * id_token: tokens.id_token,\n * },\n * });\n */\nexport interface AuthState {\n /** 1 to 4096 characters. */\n access_token: string;\n /** 1 to 4096 characters; absent for a client without refresh tokens. */\n refresh_token?: string | undefined;\n /** Epoch seconds. */\n expires_at: number;\n /** The signed-in user. */\n user: SessionUser;\n /** Kept in its own cookie (idToken), only for the logout ticket / id_token_hint. */\n id_token?: string | undefined;\n /** Epoch seconds of the login, kept across refreshes. */\n auth_time?: number | undefined;\n /** Remember-me (accounts); drives authMaxAgeSeconds when it is a function. */\n remember?: boolean | undefined;\n}\n\nconst TOKEN_MAX = 4096;\nconst TEXT_MAX = 512;\n\n/** A JSON object (not null, not an array), read through own properties only. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst own = (record: Record<string, unknown>, key: string): unknown =>\n Object.hasOwn(record, key) ? record[key] : undefined;\n\nconst isToken = (value: unknown): value is string =>\n typeof value === \"string\" && value.length >= 1 && value.length <= TOKEN_MAX;\n\nconst isText = (value: unknown): value is string =>\n typeof value === \"string\" && value.length <= TEXT_MAX;\n\nconst isRequiredText = (value: unknown): value is string => isText(value) && value.length >= 1;\n\n/** An integer >= 0 (epoch seconds or milliseconds, or a duration). */\nconst isCount = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n\nfunction parseUser(input: unknown): SessionUser | null {\n if (!isRecord(input)) return null;\n const id = own(input, \"id\");\n const name = own(input, \"name\");\n const email = own(input, \"email\");\n const avatar = own(input, \"avatar_url\");\n if (!isRequiredText(id) || !isText(name)) return null;\n if (email !== undefined && email !== null && !isText(email)) return null;\n if (avatar !== null && !isText(avatar)) return null;\n return { id, name, ...(email !== undefined ? { email } : {}), avatar_url: avatar };\n}\n\nfunction parseAuthState(input: unknown): AuthState | null {\n if (!isRecord(input)) return null;\n const accessToken = own(input, \"access_token\");\n const refreshToken = own(input, \"refresh_token\");\n const expiresAt = own(input, \"expires_at\");\n const authTime = own(input, \"auth_time\");\n const remember = own(input, \"remember\");\n const user = parseUser(own(input, \"user\"));\n if (!isToken(accessToken) || !isCount(expiresAt) || user === null) return null;\n if (refreshToken !== undefined && !isToken(refreshToken)) return null;\n if (authTime !== undefined && !isCount(authTime)) return null;\n if (remember !== undefined && typeof remember !== \"boolean\") return null;\n return {\n access_token: accessToken,\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n expires_at: expiresAt,\n ...(remember !== undefined ? { remember } : {}),\n user,\n ...(authTime !== undefined ? { auth_time: authTime } : {}),\n };\n}\n\n/**\n * The auth cookie: `{ auth?: … }` with long keys. `{}` when the object has no `auth`, null when the\n * shape is wrong. `id_token` is stripped: it lives in its own cookie.\n *\n * @example\n * parseAuthPart({ auth: { access_token: \"…\", expires_at: 1767225600, user: { id: \"u\", name: \"\", avatar_url: null } } });\n */\nexport function parseAuthPart(input: unknown): { auth?: AuthState } | null {\n if (!isRecord(input)) return null;\n const raw = own(input, \"auth\");\n if (raw === undefined) return {};\n const auth = parseAuthState(raw);\n return auth === null ? null : { auth };\n}\n\n/**\n * The idToken cookie: `{ id_token }`, 1 to 4096 chars.\n *\n * @example\n * parseIdTokenPart({ id_token: \"eyJ…\" }); // { id_token: \"eyJ…\" }\n */\nexport function parseIdTokenPart(input: unknown): { id_token: string } | null {\n if (!isRecord(input)) return null;\n const idToken = own(input, \"id_token\");\n return isToken(idToken) ? { id_token: idToken } : null;\n}\n\n/**\n * The transaction cookie (long keys, never compacted). Accepts accounts' `reauth` and the SDK's\n * `max_age`; unknown keys are stripped.\n *\n * @example\n * parseTransaction({ state, nonce, code_verifier, return_to: \"/\", created_at: Date.now() });\n */\nexport function parseTransaction(input: unknown): OidcTransaction | null {\n if (!isRecord(input)) return null;\n const state = own(input, \"state\");\n const nonce = own(input, \"nonce\");\n const codeVerifier = own(input, \"code_verifier\");\n const returnTo = own(input, \"return_to\");\n const createdAt = own(input, \"created_at\");\n const reauth = own(input, \"reauth\");\n const maxAge = own(input, \"max_age\");\n if (!isRequiredText(state) || !isRequiredText(nonce) || !isRequiredText(codeVerifier)) return null;\n if (!isText(returnTo) || !isCount(createdAt)) return null;\n if (reauth !== undefined && typeof reauth !== \"boolean\") return null;\n if (maxAge !== undefined && !isCount(maxAge)) return null;\n return {\n state,\n nonce,\n code_verifier: codeVerifier,\n return_to: returnTo,\n created_at: createdAt,\n ...(reauth !== undefined ? { reauth } : {}),\n ...(maxAge !== undefined ? { max_age: maxAge } : {}),\n };\n}\n","import type { TokenSet } from \"@plasgos/auth-shared\";\n\n/*\n * Single-flight refresh. Plasgos rotates the refresh token on every use, so a second refresh with\n * the same token looks like reuse and revokes the whole grant. Parallel requests of one session\n * therefore share one refresh, and a request that still carries the old token shortly after the\n * rotation gets the same result. Ported from the refresh lock of plasgos-shipping-v2 and\n * plasgos-accounts-v2. This module has no module-level state: the map belongs to the store that\n * `memoryLockStore()` returns.\n */\n\n/**\n * Where the client keeps refreshes in flight. The key is the SHA-256 of the refresh token, never\n * the token itself. Implement it over a shared store to hold the lock across several instances.\n *\n * @example\n * const redisLock: RefreshLockStore = {\n * run: (key, refresh, reuseMs) => runOnceAcrossInstances(redis, key, refresh, reuseMs),\n * };\n * const client = createOidcClient({ ...options, refreshLock: redisLock });\n */\nexport interface RefreshLockStore {\n /**\n * Runs `refresh` at most once per key among callers sharing this store and gives every caller the same result.\n * A fulfilled result is reused for `reuseMs`; a rejection is not cached.\n */\n run(key: string, refresh: () => Promise<TokenSet>, reuseMs: number): Promise<TokenSet>;\n}\n\ninterface LockEntry {\n promise: Promise<TokenSet>;\n reuseMs: number;\n settledAt?: number;\n}\n\n/**\n * The default lock store: a map in this process, so it only holds within one instance.\n *\n * @example\n * const client = createOidcClient({ ...options, refreshLock: memoryLockStore() });\n */\nexport function memoryLockStore(options: { now?: (() => number) | undefined } = {}): RefreshLockStore {\n const now = options.now ?? Date.now;\n const locks = new Map<string, LockEntry>();\n\n return {\n run(key, refresh, reuseMs) {\n const t = now();\n for (const [storedKey, entry] of locks) {\n if (entry.settledAt !== undefined && t - entry.settledAt >= entry.reuseMs) locks.delete(storedKey);\n }\n const hit = locks.get(key);\n if (hit) return hit.promise;\n\n const entry: LockEntry = { promise: refresh(), reuseMs };\n locks.set(key, entry);\n entry.promise.then(\n () => {\n entry.settledAt = now();\n },\n () => {\n if (locks.get(key) === entry) locks.delete(key);\n },\n );\n return entry.promise;\n },\n };\n}\n","export { deriveKeyRing, openCookie, sealCookie } from \"./cookie-crypto.js\";\nexport type { KeyRing } from \"./cookie-crypto.js\";\nexport type { OidcTransaction } from \"../core/types.js\";\nexport type { SessionData, SessionHandle, SessionSchema } from \"./handle.js\";\nexport type { AuthState, SessionUser } from \"./parsers.js\";\nexport { SessionTooLargeError, createSessionStore } from \"./store.js\";\nexport type { SessionFailureEvent, SessionStore, SessionStoreOptions } from \"./store.js\";\n// The refresh lock is part of the session surface too. The module is stateless:\n// the map belongs to the store `memoryLockStore()` returns, so both entries may bundle it.\nexport { memoryLockStore } from \"../core/refresh-lock.js\";\nexport type { RefreshLockStore } from \"../core/refresh-lock.js\";\n// The class `createSessionStore` throws for its options: the same class as in the other entries.\nexport { ConfigError } from \"@plasgos/auth-shared\";\n"],"mappings":";AAAA,SAAS,gBAAgB,kBAAkB,YAAY,UAAU,mBAAmB;AAUpF,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,SAAS;AAiBf,SAAS,IAAI,QAAwB;AACnC,SAAO,OAAO,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,MAAM;AACnD;AAWO,SAAS,cACd,SACA,QACA,UACS;AACT,QAAM,MAAM,oBAAI,IAAoB;AACpC,MAAI;AACJ,aAAW,UAAU,SAAS;AAC5B,UAAM,MAAM,OAAO;AAAA,MACjB,SAAS,UAAU,OAAO,KAAK,QAAQ,MAAM,GAAG,UAAU,UAAU,MAAM,OAAO,EAAE;AAAA,IACrF;AACA,UAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,WAAW,EAAE,MAAM,GAAG,CAAC;AAC3E,gBAAY,EAAE,KAAK,IAAI;AACvB,QAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAK,GAAG;AAAA,EACrC;AACA,MAAI,YAAY,OAAW,OAAM,IAAI,MAAM,gDAAgD;AAC3F,SAAO,EAAE,SAAS,IAAI;AACxB;AAUO,SAAS,WAAW,QAAgB,OAAgB,MAAuB;AAChF,QAAM,KAAK,YAAY,QAAQ;AAC/B,QAAM,SAAS,eAAe,eAAe,KAAK,QAAQ,KAAK,EAAE;AACjE,SAAO,OAAO,IAAI,MAAM,CAAC;AACzB,QAAM,KAAK,OAAO,OAAO,CAAC,OAAO,OAAO,KAAK,UAAU,KAAK,GAAG,MAAM,GAAG,OAAO,MAAM,CAAC,CAAC;AACvF,QAAM,MAAM,OAAO,WAAW;A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ConfigError"]}
@@ -0,0 +1,375 @@
1
+ import { Environment, OidcErrorReason, TokenSet, IdTokenClaims, UserScope, ClientProfile } from '@plasgos/auth-shared';
2
+
3
+ /**
4
+ * The step of the SDK that failed.
5
+ *
6
+ * @example
7
+ * if (event.operation === "refresh" && event.reason === "config_invalid") alertOps(event);
8
+ */
9
+ type OidcOperation = "callback" | "token" | "refresh" | "revocation" | "logout_ticket" | "service_token" | "service_request";
10
+ /**
11
+ * One failure, as the `onFailure` hook receives it. It never holds a token, code, secret, body or
12
+ * query string.
13
+ *
14
+ * @example
15
+ * const onFailure = (event: OidcFailureEvent) => {
16
+ * logger.error(`login failed: ${event.operation} ${event.reason} request_id=${event.requestId ?? "-"}`);
17
+ * };
18
+ */
19
+ interface OidcFailureEvent {
20
+ /** The `environment` of the client that failed. */
21
+ environment: Environment;
22
+ /** The step that failed. */
23
+ operation: OidcOperation;
24
+ /** The same reason an `OidcError` of this failure carries. */
25
+ reason: OidcErrorReason;
26
+ /** HTTP method of the call that failed, or null. */
27
+ method: string | null;
28
+ /** Path of the call that failed, without query string or fragment, or null. */
29
+ path: string | null;
30
+ /** HTTP status of the provider's answer; null when there was none. */
31
+ status: number | null;
32
+ /** `x-request-id` of the provider's answer, or null. */
33
+ requestId: string | null;
34
+ /** The `error` code the provider answered with, or null. */
35
+ providerError: string | null;
36
+ }
37
+
38
+ /**
39
+ * Where the client keeps refreshes in flight. The key is the SHA-256 of the refresh token, never
40
+ * the token itself. Implement it over a shared store to hold the lock across several instances.
41
+ *
42
+ * @example
43
+ * const redisLock: RefreshLockStore = {
44
+ * run: (key, refresh, reuseMs) => runOnceAcrossInstances(redis, key, refresh, reuseMs),
45
+ * };
46
+ * const client = createOidcClient({ ...options, refreshLock: redisLock });
47
+ */
48
+ interface RefreshLockStore {
49
+ /**
50
+ * Runs `refresh` at most once per key among callers sharing this store and gives every caller the same result.
51
+ * A fulfilled result is reused for `reuseMs`; a rejection is not cached.
52
+ */
53
+ run(key: string, refresh: () => Promise<TokenSet>, reuseMs: number): Promise<TokenSet>;
54
+ }
55
+ /**
56
+ * The default lock store: a map in this process, so it only holds within one instance.
57
+ *
58
+ * @example
59
+ * const client = createOidcClient({ ...options, refreshLock: memoryLockStore() });
60
+ */
61
+ declare function memoryLockStore(options?: {
62
+ now?: (() => number) | undefined;
63
+ }): RefreshLockStore;
64
+
65
+ /**
66
+ * One login in progress: what `startLogin` creates, the transaction cookie carries, and
67
+ * `handleCallback` checks the provider's answer against.
68
+ *
69
+ * @example
70
+ * const tx: OidcTransaction = {
71
+ * state, nonce, code_verifier,
72
+ * return_to: "/packages",
73
+ * created_at: Date.now(),
74
+ * };
75
+ */
76
+ interface OidcTransaction {
77
+ /** Random value the callback must return unchanged. */
78
+ state: string;
79
+ /** Random value the ID token must carry. */
80
+ nonce: string;
81
+ /** PKCE verifier, sent with the code exchange. */
82
+ code_verifier: string;
83
+ /** Where the app sends the user after the callback; the app validates it. */
84
+ return_to: string;
85
+ /** Epoch milliseconds. */
86
+ created_at: number;
87
+ /** The login re-authenticates a signed-in user (`prompt=login`). */
88
+ reauth?: boolean | undefined;
89
+ /** The `max_age` sent to the provider, in seconds. */
90
+ max_age?: number | undefined;
91
+ }
92
+ /**
93
+ * The `fetch` the SDK calls: always with a string URL and a `RequestInit`.
94
+ *
95
+ * @example
96
+ * const tracedFetch: OidcFetch = (input, init) => fetch(input, { ...init, headers: withTraceId(init.headers) });
97
+ * const client = createOidcClient({ ...options, fetch: tracedFetch });
98
+ */
99
+ type OidcFetch = (input: string, init: RequestInit) => Promise<Response>;
100
+ /**
101
+ * Options of `createOidcClient`. Values usually come from `process.env`; every problem is reported
102
+ * at once in one `ConfigError`, by field name and never by value.
103
+ *
104
+ * @example
105
+ * const options: OidcClientOptions = {
106
+ * environment: "production",
107
+ * issuer: "https://accounts.plasgos.co.id",
108
+ * backchannelUrl: process.env.PLASGOS_BACKCHANNEL_URL,
109
+ * clientId: process.env.PLASGOS_LOGIN_CLIENT_ID ?? "",
110
+ * clientSecret: process.env.PLASGOS_LOGIN_CLIENT_SECRET ?? "",
111
+ * redirectUri: "https://kirim.plasgos.co.id/auth/callback",
112
+ * scopes: ["openid", "profile", "email", "packages:read", "packages:write"],
113
+ * profile: "first-party",
114
+ * resource: "https://api.plasgos.co.id/packages",
115
+ * };
116
+ */
117
+ interface OidcClientOptions {
118
+ /** `"sandbox"` or `"production"`; checked against `issuer`, `resource` and `backchannelUrl`. */
119
+ environment: Environment;
120
+ /** Bare origin of the provider: browser URLs and the exact `iss` value. */
121
+ issuer: string;
122
+ /** Internal Plasgos server origin for the token, revocation and logout-ticket calls; `http:` allowed. Default: `issuer`. */
123
+ backchannelUrl?: string | undefined;
124
+ /** Client id of the interactive (login) client. */
125
+ clientId: string;
126
+ /** Sent only as `client_secret_basic`. */
127
+ clientSecret: string;
128
+ /** Registered callback URL, exact. `https:` unless `allowInsecureHttp`. */
129
+ redirectUri: string;
130
+ /** Registered post-logout URL, same scheme rule. */
131
+ postLogoutRedirectUri?: string | undefined;
132
+ /** Must include `"openid"`. */
133
+ scopes: readonly UserScope[];
134
+ /** `"first-party"`: an app of Plasgos itself. `"third-party"`: any other app. */
135
+ profile: ClientProfile;
136
+ /** Resource indicator (audience); required by `account:*` / `packages:*`, refused for `"third-party"`. */
137
+ resource?: string | undefined;
138
+ /**
139
+ * Mint a logout ticket at logout. Default: `true` for first-party with `endSession: "redirect"`
140
+ * and a `backchannelUrl`, otherwise `false`. An explicit `true` requires `backchannelUrl`.
141
+ */
142
+ logoutTicket?: boolean | undefined;
143
+ /** `"redirect"` (default, a GET URL) or `"form-post"` (only for an app on the issuer's own origin). */
144
+ endSession?: "redirect" | "form-post" | undefined;
145
+ /** ID token claims returned in `claims.extra`, for example `["plasgos_public_id"]`. */
146
+ extraClaims?: readonly string[] | undefined;
147
+ /** Sandbox only: `http:` for the issuer, redirect and post-logout URLs. */
148
+ allowInsecureHttp?: boolean | undefined;
149
+ /** Per call, body read included: integers from 1 to 60000. Defaults 10000 and 3000. */
150
+ timeouts?: {
151
+ tokenMs?: number | undefined;
152
+ logoutMs?: number | undefined;
153
+ } | undefined;
154
+ /** Default: the global `fetch`. */
155
+ fetch?: OidcFetch | undefined;
156
+ /** Single-flight store for refresh. Default: one `memoryLockStore()` per client. */
157
+ refreshLock?: RefreshLockStore | undefined;
158
+ /** Called once per failure, thrown or swallowed. Exceptions it throws are swallowed. */
159
+ onFailure?: ((event: OidcFailureEvent) => void) | undefined;
160
+ }
161
+ /**
162
+ * Input of `client.startLogin`.
163
+ *
164
+ * @example
165
+ * client.startLogin({ returnTo: "/orders", prompt: "login", maxAge: 0, reauth: true });
166
+ */
167
+ interface StartLoginInput {
168
+ /** Already sanitised by the app: starts with one "/", at most 512 chars. */
169
+ returnTo: string;
170
+ /** OIDC `prompt`: `"login"` forces a new login. */
171
+ prompt?: "login" | "consent" | "none" | undefined;
172
+ /** Seconds; OIDC max_age. */
173
+ maxAge?: number | undefined;
174
+ /** OIDC `login_hint`, at most 512 characters. */
175
+ loginHint?: string | undefined;
176
+ /** Marks a step-up login; returned by handleCallback for the app's subject check. */
177
+ reauth?: boolean | undefined;
178
+ /** Epoch ms, for tests. */
179
+ now?: number | undefined;
180
+ }
181
+ /**
182
+ * Where to send the browser, and the transaction to seal into the transaction cookie.
183
+ *
184
+ * @example
185
+ * const { location, transaction } = client.startLogin({ returnTo: "/" });
186
+ * headers.append("Set-Cookie", store.commitTransaction(transaction));
187
+ * headers.set("Location", location);
188
+ * return new Response(null, { status: 302, headers });
189
+ */
190
+ interface StartLoginResult {
191
+ /** The authorization URL on the issuer to redirect the browser to. */
192
+ location: string;
193
+ /** To be sealed with `store.commitTransaction` and read back at the callback. */
194
+ transaction: OidcTransaction;
195
+ }
196
+ /**
197
+ * The checked ID token claims, plus the claims named in `extraClaims` (prototype-free, frozen).
198
+ *
199
+ * @example
200
+ * // createOidcClient({ ...options, extraClaims: ["plasgos_public_id"] })
201
+ * const { claims } = await client.handleCallback(request.url, transaction);
202
+ * const publicId = claims.extra["plasgos_public_id"];
203
+ */
204
+ type VerifiedIdTokenClaims = IdTokenClaims & {
205
+ extra: Readonly<Record<string, string | number | boolean>>;
206
+ };
207
+ /**
208
+ * Options of `client.handleCallback`.
209
+ *
210
+ * @example
211
+ * await client.handleCallback(callbackUrl, transaction, { now: Date.UTC(2026, 0, 1) });
212
+ */
213
+ interface HandleCallbackOptions {
214
+ /** Epoch ms, for tests. */
215
+ now?: number | undefined;
216
+ }
217
+ /**
218
+ * What `client.handleCallback` returns: the token set, the checked ID token claims, and the
219
+ * transaction the login started with (`return_to`, `reauth`).
220
+ *
221
+ * @example
222
+ * const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
223
+ * const expiresAt = accessTokenExpiry(tokens, Date.now());
224
+ * return redirect(transaction.return_to);
225
+ */
226
+ interface CallbackResult {
227
+ /** The token set of the code exchange. */
228
+ tokens: TokenSet;
229
+ /** The checked ID token claims. */
230
+ claims: VerifiedIdTokenClaims;
231
+ /** The transaction the login started with. */
232
+ transaction: OidcTransaction;
233
+ }
234
+ /**
235
+ * The part of a stored session `client.ensureFresh` reads and renews. Any object with these fields
236
+ * fits, for example the `AuthState` of `@plasgos/oidc-client/session`.
237
+ *
238
+ * @example
239
+ * const auth: RefreshableAuth = { access_token, refresh_token, expires_at: accessTokenExpiry(tokens, Date.now()) };
240
+ * const fresh = await client.ensureFresh(auth);
241
+ */
242
+ interface RefreshableAuth {
243
+ /** The current access token. */
244
+ access_token: string;
245
+ /** Absent for a client without refresh tokens; then nothing can be renewed. */
246
+ refresh_token?: string | undefined;
247
+ /** Epoch seconds at which the access token expires. */
248
+ expires_at: number;
249
+ }
250
+ /**
251
+ * Options of `client.ensureFresh`.
252
+ *
253
+ * @example
254
+ * // The API answered 401 invalid_token: refresh once, whatever the expiry says.
255
+ * const { auth } = await client.ensureFresh(session.data.auth, { force: true });
256
+ */
257
+ interface EnsureFreshOptions {
258
+ /** Refresh when the access token expires within this many seconds. Default 60. */
259
+ skewSeconds?: number | undefined;
260
+ /** Refresh even if the token looks valid (the API answered 401 invalid_token). Default false. */
261
+ force?: boolean | undefined;
262
+ /** Epoch ms, for tests. */
263
+ now?: number | undefined;
264
+ }
265
+ /**
266
+ * What `client.ensureFresh` returns: the auth to use, and whether it has to be stored again.
267
+ *
268
+ * @example
269
+ * const { auth, changed } = await client.ensureFresh(current);
270
+ * if (changed) session.update({ auth });
271
+ */
272
+ interface EnsureFreshResult<A> {
273
+ /** The input object itself when `changed` is false, a renewed copy otherwise. */
274
+ auth: A;
275
+ /** True when `auth` was renewed and must be stored again. */
276
+ changed: boolean;
277
+ }
278
+ /**
279
+ * Input of `client.logout`: what the session being ended still holds.
280
+ *
281
+ * @example
282
+ * await client.logout({
283
+ * refreshToken: auth?.refresh_token,
284
+ * idToken: auth?.id_token,
285
+ * browser: { clientIp: null, userAgent: request.headers.get("User-Agent") },
286
+ * });
287
+ */
288
+ interface LogoutInput {
289
+ /** Revoked at the provider when given. */
290
+ refreshToken?: string | undefined;
291
+ /** Swapped for a one-time logout ticket, or sent as `id_token_hint` in `"form-post"` mode. */
292
+ idToken?: string | undefined;
293
+ /** The browser's address and agent, forwarded as X-Client-Ip / X-Client-User-Agent when not null. */
294
+ browser?: {
295
+ clientIp: string | null;
296
+ userAgent: string | null;
297
+ } | undefined;
298
+ }
299
+ /**
300
+ * Where `client.logout` sends the browser. `redirect`: a GET URL without any token; `ticket` tells
301
+ * whether the provider will end its session without asking. `form`: the fields of a POST form to
302
+ * `action`, for an app on the issuer's own origin (`endSession: "form-post"`).
303
+ *
304
+ * @example
305
+ * const result = await client.logout({ refreshToken, idToken });
306
+ * if (result.kind === "redirect") return new Response(null, { status: 303, headers: { Location: result.location } });
307
+ * return renderAutoSubmitForm(result.action, result.fields);
308
+ */
309
+ type LogoutResult = {
310
+ kind: "redirect";
311
+ location: string;
312
+ ticket: boolean;
313
+ } | {
314
+ kind: "form";
315
+ action: string;
316
+ fields: Readonly<Record<string, string>>;
317
+ };
318
+ /**
319
+ * What `createOidcClient` returns.
320
+ *
321
+ * @example
322
+ * const { location, transaction } = client.startLogin({ returnTo: "/packages" });
323
+ * headers.append("Set-Cookie", store.commitTransaction(transaction));
324
+ * headers.set("Location", location);
325
+ * return new Response(null, { status: 302, headers });
326
+ */
327
+ interface OidcClient {
328
+ /** The `environment` the client was created with. */
329
+ readonly environment: Environment;
330
+ /** The validated issuer (canonical origin). */
331
+ readonly issuer: string;
332
+ /** The client id the client was created with. */
333
+ readonly clientId: string;
334
+ /** Builds the authorization URL (code + PKCE S256) and its transaction. Throws `TypeError` on a bad input. */
335
+ startLogin(input: StartLoginInput): StartLoginResult;
336
+ /**
337
+ * Checks the callback URL against the transaction, exchanges the code and checks the ID token.
338
+ * Rejects with an `OidcError`; the app clears the transaction cookie on every path.
339
+ *
340
+ * @example
341
+ * const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
342
+ */
343
+ handleCallback(url: URL | string, transaction: OidcTransaction | null, options?: HandleCallbackOptions): Promise<CallbackResult>;
344
+ /**
345
+ * One rotated refresh. Calls with the same refresh token share one request (and its result for
346
+ * 30 s) through the client's `refreshLock`. Rejects with an `OidcError`: `invalid_grant` and
347
+ * `invalid_target` mean the session is over.
348
+ *
349
+ * @example
350
+ * const tokens = await client.refresh(auth.refresh_token);
351
+ */
352
+ refresh(refreshToken: string): Promise<TokenSet>;
353
+ /**
354
+ * Renews `auth` when its access token is about to expire. Never changes `auth` itself. A refresh
355
+ * that fails while the access token still works keeps the current auth (`changed: false`), except
356
+ * for `invalid_grant` and `invalid_target`, which always reject: the app then clears the session.
357
+ *
358
+ * @example
359
+ * const { auth, changed } = await client.ensureFresh(session.data.auth);
360
+ * if (changed) session.update({ auth });
361
+ */
362
+ ensureFresh<A extends RefreshableAuth>(auth: A, options?: EnsureFreshOptions): Promise<EnsureFreshResult<A>>;
363
+ /**
364
+ * Revokes the refresh token and builds the provider's end-session step. Never rejects: a failed
365
+ * back-channel call is one `onFailure` event. The app clears its session cookies itself.
366
+ *
367
+ * @example
368
+ * const result = await client.logout({ refreshToken: auth?.refresh_token, idToken: auth?.id_token });
369
+ * if (result.kind === "redirect") return redirect(result.location, { status: 303, headers });
370
+ */
371
+ logout(input: LogoutInput): Promise<LogoutResult>;
372
+ }
373
+
374
+ export { memoryLockStore as m };
375
+ export type { CallbackResult as C, EnsureFreshOptions as E, HandleCallbackOptions as H, LogoutInput as L, OidcClientOptions as O, RefreshLockStore as R, StartLoginInput as S, VerifiedIdTokenClaims as V, OidcClient as a, EnsureFreshResult as b, LogoutResult as c, OidcFailureEvent as d, OidcFetch as e, OidcOperation as f, OidcTransaction as g, RefreshableAuth as h, StartLoginResult as i };