@cboxdk/id-js 0.13.1 → 0.15.1

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.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AuthorizationRequest, C as CallbackParams, a as CboxIdClient, b as CboxIdConfig, c as CboxUser, D as DiscoveryDocument, R as RefreshedTokens, S as StoreSecretInput, d as StoredAuthState, T as TokenResponse, e as TokenTypeHint, V as VaultClient, f as VaultLease, g as VaultSecretRef, h as VerifyWebhookOptions, v as verifyWebhook } from './client-DD5HZzmO.cjs';
1
+ export { A as AuthorizationRequest, C as CallbackParams, a as CboxIdClient, b as CboxIdConfig, c as CboxUser, D as DiscoveryDocument, R as RefreshedTokens, S as StoreSecretInput, d as StoredAuthState, T as TokenResponse, e as TokenTypeHint, V as VaultClient, f as VaultLease, g as VaultSecretRef, h as VerifyWebhookOptions, v as verifyWebhook } from './client-CecDIu_N.cjs';
2
2
 
3
3
  /**
4
4
  * The handler on YOUR side of a legacy migration.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AuthorizationRequest, C as CallbackParams, a as CboxIdClient, b as CboxIdConfig, c as CboxUser, D as DiscoveryDocument, R as RefreshedTokens, S as StoreSecretInput, d as StoredAuthState, T as TokenResponse, e as TokenTypeHint, V as VaultClient, f as VaultLease, g as VaultSecretRef, h as VerifyWebhookOptions, v as verifyWebhook } from './client-DD5HZzmO.js';
1
+ export { A as AuthorizationRequest, C as CallbackParams, a as CboxIdClient, b as CboxIdConfig, c as CboxUser, D as DiscoveryDocument, R as RefreshedTokens, S as StoreSecretInput, d as StoredAuthState, T as TokenResponse, e as TokenTypeHint, V as VaultClient, f as VaultLease, g as VaultSecretRef, h as VerifyWebhookOptions, v as verifyWebhook } from './client-CecDIu_N.js';
2
2
 
3
3
  /**
4
4
  * The handler on YOUR side of a legacy migration.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { ConfigurationError, FrontendApiError, Discovery, AuthenticationError } from './chunk-4WSQUORS.js';
2
- export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, FrontendApiError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook } from './chunk-4WSQUORS.js';
1
+ import { ConfigurationError, assertSecureIssuer, FrontendApiError, Discovery, AuthenticationError } from './chunk-3V6OKRWF.js';
2
+ export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, FrontendApiError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook } from './chunk-3V6OKRWF.js';
3
3
 
4
4
  // src/legacy.ts
5
5
  function createLegacyVerifier(options) {
@@ -114,6 +114,7 @@ var CboxIdFrontend = class {
114
114
  if (!options.issuer) {
115
115
  throw new ConfigurationError("issuer is required.");
116
116
  }
117
+ assertSecureIssuer(options.issuer);
117
118
  if (!options.publishableKey?.startsWith("pk_")) {
118
119
  throw new ConfigurationError(
119
120
  "publishableKey must be a pk_test_\u2026 or pk_live_\u2026 key. Client secrets and API keys must never be put in a browser."
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/legacy.ts","../src/frontend.ts","../src/authz.ts"],"names":["key","json"],"mappings":";;;;AAwEO,SAAS,qBAAqB,OAAA,EAAyE;AAC5G,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,SAAS,EAAA,EAAI;AACjD,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAM,SAAA,GAAY,QAAQ,gBAAA,IAAoB,GAAA;AAE9C,EAAA,OAAO,eAAe,OAAO,OAAA,EAAqC;AAGhE,IAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,IAAA,EAAK;AAE/B,IAAA,IAAI,CAAE,MAAM,gBAAA,CAAiB,GAAA,EAAK,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA,EA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IAAU,MAAA,CAAO,MAAA,CAAO,SAAS,EAAA,EAAI;AAC/C,IAAA,MAAM,IAAI,mBAAmB,mGAAmG,CAAA;AAAA,EAClI;AACF","file":"index.js","sourcesContent":["import { ConfigurationError } from './errors.js';\n\n/**\n * The handler on YOUR side of a legacy migration.\n *\n * Cbox ID offers it an email and a password it has never seen, and your code answers with\n * the person or with nothing. On a yes they are created in Cbox ID as a result of the\n * login that just succeeded, and from their next sign-in the old system is never asked\n * again.\n *\n * WHY THIS IS A FACTORY AND NOT A DOCUMENT. The wire format is simple enough to describe\n * in a paragraph — a signed POST, JSON in, JSON out — and describing it would mean every\n * customer writes the signature check themselves. That check is exactly the part people\n * get wrong: `===` instead of a constant-time compare, no freshness window, no thought\n * about replay. So the factory owns all of it and you write the one function that knows\n * your own database.\n *\n * It is deliberately framework-agnostic: it takes a `Request` and returns a `Response`,\n * which is what Next.js route handlers, Remix, Hono, Bun and Deno all speak natively.\n */\n\n/** What your handler answers with. Returning `null` means \"no\", and is not an error. */\nexport interface LegacyUser {\n email: string;\n name?: string | null;\n emailVerified?: boolean;\n /**\n * Your stored hash, when you can expose it.\n *\n * Passing it lets the person keep their password in Cbox ID verbatim — it is stored as\n * is and upgraded to the platform hasher on their next login, exactly like a\n * bulk-imported user. Omit it and Cbox ID hashes the password they just proved they\n * know, which is the honest option when your store cannot hand a hash over.\n */\n passwordHash?: string;\n}\n\nexport interface LegacyVerifierOptions {\n /** The same secret you declared in your manifest, or configured in the console. */\n secret: string;\n /**\n * Decide whether these credentials are good, and say who they belong to.\n *\n * Return `null` for no. THROWING IS NOT THE SAME as returning null: a throw means your\n * store could not decide, and is answered with a 503 so Cbox ID refuses the sign-in\n * rather than treating an outage as a wrong password.\n */\n verify: (email: string, password: string) => Promise<LegacyUser | null>;\n /**\n * How far out of date a request may be, in seconds. Defaults to 300.\n *\n * A window is what makes a captured request stop working. Too wide and a recording is\n * useful for hours; too narrow and ordinary clock skew starts refusing real traffic.\n */\n toleranceSeconds?: number;\n}\n\n/**\n * Build the request handler.\n *\n * ```ts\n * // app/api/cbox-legacy/route.ts\n * export const POST = createLegacyVerifier({\n * secret: process.env.CBOX_LEGACY_SECRET!,\n * async verify(email, password) {\n * const row = await db.users.findByEmail(email)\n * if (!row || !(await argon2.verify(row.password, password))) return null\n * return { email: row.email, name: row.name, emailVerified: !!row.confirmedAt }\n * },\n * })\n * ```\n */\nexport function createLegacyVerifier(options: LegacyVerifierOptions): (request: Request) => Promise<Response> {\n if (!options.secret || options.secret.length < 32) {\n throw new ConfigurationError(\n 'A legacy verifier secret must be at least 32 characters; it is the only thing proving a request came from Cbox ID.',\n );\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n\n return async function handle(request: Request): Promise<Response> {\n // Read once. The signature covers the RAW body, so re-serializing parsed JSON would\n // produce different bytes and every valid request would be refused.\n const raw = await request.text();\n\n if (!(await isSignedByCboxId(raw, request.headers.get('X-Cbox-Signature'), options.secret, tolerance))) {\n // No detail. A caller who cannot sign is not owed help distinguishing \"bad\n // signature\" from \"stale timestamp\" — both mean the same thing to anyone\n // legitimate, and the difference is a hint to anyone else.\n return json({ error: 'unauthorized' }, 401);\n }\n\n let payload: { email?: unknown; password?: unknown };\n\n try {\n payload = JSON.parse(raw) as typeof payload;\n } catch {\n return json({ error: 'invalid_request' }, 400);\n }\n\n const { email, password } = payload;\n\n if (typeof email !== 'string' || email === '') {\n return json({ error: 'invalid_request' }, 400);\n }\n\n // No password means Cbox ID is asking \"do you know this address\" — the tooling path,\n // used for a dry run before cutover. It never reaches here from a sign-in.\n if (typeof password !== 'string') {\n return json({ user: null }, 200);\n }\n\n let user: LegacyUser | null;\n\n try {\n user = await options.verify(email, password);\n } catch {\n // 503, not 401. Your store could not decide, and Cbox ID must refuse the sign-in\n // rather than read an outage as a wrong password — but it should also be able to\n // tell the two apart in its own logs, which a 401 would hide.\n return json({ error: 'unavailable' }, 503);\n }\n\n if (!user) {\n return json({ user: null }, 200);\n }\n\n return json(\n {\n email: user.email,\n name: user.name ?? null,\n email_verified: user.emailVerified === true,\n ...(user.passwordHash ? { password_hash: user.passwordHash } : {}),\n },\n 200,\n );\n };\n}\n\n/**\n * Whether this body was signed by Cbox ID, recently.\n *\n * Both halves matter. The HMAC proves it came from something holding the secret; the\n * freshness window is what stops a captured request working forever. Compared in constant\n * time, because a comparison that returns early leaks how much of a guess was right.\n */\nasync function isSignedByCboxId(\n body: string,\n header: string | null,\n secret: string,\n toleranceSeconds: number,\n): Promise<boolean> {\n if (!header) {\n return false;\n }\n\n const parts: Record<string, string> = {};\n\n for (const piece of header.split(',')) {\n const [key, value] = piece.split('=', 2);\n if (key && value) {\n parts[key.trim()] = value.trim();\n }\n }\n\n const timestamp = parts['t'] ?? '';\n const signature = parts['v1'] ?? '';\n\n if (!/^\\d+$/.test(timestamp) || signature === '') {\n return false;\n }\n\n if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > toleranceSeconds) {\n return false;\n }\n\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n\n const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${body}`));\n const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join('');\n\n return timingSafeEqual(expected, signature);\n}\n\n/** Constant-time string compare. Length is not secret; content is. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let diff = 0;\n\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n\n return diff === 0;\n}\n\nfunction json(body: unknown, status: number): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","import { ConfigurationError, FrontendApiError } from './errors.js';\n\n/**\n * The browser-safe half of the SDK.\n *\n * Everything else in this package assumes a server: it holds a client secret, it exchanges\n * codes, it verifies webhooks. None of that may run in a page, which is why the UI\n * components have always been redirect shells — a page that cannot authenticate itself to\n * the identity provider cannot ask it anything, so it sends the person away and waits.\n *\n * A publishable key changes that. It is public on purpose: it ships in your bundle, it is\n * visible in devtools, and it is safe there because it only works from the origins you\n * registered. What it buys is that a page can read its OWN sign-in configuration — the\n * endpoints, the social buttons, your theme — and render a form itself.\n *\n * This client deliberately has no secret, no token storage and no crypto. It reads two\n * documents. Anything that mints or holds a credential still belongs on your server.\n */\n\n/** How a page identifies itself. Public — put it in your bundle. */\nexport interface FrontendClientOptions {\n /** Your identity provider's origin, e.g. `https://id.acme.com`. */\n issuer: string;\n /** `pk_live_…` or `pk_test_…`. Safe to publish. */\n publishableKey: string;\n /** Abort after this long. Defaults to 10s. */\n timeoutMs?: number;\n /**\n * How many times to retry a transient failure. Defaults to 2 (so three attempts).\n *\n * Only the network and 5xx are retried. A refusal is a configuration problem and\n * retrying it just delays the developer finding out; a 429 is honoured rather than\n * hammered.\n */\n retries?: number;\n /** Injectable for tests and for runtimes with a non-global fetch. */\n fetch?: typeof globalThis.fetch;\n}\n\n/** A social button to draw. Name and provider only — never an internal id. */\nexport interface SocialProvider {\n provider: string;\n name: string;\n}\n\n/** The customer's theme, when they have set one. Absent means \"use your own defaults\". */\nexport interface Appearance {\n preset: string;\n radius: string;\n font: string;\n light: Record<string, string>;\n dark: Record<string, string>;\n}\n\n/** Everything needed to draw a sign-in box, and nothing that identifies anybody. */\nexport interface FrontendConfig {\n mode: 'test' | 'live' | null;\n issuer: string;\n endpoints: {\n authorization: string;\n token: string;\n userinfo: string;\n end_session: string;\n jwks: string;\n };\n social: SocialProvider[];\n appearance?: Appearance;\n}\n\n/** What a sign-in attempt produced. */\nexport type SignInResult =\n | { status: 'ok'; loginTicket: string; expiresIn: number }\n | { status: 'mfa_required'; mfaToken: string }\n | { status: 'otp_required'; mfaToken: string }\n | { status: 'sso_required' }\n | { status: 'invalid' }\n | { status: 'rate_limited'; retryAfter: number | undefined };\n\n/** What a browser needs to ask an authenticator for a passkey assertion. */\nexport interface PasskeyOptions {\n challenge: string;\n /** Carries the challenge to the second request, in place of a session cookie. */\n challenge_token: string;\n rpId: string;\n userVerification: string;\n allowCredentials: unknown[];\n timeout: number;\n}\n\n/** Who the browser is signed in as, or nobody. */\nexport interface FrontendSession {\n user: { id: string; email: string; name: string | null } | null;\n}\n\n/**\n * Reads the public configuration and the current session from a browser.\n *\n * ```ts\n * const frontend = new CboxIdFrontend({\n * issuer: 'https://id.acme.com',\n * publishableKey: 'pk_live_…',\n * })\n *\n * const config = await frontend.config() // cached for you; safe to call per component\n * const { user } = await frontend.session(accessToken)\n * ```\n */\nexport class CboxIdFrontend {\n private readonly issuer: string;\n private readonly publishableKey: string;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n /**\n * The config document, and the in-flight promise for it.\n *\n * Deduplicated rather than merely cached: a page with a sign-in form, a user button and\n * an organization switcher mounts three components in the same tick, and three parallel\n * fetches of the same immutable document is a waste the SDK should absorb rather than\n * ask every consumer to.\n */\n private configPromise: Promise<FrontendConfig> | null = null;\n\n constructor(options: FrontendClientOptions) {\n if (!options.issuer) {\n throw new ConfigurationError('issuer is required.');\n }\n\n // Caught here rather than at the first request, because the failure otherwise arrives\n // as an opaque 401 from the network tab and the cause — a secret key pasted into a\n // browser bundle — is exactly the mistake worth naming out loud.\n if (!options.publishableKey?.startsWith('pk_')) {\n throw new ConfigurationError(\n 'publishableKey must be a pk_test_… or pk_live_… key. Client secrets and API keys must never be put in a browser.',\n );\n }\n\n this.issuer = options.issuer.replace(/\\/$/, '');\n this.publishableKey = options.publishableKey;\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.retries = Math.max(0, options.retries ?? 2);\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /** Whether this key drives real sign-ins. Handy for a \"test mode\" badge in your own UI. */\n get isLive(): boolean {\n return this.publishableKey.startsWith('pk_live_');\n }\n\n /**\n * The public sign-in configuration.\n *\n * Fetched once per client instance. The document is small and changes when somebody\n * edits it in the console, so a long-lived page picks changes up on its next full load\n * rather than mid-session — which is the right trade for something that decides layout.\n */\n async config(): Promise<FrontendConfig> {\n this.configPromise ??= this.get<FrontendConfig>('/frontend/v1/config', {}, isFrontendConfig).catch((error: unknown) => {\n // Cleared so a transient network failure does not poison the instance for the\n // lifetime of the page.\n this.configPromise = null;\n throw error;\n });\n\n return this.configPromise;\n }\n\n /**\n * Who is signed in, given an access token your app already holds.\n *\n * Returns `{ user: null }` rather than throwing when nobody is signed in. That is a\n * state, not an error: a user button renders on pages nobody has signed in on, and\n * making callers treat a rejection as a state is how flash-of-signed-out bugs happen.\n *\n * The publishable key grants nothing here — the token is the entire authority.\n */\n async session(accessToken?: string): Promise<FrontendSession> {\n if (!accessToken) {\n return { user: null };\n }\n\n return this.get<FrontendSession>(\n '/frontend/v1/session',\n { Authorization: `Bearer ${accessToken}` },\n isFrontendSession,\n );\n }\n\n /**\n * Sign in with a password, from a form your page drew.\n *\n * WHAT COMES BACK IS A TICKET, NEVER A TOKEN. Handing tokens to a page that proved a\n * password is the implicit grant, which OAuth 2.1 removes: tokens in a URL, in history,\n * in `Referer`, with no client authentication and no PKCE binding. Spend the ticket by\n * sending the browser to `/oauth/authorize` with your own PKCE challenge and\n * `login_ticket` in the query — the ordinary flow, which then issues an ordinary code.\n *\n * It expires in sixty seconds. It is for one redirect, not for storing.\n *\n * ```ts\n * const result = await frontend.signIn(email, password)\n *\n * if (result.status === 'ok') {\n * window.location.href = `${config.endpoints.authorization}?${new URLSearchParams({\n * client_id, redirect_uri, response_type: 'code', code_challenge, code_challenge_method: 'S256',\n * login_ticket: result.loginTicket,\n * })}`\n * }\n * ```\n *\n * EVERY REFUSAL IS THE SAME REFUSAL. `invalid` covers a wrong password, an unknown\n * address and a locked account, because distinguishing them is the enumeration oracle\n * the server refuses to build — do not present them differently in your UI either.\n */\n async signIn(email: string, password: string): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in', { email, password });\n\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('Retry-After') ?? '');\n\n return { status: 'rate_limited', retryAfter: Number.isFinite(retryAfter) ? retryAfter : undefined };\n }\n\n let body: { status?: string; login_ticket?: string; mfa_token?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n if (body.status === 'ok' && typeof body.login_ticket === 'string') {\n return { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 };\n }\n\n if ((body.status === 'mfa_required' || body.status === 'otp_required') && typeof body.mfa_token === 'string') {\n return { status: body.status, mfaToken: body.mfa_token };\n }\n\n if (body.status === 'sso_required') {\n return { status: 'sso_required' };\n }\n\n return { status: 'invalid' };\n }\n\n /**\n * Finish a sign-in that owed a second factor.\n *\n * The token from `signIn()` carries the pending state, because a cross-origin page has\n * no session cookie to carry it in. A TOTP code or a recovery code both work — an\n * embedded form that could not accept a recovery code would strand exactly the people\n * that escape hatch exists for.\n *\n * A wrong code costs an attempt, not the sign-in: five are allowed before the token\n * dies and the person starts from the password again.\n */\n async submitSecondFactor(mfaToken: string, code: string, method: 'mfa' | 'otp' = 'mfa'): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in/factor', { mfa_token: mfaToken, code, method });\n\n let body: { status?: string; login_ticket?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n return body.status === 'ok' && typeof body.login_ticket === 'string'\n ? { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 }\n : { status: 'invalid' };\n }\n\n /**\n * The WebAuthn options for a passkey sign-in, and the handle that carries the challenge.\n *\n * The handle exists because a cross-origin page has no session cookie to keep the\n * challenge in between the two requests WebAuthn needs. Pass it back to\n * {@link signInWithPasskey} with whatever `navigator.credentials.get()` returns.\n *\n * `allowCredentials` comes back empty on purpose: this is a discoverable-credential\n * flow, so the authenticator offers whichever passkey it holds and the page never has to\n * say who is signing in — asking for an email first, to look up which credentials exist,\n * would be an enumeration oracle.\n */\n async passkeyOptions(): Promise<PasskeyOptions> {\n const response = await this.post('/frontend/v1/sign-in/passkey/options', {});\n\n if (!response.ok) {\n throw new FrontendApiError(\n `Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list.`,\n 'origin_not_allowed',\n response.status,\n );\n }\n\n return (await response.json()) as PasskeyOptions;\n }\n\n /**\n * Complete a passkey sign-in with the assertion the authenticator produced.\n *\n * `assertion` is the credential from `navigator.credentials.get()`, serialised — the\n * server verifies the raw body, so pass it through unchanged rather than rebuilding it.\n */\n async signInWithPasskey(challengeToken: string, assertion: Record<string, unknown>): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in/passkey', { ...assertion, challenge_token: challengeToken });\n\n let body: { status?: string; login_ticket?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n return body.status === 'ok' && typeof body.login_ticket === 'string'\n ? { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 }\n : { status: 'invalid' };\n }\n\n private async post(path: string, payload: Record<string, unknown>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n return await this.fetchImpl(`${this.issuer}${path}`, {\n method: 'POST',\n headers: {\n 'X-Cbox-Publishable-Key': this.publishableKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n } catch {\n throw new FrontendApiError(\n `Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list — a refused request fails as a network error by design.`,\n 'unavailable',\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async get<T>(\n path: string,\n extraHeaders: Record<string, string> = {},\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= this.retries; attempt++) {\n // Linear, not exponential, and only between attempts. This sits inside a page\n // render: a caller waiting on their sign-in box would rather fail in a second than\n // succeed in eight.\n if (attempt > 0) {\n await new Promise((resolve) => setTimeout(resolve, 150 * attempt));\n }\n\n try {\n return await this.attempt<T>(path, extraHeaders, validate);\n } catch (error) {\n lastError = error;\n\n // Retry only what a retry can fix. A refusal is a configuration problem and\n // retrying it delays the developer finding out; a rate limit is honoured rather\n // than hammered; a malformed body will be malformed again.\n if (!(error instanceof FrontendApiError) || error.code !== 'unavailable') {\n throw error;\n }\n }\n }\n\n throw lastError;\n }\n\n private async attempt<T>(\n path: string,\n extraHeaders: Record<string, string>,\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n\n try {\n response = await this.fetchImpl(`${this.issuer}${path}`, {\n headers: {\n // A header, never a query string: a query string puts the key in server logs,\n // in `Referer` on every outbound link, and in browser history.\n 'X-Cbox-Publishable-Key': this.publishableKey,\n Accept: 'application/json',\n ...extraHeaders,\n },\n signal: controller.signal,\n });\n } catch (cause) {\n // Includes the abort on timeout, and — in a browser — a refusal, because a refused\n // request deliberately carries no CORS headers and so never becomes a Response.\n throw new FrontendApiError(\n `Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list — a refused request fails as a network error by design.`,\n 'unavailable',\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('Retry-After') ?? '');\n\n throw new FrontendApiError(\n (await described(response)) ?? 'Cbox ID is rate limiting this key.',\n 'rate_limited',\n 429,\n Number.isFinite(retryAfter) ? retryAfter : undefined,\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new FrontendApiError(\n // THE SERVER'S OWN REASON FIRST. It answers precisely — \"No publishable key was\n // presented\" is a different problem from \"That publishable key cannot be used\n // from this origin\" — and substituting a guess for it made this client less\n // precise than the API it wraps. The fallback still stands for the browser case,\n // where a refusal never becomes a readable Response at all.\n (await described(response)) ??\n `Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list, and that the key is not revoked.`,\n 'origin_not_allowed',\n response.status,\n );\n }\n\n if (!response.ok) {\n throw new FrontendApiError(\n (await described(response)) ?? `Cbox ID returned ${response.status}.`,\n 'unavailable',\n response.status,\n );\n }\n\n let body: unknown;\n\n try {\n body = await response.json();\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n // A 200 whose body is not the document we expect means something between the page and\n // us is rewriting responses — a proxy, an extension, a captive portal. Caught here so\n // it surfaces as that, rather than as `undefined` deep inside somebody's component.\n if (validate && !validate(body)) {\n throw new FrontendApiError(\n 'Cbox ID returned a body that is not the expected document.',\n 'malformed',\n response.status,\n );\n }\n\n return body as T;\n }\n}\n\n/**\n * The server's own `error_description`, when it sent one.\n *\n * Read from a CLONE: the caller may still want the body, and a Response body can only be\n * consumed once — a helper that quietly drained it would turn a precise error into a\n * different, stranger one.\n */\nasync function described(response: Response): Promise<string | undefined> {\n try {\n const body: unknown = await response.clone().json();\n\n if (typeof body === 'object' && body !== null && 'error_description' in body) {\n const description = (body as { error_description: unknown }).error_description;\n\n return typeof description === 'string' && description !== '' ? description : undefined;\n }\n } catch {\n // A refusal without a readable body is the normal case in a browser.\n }\n\n return undefined;\n}\n\n/** The shape check for the config document. Structural, not exhaustive. */\nfunction isFrontendConfig(body: unknown): body is FrontendConfig {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n\n const doc = body as Partial<FrontendConfig>;\n\n return typeof doc.issuer === 'string' && typeof doc.endpoints === 'object' && doc.endpoints !== null;\n}\n\n/** The shape check for the session document. `user: null` is valid and expected. */\nfunction isFrontendSession(body: unknown): body is FrontendSession {\n return typeof body === 'object' && body !== null && 'user' in body;\n}\n","import { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\n/**\n * A permission your app declares. `key` is a `feature:action` slug (e.g.\n * `invoices:create`); `description` is human-facing copy for the Cbox ID console.\n */\nexport interface PermissionDefinition {\n key: string;\n description?: string;\n}\n\n/**\n * A role your app declares. `permissions` lists the permission keys the role\n * grants — each must reference a declared {@link PermissionDefinition}.\n */\nexport interface RoleDefinition {\n key: string;\n name: string;\n description?: string;\n permissions: string[];\n}\n\n/**\n * The roles + permissions an app declares in code. Either list may be omitted.\n * Pass this to {@link defineAuthz} (to validate up front) or straight to\n * {@link buildManifest} / {@link publishManifest}.\n */\nexport interface AuthzDeclaration {\n permissions?: PermissionDefinition[];\n roles?: RoleDefinition[];\n /**\n * Where this app's OLD login lives, while you are migrating off it.\n *\n * Declared here for the same reason roles are: it is a fact about the app, it belongs\n * with the deploy, and the alternative is a URL pasted into a console and a secret\n * pasted into an env file that quietly disagree six weeks later.\n *\n * IT DOES NOT TAKE EFFECT ON ITS OWN. Unlike a role — which affects only the app that\n * declared it — this names a URL that every unknown email and the password typed with\n * it will be offered to, on the environment's whole sign-in path. So it arrives as a\n * proposal and an operator has to approve it in the console. Changing the url later\n * drops that approval, on purpose.\n */\n legacyLogin?: LegacyLoginDeclaration;\n}\n\n/** Where an app's old login lives. See {@link AuthzDeclaration.legacyLogin}. */\nexport interface LegacyLoginDeclaration {\n /** Must be https — a password in the clear is readable by everything on the path. */\n url: string;\n /** At least 32 characters. It is the only thing proving a request came from Cbox ID. */\n secret: string;\n}\n\n/**\n * The manifest as it is sent to Cbox ID: the declared permissions + roles plus a\n * content-derived `version`, so republishing an unchanged catalog is a no-op.\n */\nexport interface AuthzManifest {\n version: string;\n permissions: PermissionDefinition[];\n roles: RoleDefinition[];\n legacy_login?: LegacyLoginDeclaration;\n}\n\n/** What {@link publishManifest} needs to authenticate the push. */\nexport interface ManifestPublisherConfig {\n /** Base URL (issuer) of the Cbox ID instance — the `token_endpoint` is discovered from it. */\n issuer: string;\n /** Your OAuth client id. The client must hold the `apps.manifest` scope. */\n clientId: string;\n /** Your OAuth client secret. The push uses the client-credentials grant. */\n clientSecret: string;\n /** Timeout (ms) for back-channel HTTP calls. Defaults to `10000`. */\n timeoutMs?: number;\n}\n\n/**\n * The server's sync summary. The named fields are the ones the SDK/CLI reads;\n * the index signature keeps any extra fields the server returns.\n */\nexport interface ManifestSyncSummary {\n unchanged?: boolean;\n roles_declared?: number;\n permissions_declared?: number;\n version?: string;\n [key: string]: unknown;\n}\n\n/**\n * Validate a roles/permissions declaration and return it normalized (both lists\n * always present). Call this where you declare your catalog so mistakes — a role\n * that grants an undeclared permission, a duplicate key — surface immediately\n * rather than on deploy.\n *\n * @throws ConfigurationError on a missing key/name, a duplicate, or a role that\n * references a permission that was never declared.\n */\nexport function defineAuthz(\n declaration: AuthzDeclaration,\n): AuthzDeclaration & { permissions: PermissionDefinition[]; roles: RoleDefinition[] } {\n const permissions = declaration.permissions ?? [];\n const roles = declaration.roles ?? [];\n assertDeclaration(permissions, roles);\n\n // The legacy login is validated here too, so a bad one fails in the deploy that\n // introduced it rather than as a 4xx from a manifest push somebody has to go and read.\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n }\n\n // `Required<>` no longer fits: the catalog is always present after this, and the legacy\n // login legitimately is not. Returning the declaration's own optionality keeps a caller\n // from having to invent an empty one.\n return { ...declaration, permissions, roles };\n}\n\n/**\n * Build the manifest — the declared catalog plus a stable content hash `version`\n * (first 16 hex chars of the sha256 of the canonicalized catalog). The catalog is\n * sorted by key first, so declaration order never changes the version.\n */\nexport async function buildManifest(declaration: AuthzDeclaration): Promise<AuthzManifest> {\n const permissions = (declaration.permissions ?? []).map(canonicalPermission);\n const roles = (declaration.roles ?? []).map(canonicalRole);\n assertDeclaration(permissions, roles);\n\n permissions.sort((a, b) => byteCompare(a.key, b.key));\n roles.sort((a, b) => byteCompare(a.key, b.key));\n\n // The version hashes the CATALOG only, and the legacy login is deliberately outside it:\n // this canonicalization is a cross-SDK contract — id-js, id-python, id-go and the PHP\n // reference all produce the same bytes, and a shared fixture exists to keep them from\n // drifting. The server compares a declared url separately for the same reason.\n const version = (await sha256Hex(canonicalManifestJson(permissions, roles))).slice(0, 16);\n\n const manifest: AuthzManifest = { version, permissions, roles };\n\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n manifest.legacy_login = declaration.legacyLogin;\n }\n\n return manifest;\n}\n\n/**\n * Publish this app's authorization manifest (its declared roles + permissions) to\n * Cbox ID. The app owns what a role means; Cbox ID owns identity and who holds it.\n *\n * It mints a client-credentials token with the `apps.manifest` scope (token\n * endpoint discovered from the issuer's OIDC configuration), then POSTs the\n * manifest to `{issuer}/api/v1/apps/manifest`. Run it on deploy or from a script;\n * an unchanged catalog is a server-side no-op.\n *\n * @returns the server's sync summary (`unchanged`, `roles_declared`, …).\n * @throws ConfigurationError when config or the declaration is invalid.\n * @throws AuthenticationError when the token cannot be minted or the push fails.\n */\nexport async function publishManifest(\n config: ManifestPublisherConfig,\n declaration: AuthzDeclaration,\n): Promise<ManifestSyncSummary> {\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Publishing a manifest needs issuer, clientId and clientSecret.');\n }\n\n const timeoutMs = config.timeoutMs ?? 10_000;\n const manifest = await buildManifest(declaration);\n const discovery = new Discovery(config.issuer, timeoutMs, 3_600_000);\n\n const token = await mintToken(config, discovery, timeoutMs);\n\n const response = await fetchWithTimeout(\n `${config.issuer.replace(/\\/$/, '')}/api/v1/apps/manifest`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n accept: 'application/json',\n 'content-type': 'application/json',\n },\n body: JSON.stringify(manifest),\n },\n timeoutMs,\n );\n\n if (!response.ok) {\n throw new AuthenticationError(`Manifest push failed: HTTP ${response.status} ${await response.text()}`);\n }\n\n const json = (await response.json()) as unknown;\n return json !== null && typeof json === 'object' ? (json as ManifestSyncSummary) : {};\n}\n\nasync function mintToken(\n config: ManifestPublisherConfig,\n discovery: Discovery,\n timeoutMs: number,\n): Promise<string> {\n const response = await fetchWithTimeout(\n await discovery.endpoint('token_endpoint'),\n {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n scope: 'apps.manifest',\n }),\n },\n timeoutMs,\n );\n\n const json = (await response.json().catch(() => ({}))) as { access_token?: unknown };\n if (typeof json.access_token !== 'string' || json.access_token === '') {\n throw new AuthenticationError(\n 'Could not obtain an apps.manifest access token — check the client credentials and that the client holds the apps.manifest scope.',\n );\n }\n return json.access_token;\n}\n\nfunction assertDeclaration(permissions: PermissionDefinition[], roles: RoleDefinition[]): void {\n const permissionKeys = new Set<string>();\n for (const permission of permissions) {\n if (!permission.key) {\n throw new ConfigurationError('Every permission needs a non-empty `key`.');\n }\n if (permissionKeys.has(permission.key)) {\n throw new ConfigurationError(`Permission \"${permission.key}\" is declared more than once.`);\n }\n permissionKeys.add(permission.key);\n }\n\n const roleKeys = new Set<string>();\n for (const role of roles) {\n if (!role.key) {\n throw new ConfigurationError('Every role needs a non-empty `key`.');\n }\n if (!role.name) {\n throw new ConfigurationError(`Role \"${role.key}\" needs a non-empty \\`name\\`.`);\n }\n if (roleKeys.has(role.key)) {\n throw new ConfigurationError(`Role \"${role.key}\" is declared more than once.`);\n }\n roleKeys.add(role.key);\n for (const reference of role.permissions) {\n if (!permissionKeys.has(reference)) {\n throw new ConfigurationError(\n `Role \"${role.key}\" references permission \"${reference}\", which is not declared.`,\n );\n }\n }\n }\n}\n\n/** A permission with keys in a fixed order and no `undefined` fields (stable to hash). */\nfunction canonicalPermission(permission: PermissionDefinition): PermissionDefinition {\n return permission.description === undefined\n ? { key: permission.key }\n : { key: permission.key, description: permission.description };\n}\n\n/** A role with keys in a fixed order, sorted permission refs, and no `undefined` fields. */\nfunction canonicalRole(role: RoleDefinition): RoleDefinition {\n const permissions = [...role.permissions].sort(byteCompare);\n return role.description === undefined\n ? { key: role.key, name: role.name, permissions }\n : { key: role.key, name: role.name, description: role.description, permissions };\n}\n\n/**\n * Serialize {permissions, roles} to the exact canonical JSON the PHP reference hashes,\n * so the `version` is byte-for-byte identical across every Cbox ID SDK. Matches PHP\n * `json_encode` defaults: object keys in insertion order, permissions and roles sorted\n * by key, each role's permission refs sorted, an absent-or-empty description emitted as\n * `null`, forward slashes escaped as `\\/`, and every non-ASCII code unit as `\\uXXXX`.\n */\nexport function canonicalManifestJson(\n permissions: PermissionDefinition[],\n roles: RoleDefinition[],\n): string {\n const canonical = {\n permissions: [...permissions]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((p) => ({ key: p.key, description: emptyToNull(p.description) })),\n roles: [...roles]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((r) => ({\n key: r.key,\n name: r.name,\n description: emptyToNull(r.description),\n permissions: [...r.permissions].sort(byteCompare),\n })),\n };\n return escapeLikePhp(JSON.stringify(canonical));\n}\n\n/** PHP treats an absent or empty description as `null` in the hashed catalog. */\nfunction emptyToNull(value: string | undefined): string | null {\n return value === undefined || value === '' ? null : value;\n}\n\n/** Byte-wise (code-unit) comparison — matches PHP `strcmp` on the ASCII-only keys. */\nfunction byteCompare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Apply PHP `json_encode`'s default `\\/` slash and `\\uXXXX` non-ASCII escaping. */\nfunction escapeLikePhp(json: string): string {\n let out = '';\n for (let i = 0; i < json.length; i++) {\n const char = json.charAt(i);\n const code = json.charCodeAt(i);\n if (char === '/') {\n out += '\\\\/';\n } else if (code > 0x7f) {\n out += '\\\\u' + code.toString(16).padStart(4, '0');\n } else {\n out += char;\n }\n }\n return out;\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n}\n\nasync function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Refuse a legacy login declaration the server would refuse anyway.\n *\n * Checked in the SDK so it fails at build time, in the deploy that introduced it, rather\n * than as a 4xx from a manifest push somebody has to go and read. Both rules are the\n * server's and are restated here rather than inferred: https because a password in the\n * clear is readable by everything on the path, and a real secret because it is the only\n * thing proving a request came from Cbox ID.\n */\nfunction assertLegacyLogin(legacy: LegacyLoginDeclaration): void {\n if (!legacy.url.startsWith('https://')) {\n throw new ConfigurationError('legacyLogin.url must be https — a password must never cross the network in the clear.');\n }\n\n if (!legacy.secret || legacy.secret.length < 32) {\n throw new ConfigurationError('legacyLogin.secret must be at least 32 characters; it is what proves a request came from Cbox ID.');\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/legacy.ts","../src/frontend.ts","../src/authz.ts"],"names":["key","json"],"mappings":";;;;AAwEO,SAAS,qBAAqB,OAAA,EAAyE;AAC5G,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,SAAS,EAAA,EAAI;AACjD,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAM,SAAA,GAAY,QAAQ,gBAAA,IAAoB,GAAA;AAE9C,EAAA,OAAO,eAAe,OAAO,OAAA,EAAqC;AAGhE,IAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,IAAA,EAAK;AAE/B,IAAA,IAAI,CAAE,MAAM,gBAAA,CAAiB,GAAA,EAAK,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA,EAAG,OAAA,CAAQ,MAAA,EAAQ,SAAS,CAAA,EAAI;AAItG,MAAA,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,cAAA,IAAkB,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MAAM,IAAI,mBAAmB,mGAAmG,CAAA;AAAA,EAClI;AACF","file":"index.js","sourcesContent":["import { ConfigurationError } from './errors.js';\n\n/**\n * The handler on YOUR side of a legacy migration.\n *\n * Cbox ID offers it an email and a password it has never seen, and your code answers with\n * the person or with nothing. On a yes they are created in Cbox ID as a result of the\n * login that just succeeded, and from their next sign-in the old system is never asked\n * again.\n *\n * WHY THIS IS A FACTORY AND NOT A DOCUMENT. The wire format is simple enough to describe\n * in a paragraph — a signed POST, JSON in, JSON out — and describing it would mean every\n * customer writes the signature check themselves. That check is exactly the part people\n * get wrong: `===` instead of a constant-time compare, no freshness window, no thought\n * about replay. So the factory owns all of it and you write the one function that knows\n * your own database.\n *\n * It is deliberately framework-agnostic: it takes a `Request` and returns a `Response`,\n * which is what Next.js route handlers, Remix, Hono, Bun and Deno all speak natively.\n */\n\n/** What your handler answers with. Returning `null` means \"no\", and is not an error. */\nexport interface LegacyUser {\n email: string;\n name?: string | null;\n emailVerified?: boolean;\n /**\n * Your stored hash, when you can expose it.\n *\n * Passing it lets the person keep their password in Cbox ID verbatim — it is stored as\n * is and upgraded to the platform hasher on their next login, exactly like a\n * bulk-imported user. Omit it and Cbox ID hashes the password they just proved they\n * know, which is the honest option when your store cannot hand a hash over.\n */\n passwordHash?: string;\n}\n\nexport interface LegacyVerifierOptions {\n /** The same secret you declared in your manifest, or configured in the console. */\n secret: string;\n /**\n * Decide whether these credentials are good, and say who they belong to.\n *\n * Return `null` for no. THROWING IS NOT THE SAME as returning null: a throw means your\n * store could not decide, and is answered with a 503 so Cbox ID refuses the sign-in\n * rather than treating an outage as a wrong password.\n */\n verify: (email: string, password: string) => Promise<LegacyUser | null>;\n /**\n * How far out of date a request may be, in seconds. Defaults to 300.\n *\n * A window is what makes a captured request stop working. Too wide and a recording is\n * useful for hours; too narrow and ordinary clock skew starts refusing real traffic.\n */\n toleranceSeconds?: number;\n}\n\n/**\n * Build the request handler.\n *\n * ```ts\n * // app/api/cbox-legacy/route.ts\n * export const POST = createLegacyVerifier({\n * secret: process.env.CBOX_LEGACY_SECRET!,\n * async verify(email, password) {\n * const row = await db.users.findByEmail(email)\n * if (!row || !(await argon2.verify(row.password, password))) return null\n * return { email: row.email, name: row.name, emailVerified: !!row.confirmedAt }\n * },\n * })\n * ```\n */\nexport function createLegacyVerifier(options: LegacyVerifierOptions): (request: Request) => Promise<Response> {\n if (!options.secret || options.secret.length < 32) {\n throw new ConfigurationError(\n 'A legacy verifier secret must be at least 32 characters; it is the only thing proving a request came from Cbox ID.',\n );\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n\n return async function handle(request: Request): Promise<Response> {\n // Read once. The signature covers the RAW body, so re-serializing parsed JSON would\n // produce different bytes and every valid request would be refused.\n const raw = await request.text();\n\n if (!(await isSignedByCboxId(raw, request.headers.get('X-Cbox-Signature'), options.secret, tolerance))) {\n // No detail. A caller who cannot sign is not owed help distinguishing \"bad\n // signature\" from \"stale timestamp\" — both mean the same thing to anyone\n // legitimate, and the difference is a hint to anyone else.\n return json({ error: 'unauthorized' }, 401);\n }\n\n let payload: { email?: unknown; password?: unknown };\n\n try {\n payload = JSON.parse(raw) as typeof payload;\n } catch {\n return json({ error: 'invalid_request' }, 400);\n }\n\n const { email, password } = payload;\n\n if (typeof email !== 'string' || email === '') {\n return json({ error: 'invalid_request' }, 400);\n }\n\n // No password means Cbox ID is asking \"do you know this address\" — the tooling path,\n // used for a dry run before cutover. It never reaches here from a sign-in.\n if (typeof password !== 'string') {\n return json({ user: null }, 200);\n }\n\n let user: LegacyUser | null;\n\n try {\n user = await options.verify(email, password);\n } catch {\n // 503, not 401. Your store could not decide, and Cbox ID must refuse the sign-in\n // rather than read an outage as a wrong password — but it should also be able to\n // tell the two apart in its own logs, which a 401 would hide.\n return json({ error: 'unavailable' }, 503);\n }\n\n if (!user) {\n return json({ user: null }, 200);\n }\n\n return json(\n {\n email: user.email,\n name: user.name ?? null,\n email_verified: user.emailVerified === true,\n ...(user.passwordHash ? { password_hash: user.passwordHash } : {}),\n },\n 200,\n );\n };\n}\n\n/**\n * Whether this body was signed by Cbox ID, recently.\n *\n * Both halves matter. The HMAC proves it came from something holding the secret; the\n * freshness window is what stops a captured request working forever. Compared in constant\n * time, because a comparison that returns early leaks how much of a guess was right.\n */\nasync function isSignedByCboxId(\n body: string,\n header: string | null,\n secret: string,\n toleranceSeconds: number,\n): Promise<boolean> {\n if (!header) {\n return false;\n }\n\n const parts: Record<string, string> = {};\n\n for (const piece of header.split(',')) {\n const [key, value] = piece.split('=', 2);\n if (key && value) {\n parts[key.trim()] = value.trim();\n }\n }\n\n const timestamp = parts['t'] ?? '';\n const signature = parts['v1'] ?? '';\n\n if (!/^\\d+$/.test(timestamp) || signature === '') {\n return false;\n }\n\n if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > toleranceSeconds) {\n return false;\n }\n\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n\n const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${body}`));\n const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join('');\n\n return timingSafeEqual(expected, signature);\n}\n\n/** Constant-time string compare. Length is not secret; content is. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let diff = 0;\n\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n\n return diff === 0;\n}\n\nfunction json(body: unknown, status: number): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","import { assertSecureIssuer } from './issuer.js';\nimport { ConfigurationError, FrontendApiError } from './errors.js';\n\n/**\n * The browser-safe half of the SDK.\n *\n * Everything else in this package assumes a server: it holds a client secret, it exchanges\n * codes, it verifies webhooks. None of that may run in a page, which is why the UI\n * components have always been redirect shells — a page that cannot authenticate itself to\n * the identity provider cannot ask it anything, so it sends the person away and waits.\n *\n * A publishable key changes that. It is public on purpose: it ships in your bundle, it is\n * visible in devtools, and it is safe there because it only works from the origins you\n * registered. What it buys is that a page can read its OWN sign-in configuration — the\n * endpoints, the social buttons, your theme — and render a form itself.\n *\n * This client deliberately has no secret, no token storage and no crypto. It reads two\n * documents. Anything that mints or holds a credential still belongs on your server.\n */\n\n/** How a page identifies itself. Public — put it in your bundle. */\nexport interface FrontendClientOptions {\n /** Your identity provider's origin, e.g. `https://id.acme.com`. */\n issuer: string;\n /** `pk_live_…` or `pk_test_…`. Safe to publish. */\n publishableKey: string;\n /** Abort after this long. Defaults to 10s. */\n timeoutMs?: number;\n /**\n * How many times to retry a transient failure. Defaults to 2 (so three attempts).\n *\n * Only the network and 5xx are retried. A refusal is a configuration problem and\n * retrying it just delays the developer finding out; a 429 is honoured rather than\n * hammered.\n */\n retries?: number;\n /** Injectable for tests and for runtimes with a non-global fetch. */\n fetch?: typeof globalThis.fetch;\n}\n\n/** A social button to draw. Name and provider only — never an internal id. */\nexport interface SocialProvider {\n provider: string;\n name: string;\n}\n\n/** The customer's theme, when they have set one. Absent means \"use your own defaults\". */\nexport interface Appearance {\n preset: string;\n radius: string;\n font: string;\n light: Record<string, string>;\n dark: Record<string, string>;\n}\n\n/** Everything needed to draw a sign-in box, and nothing that identifies anybody. */\nexport interface FrontendConfig {\n mode: 'test' | 'live' | null;\n issuer: string;\n endpoints: {\n authorization: string;\n token: string;\n userinfo: string;\n end_session: string;\n jwks: string;\n };\n social: SocialProvider[];\n appearance?: Appearance;\n}\n\n/** What a sign-in attempt produced. */\nexport type SignInResult =\n | { status: 'ok'; loginTicket: string; expiresIn: number }\n | { status: 'mfa_required'; mfaToken: string }\n | { status: 'otp_required'; mfaToken: string }\n | { status: 'sso_required' }\n | { status: 'invalid' }\n | { status: 'rate_limited'; retryAfter: number | undefined };\n\n/** What a browser needs to ask an authenticator for a passkey assertion. */\nexport interface PasskeyOptions {\n challenge: string;\n /** Carries the challenge to the second request, in place of a session cookie. */\n challenge_token: string;\n rpId: string;\n userVerification: string;\n allowCredentials: unknown[];\n timeout: number;\n}\n\n/** Who the browser is signed in as, or nobody. */\nexport interface FrontendSession {\n user: { id: string; email: string; name: string | null } | null;\n}\n\n/**\n * Reads the public configuration and the current session from a browser.\n *\n * ```ts\n * const frontend = new CboxIdFrontend({\n * issuer: 'https://id.acme.com',\n * publishableKey: 'pk_live_…',\n * })\n *\n * const config = await frontend.config() // cached for you; safe to call per component\n * const { user } = await frontend.session(accessToken)\n * ```\n */\nexport class CboxIdFrontend {\n private readonly issuer: string;\n private readonly publishableKey: string;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n /**\n * The config document, and the in-flight promise for it.\n *\n * Deduplicated rather than merely cached: a page with a sign-in form, a user button and\n * an organization switcher mounts three components in the same tick, and three parallel\n * fetches of the same immutable document is a waste the SDK should absorb rather than\n * ask every consumer to.\n */\n private configPromise: Promise<FrontendConfig> | null = null;\n\n constructor(options: FrontendClientOptions) {\n if (!options.issuer) {\n throw new ConfigurationError('issuer is required.');\n }\n\n // The browser channel carries login tickets, one-time codes and the session the user\n // is in the middle of establishing. Over `http` a network attacker on the same café\n // Wi-Fi reads the ticket and redeems it — and the sign-in box the user is looking at\n // is served by the attacker, so nothing about the page tells them.\n assertSecureIssuer(options.issuer);\n\n // Caught here rather than at the first request, because the failure otherwise arrives\n // as an opaque 401 from the network tab and the cause — a secret key pasted into a\n // browser bundle — is exactly the mistake worth naming out loud.\n if (!options.publishableKey?.startsWith('pk_')) {\n throw new ConfigurationError(\n 'publishableKey must be a pk_test_… or pk_live_… key. Client secrets and API keys must never be put in a browser.',\n );\n }\n\n this.issuer = options.issuer.replace(/\\/$/, '');\n this.publishableKey = options.publishableKey;\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.retries = Math.max(0, options.retries ?? 2);\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /** Whether this key drives real sign-ins. Handy for a \"test mode\" badge in your own UI. */\n get isLive(): boolean {\n return this.publishableKey.startsWith('pk_live_');\n }\n\n /**\n * The public sign-in configuration.\n *\n * Fetched once per client instance. The document is small and changes when somebody\n * edits it in the console, so a long-lived page picks changes up on its next full load\n * rather than mid-session — which is the right trade for something that decides layout.\n */\n async config(): Promise<FrontendConfig> {\n this.configPromise ??= this.get<FrontendConfig>('/frontend/v1/config', {}, isFrontendConfig).catch((error: unknown) => {\n // Cleared so a transient network failure does not poison the instance for the\n // lifetime of the page.\n this.configPromise = null;\n throw error;\n });\n\n return this.configPromise;\n }\n\n /**\n * Who is signed in, given an access token your app already holds.\n *\n * Returns `{ user: null }` rather than throwing when nobody is signed in. That is a\n * state, not an error: a user button renders on pages nobody has signed in on, and\n * making callers treat a rejection as a state is how flash-of-signed-out bugs happen.\n *\n * The publishable key grants nothing here — the token is the entire authority.\n */\n async session(accessToken?: string): Promise<FrontendSession> {\n if (!accessToken) {\n return { user: null };\n }\n\n return this.get<FrontendSession>(\n '/frontend/v1/session',\n { Authorization: `Bearer ${accessToken}` },\n isFrontendSession,\n );\n }\n\n /**\n * Sign in with a password, from a form your page drew.\n *\n * WHAT COMES BACK IS A TICKET, NEVER A TOKEN. Handing tokens to a page that proved a\n * password is the implicit grant, which OAuth 2.1 removes: tokens in a URL, in history,\n * in `Referer`, with no client authentication and no PKCE binding. Spend the ticket by\n * sending the browser to `/oauth/authorize` with your own PKCE challenge and\n * `login_ticket` in the query — the ordinary flow, which then issues an ordinary code.\n *\n * It expires in sixty seconds. It is for one redirect, not for storing.\n *\n * ```ts\n * const result = await frontend.signIn(email, password)\n *\n * if (result.status === 'ok') {\n * window.location.href = `${config.endpoints.authorization}?${new URLSearchParams({\n * client_id, redirect_uri, response_type: 'code', code_challenge, code_challenge_method: 'S256',\n * login_ticket: result.loginTicket,\n * })}`\n * }\n * ```\n *\n * EVERY REFUSAL IS THE SAME REFUSAL. `invalid` covers a wrong password, an unknown\n * address and a locked account, because distinguishing them is the enumeration oracle\n * the server refuses to build — do not present them differently in your UI either.\n */\n async signIn(email: string, password: string): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in', { email, password });\n\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('Retry-After') ?? '');\n\n return { status: 'rate_limited', retryAfter: Number.isFinite(retryAfter) ? retryAfter : undefined };\n }\n\n let body: { status?: string; login_ticket?: string; mfa_token?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n if (body.status === 'ok' && typeof body.login_ticket === 'string') {\n return { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 };\n }\n\n if ((body.status === 'mfa_required' || body.status === 'otp_required') && typeof body.mfa_token === 'string') {\n return { status: body.status, mfaToken: body.mfa_token };\n }\n\n if (body.status === 'sso_required') {\n return { status: 'sso_required' };\n }\n\n return { status: 'invalid' };\n }\n\n /**\n * Finish a sign-in that owed a second factor.\n *\n * The token from `signIn()` carries the pending state, because a cross-origin page has\n * no session cookie to carry it in. A TOTP code or a recovery code both work — an\n * embedded form that could not accept a recovery code would strand exactly the people\n * that escape hatch exists for.\n *\n * A wrong code costs an attempt, not the sign-in: five are allowed before the token\n * dies and the person starts from the password again.\n */\n async submitSecondFactor(mfaToken: string, code: string, method: 'mfa' | 'otp' = 'mfa'): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in/factor', { mfa_token: mfaToken, code, method });\n\n let body: { status?: string; login_ticket?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n return body.status === 'ok' && typeof body.login_ticket === 'string'\n ? { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 }\n : { status: 'invalid' };\n }\n\n /**\n * The WebAuthn options for a passkey sign-in, and the handle that carries the challenge.\n *\n * The handle exists because a cross-origin page has no session cookie to keep the\n * challenge in between the two requests WebAuthn needs. Pass it back to\n * {@link signInWithPasskey} with whatever `navigator.credentials.get()` returns.\n *\n * `allowCredentials` comes back empty on purpose: this is a discoverable-credential\n * flow, so the authenticator offers whichever passkey it holds and the page never has to\n * say who is signing in — asking for an email first, to look up which credentials exist,\n * would be an enumeration oracle.\n */\n async passkeyOptions(): Promise<PasskeyOptions> {\n const response = await this.post('/frontend/v1/sign-in/passkey/options', {});\n\n if (!response.ok) {\n throw new FrontendApiError(\n `Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list.`,\n 'origin_not_allowed',\n response.status,\n );\n }\n\n return (await response.json()) as PasskeyOptions;\n }\n\n /**\n * Complete a passkey sign-in with the assertion the authenticator produced.\n *\n * `assertion` is the credential from `navigator.credentials.get()`, serialised — the\n * server verifies the raw body, so pass it through unchanged rather than rebuilding it.\n */\n async signInWithPasskey(challengeToken: string, assertion: Record<string, unknown>): Promise<SignInResult> {\n const response = await this.post('/frontend/v1/sign-in/passkey', { ...assertion, challenge_token: challengeToken });\n\n let body: { status?: string; login_ticket?: string; expires_in?: number };\n\n try {\n body = (await response.json()) as typeof body;\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n return body.status === 'ok' && typeof body.login_ticket === 'string'\n ? { status: 'ok', loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 }\n : { status: 'invalid' };\n }\n\n private async post(path: string, payload: Record<string, unknown>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n return await this.fetchImpl(`${this.issuer}${path}`, {\n method: 'POST',\n headers: {\n 'X-Cbox-Publishable-Key': this.publishableKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n } catch {\n throw new FrontendApiError(\n `Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list — a refused request fails as a network error by design.`,\n 'unavailable',\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async get<T>(\n path: string,\n extraHeaders: Record<string, string> = {},\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= this.retries; attempt++) {\n // Linear, not exponential, and only between attempts. This sits inside a page\n // render: a caller waiting on their sign-in box would rather fail in a second than\n // succeed in eight.\n if (attempt > 0) {\n await new Promise((resolve) => setTimeout(resolve, 150 * attempt));\n }\n\n try {\n return await this.attempt<T>(path, extraHeaders, validate);\n } catch (error) {\n lastError = error;\n\n // Retry only what a retry can fix. A refusal is a configuration problem and\n // retrying it delays the developer finding out; a rate limit is honoured rather\n // than hammered; a malformed body will be malformed again.\n if (!(error instanceof FrontendApiError) || error.code !== 'unavailable') {\n throw error;\n }\n }\n }\n\n throw lastError;\n }\n\n private async attempt<T>(\n path: string,\n extraHeaders: Record<string, string>,\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n\n try {\n response = await this.fetchImpl(`${this.issuer}${path}`, {\n headers: {\n // A header, never a query string: a query string puts the key in server logs,\n // in `Referer` on every outbound link, and in browser history.\n 'X-Cbox-Publishable-Key': this.publishableKey,\n Accept: 'application/json',\n ...extraHeaders,\n },\n signal: controller.signal,\n });\n } catch (cause) {\n // Includes the abort on timeout, and — in a browser — a refusal, because a refused\n // request deliberately carries no CORS headers and so never becomes a Response.\n throw new FrontendApiError(\n `Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list — a refused request fails as a network error by design.`,\n 'unavailable',\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('Retry-After') ?? '');\n\n throw new FrontendApiError(\n (await described(response)) ?? 'Cbox ID is rate limiting this key.',\n 'rate_limited',\n 429,\n Number.isFinite(retryAfter) ? retryAfter : undefined,\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new FrontendApiError(\n // THE SERVER'S OWN REASON FIRST. It answers precisely — \"No publishable key was\n // presented\" is a different problem from \"That publishable key cannot be used\n // from this origin\" — and substituting a guess for it made this client less\n // precise than the API it wraps. The fallback still stands for the browser case,\n // where a refusal never becomes a readable Response at all.\n (await described(response)) ??\n `Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list, and that the key is not revoked.`,\n 'origin_not_allowed',\n response.status,\n );\n }\n\n if (!response.ok) {\n throw new FrontendApiError(\n (await described(response)) ?? `Cbox ID returned ${response.status}.`,\n 'unavailable',\n response.status,\n );\n }\n\n let body: unknown;\n\n try {\n body = await response.json();\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n // A 200 whose body is not the document we expect means something between the page and\n // us is rewriting responses — a proxy, an extension, a captive portal. Caught here so\n // it surfaces as that, rather than as `undefined` deep inside somebody's component.\n if (validate && !validate(body)) {\n throw new FrontendApiError(\n 'Cbox ID returned a body that is not the expected document.',\n 'malformed',\n response.status,\n );\n }\n\n return body as T;\n }\n}\n\n/**\n * The server's own `error_description`, when it sent one.\n *\n * Read from a CLONE: the caller may still want the body, and a Response body can only be\n * consumed once — a helper that quietly drained it would turn a precise error into a\n * different, stranger one.\n */\nasync function described(response: Response): Promise<string | undefined> {\n try {\n const body: unknown = await response.clone().json();\n\n if (typeof body === 'object' && body !== null && 'error_description' in body) {\n const description = (body as { error_description: unknown }).error_description;\n\n return typeof description === 'string' && description !== '' ? description : undefined;\n }\n } catch {\n // A refusal without a readable body is the normal case in a browser.\n }\n\n return undefined;\n}\n\n/** The shape check for the config document. Structural, not exhaustive. */\nfunction isFrontendConfig(body: unknown): body is FrontendConfig {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n\n const doc = body as Partial<FrontendConfig>;\n\n return typeof doc.issuer === 'string' && typeof doc.endpoints === 'object' && doc.endpoints !== null;\n}\n\n/** The shape check for the session document. `user: null` is valid and expected. */\nfunction isFrontendSession(body: unknown): body is FrontendSession {\n return typeof body === 'object' && body !== null && 'user' in body;\n}\n","import { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\n/**\n * A permission your app declares. `key` is a `feature:action` slug (e.g.\n * `invoices:create`); `description` is human-facing copy for the Cbox ID console.\n */\nexport interface PermissionDefinition {\n key: string;\n description?: string;\n}\n\n/**\n * A role your app declares. `permissions` lists the permission keys the role\n * grants — each must reference a declared {@link PermissionDefinition}.\n */\nexport interface RoleDefinition {\n key: string;\n name: string;\n description?: string;\n permissions: string[];\n}\n\n/**\n * The roles + permissions an app declares in code. Either list may be omitted.\n * Pass this to {@link defineAuthz} (to validate up front) or straight to\n * {@link buildManifest} / {@link publishManifest}.\n */\nexport interface AuthzDeclaration {\n permissions?: PermissionDefinition[];\n roles?: RoleDefinition[];\n /**\n * Where this app's OLD login lives, while you are migrating off it.\n *\n * Declared here for the same reason roles are: it is a fact about the app, it belongs\n * with the deploy, and the alternative is a URL pasted into a console and a secret\n * pasted into an env file that quietly disagree six weeks later.\n *\n * IT DOES NOT TAKE EFFECT ON ITS OWN. Unlike a role — which affects only the app that\n * declared it — this names a URL that every unknown email and the password typed with\n * it will be offered to, on the environment's whole sign-in path. So it arrives as a\n * proposal and an operator has to approve it in the console. Changing the url later\n * drops that approval, on purpose.\n */\n legacyLogin?: LegacyLoginDeclaration;\n}\n\n/** Where an app's old login lives. See {@link AuthzDeclaration.legacyLogin}. */\nexport interface LegacyLoginDeclaration {\n /** Must be https — a password in the clear is readable by everything on the path. */\n url: string;\n /** At least 32 characters. It is the only thing proving a request came from Cbox ID. */\n secret: string;\n}\n\n/**\n * The manifest as it is sent to Cbox ID: the declared permissions + roles plus a\n * content-derived `version`, so republishing an unchanged catalog is a no-op.\n */\nexport interface AuthzManifest {\n version: string;\n permissions: PermissionDefinition[];\n roles: RoleDefinition[];\n legacy_login?: LegacyLoginDeclaration;\n}\n\n/** What {@link publishManifest} needs to authenticate the push. */\nexport interface ManifestPublisherConfig {\n /** Base URL (issuer) of the Cbox ID instance — the `token_endpoint` is discovered from it. */\n issuer: string;\n /** Your OAuth client id. The client must hold the `apps.manifest` scope. */\n clientId: string;\n /** Your OAuth client secret. The push uses the client-credentials grant. */\n clientSecret: string;\n /** Timeout (ms) for back-channel HTTP calls. Defaults to `10000`. */\n timeoutMs?: number;\n}\n\n/**\n * The server's sync summary. The named fields are the ones the SDK/CLI reads;\n * the index signature keeps any extra fields the server returns.\n */\nexport interface ManifestSyncSummary {\n unchanged?: boolean;\n roles_declared?: number;\n permissions_declared?: number;\n version?: string;\n [key: string]: unknown;\n}\n\n/**\n * Validate a roles/permissions declaration and return it normalized (both lists\n * always present). Call this where you declare your catalog so mistakes — a role\n * that grants an undeclared permission, a duplicate key — surface immediately\n * rather than on deploy.\n *\n * @throws ConfigurationError on a missing key/name, a duplicate, or a role that\n * references a permission that was never declared.\n */\nexport function defineAuthz(\n declaration: AuthzDeclaration,\n): AuthzDeclaration & { permissions: PermissionDefinition[]; roles: RoleDefinition[] } {\n const permissions = declaration.permissions ?? [];\n const roles = declaration.roles ?? [];\n assertDeclaration(permissions, roles);\n\n // The legacy login is validated here too, so a bad one fails in the deploy that\n // introduced it rather than as a 4xx from a manifest push somebody has to go and read.\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n }\n\n // `Required<>` no longer fits: the catalog is always present after this, and the legacy\n // login legitimately is not. Returning the declaration's own optionality keeps a caller\n // from having to invent an empty one.\n return { ...declaration, permissions, roles };\n}\n\n/**\n * Build the manifest — the declared catalog plus a stable content hash `version`\n * (first 16 hex chars of the sha256 of the canonicalized catalog). The catalog is\n * sorted by key first, so declaration order never changes the version.\n */\nexport async function buildManifest(declaration: AuthzDeclaration): Promise<AuthzManifest> {\n const permissions = (declaration.permissions ?? []).map(canonicalPermission);\n const roles = (declaration.roles ?? []).map(canonicalRole);\n assertDeclaration(permissions, roles);\n\n permissions.sort((a, b) => byteCompare(a.key, b.key));\n roles.sort((a, b) => byteCompare(a.key, b.key));\n\n // The version hashes the CATALOG only, and the legacy login is deliberately outside it:\n // this canonicalization is a cross-SDK contract — id-js, id-python, id-go and the PHP\n // reference all produce the same bytes, and a shared fixture exists to keep them from\n // drifting. The server compares a declared url separately for the same reason.\n const version = (await sha256Hex(canonicalManifestJson(permissions, roles))).slice(0, 16);\n\n const manifest: AuthzManifest = { version, permissions, roles };\n\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n manifest.legacy_login = declaration.legacyLogin;\n }\n\n return manifest;\n}\n\n/**\n * Publish this app's authorization manifest (its declared roles + permissions) to\n * Cbox ID. The app owns what a role means; Cbox ID owns identity and who holds it.\n *\n * It mints a client-credentials token with the `apps.manifest` scope (token\n * endpoint discovered from the issuer's OIDC configuration), then POSTs the\n * manifest to `{issuer}/api/v1/apps/manifest`. Run it on deploy or from a script;\n * an unchanged catalog is a server-side no-op.\n *\n * @returns the server's sync summary (`unchanged`, `roles_declared`, …).\n * @throws ConfigurationError when config or the declaration is invalid.\n * @throws AuthenticationError when the token cannot be minted or the push fails.\n */\nexport async function publishManifest(\n config: ManifestPublisherConfig,\n declaration: AuthzDeclaration,\n): Promise<ManifestSyncSummary> {\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Publishing a manifest needs issuer, clientId and clientSecret.');\n }\n\n const timeoutMs = config.timeoutMs ?? 10_000;\n const manifest = await buildManifest(declaration);\n const discovery = new Discovery(config.issuer, timeoutMs, 3_600_000);\n\n const token = await mintToken(config, discovery, timeoutMs);\n\n const response = await fetchWithTimeout(\n `${config.issuer.replace(/\\/$/, '')}/api/v1/apps/manifest`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n accept: 'application/json',\n 'content-type': 'application/json',\n },\n body: JSON.stringify(manifest),\n },\n timeoutMs,\n );\n\n if (!response.ok) {\n throw new AuthenticationError(`Manifest push failed: HTTP ${response.status} ${await response.text()}`);\n }\n\n const json = (await response.json()) as unknown;\n return json !== null && typeof json === 'object' ? (json as ManifestSyncSummary) : {};\n}\n\nasync function mintToken(\n config: ManifestPublisherConfig,\n discovery: Discovery,\n timeoutMs: number,\n): Promise<string> {\n const response = await fetchWithTimeout(\n await discovery.endpoint('token_endpoint'),\n {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n scope: 'apps.manifest',\n }),\n },\n timeoutMs,\n );\n\n const json = (await response.json().catch(() => ({}))) as { access_token?: unknown };\n if (typeof json.access_token !== 'string' || json.access_token === '') {\n throw new AuthenticationError(\n 'Could not obtain an apps.manifest access token — check the client credentials and that the client holds the apps.manifest scope.',\n );\n }\n return json.access_token;\n}\n\nfunction assertDeclaration(permissions: PermissionDefinition[], roles: RoleDefinition[]): void {\n const permissionKeys = new Set<string>();\n for (const permission of permissions) {\n if (!permission.key) {\n throw new ConfigurationError('Every permission needs a non-empty `key`.');\n }\n if (permissionKeys.has(permission.key)) {\n throw new ConfigurationError(`Permission \"${permission.key}\" is declared more than once.`);\n }\n permissionKeys.add(permission.key);\n }\n\n const roleKeys = new Set<string>();\n for (const role of roles) {\n if (!role.key) {\n throw new ConfigurationError('Every role needs a non-empty `key`.');\n }\n if (!role.name) {\n throw new ConfigurationError(`Role \"${role.key}\" needs a non-empty \\`name\\`.`);\n }\n if (roleKeys.has(role.key)) {\n throw new ConfigurationError(`Role \"${role.key}\" is declared more than once.`);\n }\n roleKeys.add(role.key);\n for (const reference of role.permissions) {\n if (!permissionKeys.has(reference)) {\n throw new ConfigurationError(\n `Role \"${role.key}\" references permission \"${reference}\", which is not declared.`,\n );\n }\n }\n }\n}\n\n/** A permission with keys in a fixed order and no `undefined` fields (stable to hash). */\nfunction canonicalPermission(permission: PermissionDefinition): PermissionDefinition {\n return permission.description === undefined\n ? { key: permission.key }\n : { key: permission.key, description: permission.description };\n}\n\n/** A role with keys in a fixed order, sorted permission refs, and no `undefined` fields. */\nfunction canonicalRole(role: RoleDefinition): RoleDefinition {\n const permissions = [...role.permissions].sort(byteCompare);\n return role.description === undefined\n ? { key: role.key, name: role.name, permissions }\n : { key: role.key, name: role.name, description: role.description, permissions };\n}\n\n/**\n * Serialize {permissions, roles} to the exact canonical JSON the PHP reference hashes,\n * so the `version` is byte-for-byte identical across every Cbox ID SDK. Matches PHP\n * `json_encode` defaults: object keys in insertion order, permissions and roles sorted\n * by key, each role's permission refs sorted, an absent-or-empty description emitted as\n * `null`, forward slashes escaped as `\\/`, and every non-ASCII code unit as `\\uXXXX`.\n */\nexport function canonicalManifestJson(\n permissions: PermissionDefinition[],\n roles: RoleDefinition[],\n): string {\n const canonical = {\n permissions: [...permissions]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((p) => ({ key: p.key, description: emptyToNull(p.description) })),\n roles: [...roles]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((r) => ({\n key: r.key,\n name: r.name,\n description: emptyToNull(r.description),\n permissions: [...r.permissions].sort(byteCompare),\n })),\n };\n return escapeLikePhp(JSON.stringify(canonical));\n}\n\n/** PHP treats an absent or empty description as `null` in the hashed catalog. */\nfunction emptyToNull(value: string | undefined): string | null {\n return value === undefined || value === '' ? null : value;\n}\n\n/** Byte-wise (code-unit) comparison — matches PHP `strcmp` on the ASCII-only keys. */\nfunction byteCompare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Apply PHP `json_encode`'s default `\\/` slash and `\\uXXXX` non-ASCII escaping. */\nfunction escapeLikePhp(json: string): string {\n let out = '';\n for (let i = 0; i < json.length; i++) {\n const char = json.charAt(i);\n const code = json.charCodeAt(i);\n if (char === '/') {\n out += '\\\\/';\n } else if (code > 0x7f) {\n out += '\\\\u' + code.toString(16).padStart(4, '0');\n } else {\n out += char;\n }\n }\n return out;\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n}\n\nasync function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Refuse a legacy login declaration the server would refuse anyway.\n *\n * Checked in the SDK so it fails at build time, in the deploy that introduced it, rather\n * than as a 4xx from a manifest push somebody has to go and read. Both rules are the\n * server's and are restated here rather than inferred: https because a password in the\n * clear is readable by everything on the path, and a real secret because it is the only\n * thing proving a request came from Cbox ID.\n */\nfunction assertLegacyLogin(legacy: LegacyLoginDeclaration): void {\n if (!legacy.url.startsWith('https://')) {\n throw new ConfigurationError('legacyLogin.url must be https — a password must never cross the network in the clear.');\n }\n\n if (!legacy.secret || legacy.secret.length < 32) {\n throw new ConfigurationError('legacyLogin.secret must be at least 32 characters; it is what proves a request came from Cbox ID.');\n }\n}\n"]}
package/dist/nextjs.cjs CHANGED
@@ -46,7 +46,7 @@ async function oauthError(response, fallback) {
46
46
  }
47
47
  } catch {
48
48
  }
49
- const detail = code ?? (body.trim() === "" ? `HTTP ${response.status}` : body.slice(0, 200));
49
+ const detail = code ?? `HTTP ${response.status}`;
50
50
  const retryAfterHeader = response.headers.get("retry-after");
51
51
  const retryAfter = retryAfterHeader !== null && /^\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader.trim()) : void 0;
52
52
  return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status, retryAfter);
@@ -69,7 +69,7 @@ var Discovery = class {
69
69
  if (this.cached && this.cached.expiresAt > this.now()) {
70
70
  return this.cached.doc;
71
71
  }
72
- const url = `${this.issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
72
+ const url = `${trimSlash(this.issuer)}/.well-known/openid-configuration`;
73
73
  const controller = new AbortController();
74
74
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
75
75
  let doc;
@@ -90,6 +90,11 @@ var Discovery = class {
90
90
  if (typeof doc.issuer !== "string" || doc.issuer === "") {
91
91
  throw new AuthenticationError("The discovery document was missing an issuer.");
92
92
  }
93
+ if (trimSlash(doc.issuer) !== trimSlash(this.issuer)) {
94
+ throw new AuthenticationError(
95
+ `The discovery document is for a different issuer (${doc.issuer}).`
96
+ );
97
+ }
93
98
  this.cached = { doc, expiresAt: this.now() + this.cacheTtlMs };
94
99
  return doc;
95
100
  }
@@ -107,6 +112,29 @@ var Discovery = class {
107
112
  return typeof value === "string" && value !== "" ? value : null;
108
113
  }
109
114
  };
115
+ function trimSlash(value) {
116
+ return value.replace(/\/+$/, "");
117
+ }
118
+
119
+ // src/issuer.ts
120
+ function assertSecureIssuer(issuer) {
121
+ let url;
122
+ try {
123
+ url = new URL(issuer);
124
+ } catch {
125
+ throw new ConfigurationError("Cbox ID config `issuer` is not a valid URL.");
126
+ }
127
+ if (url.protocol === "https:") {
128
+ return;
129
+ }
130
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "::1";
131
+ if (url.protocol === "http:" && loopback) {
132
+ return;
133
+ }
134
+ throw new ConfigurationError(
135
+ `Cbox ID config \`issuer\` must be https (got ${url.protocol}//${url.hostname}).`
136
+ );
137
+ }
110
138
 
111
139
  // src/pkce.ts
112
140
  function base64url(bytes) {
@@ -275,6 +303,7 @@ var CboxIdClient = class {
275
303
  if (!config.redirectUri) {
276
304
  throw new ConfigurationError("Cbox ID config `redirectUri` is required.");
277
305
  }
306
+ assertSecureIssuer(config.issuer);
278
307
  this.discovery = new Discovery(
279
308
  config.issuer,
280
309
  config.timeoutMs ?? 1e4,
@@ -347,15 +376,25 @@ var CboxIdClient = class {
347
376
  if (!tokens.access_token) {
348
377
  throw new AuthenticationError("No access token was returned.");
349
378
  }
350
- let claims = {};
379
+ let verified = {};
351
380
  if (tokens.id_token) {
352
- claims = await this.verifyIdToken(tokens.id_token, stored.nonce, stored.maxAge);
381
+ verified = await this.verifyIdToken(tokens.id_token, stored.nonce, stored.maxAge);
382
+ } else if ((stored.scopes ?? this.scopes()).includes("openid")) {
383
+ throw new AuthenticationError(
384
+ "An openid login returned no id_token, so the identity could not be verified."
385
+ );
353
386
  } else if (typeof stored.maxAge === "number") {
354
387
  throw new AuthenticationError(
355
388
  "A max_age was requested but no id_token was returned, so the authentication age could not be verified."
356
389
  );
357
390
  }
358
- claims = { ...claims, ...await this.userinfo(tokens.access_token) };
391
+ const profile = await this.userinfo(tokens.access_token);
392
+ const verifiedSub = verified["sub"];
393
+ const profileSub = profile["sub"];
394
+ if (typeof verifiedSub === "string" && typeof profileSub === "string" && !timingSafeEqualString(verifiedSub, profileSub)) {
395
+ throw new AuthenticationError("The UserInfo subject does not match the verified id_token.");
396
+ }
397
+ const claims = { ...profile, ...verified };
359
398
  const sub = claims["sub"];
360
399
  if (typeof sub !== "string" || sub === "") {
361
400
  throw new AuthenticationError("The verified token carried no subject.");
@@ -400,6 +439,9 @@ var CboxIdClient = class {
400
439
  if (!tokens.access_token) {
401
440
  throw new AuthenticationError("The refresh response carried no access token.");
402
441
  }
442
+ if (tokens.id_token) {
443
+ await this.verifyIdToken(tokens.id_token, "");
444
+ }
403
445
  return {
404
446
  accessToken: tokens.access_token,
405
447
  // Keep the presented token when the server does not rotate (OAuth 2.0 §6);