@cboxdk/id-js 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/errors.ts","../src/agent/http.ts","../src/agent/client-auth.ts","../src/agent/register.ts","../src/agent/grants.ts","../src/agent/binding.ts"],"names":["alg"],"mappings":";;;;;;;AAaO,IAAM,eAAA,GAAN,cAA8B,mBAAA,CAAoB;AAAC;AAGnD,IAAM,iBAAA,GAAN,cAAgC,eAAA,CAAgB;AAAC;AAMjD,IAAM,iBAAA,GAAN,cAAgC,eAAA,CAAgB;AAAC;AAGjD,IAAM,iBAAA,GAAN,cAAgC,eAAA,CAAgB;AAAC;AAQjD,IAAM,kBAAA,GAAN,cAAiC,eAAA,CAAgB;AAAC;AAMlD,IAAM,kBAAA,GAAN,cAAiC,eAAA,CAAgB;AAAC;AAGlD,IAAM,kBAAA,GAAN,cAAiC,eAAA,CAAgB;AAAC;AAMlD,IAAM,0BAAA,GAAN,cAAyC,eAAA,CAAgB;AAAC;AAO1D,IAAM,aAAA,GAAN,cAA4B,eAAA,CAAgB;AAAC;AAG7C,IAAM,mBAAA,GAAN,cAAkC,WAAA,CAAY;AAAC;AAEtD,IAAM,OAAA,GAAkD;AAAA,EACtD,aAAA,EAAe,iBAAA;AAAA,EACf,aAAA,EAAe,iBAAA;AAAA,EACf,aAAA,EAAe,iBAAA;AAAA,EACf,cAAA,EAAgB,kBAAA;AAAA,EAChB,cAAA,EAAgB,kBAAA;AAAA,EAChB,eAAA,EAAiB,kBAAA;AAAA,EACjB,uBAAA,EAAyB,0BAAA;AAAA,EACzB,SAAA,EAAW;AACb,CAAA;AAeA,eAAsB,iBAAiB,QAAA,EAA2C;AAChF,EAAA,MAAM,OAAO,MAAM,QAAA,CAAS,MAAK,CAAE,KAAA,CAAM,MAAM,EAAE,CAAA;AACjD,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI,gB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AA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH;;;AChdO,IAAM,qBAAA,GAAwB;AAY9B,SAAS,iBAAA,CAAkB,SAAS,CAAA,EAAW;AACpD,EAAA,IAAI,CAAC,OAAO,SAAA,CAAU,MAAM,KAAK,MAAA,GAAS,CAAA,IAAK,SAAS,EAAA,EAAI;AAC1D,IAAA,MAAM,IAAI,mBAAmB,wDAAwD,CAAA;AAAA,EACvF;AAEA,EAAA,MAAM,OAAO,qBAAA,CAAsB,MAAA;AAGnC,EAAA,MAAM,KAAA,GAAQ,MAAO,GAAA,GAAM,IAAA;AAC3B,EAAA,IAAI,IAAA,GAAO,EAAA;AAEX,EAAA,OAAO,IAAA,CAAK,SAAS,MAAA,EAAQ;AAC3B,IAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,eAAA,CAAgB,IAAI,WAAW,MAAA,GAAS,CAAC,CAAC,CAAA,EAAG;AACrE,MAAA,IAAI,IAAA,GAAO,KAAA,IAAS,IAAA,CAAK,MAAA,GAAS,MAAA,EAAQ;AACxC,QAAA,IAAA,IAAQ,qBAAA,CAAsB,OAAO,IAAI,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT","file":"agent.js","sourcesContent":["import { AuthenticationError, CboxIdError } from '../errors.js';\n\n/**\n * A CIBA, device-grant or registration request was refused with an OAuth error.\n *\n * Extends {@link AuthenticationError}, so `error`, `errorDescription`, `status` and\n * `retryAfter` read the same as on every other back-channel failure in this SDK, and a\n * caller already catching `AuthenticationError` keeps working. Branch on the subclass (or\n * on `error`), never on the message.\n *\n * The REQUEST is never part of the error: these calls carry client assertions, secrets and\n * device codes, and production CLIs log what they throw.\n */\nexport class AgentGrantError extends AuthenticationError {}\n\n/** The person declined (`access_denied`). Final — do not poll again. */\nexport class AccessDeniedError extends AgentGrantError {}\n\n/**\n * The `auth_req_id` or `device_code` expired before anyone approved it (`expired_token`).\n * Also thrown locally when the wait outlives the request's `expires_in`. Start again.\n */\nexport class ExpiredTokenError extends AgentGrantError {}\n\n/** The `auth_req_id`, `device_code` or refresh token is not valid (`invalid_grant`). */\nexport class InvalidGrantError extends AgentGrantError {}\n\n/**\n * The `resource` (RFC 8707) is not one this client may ask for, the poll named a\n * different resource than the request that started it, or the resource lets\n * self-registered clients use CIBA only with `private_key_jwt` and this one is keyless\n * (`invalid_target`).\n */\nexport class InvalidTargetError extends AgentGrantError {}\n\n/**\n * Client authentication failed (`invalid_client`): an unknown `client_id`, a bad secret, an\n * assertion signed by a key the server does not hold, or a replayed `jti`.\n */\nexport class InvalidClientError extends AgentGrantError {}\n\n/** The `login_hint` names nobody the server can reach (`unknown_user_id`). */\nexport class UnknownUserIdError extends AgentGrantError {}\n\n/**\n * The `binding_message` is missing where the server requires one (self-registered clients),\n * or too long to show beside Approve (`invalid_binding_message`).\n */\nexport class InvalidBindingMessageError extends AgentGrantError {}\n\n/**\n * The server asked us to slow down (`slow_down`, or HTTP 429). `retryAfter` carries the\n * `Retry-After` seconds when the server sent them. The wait helpers absorb this themselves;\n * it is thrown only from a call that does not loop (registration, starting a flow).\n */\nexport class SlowDownError extends AgentGrantError {}\n\n/** The caller aborted the wait (its `AbortSignal` fired). */\nexport class GrantCancelledError extends CboxIdError {}\n\nconst BY_CODE: Record<string, typeof AgentGrantError> = {\n access_denied: AccessDeniedError,\n expired_token: ExpiredTokenError,\n invalid_grant: InvalidGrantError,\n invalid_target: InvalidTargetError,\n invalid_client: InvalidClientError,\n unknown_user_id: UnknownUserIdError,\n invalid_binding_message: InvalidBindingMessageError,\n slow_down: SlowDownError,\n};\n\n/** A parsed `{ error, error_description }` body plus the bits of the response that matter. */\nexport interface OAuthFailure {\n error: string | undefined;\n errorDescription: string | undefined;\n status: number;\n retryAfter: number | undefined;\n}\n\n/**\n * Read an OAuth error body without ever echoing it. A 502 from a proxy is HTML, and an\n * error page that reflects the request would put a client assertion into a log line — so\n * only the server's own `error` code (or the status) reaches the message.\n */\nexport async function readOAuthFailure(response: Response): Promise<OAuthFailure> {\n const text = await response.text().catch(() => '');\n let error: string | undefined;\n let errorDescription: string | undefined;\n\n try {\n const parsed: unknown = JSON.parse(text);\n\n if (typeof parsed === 'object' && parsed !== null) {\n const record = parsed as Record<string, unknown>;\n error = typeof record['error'] === 'string' ? record['error'] : undefined;\n errorDescription = typeof record['error_description'] === 'string' ? record['error_description'] : undefined;\n }\n } catch {\n // Not JSON: the status alone is what there is to report.\n }\n\n // A 429 IS slow_down, whatever (or whether) the body says — the limiter in front of the\n // endpoint may answer before the OAuth layer does.\n if (response.status === 429 && error === undefined) {\n error = 'slow_down';\n }\n\n // Seconds only. The HTTP-date form is legal but guessing at clock skew is worse than\n // falling back to the +5s rule.\n const header = response.headers.get('retry-after');\n const retryAfter = header !== null && /^\\d+$/.test(header.trim()) ? Number(header.trim()) : undefined;\n\n return { error, errorDescription, status: response.status, retryAfter };\n}\n\n/** The typed error for a failure: a subclass for the codes callers branch on, else the base. */\nexport function grantError(failure: OAuthFailure, fallback: string): AgentGrantError {\n const Klass = (failure.error !== undefined ? BY_CODE[failure.error] : undefined) ?? AgentGrantError;\n const detail = failure.error ?? `HTTP ${failure.status}`;\n\n return new Klass(`${fallback}: ${detail}`, failure.error, failure.errorDescription, failure.status, failure.retryAfter);\n}\n","import { assertSecureIssuer } from '../issuer.js';\nimport { AuthenticationError, ConfigurationError } from '../errors.js';\nimport { GrantCancelledError } from './errors.js';\n\n/**\n * RFC 8414 authorization server metadata, as Cbox ID publishes it at\n * `{issuer}/.well-known/oauth-authorization-server`. Only the members this module reads are\n * typed; the rest pass through.\n */\nexport interface AuthorizationServerMetadata {\n issuer: string;\n token_endpoint: string;\n registration_endpoint?: string;\n backchannel_authentication_endpoint?: string;\n device_authorization_endpoint?: string;\n backchannel_token_delivery_modes_supported?: string[];\n backchannel_user_code_parameter_supported?: boolean;\n grant_types_supported?: string[];\n token_endpoint_auth_methods_supported?: string[];\n token_endpoint_auth_signing_alg_values_supported?: string[];\n [member: string]: unknown;\n}\n\n/** Transport options every call in this module takes. */\nexport interface AgentRequestOptions {\n /** A `fetch` to use instead of the global one (tests, proxies, instrumentation). */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 10 000. */\n timeoutMs?: number;\n /** Abort the call (and, for the wait helpers, the whole wait). */\n signal?: AbortSignal;\n}\n\n/** Where to find the server: its issuer, and optionally metadata you already discovered. */\nexport interface AgentServerOptions extends AgentRequestOptions {\n /** The Cbox ID issuer, e.g. `https://acme.cboxid.com`. Must be https (loopback excepted). */\n issuer: string;\n /**\n * Metadata from {@link discoverAuthorizationServer}. Pass it to skip a discovery round\n * trip per call; omitted, each call discovers it (the wait helpers discover once).\n */\n metadata?: AuthorizationServerMetadata;\n}\n\n/**\n * Fetch and check the authorization server metadata (RFC 8414).\n *\n * The document's `issuer` must equal the one asked for (§3.3) — otherwise a host answering\n * with another tenant's metadata would receive this client's assertions and codes.\n */\nexport async function discoverAuthorizationServer(\n issuer: string,\n options: AgentRequestOptions = {},\n): Promise<AuthorizationServerMetadata> {\n if (!issuer) {\n throw new ConfigurationError('An `issuer` is required.');\n }\n assertSecureIssuer(issuer);\n\n const url = `${trimSlash(issuer)}/.well-known/oauth-authorization-server`;\n const response = await send(url, { method: 'GET', headers: { accept: 'application/json' } }, options);\n\n if (!response.ok) {\n throw new AuthenticationError(`Discovery request failed with status ${response.status}.`, undefined, undefined, response.status);\n }\n\n let doc: unknown;\n try {\n doc = await response.json();\n } catch {\n throw new AuthenticationError('The authorization server metadata was not JSON.');\n }\n\n if (typeof doc !== 'object' || doc === null) {\n throw new AuthenticationError('The authorization server metadata was not an object.');\n }\n\n const metadata = doc as AuthorizationServerMetadata;\n\n if (typeof metadata.issuer !== 'string' || trimSlash(metadata.issuer) !== trimSlash(issuer)) {\n throw new AuthenticationError(`The authorization server metadata is for a different issuer (${String(metadata.issuer)}).`);\n }\n if (typeof metadata.token_endpoint !== 'string' || metadata.token_endpoint === '') {\n throw new AuthenticationError('The authorization server metadata has no token_endpoint.');\n }\n\n return metadata;\n}\n\n/** Metadata from the options, or discovered. */\nexport function resolveMetadata(options: AgentServerOptions): Promise<AuthorizationServerMetadata> {\n return options.metadata !== undefined\n ? Promise.resolve(options.metadata)\n : discoverAuthorizationServer(options.issuer, options);\n}\n\n/** A named endpoint, or a ConfigurationError saying the server does not offer it. */\nexport function requireEndpoint(\n metadata: AuthorizationServerMetadata,\n name: 'registration_endpoint' | 'backchannel_authentication_endpoint' | 'device_authorization_endpoint' | 'token_endpoint',\n what: string,\n): string {\n const value = metadata[name];\n if (typeof value !== 'string' || value === '') {\n throw new ConfigurationError(`This Cbox ID instance does not advertise a ${name}, so it does not support ${what}.`);\n }\n return value;\n}\n\n/**\n * `fetch` with a timeout and the caller's signal combined. A caller abort becomes\n * {@link GrantCancelledError}; a timeout or network failure an {@link AuthenticationError}.\n */\nexport async function send(url: string, init: RequestInit, options: AgentRequestOptions): Promise<Response> {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 10_000);\n const onAbort = (): void => controller.abort();\n\n if (options.signal?.aborted === true) {\n clearTimeout(timer);\n throw new GrantCancelledError('The request was cancelled.');\n }\n options.signal?.addEventListener('abort', onAbort, { once: true });\n\n try {\n return await fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n // Re-read through a widened type: the early return above narrowed `aborted` to false,\n // but the signal may have fired while the request was in flight.\n if ((options.signal as AbortSignal | undefined)?.aborted === true) {\n throw new GrantCancelledError('The request was cancelled.');\n }\n if (controller.signal.aborted) {\n throw new AuthenticationError(`The request to ${new URL(url).origin} timed out.`);\n }\n throw new AuthenticationError(`The request to ${new URL(url).origin} failed: ${String(error)}`);\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener('abort', onAbort);\n }\n}\n\nexport function trimSlash(value: string): string {\n return value.replace(/\\/+$/, '');\n}\n","import { calculateJwkThumbprint, exportJWK, generateKeyPair, importJWK, SignJWT, type JWK } from 'jose';\nimport { ConfigurationError } from '../errors.js';\nimport { randomToken } from '../pkce.js';\n\n/** The client-assertion algorithms this module signs with. Cbox ID accepts both. */\nexport type ClientKeyAlgorithm = 'ES256' | 'RS256';\n\n/** A signing key pair for `private_key_jwt`, from {@link generateClientKeyPair}. */\nexport interface ClientKeyPair {\n alg: ClientKeyAlgorithm;\n /** The RFC 7638 thumbprint of the public key, used as `kid`. */\n kid: string;\n /** The public JWK (with `kid`, `alg`, `use: 'sig'`) — what registration sends in `jwks`. */\n publicJwk: JWK;\n /**\n * The private JWK. PERSIST THIS, and only this, somewhere the user alone can read\n * (mode 0600, the OS keychain). It is the client's credential: whoever holds it is the\n * client. Never log it, never commit it.\n */\n privateJwk: JWK;\n /** The private key as a WebCrypto `CryptoKey`, ready to sign with. */\n privateKey: CryptoKey;\n}\n\n/**\n * How the client authenticates at the backchannel, device and token endpoints.\n *\n * - `private_key_jwt` (RFC 7523): a short-lived assertion signed with your private key.\n * The right choice for a self-registered agent or CLI: nothing secret ever crosses the\n * wire, and the server stores only the public key.\n * - `client_secret_basic` / `client_secret_post`: a console-issued secret.\n * - `none`: a public client names itself by `client_id` only. Fine for the device grant.\n * For CIBA, Cbox ID accepts a keyless self-registered client only when the resource\n * allows it (`dynamic_public_backchannel`); otherwise the answer is `invalid_target`.\n * Prefer `private_key_jwt` for CIBA: a public `client_id` proves nothing, and CIBA has no front\n * channel to bind the flow to.\n */\nexport type ClientAuth =\n | {\n method: 'private_key_jwt';\n clientId: string;\n /** A `CryptoKey`, or the private JWK you persisted from {@link generateClientKeyPair}. */\n privateKey: CryptoKey | JWK;\n /** Inferred from the key when omitted. */\n alg?: ClientKeyAlgorithm;\n /** Sent as the assertion's `kid`. Taken from a JWK's own `kid` when omitted. */\n kid?: string;\n }\n | { method: 'client_secret_basic' | 'client_secret_post'; clientId: string; clientSecret: string }\n | { method: 'none'; clientId: string };\n\n/**\n * A fresh signing key pair for `private_key_jwt`, generated with WebCrypto (via `jose`), so\n * it runs on Node, Deno, Bun and edge runtimes. ES256 by default — small keys, small\n * signatures. The private key is extractable on purpose: the caller must persist it.\n */\nexport async function generateClientKeyPair(alg: ClientKeyAlgorithm = 'ES256'): Promise<ClientKeyPair> {\n const { publicKey, privateKey } = await generateKeyPair(alg, { extractable: true });\n const publicBare = await exportJWK(publicKey);\n const kid = await calculateJwkThumbprint(publicBare, 'sha256');\n\n const publicJwk: JWK = { ...publicBare, kid, alg, use: 'sig' };\n const privateJwk: JWK = { ...(await exportJWK(privateKey)), kid, alg, use: 'sig' };\n\n return { alg, kid, publicJwk, privateJwk, privateKey };\n}\n\n/**\n * A signed RFC 7523 client assertion: `iss` = `sub` = client id, `aud` = the token\n * endpoint, a random `jti` (the server remembers it, so each assertion is single-use),\n * `iat` now and `exp` at most 60 seconds later.\n */\nexport async function createClientAssertion(\n auth: Extract<ClientAuth, { method: 'private_key_jwt' }>,\n audience: string,\n options: { now?: () => number; lifetimeSeconds?: number } = {},\n): Promise<string> {\n const lifetime = Math.min(Math.max(options.lifetimeSeconds ?? 60, 1), 60);\n const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000);\n const { key, alg, kid } = await signingKey(auth);\n\n const header: { alg: string; kid?: string } = { alg };\n if (kid !== undefined) {\n header.kid = kid;\n }\n\n return new SignJWT({})\n .setProtectedHeader(header)\n .setIssuer(auth.clientId)\n .setSubject(auth.clientId)\n .setAudience(audience)\n .setJti(randomToken(16))\n .setIssuedAt(nowSeconds)\n .setExpirationTime(nowSeconds + lifetime)\n .sign(key);\n}\n\n/**\n * Put client authentication on a request: fields in the form body, and/or an\n * `Authorization` header. `audience` is the token endpoint, the one value Cbox ID accepts\n * on assertions to all of its endpoints.\n */\nexport async function applyClientAuth(\n auth: ClientAuth,\n body: URLSearchParams,\n headers: Record<string, string>,\n audience: string,\n): Promise<void> {\n if (!auth.clientId) {\n throw new ConfigurationError('A `clientId` is required.');\n }\n\n switch (auth.method) {\n case 'private_key_jwt':\n body.set('client_id', auth.clientId);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await createClientAssertion(auth, audience));\n return;\n case 'client_secret_basic':\n if (!auth.clientSecret) {\n throw new ConfigurationError('`client_secret_basic` needs a `clientSecret`.');\n }\n // RFC 6749 §2.3.1: both halves are form-encoded before they are joined.\n headers['authorization'] = `Basic ${btoa(`${formEncode(auth.clientId)}:${formEncode(auth.clientSecret)}`)}`;\n return;\n case 'client_secret_post':\n if (!auth.clientSecret) {\n throw new ConfigurationError('`client_secret_post` needs a `clientSecret`.');\n }\n body.set('client_id', auth.clientId);\n body.set('client_secret', auth.clientSecret);\n return;\n case 'none':\n body.set('client_id', auth.clientId);\n return;\n }\n}\n\nasync function signingKey(\n auth: Extract<ClientAuth, { method: 'private_key_jwt' }>,\n): Promise<{ key: CryptoKey | Uint8Array; alg: ClientKeyAlgorithm; kid: string | undefined }> {\n const source = auth.privateKey;\n\n if (isCryptoKey(source)) {\n const alg = auth.alg ?? algFromCryptoKey(source);\n return { key: source, alg, kid: auth.kid };\n }\n\n if (typeof source !== 'object' || source === null || typeof source.d !== 'string') {\n throw new ConfigurationError('`privateKey` must be a CryptoKey or a private JWK (with `d`).');\n }\n\n const alg = auth.alg ?? algFromJwk(source);\n const key = await importJWK(source, alg);\n\n return { key, alg, kid: auth.kid ?? (typeof source.kid === 'string' ? source.kid : undefined) };\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof CryptoKey !== 'undefined' && value instanceof CryptoKey;\n}\n\nfunction algFromCryptoKey(key: CryptoKey): ClientKeyAlgorithm {\n if (key.algorithm.name === 'ECDSA') {\n return 'ES256';\n }\n if (key.algorithm.name === 'RSASSA-PKCS1-v1_5') {\n return 'RS256';\n }\n throw new ConfigurationError(`Unsupported client key algorithm ${key.algorithm.name}; use ES256 or RS256.`);\n}\n\nfunction algFromJwk(jwk: JWK): ClientKeyAlgorithm {\n if (jwk.alg === 'ES256' || jwk.alg === 'RS256') {\n return jwk.alg as ClientKeyAlgorithm;\n }\n if (jwk.alg === undefined && jwk.kty === 'EC' && jwk.crv === 'P-256') {\n return 'ES256';\n }\n if (jwk.alg === undefined && jwk.kty === 'RSA') {\n return 'RS256';\n }\n throw new ConfigurationError('The private JWK is not an ES256 (P-256) or RS256 key.');\n}\n\nfunction formEncode(value: string): string {\n return encodeURIComponent(value).replace(/%20/g, '+');\n}\n","import { AuthenticationError, ConfigurationError } from '../errors.js';\nimport { generateClientKeyPair, type ClientAuth, type ClientKeyAlgorithm, type ClientKeyPair } from './client-auth.js';\nimport { grantError, readOAuthFailure } from './errors.js';\nimport { requireEndpoint, resolveMetadata, send, type AgentServerOptions } from './http.js';\n\n/** The CIBA grant type (OpenID CIBA Core). */\nexport const CIBA_GRANT_TYPE = 'urn:openid:params:grant-type:ciba';\n/** The device authorization grant type (RFC 8628). */\nexport const DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\n\nexport interface RegisterAgentClientOptions extends AgentServerOptions {\n /** Shown to the person approving, so make it recognisable: \"Cbox Brain CLI on ada-mbp\". */\n clientName: string;\n /** e.g. `[CIBA_GRANT_TYPE, 'refresh_token']` or `[DEVICE_CODE_GRANT_TYPE, 'refresh_token']`. */\n grantTypes: string[];\n /** The scope ceiling to register. A space-separated string or a list. */\n scope?: string | string[];\n /**\n * `private_key_jwt` (default): a key pair is generated (or `keyPair` used) and the\n * public half registered inline as `jwks`. `none`: a public client — the device grant,\n * or CIBA where the resource allows keyless clients. `private_key_jwt` is recommended for CIBA.\n */\n tokenEndpointAuthMethod?: 'private_key_jwt' | 'none';\n /** Algorithm for the generated key pair. Default ES256. */\n alg?: ClientKeyAlgorithm;\n /** Register an existing key pair instead of generating one. */\n keyPair?: ClientKeyPair;\n /** RFC 7591 §3 initial access token, when the instance requires one to register. */\n initialAccessToken?: string;\n /** Further RFC 7591 client metadata, sent as-is (e.g. `software_id`, `client_uri`). */\n extraMetadata?: Record<string, unknown>;\n}\n\nexport interface RegisteredAgentClient {\n clientId: string;\n /** Present only if the server issued one; a `private_key_jwt` or `none` client has none. */\n clientSecret: string | null;\n /** RFC 7592 credential for reading/updating/deleting the registration. Persist it if you need that. */\n registrationAccessToken: string | null;\n registrationClientUri: string | null;\n tokenEndpointAuthMethod: string;\n grantTypes: string[];\n scope: string | null;\n /** The key pair registered, for `private_key_jwt`. Persist `keyPair.privateJwk`. */\n keyPair: ClientKeyPair | null;\n /** Ready to hand to {@link startBackchannel} / {@link startDeviceAuthorization}. */\n auth: ClientAuth;\n /** The full registration response. */\n raw: Record<string, unknown>;\n}\n\n/**\n * Register this agent or CLI as an OAuth client (RFC 7591 dynamic client registration).\n *\n * Do it once per installation and persist the result: `clientId` and, for\n * `private_key_jwt`, `keyPair.privateJwk`. Re-registering on every run fills the\n * environment's app list with copies.\n *\n * @throws ConfigurationError when the instance has dynamic registration switched off.\n * @throws AgentGrantError (e.g. `invalid_client_metadata`) when the server refuses.\n */\nexport async function registerAgentClient(options: RegisterAgentClientOptions): Promise<RegisteredAgentClient> {\n if (!options.clientName) {\n throw new ConfigurationError('`clientName` is required.');\n }\n if (options.grantTypes.length === 0) {\n throw new ConfigurationError('`grantTypes` must name at least one grant.');\n }\n\n const metadata = await resolveMetadata(options);\n const endpoint = requireEndpoint(metadata, 'registration_endpoint', 'dynamic client registration');\n const method = options.tokenEndpointAuthMethod ?? 'private_key_jwt';\n\n const keyPair = method === 'private_key_jwt'\n ? options.keyPair ?? (await generateClientKeyPair(options.alg ?? 'ES256'))\n : null;\n\n const document: Record<string, unknown> = {\n ...options.extraMetadata,\n client_name: options.clientName,\n grant_types: options.grantTypes,\n token_endpoint_auth_method: method,\n // Neither CIBA nor the device grant has a redirect; say so rather than let the server\n // assume an authorization-code client.\n redirect_uris: [],\n response_types: [],\n };\n\n if (options.scope !== undefined) {\n document['scope'] = scopeString(options.scope);\n }\n if (keyPair !== null) {\n document['jwks'] = { keys: [keyPair.publicJwk] };\n }\n\n const headers: Record<string, string> = { 'content-type': 'application/json', accept: 'application/json' };\n if (options.initialAccessToken) {\n headers['authorization'] = `Bearer ${options.initialAccessToken}`;\n }\n\n const response = await send(endpoint, { method: 'POST', headers, body: JSON.stringify(document) }, options);\n\n if (!response.ok) {\n throw grantError(await readOAuthFailure(response), 'Client registration failed');\n }\n\n const raw = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n const clientId = raw?.['client_id'];\n\n if (raw === null || typeof clientId !== 'string' || clientId === '') {\n throw new AuthenticationError('The registration response carried no client_id.');\n }\n\n const clientSecret = typeof raw['client_secret'] === 'string' ? raw['client_secret'] : null;\n const registeredMethod = typeof raw['token_endpoint_auth_method'] === 'string' ? raw['token_endpoint_auth_method'] : method;\n\n let auth: ClientAuth;\n if (keyPair !== null) {\n auth = { method: 'private_key_jwt', clientId, privateKey: keyPair.privateKey, alg: keyPair.alg, kid: keyPair.kid };\n } else if (clientSecret !== null) {\n auth = { method: 'client_secret_basic', clientId, clientSecret };\n } else {\n auth = { method: 'none', clientId };\n }\n\n return {\n clientId,\n clientSecret,\n registrationAccessToken: typeof raw['registration_access_token'] === 'string' ? raw['registration_access_token'] : null,\n registrationClientUri: typeof raw['registration_client_uri'] === 'string' ? raw['registration_client_uri'] : null,\n tokenEndpointAuthMethod: registeredMethod,\n grantTypes: Array.isArray(raw['grant_types']) ? raw['grant_types'].filter((g): g is string => typeof g === 'string') : options.grantTypes,\n scope: typeof raw['scope'] === 'string' ? raw['scope'] : null,\n keyPair,\n auth,\n raw,\n };\n}\n\nexport function scopeString(scope: string | string[]): string {\n return (typeof scope === 'string' ? scope.split(/\\s+/) : scope).filter((s) => s !== '').join(' ');\n}\n","import { AuthenticationError, ConfigurationError } from '../errors.js';\nimport { applyClientAuth, type ClientAuth } from './client-auth.js';\nimport { ExpiredTokenError, GrantCancelledError, grantError, readOAuthFailure } from './errors.js';\nimport {\n requireEndpoint,\n resolveMetadata,\n send,\n type AgentServerOptions,\n type AuthorizationServerMetadata,\n} from './http.js';\nimport { CIBA_GRANT_TYPE, DEVICE_CODE_GRANT_TYPE, scopeString } from './register.js';\n\n/** Tokens from a completed CIBA or device grant. */\nexport interface AgentTokens {\n accessToken: string;\n tokenType: string;\n /** Seconds, when the server said. */\n expiresIn: number | null;\n refreshToken: string | null;\n /**\n * The id_token, when `openid` was granted — returned as-is, NOT verified here. Verify it\n * with `CboxIdClient` (or `jose` against the JWKS) before trusting anything in it.\n */\n idToken: string | null;\n scope: string | null;\n /** The full token response. */\n raw: Record<string, unknown>;\n}\n\n/** One poll's outcome. Final failures are thrown, not returned. */\nexport type PollResult =\n | { status: 'complete'; tokens: AgentTokens }\n | { status: 'pending' }\n /** Slow down: add 5 s to the interval, and wait at least `retryAfter` seconds if given. */\n | { status: 'slow_down'; retryAfter: number | null };\n\n/** Options shared by the wait helpers. */\nexport interface WaitOptions {\n /** Replace the timer — tests pass a fake that records the waits. Must honour `signal`. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Clock in epoch milliseconds. Default `Date.now`. */\n now?: () => number;\n}\n\ninterface ClientOptions extends AgentServerOptions {\n /** How the client authenticates. See {@link ClientAuth}. */\n client: ClientAuth;\n}\n\n// ---------------------------------------------------------------------------------------\n// CIBA (poll mode)\n// ---------------------------------------------------------------------------------------\n\nexport interface StartBackchannelOptions extends ClientOptions {\n /** Who should approve: a Cbox ID user id, or a confirmed email address. */\n loginHint: string;\n /** Space-separated string or list. Bounded by the client's registered scopes. */\n scope: string | string[];\n /**\n * Shown beside Approve. Put a {@link createBindingCode} code in it and print the same\n * code locally. Required by Cbox ID for self-registered clients; at most 255 characters.\n */\n bindingMessage: string;\n /**\n * RFC 8707 resource indicator(s) — the API the token is for. Optional in the type, but\n * REQUIRED by Cbox ID for self-registered clients.\n * Its settings also decide whether a keyless (`none`) client may use CIBA at all.\n */\n resource?: string | string[];\n /** Seconds the request may wait for approval (the server may shorten it). */\n requestedExpiry?: number;\n /** Echoed into the id_token, so you can bind it to this request. */\n nonce?: string;\n}\n\n/** A started CIBA request. Persistable as JSON. */\nexport interface BackchannelAuthorization {\n authReqId: string;\n expiresIn: number;\n /** Seconds between polls. */\n interval: number;\n /** Epoch ms after which polling is pointless. */\n expiresAt: number;\n /** The resource(s) the request named, re-sent on every poll (the server checks they match). */\n resource: string[];\n}\n\n/**\n * Start a CIBA request (OpenID CIBA Core §7, poll mode): Cbox ID shows `bindingMessage` to\n * the person named by `loginHint` and waits for Approve.\n *\n * `backchannel_user_code_parameter` is not supported by Cbox ID, so no user code is sent.\n *\n * @throws InvalidClientError, UnknownUserIdError, InvalidBindingMessageError,\n * InvalidTargetError, SlowDownError, AgentGrantError.\n */\nexport async function startBackchannel(options: StartBackchannelOptions): Promise<BackchannelAuthorization> {\n const now = Date.now();\n const metadata = await resolveMetadata(options);\n const endpoint = requireEndpoint(metadata, 'backchannel_authentication_endpoint', 'CIBA');\n\n if (!options.loginHint) {\n throw new ConfigurationError('`loginHint` is required.');\n }\n\n const resource = resourceList(options.resource);\n const body = new URLSearchParams({ login_hint: options.loginHint, scope: scopeString(options.scope) });\n\n if (options.bindingMessage !== '') {\n body.set('binding_message', options.bindingMessage);\n }\n for (const r of resource) {\n body.append('resource', r);\n }\n if (options.requestedExpiry !== undefined) {\n body.set('requested_expiry', String(options.requestedExpiry));\n }\n if (options.nonce !== undefined && options.nonce !== '') {\n body.set('nonce', options.nonce);\n }\n\n const payload = await postForm(endpoint, body, options, metadata, 'Backchannel authentication request failed');\n const authReqId = payload['auth_req_id'];\n\n if (typeof authReqId !== 'string' || authReqId === '') {\n throw new AuthenticationError('The backchannel authentication response carried no auth_req_id.');\n }\n\n const expiresIn = positiveNumber(payload['expires_in']) ?? 120;\n\n return {\n authReqId,\n expiresIn,\n // CIBA Core §7.3: absent means 5 seconds.\n interval: positiveNumber(payload['interval']) ?? 5,\n expiresAt: now + expiresIn * 1000,\n resource,\n };\n}\n\nexport interface PollBackchannelOptions extends ClientOptions {\n authorization: Pick<BackchannelAuthorization, 'authReqId' | 'resource'>;\n}\n\n/**\n * Poll the token endpoint once for a CIBA request.\n *\n * @throws AccessDeniedError, ExpiredTokenError, InvalidGrantError, InvalidTargetError,\n * InvalidClientError, AgentGrantError.\n */\nexport async function pollBackchannel(options: PollBackchannelOptions): Promise<PollResult> {\n const body = new URLSearchParams({ grant_type: CIBA_GRANT_TYPE, auth_req_id: options.authorization.authReqId });\n return pollToken(body, options.authorization.resource, options, 'Backchannel token request failed');\n}\n\n/**\n * Poll until the person approves, and return the tokens.\n *\n * Waits `interval` seconds before each poll; on `slow_down` (or a 429) adds five seconds\n * for good and waits at least `Retry-After`; keeps going on `authorization_pending`; stops\n * on anything final. Throws {@link ExpiredTokenError} once `expiresAt` passes and\n * {@link GrantCancelledError} when `signal` fires — wire it to Ctrl-C.\n */\nexport async function waitForBackchannelToken(\n options: PollBackchannelOptions & WaitOptions & { authorization: BackchannelAuthorization },\n): Promise<AgentTokens> {\n const metadata = await resolveMetadata(options);\n const authorization = options.authorization;\n\n return waitLoop(authorization, options, () => pollBackchannel({ ...options, metadata }), 'backchannel request');\n}\n\n// ---------------------------------------------------------------------------------------\n// Device authorization grant (RFC 8628)\n// ---------------------------------------------------------------------------------------\n\nexport interface StartDeviceAuthorizationOptions extends ClientOptions {\n scope?: string | string[];\n /** RFC 8707 resource indicator(s). */\n resource?: string | string[];\n}\n\n/** A started device authorization. Persistable as JSON. */\nexport interface DeviceGrantAuthorization {\n deviceCode: string;\n /** Show this to the person. */\n userCode: string;\n /** Where they enter it. */\n verificationUri: string;\n /** The same page with the code filled in — good for a QR code or `open`. */\n verificationUriComplete: string | null;\n expiresIn: number;\n interval: number;\n expiresAt: number;\n resource: string[];\n}\n\n/**\n * Start the device authorization grant: you get a `userCode` to show and a\n * `verificationUri` for the person to open on any device.\n *\n * @throws InvalidClientError, InvalidTargetError, SlowDownError, AgentGrantError.\n */\nexport async function startDeviceAuthorization(options: StartDeviceAuthorizationOptions): Promise<DeviceGrantAuthorization> {\n const now = Date.now();\n const metadata = await resolveMetadata(options);\n const endpoint = requireEndpoint(metadata, 'device_authorization_endpoint', 'the device grant');\n const resource = resourceList(options.resource);\n const body = new URLSearchParams();\n\n if (options.scope !== undefined) {\n body.set('scope', scopeString(options.scope));\n }\n for (const r of resource) {\n body.append('resource', r);\n }\n\n const payload = await postForm(endpoint, body, options, metadata, 'Device authorization request failed');\n const deviceCode = payload['device_code'];\n const userCode = payload['user_code'];\n const verificationUri = payload['verification_uri'];\n\n if (typeof deviceCode !== 'string' || typeof userCode !== 'string' || typeof verificationUri !== 'string') {\n throw new AuthenticationError('The device authorization response was incomplete.');\n }\n\n const expiresIn = positiveNumber(payload['expires_in']) ?? 600;\n\n return {\n deviceCode,\n userCode,\n verificationUri,\n verificationUriComplete: typeof payload['verification_uri_complete'] === 'string' ? payload['verification_uri_complete'] : null,\n expiresIn,\n // RFC 8628 §3.2: absent means 5 seconds.\n interval: positiveNumber(payload['interval']) ?? 5,\n expiresAt: now + expiresIn * 1000,\n resource,\n };\n}\n\nexport interface PollDeviceAuthorizationOptions extends ClientOptions {\n authorization: Pick<DeviceGrantAuthorization, 'deviceCode' | 'resource'>;\n}\n\n/** Poll the token endpoint once for a device authorization. */\nexport async function pollDeviceAuthorization(options: PollDeviceAuthorizationOptions): Promise<PollResult> {\n const body = new URLSearchParams({ grant_type: DEVICE_CODE_GRANT_TYPE, device_code: options.authorization.deviceCode });\n return pollToken(body, options.authorization.resource, options, 'Device token request failed');\n}\n\n/** Poll until the person approves the device code. Same rules as {@link waitForBackchannelToken}. */\nexport async function waitForDeviceToken(\n options: PollDeviceAuthorizationOptions & WaitOptions & { authorization: DeviceGrantAuthorization },\n): Promise<AgentTokens> {\n const metadata = await resolveMetadata(options);\n\n return waitLoop(options.authorization, options, () => pollDeviceAuthorization({ ...options, metadata }), 'device code');\n}\n\n// ---------------------------------------------------------------------------------------\n// Refresh\n// ---------------------------------------------------------------------------------------\n\nexport interface RefreshAgentTokensOptions extends ClientOptions {\n refreshToken: string;\n /** Narrow the scope (never widen it). */\n scope?: string | string[];\n /** RFC 8707 resource indicator(s) for the new access token. */\n resource?: string | string[];\n}\n\n/**\n * Exchange a refresh token, authenticating the same way the grant did (including\n * `private_key_jwt`). Cbox ID rotates refresh tokens and revokes the family on reuse, so\n * ALWAYS persist the returned `refreshToken` and discard the old one.\n *\n * @throws InvalidGrantError when the refresh token is no longer valid — sign in again.\n */\nexport async function refreshAgentTokens(options: RefreshAgentTokensOptions): Promise<AgentTokens> {\n if (!options.refreshToken) {\n throw new ConfigurationError('`refreshToken` is required.');\n }\n\n const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: options.refreshToken });\n if (options.scope !== undefined) {\n body.set('scope', scopeString(options.scope));\n }\n\n // `polling: false`: pending and slow_down mean nothing on a refresh, so they are thrown\n // like any other refusal (a 429 as SlowDownError with its Retry-After).\n const result = await pollToken(body, resourceList(options.resource), options, 'Token refresh failed', false);\n\n return (result as Extract<PollResult, { status: 'complete' }>).tokens;\n}\n\n// ---------------------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------------------\n\nasync function waitLoop(\n authorization: { interval: number; expiresAt: number },\n options: WaitOptions & { signal?: AbortSignal },\n poll: () => Promise<PollResult>,\n what: string,\n): Promise<AgentTokens> {\n const sleep = options.sleep ?? defaultSleep;\n const now = options.now ?? Date.now;\n let intervalMs = Math.max(authorization.interval, 0) * 1000;\n let nextWaitMs = intervalMs;\n\n for (;;) {\n throwIfAborted(options.signal);\n\n if (now() >= authorization.expiresAt) {\n throw new ExpiredTokenError(`The ${what} expired before it was approved. Start again.`, 'expired_token');\n }\n\n await sleep(nextWaitMs, options.signal);\n // A custom sleep may not honour the signal; check again before spending a request.\n throwIfAborted(options.signal);\n\n if (now() >= authorization.expiresAt) {\n throw new ExpiredTokenError(`The ${what} expired before it was approved. Start again.`, 'expired_token');\n }\n\n const result = await poll();\n\n if (result.status === 'complete') {\n return result.tokens;\n }\n\n if (result.status === 'slow_down') {\n // Permanently, not for one round (RFC 8628 §3.5, CIBA Core §11): returning to the\n // refused rate earns the same answer forever.\n intervalMs += 5000;\n nextWaitMs = Math.max(intervalMs, (result.retryAfter ?? 0) * 1000);\n continue;\n }\n\n nextWaitMs = intervalMs;\n }\n}\n\nasync function pollToken(\n body: URLSearchParams,\n resource: readonly string[],\n options: ClientOptions,\n fallback: string,\n polling = true,\n): Promise<PollResult> {\n const metadata = await resolveMetadata(options);\n const endpoint = requireEndpoint(metadata, 'token_endpoint', 'token requests');\n\n // The same resource(s) the request started with; Cbox ID refuses a mismatch with\n // invalid_target.\n for (const r of resource) {\n body.append('resource', r);\n }\n\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };\n await applyClientAuth(options.client, body, headers, metadata.token_endpoint);\n\n const response = await send(endpoint, { method: 'POST', headers, body }, options);\n\n if (response.ok) {\n return { status: 'complete', tokens: await tokensFrom(response) };\n }\n\n const failure = await readOAuthFailure(response);\n\n if (polling && failure.error === 'authorization_pending') {\n return { status: 'pending' };\n }\n if (polling && failure.error === 'slow_down') {\n return { status: 'slow_down', retryAfter: failure.retryAfter ?? null };\n }\n\n throw grantError(failure, fallback);\n}\n\nasync function postForm(\n endpoint: string,\n body: URLSearchParams,\n options: ClientOptions,\n metadata: AuthorizationServerMetadata,\n fallback: string,\n): Promise<Record<string, unknown>> {\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };\n await applyClientAuth(options.client, body, headers, metadata.token_endpoint);\n\n const response = await send(endpoint, { method: 'POST', headers, body }, options);\n\n if (!response.ok) {\n throw grantError(await readOAuthFailure(response), fallback);\n }\n\n const payload: unknown = await response.json().catch(() => null);\n if (typeof payload !== 'object' || payload === null) {\n throw new AuthenticationError(`${fallback}: the response was not a JSON object.`);\n }\n return payload as Record<string, unknown>;\n}\n\nasync function tokensFrom(response: Response): Promise<AgentTokens> {\n const raw = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n const accessToken = raw?.['access_token'];\n\n if (raw === null || typeof accessToken !== 'string' || accessToken === '') {\n throw new AuthenticationError('The token response carried no access_token.');\n }\n\n return {\n accessToken,\n tokenType: typeof raw['token_type'] === 'string' ? raw['token_type'] : 'Bearer',\n expiresIn: typeof raw['expires_in'] === 'number' ? raw['expires_in'] : null,\n refreshToken: typeof raw['refresh_token'] === 'string' ? raw['refresh_token'] : null,\n idToken: typeof raw['id_token'] === 'string' ? raw['id_token'] : null,\n scope: typeof raw['scope'] === 'string' ? raw['scope'] : null,\n raw,\n };\n}\n\nfunction resourceList(resource: string | string[] | undefined): string[] {\n if (resource === undefined) {\n return [];\n }\n const list = typeof resource === 'string' ? [resource] : [...resource];\n for (const r of list) {\n // RFC 8707 §2: an absolute URI without a fragment.\n let url: URL;\n try {\n url = new URL(r);\n } catch {\n throw new ConfigurationError(`\\`resource\\` must be an absolute URI (got ${r}).`);\n }\n if (url.hash !== '') {\n throw new ConfigurationError('`resource` must not contain a fragment.');\n }\n }\n return list;\n}\n\nfunction positiveNumber(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) {\n throw new GrantCancelledError('The wait for approval was cancelled.');\n }\n}\n\n/** An interruptible timer: the abort is wired to the timer, so Ctrl-C does not wait out an interval. */\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(new GrantCancelledError('The wait for approval was cancelled.'));\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(new GrantCancelledError('The wait for approval was cancelled.'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","import { ConfigurationError } from '../errors.js';\n\n/**\n * Uppercase letters and digits a person cannot confuse when reading them off one screen\n * and matching them on another: no 0/O, 1/I/L, 5/S, 2/Z, 8/B.\n */\nexport const BINDING_CODE_ALPHABET = 'ACDEFGHJKMNPQRTUVWXY34679';\n\n/**\n * A short random code for a CIBA `binding_message`, e.g. `K7QM`.\n *\n * Show it in your terminal and put it in the binding message; Cbox ID shows the message\n * beside Approve, and the person approves only when the two match. That is what stops a\n * prompt somebody else triggered from being approved by reflex. Cbox ID requires a\n * binding message from self-registered clients.\n *\n * Uniform over the alphabet (rejection sampling, WebCrypto randomness).\n */\nexport function createBindingCode(length = 4): string {\n if (!Number.isInteger(length) || length < 1 || length > 32) {\n throw new ConfigurationError('A binding code length must be an integer from 1 to 32.');\n }\n\n const size = BINDING_CODE_ALPHABET.length;\n // The largest multiple of `size` that fits in a byte; bytes at or above it are dropped so\n // every character is equally likely.\n const limit = 256 - (256 % size);\n let code = '';\n\n while (code.length < length) {\n for (const byte of crypto.getRandomValues(new Uint8Array(length * 2))) {\n if (byte < limit && code.length < length) {\n code += BINDING_CODE_ALPHABET[byte % size];\n }\n }\n }\n\n return code;\n}\n"]}
@@ -1,26 +1,8 @@
1
+ import { createVerifier, randomToken, challenge } from './chunk-VGQASHTI.js';
1
2
  import { assertSecureIssuer } from './chunk-QQW63PGU.js';
2
3
  import { CboxIdError, AuthenticationError, ConfigurationError, InvalidStateError, oauthError } from './chunk-SEUD4TE4.js';
3
4
  import { createRemoteJWKSet, jwtVerify } from 'jose';
4
5
 
5
- // src/pkce.ts
6
- function base64url(bytes) {
7
- let binary = "";
8
- for (const byte of bytes) {
9
- binary += String.fromCharCode(byte);
10
- }
11
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
- }
13
- function randomToken(bytes = 32) {
14
- return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
15
- }
16
- function createVerifier() {
17
- return randomToken(32);
18
- }
19
- async function challenge(verifier) {
20
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
21
- return base64url(new Uint8Array(digest));
22
- }
23
-
24
6
  // src/claims.ts
25
7
  var ORGANIZATION_ROLES = /* @__PURE__ */ new Set([
26
8
  "owner",
@@ -1141,6 +1123,6 @@ function sleep(ms, signal) {
1141
1123
  });
1142
1124
  }
1143
1125
 
1144
- export { CboxIdClient, Discovery, FEATURE_FLAGS_SCOPE, PipeLeaseDeniedError, PipeLeaseError, PipeNotConnectedError, PipeReauthorizationRequiredError, PipeTemporarilyUnavailableError, VaultClient, actor, challenge, createVerifier, featureFlags, hasFeature, hasPermission, hasRole, isSupportSession, organization, permissions, pipeConnectUrl, randomToken, roles, sessionId, verifyStandardWebhook, verifyWebhook, withConnectReturn };
1145
- //# sourceMappingURL=chunk-YGLMLIKL.js.map
1146
- //# sourceMappingURL=chunk-YGLMLIKL.js.map
1126
+ export { CboxIdClient, Discovery, FEATURE_FLAGS_SCOPE, PipeLeaseDeniedError, PipeLeaseError, PipeNotConnectedError, PipeReauthorizationRequiredError, PipeTemporarilyUnavailableError, VaultClient, actor, featureFlags, hasFeature, hasPermission, hasRole, isSupportSession, organization, permissions, pipeConnectUrl, roles, sessionId, verifyStandardWebhook, verifyWebhook, withConnectReturn };
1127
+ //# sourceMappingURL=chunk-T5LCQOLS.js.map
1128
+ //# sourceMappingURL=chunk-T5LCQOLS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/claims.ts","../src/vault.ts","../src/webhook.ts","../src/discovery.ts","../src/client.ts"],"names":["header","key"],"mappings":";;;;;;AAUA,IAAM,kBAAA,uBAA8C,GAAA,CAAsB;AAAA,EACxE,OAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF,CAAC,CAAA;AA6CM,SAAS,aAAa,MAAA,EAAoD;AAC/E,EAAA,MAAM,MAAA,GAAS,SAAS,MAAM,CAAA;AAC9B,EAAA,MAAM,EAAA,GAAK,OAAO,KAAK,CAAA;AAEvB,EAA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A,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH","file":"chunk-T5LCQOLS.js","sourcesContent":["import type { CboxUser } from './types.js';\n\n/**\n * The membership tier a person holds in the organization a token is bound to — the\n * `org_role` claim. Coarse on purpose: it says who may administer the organization\n * itself (invite, bill, delete). What they may do inside YOUR app is `roles` /\n * `permissions`, which your app declares and Cbox ID assigns.\n */\nexport type OrganizationRole = 'owner' | 'admin' | 'developer' | 'member' | 'viewer';\n\nconst ORGANIZATION_ROLES: ReadonlySet<string> = new Set<OrganizationRole>([\n 'owner',\n 'admin',\n 'developer',\n 'member',\n 'viewer',\n]);\n\n/** The organization a token is bound to: the `org`, `org_name` and `org_role` claims. */\nexport interface CboxActiveOrganization {\n /** The stable organization id (`org`). */\n id: string;\n /** Its display name (`org_name`), when the instance sent one. */\n name: string | null;\n /**\n * The person's membership tier in it (`org_role`). Null when the claim is absent, or\n * carries a tier this SDK version does not know — an unrecognised tier is never\n * guessed upward into one that grants something.\n */\n role: OrganizationRole | null;\n}\n\n/**\n * Who is actually driving a delegated session — the RFC 8693 §4.1 `act` claim. Cbox ID\n * sets it on the tokens of a SUPPORT SESSION: a staff member acting as one of your users,\n * with a stated reason, for at most an hour, with no refresh token.\n *\n * `sub` is the actor's subject id. It is null when an `act` claim is present but not in\n * the shape RFC 8693 describes — the token is still acted, and saying so matters more\n * than knowing by whom (see {@link isSupportSession}).\n */\nexport interface CboxActor {\n sub: string | null;\n /** The prior actor, when delegation was chained (RFC 8693 §4.1 nested `act`). */\n actor: CboxActor | null;\n}\n\n/**\n * Anything the helpers below can read claims from: a {@link CboxUser} from sign-in, or a\n * claim set you verified yourself — an access token's payload on a resource server, say.\n */\nexport type ClaimSource = CboxUser | Readonly<Record<string, unknown>>;\n\n/**\n * The organization this session is bound to, or null when it is bound to none.\n *\n * ```ts\n * const org = organization(user);\n * if (org?.role === 'owner') showBilling();\n * ```\n */\nexport function organization(source: ClaimSource): CboxActiveOrganization | null {\n const claims = claimsOf(source);\n const id = claims['org'];\n\n if (typeof id !== 'string' || id === '') {\n return null;\n }\n\n const name = claims['org_name'];\n const role = claims['org_role'];\n\n return {\n id,\n name: typeof name === 'string' && name !== '' ? name : null,\n role: typeof role === 'string' && ORGANIZATION_ROLES.has(role) ? (role as OrganizationRole) : null,\n };\n}\n\n/**\n * The actor behind a support session (`act`), or null for an ordinary session in which\n * the person is acting as themselves.\n */\nexport function actor(source: ClaimSource): CboxActor | null {\n return parseActor(claimsOf(source)['act'], 0);\n}\n\n/**\n * Whether somebody other than the signed-in person is driving this session — a staff\n * member in a support session (the token carries `act`).\n *\n * FAIL-CLOSED. Any `act` claim at all counts, including one whose shape this SDK cannot\n * read: the check exists so an app can show a banner and refuse the things a helper\n * should never do on somebody's behalf (change their password, move their money), and a\n * malformed claim is not evidence that nobody else is at the keyboard.\n */\nexport function isSupportSession(source: ClaimSource): boolean {\n return actor(source) !== null;\n}\n\n/**\n * The Cbox ID sign-in session this token came from — the ID Token's `sid` claim — or null\n * when the instance sent none.\n *\n * Store it with your own session: an OIDC Back-Channel Logout token names the session it\n * ends by this value, and matching on it is how you end the right one (rather than every\n * session the person has) when they sign out of Cbox ID elsewhere.\n */\nexport function sessionId(source: ClaimSource): string | null {\n const sid = claimsOf(source)['sid'];\n\n return typeof sid === 'string' && sid !== '' ? sid : null;\n}\n\n/** The app roles this session holds — the `roles` claim; empty when there are none. */\nexport function roles(source: ClaimSource): string[] {\n return stringList(claimsOf(source)['roles']);\n}\n\n/**\n * The permissions this session holds — the `permissions` claim, already expanded from\n * `roles` by Cbox ID; empty when there are none.\n */\nexport function permissions(source: ClaimSource): string[] {\n return stringList(claimsOf(source)['permissions']);\n}\n\n/** Whether the session holds `role`. Exact match; no wildcards. */\nexport function hasRole(source: ClaimSource, role: string): boolean {\n return roles(source).includes(role);\n}\n\n/**\n * Whether the session holds `permission` (`feature:action`). Exact match; no wildcards\n * — a claim of `invoices:*` does not grant `invoices:delete`, because nothing on the\n * issuing side ever mints one.\n */\nexport function hasPermission(source: ClaimSource, permission: string): boolean {\n return permissions(source).includes(permission);\n}\n\n/**\n * The scope that puts the `feature_flags` claim on the ID token, the access token and\n * UserInfo. Request it at sign-in (`scopes: ['openid', 'profile', FEATURE_FLAGS_SCOPE]`)\n * and give the app the scope on its Scopes tab.\n */\nexport const FEATURE_FLAGS_SCOPE = 'feature_flags';\n\n/**\n * The keys of the feature flags that are on for this person, in the organization the\n * session is bound to — the `feature_flags` claim, sorted as the server sent it.\n *\n * NULL IS NOT EMPTY. `null` means the claim is absent: the `feature_flags` scope was not\n * requested, or the instance predates it. `[]` means it was asked and nothing is on. A\n * token carries the flags as they were when it was issued; the next refresh, or UserInfo,\n * picks up a change.\n */\nexport function featureFlags(source: ClaimSource): string[] | null {\n const claim = claimsOf(source)['feature_flags'];\n\n return Array.isArray(claim) ? stringList(claim) : null;\n}\n\n/**\n * Whether the feature flag `key` is on for this session. Exact match on the key.\n *\n * False when the claim is absent — an app that forgot to request the scope sees every\n * feature off, never every feature on. Use {@link featureFlags} to tell the two apart.\n */\nexport function hasFeature(source: ClaimSource, key: string): boolean {\n return featureFlags(source)?.includes(key) ?? false;\n}\n\n/**\n * Nesting is bounded: RFC 8693 chains are a handful deep in practice, and a claim nested\n * thousands deep is either a bug or an attempt to exhaust the stack. Past the bound the\n * chain is cut, not dropped — the session is still acted.\n */\nconst MAX_ACTOR_DEPTH = 8;\n\nfunction parseActor(claim: unknown, depth: number): CboxActor | null {\n if (claim === undefined || claim === null) {\n return null;\n }\n\n if (typeof claim !== 'object' || Array.isArray(claim)) {\n return { sub: null, actor: null };\n }\n\n const record = claim as Record<string, unknown>;\n const sub = record['sub'];\n\n return {\n sub: typeof sub === 'string' && sub !== '' ? sub : null,\n actor: depth + 1 < MAX_ACTOR_DEPTH ? parseActor(record['act'], depth + 1) : null,\n };\n}\n\nfunction stringList(claim: unknown): string[] {\n return Array.isArray(claim)\n ? claim.filter((value): value is string => typeof value === 'string' && value !== '')\n : [];\n}\n\nfunction claimsOf(source: ClaimSource): Readonly<Record<string, unknown>> {\n return isUser(source) ? source.claims : source;\n}\n\n/**\n * A `CboxUser` is told apart by the credential it carries alongside its claims. A raw\n * claim set never has an `accessToken` key — JWT claims are snake_case — so a verified\n * payload is never mistaken for a user and read from the wrong place.\n */\nfunction isUser(source: ClaimSource): source is CboxUser {\n return (\n typeof source['claims'] === 'object' &&\n source['claims'] !== null &&\n typeof source['accessToken'] === 'string'\n );\n}\n","import { AuthenticationError, CboxIdError } from './errors.js';\n\n/** A stored vault secret's metadata (never its plaintext). */\nexport interface VaultSecretRef {\n id: string;\n name: string;\n provider: string;\n ownerType: string | null;\n ownerId: string | null;\n expiresAt: string | null;\n revoked: boolean;\n}\n\n/** A brokered credential — the plaintext, for immediate use. */\nexport interface VaultLease {\n secretId: string;\n provider: string;\n secret: string;\n expiresAt: string;\n}\n\n/** A provider a pipe can connect to. */\nexport type PipeProvider = 'github' | 'google' | 'microsoft' | 'slack' | 'salesforce' | 'hubspot' | 'linear' | 'notion';\n\n/**\n * A fresh access token for one person's connected account at a provider — what\n * {@link VaultClient.leasePipeToken} returns. Use it, drop it, lease again next time.\n */\nexport interface PipeToken {\n /** The provider's access token. Send it as a bearer token to the provider's API. */\n accessToken: string;\n tokenType: 'Bearer';\n provider: string;\n userId: string;\n connectionId: string;\n /** What the person consented to. */\n scopes: string[];\n /** When the PROVIDER stops accepting it; null for tokens that do not expire. */\n expiresAt: string | null;\n /** When to drop it and lease again. */\n leaseExpiresAt: string;\n /** What some providers need to be called at all — Salesforce's `instance_url`, Slack's `team.id`. */\n metadata: Record<string, string>;\n}\n\n/** Where a person connects a provider, and where they come back to afterwards. */\nexport interface PipeConnectOptions {\n /** Your app's client id — the connect page shows its name and allows its origins. */\n clientId?: string;\n /**\n * Where to land afterwards, with `?provider=…&status=connected|cancelled|failed`. Must be\n * on one of the app's registered redirect origins, or it is ignored.\n */\n returnTo?: string;\n}\n\n/**\n * Add `client_id` and `return_to` to a connect URL — the one a lease error carries, or\n * one built with {@link pipeConnectUrl}.\n */\nexport function withConnectReturn(connectUrl: string, options: PipeConnectOptions = {}): string {\n const url = new URL(connectUrl);\n if (options.clientId) url.searchParams.set('client_id', options.clientId);\n if (options.returnTo) url.searchParams.set('return_to', options.returnTo);\n return url.toString();\n}\n\n/**\n * The hosted page where the signed-in person connects their account at `provider`:\n * `{issuer}/account/connected-services/{provider}/connect?client_id=…&return_to=…`.\n */\nexport function pipeConnectUrl(issuer: string, provider: PipeProvider | string, options: PipeConnectOptions = {}): string {\n return withConnectReturn(\n `${issuer.replace(/\\/$/, '')}/account/connected-services/${encodeURIComponent(provider)}/connect`,\n options,\n );\n}\n\n/**\n * A pipe token lease was refused. Catch the subclasses for the cases you can act on:\n *\n * - {@link PipeNotConnectedError} (404) and {@link PipeReauthorizationRequiredError}\n * (409) — send the person to `connectUrl`.\n * - {@link PipeTemporarilyUnavailableError} (503) — retry after `retryAfter` seconds.\n * - {@link PipeLeaseDeniedError} (403) — a configuration problem: the app is not granted\n * the pipe, it is disabled, or the person is outside the app's organization.\n *\n * Anything else (401, 422, 429) arrives as this base class with `status` and `error`.\n */\nexport class PipeLeaseError extends CboxIdError {\n constructor(\n message: string,\n /** The server's error code, e.g. `not_connected`. */\n readonly error: string | null,\n readonly status: number,\n /** Where to send the person to (re)connect — set on 404 and 409. */\n readonly connectUrl: string | null = null,\n /** Seconds to wait off `Retry-After`, when the server sent one. */\n readonly retryAfter: number | null = null,\n ) {\n super(message);\n }\n\n /** `connectUrl` with your `client_id` and `return_to` on it, or null when there is none. */\n connectUrlWith(options: PipeConnectOptions): string | null {\n return this.connectUrl === null ? null : withConnectReturn(this.connectUrl, options);\n }\n}\n\n/** The person has not connected this provider (404 `not_connected`). Send them to `connectUrl`. */\nexport class PipeNotConnectedError extends PipeLeaseError {\n declare readonly connectUrl: string;\n}\n\n/**\n * The provider stopped accepting the connection — revoked, or the refresh token expired\n * (409 `reauthorization_required`). Send the person to `connectUrl` to connect again.\n */\nexport class PipeReauthorizationRequiredError extends PipeLeaseError {\n declare readonly connectUrl: string;\n}\n\n/** The provider could not refresh the token just now (503). Retry after `retryAfter`. */\nexport class PipeTemporarilyUnavailableError extends PipeLeaseError {}\n\n/**\n * The lease was denied (403 `lease_denied`): the app is not granted the pipe, the pipe is\n * disabled or missing, the person is not in the app's organization, or `userId` names\n * someone other than the token's person. One answer for every reason, by design.\n */\nexport class PipeLeaseDeniedError extends PipeLeaseError {}\n\nexport interface StoreSecretInput {\n name: string;\n provider: string;\n secret: string;\n ownerType?: 'organization' | 'user';\n ownerId?: string;\n expiresAt?: string;\n}\n\n/**\n * Client for a Cbox ID instance's Token Vault API. Bind it to an access token\n * (obtain one with {@link CboxIdClient.machineToken}, scoped `vault.manage` for\n * provisioning or `vault.lease` for redeeming). All calls are server-to-server.\n */\nexport class VaultClient {\n private readonly base: string;\n\n constructor(\n issuer: string,\n private readonly token: string,\n private readonly timeoutMs = 10_000,\n ) {\n this.base = `${issuer.replace(/\\/$/, '')}/api/v1/vault`;\n }\n\n /** Ingest a downstream credential, sealed at rest (scope `vault.manage`). */\n store(input: StoreSecretInput): Promise<VaultSecretRef> {\n return this.json<VaultSecretRef>('POST', '/secrets', {\n name: input.name,\n provider: input.provider,\n secret: input.secret,\n owner_type: input.ownerType,\n owner_id: input.ownerId,\n expires_at: input.expiresAt,\n });\n }\n\n /** Rotate a secret's value, keeping its id and grants (scope `vault.manage`). */\n rotate(secretId: string, secret: string): Promise<VaultSecretRef> {\n return this.json<VaultSecretRef>('POST', `/secrets/${encodeURIComponent(secretId)}/rotate`, { secret });\n }\n\n /** Revoke a secret permanently (scope `vault.manage`). */\n async revoke(secretId: string): Promise<void> {\n await this.request('DELETE', `/secrets/${encodeURIComponent(secretId)}`);\n }\n\n /** Authorize an agent client to lease a secret (scope `vault.manage`). */\n grant(\n secretId: string,\n clientId: string,\n maxTtlSeconds?: number,\n ): Promise<{ secretId: string; clientId: string; maxTtlSeconds: number | null }> {\n return this.json('POST', `/secrets/${encodeURIComponent(secretId)}/grants`, {\n client_id: clientId,\n max_ttl_seconds: maxTtlSeconds,\n }).then((raw) => {\n const r = raw as { secret_id: string; client_id: string; max_ttl_seconds: number | null };\n return { secretId: r.secret_id, clientId: r.client_id, maxTtlSeconds: r.max_ttl_seconds };\n });\n }\n\n /** Revoke an agent's authorization (scope `vault.manage`). */\n async revokeGrant(secretId: string, clientId: string): Promise<void> {\n await this.request(\n 'DELETE',\n `/secrets/${encodeURIComponent(secretId)}/grants/${encodeURIComponent(clientId)}`,\n );\n }\n\n /**\n * Redeem a leased credential for immediate use (scope `vault.lease`). The caller\n * is identified by the token's client; a lease with no live grant is refused.\n */\n lease(secretId: string, purpose: string): Promise<VaultLease> {\n return this.json('POST', `/secrets/${encodeURIComponent(secretId)}/lease`, { purpose }).then((raw) => {\n const r = raw as { secret_id: string; provider: string; secret: string; expires_at: string };\n return { secretId: r.secret_id, provider: r.provider, secret: r.secret, expiresAt: r.expires_at };\n });\n }\n\n /**\n * Lease a fresh access token for a person's connected account at `provider` (Pipes,\n * scope `vault.lease`). The token is refreshed first when it is about to expire, so\n * you never handle a refresh token.\n *\n * With a client-credentials token, name the person in `userId`. With a token issued to\n * your app FOR a person, leave it out — the lease is theirs.\n *\n * ```ts\n * try {\n * const { accessToken } = await vault.leasePipeToken('github', { userId, purpose: 'list-repos' })\n * } catch (e) {\n * if (e instanceof PipeNotConnectedError || e instanceof PipeReauthorizationRequiredError) {\n * return redirect(e.connectUrlWith({ clientId, returnTo }))\n * }\n * throw e\n * }\n * ```\n */\n async leasePipeToken(\n provider: PipeProvider | string,\n options: { purpose: string; userId?: string },\n ): Promise<PipeToken> {\n const path = `/pipes/${encodeURIComponent(provider)}/token`;\n const response = await this.send('POST', path, {\n purpose: options.purpose,\n ...(options.userId !== undefined ? { user_id: options.userId } : {}),\n });\n\n let body: Record<string, unknown> = {};\n try {\n const parsed: unknown = await response.json();\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n body = parsed as Record<string, unknown>;\n }\n } catch {\n // Not JSON — a proxy's error page. The status below is all there is.\n }\n\n if (!response.ok) {\n throw pipeLeaseError(response, body);\n }\n\n if (typeof body.access_token !== 'string') {\n throw new PipeLeaseError('The pipe lease answered without an access token.', null, response.status);\n }\n\n return {\n accessToken: body.access_token,\n tokenType: 'Bearer',\n provider: String(body.provider ?? provider),\n userId: String(body.user_id ?? ''),\n connectionId: String(body.connection_id ?? ''),\n scopes: Array.isArray(body.scopes) ? body.scopes.filter((s): s is string => typeof s === 'string') : [],\n expiresAt: typeof body.expires_at === 'string' ? body.expires_at : null,\n leaseExpiresAt: String(body.lease_expires_at ?? ''),\n metadata: isStringRecord(body.metadata) ? body.metadata : {},\n };\n }\n\n private async json<T>(method: string, path: string, body: Record<string, unknown>): Promise<T> {\n const response = await this.request(method, path, body);\n return (await response.json()) as T;\n }\n\n private async request(method: string, path: string, body?: Record<string, unknown>): Promise<Response> {\n const response = await this.send(method, path, body);\n if (!response.ok) {\n throw new AuthenticationError(`Vault ${method} ${path} failed with status ${response.status}.`);\n }\n return response;\n }\n\n private async send(method: string, path: string, body?: Record<string, unknown>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const init: RequestInit = {\n method,\n headers: {\n authorization: `Bearer ${this.token}`,\n ...(body ? { 'content-type': 'application/json' } : {}),\n },\n signal: controller.signal,\n };\n if (body) {\n init.body = JSON.stringify(body);\n }\n return await fetch(`${this.base}${path}`, init);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\nfunction pipeLeaseError(response: Response, body: Record<string, unknown>): PipeLeaseError {\n const error = typeof body.error === 'string' ? body.error : null;\n const message = typeof body.message === 'string' && body.message !== ''\n ? body.message\n : `The pipe lease failed with status ${response.status}.`;\n const connectUrl = typeof body.connect_url === 'string' && body.connect_url !== '' ? body.connect_url : null;\n const header = response.headers.get('retry-after')?.trim() ?? '';\n const retryAfter = /^\\d+$/.test(header) ? Number(header) : null;\n\n if (response.status === 404 && connectUrl !== null) {\n return new PipeNotConnectedError(message, error, 404, connectUrl, retryAfter);\n }\n if (response.status === 409 && connectUrl !== null) {\n return new PipeReauthorizationRequiredError(message, error, 409, connectUrl, retryAfter);\n }\n if (response.status === 503) {\n return new PipeTemporarilyUnavailableError(message, error, 503, connectUrl, retryAfter);\n }\n if (response.status === 403 && error !== 'insufficient_scope') {\n return new PipeLeaseDeniedError(message, error, 403, connectUrl, retryAfter);\n }\n\n return new PipeLeaseError(message, error, response.status, connectUrl, retryAfter);\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.values(value).every((v) => typeof v === 'string')\n );\n}\n","/**\n * Verify a Cbox ID webhook / inline-action signature. The header is\n * `X-Cbox-Signature: t={unix},v1={hex hmac}` — an HMAC-SHA256 over\n * `\"{timestamp}.{raw body}\"`, valid within a freshness window. Built on Web Crypto\n * so it runs on Node, edge and the browser.\n */\n\n/** Constant-time compare of two hex strings. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\nfunction toHex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nexport interface VerifyWebhookOptions {\n /** The RAW request body — the exact bytes received, not a re-encoded copy. */\n payload: string;\n /** The value of the `X-Cbox-Signature` header. */\n signatureHeader: string | null | undefined;\n /** The signing secret issued when the webhook/action endpoint was registered. */\n secret: string;\n /** Freshness window in seconds. Defaults to 300 (5 minutes). */\n toleranceSeconds?: number;\n /** Injectable clock (unix seconds), for tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\n/** Returns `true` only when the signature is present, fresh and valid. Never throws. */\nexport async function verifyWebhook(options: VerifyWebhookOptions): Promise<boolean> {\n const { payload, signatureHeader, secret } = options;\n const toleranceSeconds = options.toleranceSeconds ?? 300;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n if (!signatureHeader) {\n return false;\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const [key, value] = segment.trim().split('=', 2);\n if (key) {\n parts[key] = value ?? '';\n }\n }\n\n const timestamp = parts['t'] ?? '';\n const signature = parts['v1'] ?? '';\n\n if (timestamp === '' || signature === '' || !/^\\d+$/.test(timestamp)) {\n return false;\n }\n\n if (Math.abs(now - 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 const expected = toHex(\n await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${payload}`)),\n );\n\n return timingSafeEqual(expected, signature);\n}\n\n/** Headers as a `Headers` object or a plain record (Node's `IncomingHttpHeaders`, a framework's map). */\nexport type WebhookHeaders = Headers | Record<string, string | readonly string[] | undefined>;\n\nexport interface VerifyStandardWebhookOptions {\n /** The RAW request body — the exact bytes received, not a re-encoded copy. */\n payload: string;\n /** The request headers; `webhook-id`, `webhook-timestamp` and `webhook-signature` are read. */\n headers: WebhookHeaders;\n /**\n * The endpoint's secret: a `whsec_…` secret, or the 64-hex secret of an endpoint that\n * moved from the `cbox` scheme (Cbox ID uses it as `whsec_` + base64 of the hex string,\n * which keys the HMAC with the same bytes).\n */\n secret: string;\n /** Freshness window in seconds. Defaults to 300 (5 minutes). */\n toleranceSeconds?: number;\n /** Injectable clock (unix seconds), for tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\nfunction header(headers: WebhookHeaders, name: string): string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name) ?? undefined;\n }\n\n const record = headers as Record<string, string | readonly string[] | undefined>;\n const key = Object.keys(record).find((k) => k.toLowerCase() === name);\n const value = key === undefined ? undefined : record[key];\n\n return Array.isArray(value) ? value.join(' ') : (value as string | undefined);\n}\n\nfunction base64ToBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value);\n return Uint8Array.from(binary, (c) => c.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nfunction toBase64(bytes: ArrayBuffer): string {\n let binary = '';\n for (const byte of new Uint8Array(bytes)) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/**\n * Verify a delivery from an endpoint on the `standard_webhooks` signature scheme\n * ([Standard Webhooks](https://www.standardwebhooks.com/)): `webhook-signature` carries one or\n * more space-separated `v1,<base64 HMAC-SHA256 of \"{webhook-id}.{webhook-timestamp}.{body}\">`,\n * and the timestamp must be within the freshness window. Use {@link verifyWebhook} for the\n * default `cbox` scheme (`X-Cbox-Signature`).\n *\n * Returns `true` only when a signature is present, fresh and valid. Never throws.\n */\nexport async function verifyStandardWebhook(options: VerifyStandardWebhookOptions): Promise<boolean> {\n const { payload, headers, secret } = options;\n const toleranceSeconds = options.toleranceSeconds ?? 300;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n const id = header(headers, 'webhook-id');\n const timestamp = header(headers, 'webhook-timestamp');\n const signatures = header(headers, 'webhook-signature');\n\n if (!id || !timestamp || !signatures || !/^\\d+$/.test(timestamp)) {\n return false;\n }\n\n if (Math.abs(now - Number(timestamp)) > toleranceSeconds) {\n return false;\n }\n\n const keyBytes: Uint8Array<ArrayBuffer> | null = secret.startsWith('whsec_') ? base64ToBytes(secret.slice('whsec_'.length)) : new TextEncoder().encode(secret);\n\n if (keyBytes === null || keyBytes.length === 0) {\n return false;\n }\n\n const key = await crypto.subtle.importKey('raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const expected = toBase64(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${id}.${timestamp}.${payload}`)));\n\n // Several signatures may be sent while a secret rotates; any valid `v1` one is enough.\n let valid = false;\n for (const candidate of signatures.split(' ')) {\n const [version, signature] = candidate.split(',', 2);\n if (version === 'v1' && signature !== undefined && timingSafeEqual(expected, signature)) {\n valid = true;\n }\n }\n\n return valid;\n}\n","import { AuthenticationError, ConfigurationError } from './errors.js';\nimport type { DiscoveryDocument } from './types.js';\n\n/**\n * Fetches and caches an instance's OIDC discovery document. One instance of this\n * lives per {@link CboxIdClient}; the document is refetched only after the TTL.\n */\nexport class Discovery {\n private cached: { doc: DiscoveryDocument; expiresAt: number } | null = null;\n\n constructor(\n private readonly issuer: string,\n private readonly timeoutMs: number,\n private readonly cacheTtlMs: number,\n private readonly now: () => number = Date.now,\n ) {}\n\n async document(): Promise<DiscoveryDocument> {\n if (this.cached && this.cached.expiresAt > this.now()) {\n return this.cached.doc;\n }\n\n const url = `${trimSlash(this.issuer)}/.well-known/openid-configuration`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let doc: DiscoveryDocument;\n try {\n const response = await fetch(url, { signal: controller.signal });\n if (!response.ok) {\n throw new AuthenticationError(`Discovery request failed with status ${response.status}.`);\n }\n doc = (await response.json()) as DiscoveryDocument;\n } catch (error) {\n if (error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(`Discovery request failed: ${String(error)}`);\n } finally {\n clearTimeout(timer);\n }\n\n if (typeof doc.issuer !== 'string' || doc.issuer === '') {\n throw new AuthenticationError('The discovery document was missing an issuer.');\n }\n\n // RFC 8414 §3.3: the `issuer` in the document MUST match the one it was fetched for.\n // Without this the SDK sends credentials to whatever endpoints the document names and\n // verifies tokens against whatever JWKS it points at, while the caller still believes\n // it is talking to the issuer it configured — so one tenant's host answering with\n // another tenant's document silently redirects the whole flow.\n if (trimSlash(doc.issuer) !== trimSlash(this.issuer)) {\n throw new AuthenticationError(\n `The discovery document is for a different issuer (${doc.issuer}).`,\n );\n }\n\n this.cached = { doc, expiresAt: this.now() + this.cacheTtlMs };\n return doc;\n }\n\n /** A required endpoint from the discovery document. */\n async endpoint(name: keyof DiscoveryDocument): Promise<string> {\n const value = (await this.document())[name];\n if (typeof value !== 'string' || value === '') {\n throw new ConfigurationError(`The instance does not advertise a ${name}.`);\n }\n return value;\n }\n\n /** An optional endpoint, or null when the instance advertises none. */\n async optionalEndpoint(name: keyof DiscoveryDocument): Promise<string | null> {\n const value = (await this.document())[name];\n return typeof value === 'string' && value !== '' ? value : null;\n }\n}\n\n/** Compare issuers without letting a trailing slash decide identity. */\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, '');\n}\n","import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';\nimport { Discovery } from './discovery.js';\nimport { assertSecureIssuer } from './issuer.js';\nimport { AuthenticationError, ConfigurationError, InvalidStateError, oauthError } from './errors.js';\nimport { challenge, createVerifier, randomToken } from './pkce.js';\nimport { actor, featureFlags, organization, permissions, roles, sessionId } from './claims.js';\nimport { pipeConnectUrl, type PipeProvider } from './vault.js';\nimport type {\n AuthorizationPrompt,\n AuthorizationRequest,\n AuthorizationRequestOptions,\n CboxIdConfig,\n DeviceAuthorization,\n CboxOrganization,\n CboxUser,\n RefreshedTokens,\n TokenResponse,\n TokenTypeHint,\n} from './types.js';\nimport { VaultClient } from './vault.js';\nimport { verifyWebhook, type VerifyWebhookOptions } from './webhook.js';\n\ntype JwksResolver = ReturnType<typeof createRemoteJWKSet>;\n\n/** Query parameters as they arrive on your callback route. */\nexport interface CallbackParams {\n code?: string | null;\n state?: string | null;\n error?: string | null;\n error_description?: string | null;\n}\n\n/** The values you persisted from {@link CboxIdClient.createAuthorizationRequest}. */\nexport interface StoredAuthState {\n state: string;\n codeVerifier: string;\n nonce: string;\n /** The `maxAge` this login demanded, if any. See {@link AuthorizationRequest.maxAge}. */\n maxAge?: number;\n /**\n * The organization this sign-in was bound to, if any. See\n * {@link AuthorizationRequest.organization}.\n *\n * Checked, not trusted: a binding nobody verifies is a binding in name only. An\n * instance that predates the `organization` parameter ignores it and returns tokens for\n * whichever organization the session already had — and an app that switched to \"Globex\"\n * would then show Globex's name over Acme's data.\n */\n organization?: string;\n /**\n * The scopes THIS authorization asked for, when you overrode the configured set.\n *\n * Read so `authenticate()` can judge the response against what was requested rather\n * than against the config: a login that asked for `openid` and came back without an\n * id_token is a protocol violation, and one that never asked cannot be held to it.\n * Omitted, the configured scopes are assumed — which is what a caller who did not\n * override them actually sent.\n */\n scopes?: string[];\n}\n\n/**\n * Turnkey Cbox ID client for JavaScript/TypeScript. It speaks standard OpenID\n * Connect against a Cbox ID instance — so integrating is a redirect and a callback,\n * not a rewrite — and adds the conveniences a hosted-identity product needs: a\n * redirect to the instance's hosted profile page, and back-channel helpers (machine\n * tokens, userinfo, introspection, webhook verification).\n *\n * Login is hardened by default: PKCE (S256), a CSRF state check, a nonce, and full\n * id_token signature + issuer + audience verification against the instance's JWKS\n * (via `jose`).\n *\n * The class is framework-agnostic: {@link createAuthorizationRequest} hands you the\n * `state`, `codeVerifier` and `nonce` to persist however you like, and\n * {@link authenticate} takes them back. For Next.js, the `@cboxdk/id-js/nextjs`\n * entry wires this to cookies for you.\n */\nexport class CboxIdClient {\n private readonly discovery: Discovery;\n private readonly jwksByUri = new Map<string, JwksResolver>();\n\n constructor(private readonly config: CboxIdConfig) {\n if (!config.issuer) {\n throw new ConfigurationError('Cbox ID config `issuer` is required.');\n }\n if (!config.clientId) {\n throw new ConfigurationError('Cbox ID config `clientId` is required.');\n }\n assertSecureIssuer(config.issuer);\n this.discovery = new Discovery(\n config.issuer,\n config.timeoutMs ?? 10_000,\n config.cacheTtlMs ?? 3_600_000,\n );\n }\n\n /**\n * Begin login. Returns the authorize URL plus the `state`, `codeVerifier` and\n * `nonce` — persist those (signed, httpOnly cookies are ideal) and hand them back\n * to {@link authenticate} on the callback.\n */\n async createAuthorizationRequest(options: AuthorizationRequestOptions = {}): Promise<AuthorizationRequest> {\n const prompt = promptValue(options.prompt);\n assertOrganizationOptions(options, prompt);\n\n const codeVerifier = createVerifier();\n const state = options.state ?? randomToken(16);\n const nonce = randomToken(16);\n\n const redirectUri = options.redirectUri ?? this.config.redirectUri;\n\n if (redirectUri === undefined || redirectUri === '') {\n // Checked where it is needed rather than at construction, so a CLI can build a\n // client at all. An authorize URL without `redirect_uri` would fail at the\n // authorization server instead, describing a request the caller never knowingly\n // made — see the device grant, which has no callback to name.\n throw new ConfigurationError(\n 'A `redirectUri` is required to start the browser sign-in flow. Set it in the config, or pass it to createAuthorizationRequest.',\n );\n }\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: this.config.clientId,\n redirect_uri: redirectUri,\n scope: (options.scopes ?? this.scopes()).join(' '),\n state,\n nonce,\n code_challenge: await challenge(codeVerifier),\n code_challenge_method: 'S256',\n });\n if (prompt.length > 0) {\n params.set('prompt', prompt.join(' '));\n }\n if (options.loginHint) {\n params.set('login_hint', options.loginHint);\n }\n if (typeof options.maxAge === 'number') {\n params.set('max_age', String(options.maxAge));\n }\n if (options.organization !== undefined) {\n params.set('organization', options.organization);\n }\n if (options.organizationHint !== undefined) {\n params.set('organization_hint', options.organizationHint);\n }\n\n const endpoint = await this.discovery.endpoint('authorization_endpoint');\n return {\n url: `${endpoint}?${params.toString()}`,\n state,\n codeVerifier,\n nonce,\n // Carried through so authenticate() can hold the instance to it. Only present\n // when requested (exactOptionalPropertyTypes).\n ...(typeof options.maxAge === 'number' ? { maxAge: options.maxAge } : {}),\n ...(options.organization !== undefined ? { organization: options.organization } : {}),\n };\n }\n\n /**\n * Switch the signed-in person to another organization: a new authorization bound to\n * `organizationId`. Persist and redirect exactly as for\n * {@link createAuthorizationRequest} — it is one, with `organization` set.\n *\n * Cbox ID already holds the person's session, so this is normally a redirect there and\n * straight back with no sign-in form. The tokens that come back carry the new `org`,\n * `org_role`, `roles` and `permissions`; replace your session with them rather than\n * patching the old one, because every one of those can differ between organizations.\n *\n * A person who is not (or is no longer) an active member of that organization comes\n * back with `error=access_denied`, which {@link authenticate} throws as an\n * `AuthenticationError` with `error === 'access_denied'`.\n */\n switchOrganization(\n organizationId: string,\n options: Omit<AuthorizationRequestOptions, 'organization' | 'organizationHint'> = {},\n ): Promise<AuthorizationRequest> {\n return this.createAuthorizationRequest({ ...options, organization: organizationId });\n }\n\n /**\n * Complete login on your callback route: verify state, exchange the code with the\n * PKCE verifier, verify the id_token, and return the authenticated user.\n *\n * @throws InvalidStateError when state does not match (forged/stale request)\n * @throws AuthenticationError on any other failure\n */\n async authenticate(input: {\n params: CallbackParams;\n stored: StoredAuthState;\n redirectUri?: string;\n }): Promise<CboxUser> {\n const { params, stored } = input;\n\n if (!params.state || !stored.state || !timingSafeEqualString(params.state, stored.state)) {\n throw new InvalidStateError('The login state did not match — the request may be forged or stale.');\n }\n\n if (params.error) {\n // The code travels as `error`, not only in the message: `access_denied` after a\n // switchOrganization() means \"not a member of that organization\", which an app\n // answers by switching back — not by signing the person out.\n throw new AuthenticationError(\n `Cbox ID returned an error: ${params.error}${params.error_description ? ` (${params.error_description})` : ''}`,\n params.error,\n params.error_description ?? undefined,\n );\n }\n\n if (!params.code) {\n throw new AuthenticationError('The callback was missing an authorization code.');\n }\n\n const tokens = await this.exchange(params.code, stored.codeVerifier, input.redirectUri);\n\n if (!tokens.access_token) {\n throw new AuthenticationError('No access token was returned.');\n }\n\n let verified: Record<string, unknown> = {};\n\n if (tokens.id_token) {\n verified = await this.verifyIdToken(tokens.id_token, stored.nonce, stored.maxAge);\n } else if ((stored.scopes ?? this.scopes()).includes('openid')) {\n // AN `openid` REQUEST WITHOUT AN ID_TOKEN IS A PROTOCOL VIOLATION, and refusing it\n // is the difference between an authenticated login and a bearer token. Without this\n // the identity below came from UserInfo alone — a bearer-authenticated endpoint\n // whose response nothing signed — and the `nonce` pulled from storage was never used.\n //\n // Asked of the SCOPES REQUESTED, not of the response: a caller who never asked for\n // `openid` is running an OAuth flow and is not held to an OIDC rule.\n throw new AuthenticationError(\n 'An openid login returned no id_token, so the identity could not be verified.',\n );\n } else if (typeof stored.maxAge === 'number') {\n // No id_token means no auth_time, and therefore no evidence the demanded\n // re-authentication happened. Accepting that silently is the whole defect.\n throw new AuthenticationError(\n 'A max_age was requested but no id_token was returned, so the authentication age could not be verified.',\n );\n }\n\n const user = await this.identityFrom(tokens, verified);\n\n if (stored.organization !== undefined && user.organizationId !== stored.organization) {\n throw new AuthenticationError(\n `The sign-in was bound to organization ${stored.organization}, but the tokens are for ${user.organizationId ?? 'no organization'}. The instance may not support organization selection.`,\n );\n }\n\n return user;\n }\n\n /**\n * Turn a token response into the verified {@link CboxUser} every flow returns.\n *\n * Shared by the browser flow and the device flow rather than written twice: the checks\n * in here — the UserInfo subject matching the id_token's, the merge that lets UserInfo\n * enrich but never overwrite signed claims — are the ones that decide whether an\n * identity is trustworthy. A second copy is a second place for one of them to be\n * quietly missing, and the flow it was missing from would look exactly as correct.\n */\n private async identityFrom(\n tokens: TokenResponse,\n verified: Record<string, unknown>,\n ): Promise<CboxUser> {\n const profile = await this.userinfo(tokens.access_token);\n\n // OIDC Core §5.3.2: the UserInfo `sub` MUST match the id_token's, and when it does\n // not the response MUST NOT be used. UserInfo is fetched with a bearer token and its\n // body carries no signature, so without this an IdP — or anything able to answer as\n // one — hands back `{\"sub\":\"somebody-else\"}` and the SDK returns it as the identity.\n const verifiedSub = verified['sub'];\n const profileSub = profile['sub'];\n\n if (typeof verifiedSub === 'string' && typeof profileSub === 'string' && !timingSafeEqualString(verifiedSub, profileSub)) {\n throw new AuthenticationError('The UserInfo subject does not match the verified id_token.');\n }\n\n // ENRICHES, NEVER REPLACES. UserInfo fills in what a minimal id_token omits (email,\n // name, org) and the verified claims go back on top, so the merge cannot move `sub`,\n // `iss`, `aud`, `nonce` or anything else the signature covered. The spread used to run\n // the other way round.\n const claims: Record<string, unknown> = { ...profile, ...verified };\n\n const sub = claims['sub'];\n if (typeof sub !== 'string' || sub === '') {\n throw new AuthenticationError('The verified token carried no subject.');\n }\n\n const organizations = parseOrganizations(claims['organizations']);\n\n return {\n id: sub,\n email: typeof claims['email'] === 'string' ? claims['email'] : null,\n name: typeof claims['name'] === 'string' ? claims['name'] : null,\n organizationId: typeof claims['org'] === 'string' ? claims['org'] : null,\n organization: organization(claims),\n roles: roles(claims),\n permissions: permissions(claims),\n featureFlags: featureFlags(claims),\n actor: actor(claims),\n sessionId: sessionId(claims),\n // Only present when the instance emitted the claim (exactOptionalPropertyTypes).\n ...(organizations ? { organizations } : {}),\n claims,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n idToken: tokens.id_token ?? null,\n expiresIn: typeof tokens.expires_in === 'number' ? tokens.expires_in : 0,\n };\n }\n\n /**\n * Start the device authorization grant (RFC 8628) — the flow for a program with no\n * browser of its own: a CLI, a CI job, a container, a TV.\n *\n * Print `userCode` and `verificationUri`, then call\n * {@link CboxIdClient.pollDeviceToken}. If the machine has a desktop you may also open\n * `verificationUriComplete`, which fills the code in — but print the code anyway: the\n * machine running your program is often not the one the person is looking at.\n *\n * The scopes are bounded by what the app is REGISTERED for. A device request naming one\n * outside that ceiling is refused with `invalid_scope` rather than quietly reduced,\n * because no browser is in front of it to notice a smaller grant.\n *\n * @throws ConfigurationError when the instance advertises no device endpoint.\n */\n async requestDeviceAuthorization(scopes?: string[]): Promise<DeviceAuthorization> {\n const endpoint = await this.discovery.optionalEndpoint('device_authorization_endpoint');\n\n if (endpoint === null) {\n throw new ConfigurationError(\n 'This instance does not advertise a device_authorization_endpoint, so it does not support CLI sign-in.',\n );\n }\n\n const body = new URLSearchParams({\n client_id: this.config.clientId,\n scope: (scopes ?? this.scopes()).join(' '),\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(endpoint, body);\n if (!response.ok) {\n throw await oauthError(response, 'Device authorization request failed');\n }\n\n const payload = (await response.json()) as Record<string, unknown>;\n\n const deviceCode = payload['device_code'];\n const userCode = payload['user_code'];\n const verificationUri = payload['verification_uri'];\n\n if (typeof deviceCode !== 'string' || typeof userCode !== 'string' || typeof verificationUri !== 'string') {\n throw new AuthenticationError('The device authorization response was incomplete.');\n }\n\n return {\n deviceCode,\n userCode,\n verificationUri,\n verificationUriComplete:\n typeof payload['verification_uri_complete'] === 'string'\n ? payload['verification_uri_complete']\n : null,\n expiresIn: typeof payload['expires_in'] === 'number' ? payload['expires_in'] : 600,\n // RFC 8628 §3.2: absent means 5 seconds. Polling faster than the server allows is\n // answered with `slow_down`, so the default is the one the server assumes too.\n interval: typeof payload['interval'] === 'number' ? payload['interval'] : 5,\n };\n }\n\n /**\n * Poll until the person approves, and return them.\n *\n * Blocks. It honours the server's `interval`, backs off permanently by five seconds on\n * `slow_down` (RFC 8628 §3.5), and stops on the three answers that are final: they\n * declined, the code expired, or tokens arrived. Pass an `AbortSignal` to give up\n * early — a CLI should let Ctrl-C work.\n *\n * @throws AuthenticationError when the person declines or the code expires.\n */\n async pollDeviceToken(\n authorization: DeviceAuthorization,\n options: { signal?: AbortSignal } = {},\n ): Promise<CboxUser> {\n const endpoint = await this.discovery.endpoint('token_endpoint');\n const deadline = Date.now() + authorization.expiresIn * 1000;\n let intervalMs = authorization.interval * 1000;\n\n for (;;) {\n if (options.signal?.aborted === true) {\n throw new AuthenticationError('Device sign-in was cancelled.');\n }\n if (Date.now() > deadline) {\n throw new AuthenticationError(\n 'The device code expired before it was approved. Start the sign-in again.',\n );\n }\n\n await sleep(intervalMs, options.signal);\n\n const body = new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: authorization.deviceCode,\n client_id: this.config.clientId,\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(endpoint, body);\n\n if (response.ok) {\n const tokens = (await response.json()) as TokenResponse;\n\n if (!tokens.access_token) {\n throw new AuthenticationError('The device token response carried no access token.');\n }\n\n // No nonce: RFC 8628 has no browser leg to carry one, so there is nothing to\n // bind. Everything else about the id_token — signature, issuer, audience,\n // expiry — is verified exactly as it is on the browser flow.\n const verified = tokens.id_token ? await this.verifyIdToken(tokens.id_token, '') : {};\n\n return await this.identityFrom(tokens, verified);\n }\n\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n const error = typeof payload['error'] === 'string' ? payload['error'] : 'invalid_request';\n\n if (error === 'authorization_pending') {\n continue;\n }\n\n if (error === 'slow_down') {\n // Permanently, not for one round: the server is telling us our rate is wrong,\n // and returning to it next tick earns the same answer forever.\n intervalMs += 5000;\n continue;\n }\n\n if (error === 'access_denied') {\n throw new AuthenticationError('Sign-in was declined.');\n }\n\n if (error === 'expired_token') {\n throw new AuthenticationError(\n 'The device code expired before it was approved. Start the sign-in again.',\n );\n }\n\n throw await oauthError(response, 'Device sign-in failed');\n }\n }\n\n /**\n * Exchange a refresh token for a fresh access token (OAuth 2.0 `refresh_token`\n * grant). Cbox ID rotates refresh tokens and detects reuse, so ALWAYS persist the\n * returned `refreshToken` and discard the one you passed — presenting a rotated\n * token again revokes the entire token family.\n *\n * @throws AuthenticationError when the refresh token is invalid, expired, or already rotated.\n */\n async refresh(refreshToken: string): Promise<RefreshedTokens> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.config.clientId,\n refresh_token: refreshToken,\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n // The most consequential of these: `invalid_grant` means the refresh token is\n // spent, revoked or replayed and the person must sign in again, while a 5xx or\n // `temporarily_unavailable` means the same token is still good in a moment. One\n // message string for both is what makes callers guess.\n throw await oauthError(response, 'Token refresh failed');\n }\n\n const tokens = (await response.json()) as TokenResponse;\n if (!tokens.access_token) {\n throw new AuthenticationError('The refresh response carried no access token.');\n }\n\n // VERIFIED BEFORE IT IS HANDED BACK. A refresh response carries a fresh id_token, and\n // this returned it unchecked — so an application that refreshes its session claims\n // from `refresh().idToken` accepted a forged, expired, wrong-audience or wrong-issuer\n // token, having verified only the one it got at login. The nonce is not re-checked:\n // RFC 6749 has no nonce on this leg, and OIDC Core §12.2 says an id_token from a\n // refresh need not carry one.\n if (tokens.id_token) {\n await this.verifyIdToken(tokens.id_token, '');\n }\n\n return {\n accessToken: tokens.access_token,\n // Keep the presented token when the server does not rotate (OAuth 2.0 §6);\n // callers persist this value, so it must never come back null.\n refreshToken: tokens.refresh_token ?? refreshToken,\n idToken: tokens.id_token ?? null,\n expiresIn: typeof tokens.expires_in === 'number' ? tokens.expires_in : 0,\n scope: typeof tokens.scope === 'string' ? tokens.scope : null,\n };\n }\n\n /**\n * The URL of the instance's hosted account/profile page (self-service password,\n * MFA, passkeys, sessions). A signed-in user is authenticated there by their Cbox\n * ID session; `returnTo` is passed so the page can link back to your app.\n */\n profileUrl(returnTo?: string): string {\n const base = `${this.config.issuer.replace(/\\/$/, '')}${this.accountPath()}`;\n return returnTo ? `${base}?${new URLSearchParams({ return_to: returnTo }).toString()}` : base;\n }\n\n /**\n * The hosted page where a person creates and revokes API keys for your API — Cbox ID's\n * `/account/api-keys`, preselected to this app (or `clientId`). Keys made there are\n * checked with `ApiKeyVerifier` from `@cboxdk/id-js/server`.\n *\n * `returnTo` becomes a link back to your app, honoured only for an origin the app\n * registered. `organization` picks which of the person's organizations the keys act in;\n * omitted, the page uses the one they are in.\n */\n /**\n * The hosted page where the signed-in person connects their account at `provider`\n * (Pipes) — `/account/connected-services/{provider}/connect`, preselected to this app.\n * They come back to `returnTo` with `?provider=…&status=connected|cancelled|failed`,\n * honoured only on an origin the app registered.\n */\n pipeConnectUrl(provider: PipeProvider | string, returnTo?: string): string {\n return pipeConnectUrl(this.config.issuer, provider, {\n clientId: this.config.clientId,\n ...(returnTo !== undefined ? { returnTo } : {}),\n });\n }\n\n apiKeysUrl(options: { clientId?: string; returnTo?: string; organization?: string } = {}): string {\n const params = new URLSearchParams({ client_id: options.clientId ?? this.config.clientId });\n if (options.returnTo) {\n params.set('return_to', options.returnTo);\n }\n if (options.organization) {\n params.set('organization', options.organization);\n }\n\n return `${this.config.issuer.replace(/\\/$/, '')}/account/api-keys?${params.toString()}`;\n }\n\n /**\n * The RP-initiated logout URL, or null when the instance advertises none.\n *\n * `client_id` is always sent, even without a `returnTo`: the OP validates\n * `post_logout_redirect_uri` against the registered allow-list of THAT client\n * (OIDC RP-Initiated Logout 1.0 §2). With no way to name the RP the OP cannot\n * check the list, so it silently drops the return URL and strands the user on a\n * bare \"you are signed out\" page. `idTokenHint` — the user's `id_token`, if you\n * still hold it — is the spec's other way to identify the RP, and additionally\n * tells the OP which subject is logging out.\n *\n * PASS THE HINT IF YOU WANT \"SIGN OUT EVERYWHERE\". Cbox ID revokes every session\n * the person holds only when a hint it can VERIFY names the subject holding the\n * browser; with no hint it signs this browser out and leaves their other devices\n * alone. That is deliberate: the endpoint is unauthenticated and reached by a\n * redirect, so a request carrying no proof of who it concerns could otherwise be\n * forged into ending anyone's sessions everywhere. See laravel-id UPGRADING.md\n * for 1.8.0.\n */\n async logoutUrl(returnTo?: string, idTokenHint?: string): Promise<string | null> {\n const endpoint = await this.discovery.optionalEndpoint('end_session_endpoint');\n if (!endpoint) {\n return null;\n }\n const params = new URLSearchParams({ client_id: this.config.clientId });\n if (returnTo) {\n params.set('post_logout_redirect_uri', returnTo);\n }\n if (idTokenHint) {\n params.set('id_token_hint', idTokenHint);\n }\n return `${endpoint}?${params.toString()}`;\n }\n\n /**\n * A machine (client-credentials) access token for calling Cbox ID APIs as your\n * app, not on a user's behalf. Requires a client secret.\n */\n async machineToken(options: { scopes?: string[]; resource?: string } = {}): Promise<string> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.requireSecret(),\n });\n if (options.scopes && options.scopes.length > 0) {\n body.set('scope', options.scopes.join(' '));\n }\n if (options.resource) {\n body.set('resource', options.resource);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n throw await oauthError(response, 'Machine token request failed');\n }\n const json = (await response.json()) as { access_token?: unknown };\n if (typeof json.access_token !== 'string') {\n throw new AuthenticationError('The token response had no access_token.');\n }\n return json.access_token;\n }\n\n /** The OIDC userinfo claims for an access token. */\n async userinfo(accessToken: string): Promise<Record<string, unknown>> {\n const endpoint = await this.discovery.optionalEndpoint('userinfo_endpoint');\n if (!endpoint) {\n return {};\n }\n const response = await this.fetchWithTimeout(endpoint, {\n headers: { authorization: `Bearer ${accessToken}` },\n });\n if (!response.ok) {\n throw await oauthError(response, 'Userinfo request failed');\n }\n return (await response.json()) as Record<string, unknown>;\n }\n\n /**\n * RFC 7662 token introspection (confidential-client auth). Returns the raw\n * response; `active` tells you if the token is currently valid. Requires a secret.\n */\n async introspect(token: string): Promise<Record<string, unknown>> {\n const endpoint = await this.discovery.endpoint('introspection_endpoint');\n const basic = btoa(`${this.config.clientId}:${this.requireSecret()}`);\n const response = await this.post(\n endpoint,\n new URLSearchParams({ token }),\n { authorization: `Basic ${basic}` },\n );\n if (!response.ok) {\n throw await oauthError(response, 'Introspection request failed');\n }\n return (await response.json()) as Record<string, unknown>;\n }\n\n /**\n * RFC 7009 token revocation. Revokes an access or refresh token; revoking a refresh\n * token drops the whole token family, so this is what a real \"sign out everywhere\" does.\n *\n * **PUBLIC CLIENTS TOO.** This demanded a secret and threw `ConfigurationError` without\n * one — so the clients that most need it were the ones that could not call it. A PKCE\n * browser or native app authenticates with `none`, holds no secret, and is exactly the\n * case where a refresh token sits in storage on a device somebody has just signed out\n * of. Cbox ID's revocation endpoint accepts a public client, and its discovery document\n * advertises `none` among the revocation auth methods; RFC 7009 §2.1 scopes every\n * revocation to the calling client, so the only capability here is \"destroy a token you\n * are already holding\". The SDK was the half saying no.\n *\n * A confidential client still authenticates with Basic; a public one names itself in the\n * body, the same shape {@link exchange} already uses for the token endpoint.\n *\n * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so\n * success means \"this token is not valid any more\", not \"it existed\".\n *\n * @param tokenTypeHint which store to search first — only a hint, never required.\n */\n async revoke(token: string, tokenTypeHint?: TokenTypeHint): Promise<void> {\n const endpoint = await this.discovery.endpoint('revocation_endpoint');\n const body = new URLSearchParams({ token, client_id: this.config.clientId });\n if (tokenTypeHint) {\n body.set('token_type_hint', tokenTypeHint);\n }\n\n const headers: Record<string, string> = {};\n if (this.config.clientSecret) {\n headers.authorization = `Basic ${btoa(`${this.config.clientId}:${this.config.clientSecret}`)}`;\n }\n\n const response = await this.post(endpoint, body, headers);\n if (!response.ok) {\n throw await oauthError(response, 'Revocation request failed');\n }\n }\n\n /** Verify a Cbox ID webhook / inline-action signature. See {@link verifyWebhook}. */\n verifyWebhook(options: VerifyWebhookOptions): Promise<boolean> {\n return verifyWebhook(options);\n }\n\n /**\n * A Token Vault client bound to an access token. Obtain the token with\n * {@link machineToken} (scope `vault.manage` to provision/grant, `vault.lease` to\n * redeem), then call `store` / `grant` / `lease` etc.\n */\n vault(accessToken: string): VaultClient {\n return new VaultClient(this.config.issuer, accessToken, this.config.timeoutMs ?? 10_000);\n }\n\n private async exchange(code: string, verifier: string, redirectUri?: string): Promise<TokenResponse> {\n const callback = redirectUri ?? this.config.redirectUri;\n\n if (callback === undefined || callback === '') {\n throw new ConfigurationError(\n 'A `redirectUri` is required to exchange an authorization code. It must be the same one the authorization request used.',\n );\n }\n\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: callback,\n client_id: this.config.clientId,\n code_verifier: verifier,\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n throw await oauthError(response, 'Token exchange failed');\n }\n return (await response.json()) as TokenResponse;\n }\n\n private async verifyIdToken(\n idToken: string,\n // Empty skips the nonce comparison below, which is what a refresh leg needs: RFC 6749\n // has no nonce there and OIDC Core §12.2 says the id_token from a refresh need not\n // carry one. Signature, issuer, audience and expiry are checked either way.\n nonce: string,\n maxAge?: number,\n ): Promise<Record<string, unknown>> {\n const jwksUri = await this.discovery.endpoint('jwks_uri');\n let resolver = this.jwksByUri.get(jwksUri);\n if (!resolver) {\n resolver = createRemoteJWKSet(new URL(jwksUri));\n this.jwksByUri.set(jwksUri, resolver);\n }\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(idToken, resolver, {\n issuer: this.config.issuer,\n audience: this.config.clientId,\n // Pin the accepted signature algorithms explicitly. `jose` already refuses\n // `alg: none` and key-type confusion, so this is belt-and-braces — but it\n // states the contract in code rather than relying on a library default.\n algorithms: ['RS256', 'ES256'],\n }));\n } catch (error) {\n throw new AuthenticationError(`The id_token could not be verified: ${String(error)}`);\n }\n\n if (nonce && payload['nonce'] !== nonce) {\n throw new AuthenticationError('The id_token nonce did not match — possible replay.');\n }\n\n // OIDC Core §3.1.3.7 step 12: when max_age was requested, `auth_time` is REQUIRED\n // and the relying party MUST check it. `max_age` is the control you reach for\n // before a payment or an admin grant, and the whole point is that the person\n // authenticated JUST NOW — so a login({maxAge}) whose result is never checked is a\n // step-up in name only: a day-old session comes back carrying its original\n // auth_time and nothing anywhere says so.\n if (typeof maxAge === 'number') {\n const authTime = payload['auth_time'];\n\n if (typeof authTime !== 'number') {\n throw new AuthenticationError(\n 'A max_age was requested but the id_token carried no auth_time, so the authentication age could not be verified.',\n );\n }\n\n const tolerance = this.config.authTimeToleranceSeconds ?? 60;\n const age = Math.floor(Date.now() / 1000) - authTime;\n\n if (age > maxAge + tolerance) {\n throw new AuthenticationError(\n `The authentication is ${age}s old but max_age required ${maxAge}s — the user did not re-authenticate.`,\n );\n }\n }\n\n return payload as Record<string, unknown>;\n }\n\n private scopes(): string[] {\n const scopes = this.config.scopes;\n return scopes && scopes.length > 0 ? scopes : ['openid', 'profile', 'email'];\n }\n\n private accountPath(): string {\n const path = this.config.accountPath;\n // `/account`, not `/settings`. The latter is the organization-admin page: it\n // redirects a non-admin to `/account` and drops `return_to` on the way, so a member\n // following this link arrives at the right screen having lost where they came from.\n return path && path !== '' ? `/${path.replace(/^\\//, '')}` : '/account';\n }\n\n private requireSecret(): string {\n if (!this.config.clientSecret) {\n throw new ConfigurationError('This call requires a `clientSecret`, but none is configured.');\n }\n return this.config.clientSecret;\n }\n\n private post(url: string, body: URLSearchParams, headers: Record<string, string> = {}): Promise<Response> {\n return this.fetchWithTimeout(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers },\n body,\n });\n }\n\n private async fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 10_000);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** Normalise `prompt` to a de-duplicated list, refusing what the server would refuse. */\nfunction promptValue(prompt: AuthorizationRequestOptions['prompt']): AuthorizationPrompt[] {\n if (prompt === undefined) {\n return [];\n }\n\n const values = [...new Set(typeof prompt === 'string' ? [prompt] : prompt)];\n\n // OIDC Core §3.1.2.1: `none` with any other value is an error. Failing here names the\n // call that built it; failing at the server names nothing the caller can find.\n if (values.includes('none') && values.length > 1) {\n throw new ConfigurationError(\"`prompt: 'none'` cannot be combined with another prompt value.\");\n }\n\n return values;\n}\n\n/**\n * Refuse organization options that contradict each other. Each of these would reach the\n * server as a request with two incompatible meanings and come back as a generic error\n * after a full redirect — far from the line that built it.\n */\nfunction assertOrganizationOptions(options: AuthorizationRequestOptions, prompt: AuthorizationPrompt[]): void {\n // An empty id is not \"no organization\" at the server — it is a parameter that is\n // present and names nothing. Omit the option instead.\n if (options.organization === '') {\n throw new ConfigurationError('`organization` is empty. Omit it to sign in without binding to an organization.');\n }\n if (options.organizationHint === '') {\n throw new ConfigurationError('`organizationHint` is empty. Omit it when you have no organization to suggest.');\n }\n\n if (options.organization === undefined) {\n return;\n }\n\n // `organization` binds to an existing organization; both prompts below ask the person\n // to choose or create one. Sending both leaves the server to guess which you meant.\n if (prompt.includes('select_organization')) {\n throw new ConfigurationError(\n \"`organization` binds the sign-in to one organization, so `prompt: 'select_organization'` has nothing to choose. Use `organizationHint` to preselect an organization in the picker instead.\",\n );\n }\n if (prompt.includes('create_organization')) {\n throw new ConfigurationError(\n \"`organization` binds the sign-in to an existing organization and `prompt: 'create_organization'` creates a new one. Send one or the other.\",\n );\n }\n}\n\n/** Constant-time string compare, so state validation doesn't leak via timing. */\nfunction timingSafeEqualString(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Parse an `organizations` claim into typed orgs, ignoring anything malformed. The\n * claim is optional and instance-specific; absent or non-array → undefined, so\n * callers can tell \"no claim\" from \"empty\".\n */\nfunction parseOrganizations(claim: unknown): CboxOrganization[] | undefined {\n if (!Array.isArray(claim)) {\n return undefined;\n }\n const orgs: CboxOrganization[] = [];\n for (const entry of claim) {\n if (typeof entry !== 'object' || entry === null) {\n continue;\n }\n const record = entry as Record<string, unknown>;\n const id = record['id'];\n const name = record['name'];\n if (typeof id === 'string' && id !== '' && typeof name === 'string' && name !== '') {\n orgs.push({ id, name, role: typeof record['role'] === 'string' ? record['role'] : null });\n }\n }\n return orgs;\n}\n\n/**\n * Wait, but stay interruptible.\n *\n * A CLI that ignores Ctrl-C for five seconds at a time feels broken, and a bare\n * `setTimeout` promise cannot be cancelled — so the abort is wired to the same timer\n * rather than checked after it.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(new AuthenticationError('Device sign-in was cancelled.'));\n return;\n }\n\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(new AuthenticationError('Device sign-in was cancelled.'));\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"]}
@@ -0,0 +1,22 @@
1
+ // src/pkce.ts
2
+ function base64url(bytes) {
3
+ let binary = "";
4
+ for (const byte of bytes) {
5
+ binary += String.fromCharCode(byte);
6
+ }
7
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8
+ }
9
+ function randomToken(bytes = 32) {
10
+ return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
11
+ }
12
+ function createVerifier() {
13
+ return randomToken(32);
14
+ }
15
+ async function challenge(verifier) {
16
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
17
+ return base64url(new Uint8Array(digest));
18
+ }
19
+
20
+ export { challenge, createVerifier, randomToken };
21
+ //# sourceMappingURL=chunk-VGQASHTI.js.map
22
+ //# sourceMappingURL=chunk-VGQASHTI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pkce.ts"],"names":[],"mappings":";AAKA,SAAS,UAAU,KAAA,EAA2B;AAC5C,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/E;AAGO,SAAS,WAAA,CAAY,QAAQ,EAAA,EAAY;AAC9C,EAAA,OAAO,UAAU,MAAA,CAAO,eAAA,CAAgB,IAAI,UAAA,CAAW,KAAK,CAAC,CAAC,CAAA;AAChE;AAGO,SAAS,cAAA,GAAyB;AACvC,EAAA,OAAO,YAAY,EAAE,CAAA;AACvB;AAGA,eAAsB,UAAU,QAAA,EAAmC;AACjE,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,QAAQ,CAAC,CAAA;AACvF,EAAA,OAAO,SAAA,CAAU,IAAI,UAAA,CAAW,MAAM,CAAC,CAAA;AACzC","file":"chunk-VGQASHTI.js","sourcesContent":["/**\n * PKCE (RFC 7636) and the random values the login flow needs, built on Web Crypto\n * (`globalThis.crypto`) so the same code runs on Node, edge runtimes and browsers.\n */\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** A URL-safe random token of `bytes` bytes (default 32), for state and nonce. */\nexport function randomToken(bytes = 32): string {\n return base64url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/** A high-entropy PKCE code verifier. */\nexport function createVerifier(): string {\n return randomToken(32);\n}\n\n/** The S256 code challenge for a verifier. */\nexport async function challenge(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n"]}
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { Discovery } from './chunk-YGLMLIKL.js';
2
- export { CboxIdClient, FEATURE_FLAGS_SCOPE, PipeLeaseDeniedError, PipeLeaseError, PipeNotConnectedError, PipeReauthorizationRequiredError, PipeTemporarilyUnavailableError, VaultClient, actor, challenge, createVerifier, featureFlags, hasFeature, hasPermission, hasRole, isSupportSession, organization, permissions, pipeConnectUrl, randomToken, roles, sessionId, verifyStandardWebhook, verifyWebhook, withConnectReturn } from './chunk-YGLMLIKL.js';
1
+ import { Discovery } from './chunk-T5LCQOLS.js';
2
+ export { CboxIdClient, FEATURE_FLAGS_SCOPE, PipeLeaseDeniedError, PipeLeaseError, PipeNotConnectedError, PipeReauthorizationRequiredError, PipeTemporarilyUnavailableError, VaultClient, actor, featureFlags, hasFeature, hasPermission, hasRole, isSupportSession, organization, permissions, pipeConnectUrl, roles, sessionId, verifyStandardWebhook, verifyWebhook, withConnectReturn } from './chunk-T5LCQOLS.js';
3
3
  export { PermissionDecision, checkPermissions } from './chunk-EVZ6RB3K.js';
4
+ export { challenge, createVerifier, randomToken } from './chunk-VGQASHTI.js';
4
5
  import { assertSecureIssuer } from './chunk-QQW63PGU.js';
5
6
  import { ConfigurationError, FrontendApiError, AuthenticationError } from './chunk-SEUD4TE4.js';
6
7
  export { AuthenticationError, CboxIdError, ConfigurationError, FrontendApiError, InvalidStateError } from './chunk-SEUD4TE4.js';