@cboxdk/id-js 0.11.3 → 0.12.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.
@@ -12,7 +12,32 @@ var ConfigurationError = class extends CboxIdError {
12
12
  var InvalidStateError = class extends CboxIdError {
13
13
  };
14
14
  var AuthenticationError = class extends CboxIdError {
15
+ constructor(message, error, errorDescription, status) {
16
+ super(message);
17
+ this.error = error;
18
+ this.errorDescription = errorDescription;
19
+ this.status = status;
20
+ }
21
+ error;
22
+ errorDescription;
23
+ status;
15
24
  };
25
+ async function oauthError(response, fallback) {
26
+ const body = await response.text().catch(() => "");
27
+ let code;
28
+ let description;
29
+ try {
30
+ const parsed = JSON.parse(body);
31
+ if (typeof parsed === "object" && parsed !== null) {
32
+ const { error, error_description: errorDescription } = parsed;
33
+ code = typeof error === "string" ? error : void 0;
34
+ description = typeof errorDescription === "string" ? errorDescription : void 0;
35
+ }
36
+ } catch {
37
+ }
38
+ const detail = code ?? (body.trim() === "" ? `HTTP ${response.status}` : body.slice(0, 200));
39
+ return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status);
40
+ }
16
41
  var FrontendApiError = class extends CboxIdError {
17
42
  constructor(message, code, status, retryAfter) {
18
43
  super(message);
@@ -367,7 +392,7 @@ var CboxIdClient = class {
367
392
  }
368
393
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
369
394
  if (!response.ok) {
370
- throw new AuthenticationError(`Token refresh failed: ${await response.text()}`);
395
+ throw await oauthError(response, "Token refresh failed");
371
396
  }
372
397
  const tokens = await response.json();
373
398
  if (!tokens.access_token) {
@@ -443,7 +468,7 @@ var CboxIdClient = class {
443
468
  }
444
469
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
445
470
  if (!response.ok) {
446
- throw new AuthenticationError(`Machine token request failed: ${await response.text()}`);
471
+ throw await oauthError(response, "Machine token request failed");
447
472
  }
448
473
  const json = await response.json();
449
474
  if (typeof json.access_token !== "string") {
@@ -461,7 +486,7 @@ var CboxIdClient = class {
461
486
  headers: { authorization: `Bearer ${accessToken}` }
462
487
  });
463
488
  if (!response.ok) {
464
- throw new AuthenticationError("Userinfo request failed.");
489
+ throw await oauthError(response, "Userinfo request failed");
465
490
  }
466
491
  return await response.json();
467
492
  }
@@ -478,30 +503,44 @@ var CboxIdClient = class {
478
503
  { authorization: `Basic ${basic}` }
479
504
  );
480
505
  if (!response.ok) {
481
- throw new AuthenticationError("Introspection request failed.");
506
+ throw await oauthError(response, "Introspection request failed");
482
507
  }
483
508
  return await response.json();
484
509
  }
485
510
  /**
486
- * RFC 7009 token revocation (confidential-client auth). Revokes an access or
487
- * refresh token; revoking a refresh token also drops the whole token family, so
488
- * this is what a real "sign out everywhere" does. Requires a secret.
511
+ * RFC 7009 token revocation. Revokes an access or refresh token; revoking a refresh
512
+ * token drops the whole token family, so this is what a real "sign out everywhere" does.
513
+ *
514
+ * **PUBLIC CLIENTS TOO.** This demanded a secret and threw `ConfigurationError` without
515
+ * one — so the clients that most need it were the ones that could not call it. A PKCE
516
+ * browser or native app authenticates with `none`, holds no secret, and is exactly the
517
+ * case where a refresh token sits in storage on a device somebody has just signed out
518
+ * of. Cbox ID's revocation endpoint accepts a public client, and its discovery document
519
+ * advertises `none` among the revocation auth methods; RFC 7009 §2.1 scopes every
520
+ * revocation to the calling client, so the only capability here is "destroy a token you
521
+ * are already holding". The SDK was the half saying no.
522
+ *
523
+ * A confidential client still authenticates with Basic; a public one names itself in the
524
+ * body, the same shape {@link exchange} already uses for the token endpoint.
489
525
  *
490
526
  * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so
491
- * a successful call means "the token is not valid any more", not "it existed".
527
+ * success means "this token is not valid any more", not "it existed".
492
528
  *
493
529
  * @param tokenTypeHint which store to search first — only a hint, never required.
494
530
  */
495
531
  async revoke(token, tokenTypeHint) {
496
532
  const endpoint = await this.discovery.endpoint("revocation_endpoint");
497
- const basic = btoa(`${this.config.clientId}:${this.requireSecret()}`);
498
- const body = new URLSearchParams({ token });
533
+ const body = new URLSearchParams({ token, client_id: this.config.clientId });
499
534
  if (tokenTypeHint) {
500
535
  body.set("token_type_hint", tokenTypeHint);
501
536
  }
502
- const response = await this.post(endpoint, body, { authorization: `Basic ${basic}` });
537
+ const headers = {};
538
+ if (this.config.clientSecret) {
539
+ headers.authorization = `Basic ${btoa(`${this.config.clientId}:${this.config.clientSecret}`)}`;
540
+ }
541
+ const response = await this.post(endpoint, body, headers);
503
542
  if (!response.ok) {
504
- throw new AuthenticationError("Revocation request failed.");
543
+ throw await oauthError(response, "Revocation request failed");
505
544
  }
506
545
  }
507
546
  /** Verify a Cbox ID webhook / inline-action signature. See {@link verifyWebhook}. */
@@ -529,7 +568,7 @@ var CboxIdClient = class {
529
568
  }
530
569
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
531
570
  if (!response.ok) {
532
- throw new AuthenticationError(`Token exchange failed: ${await response.text()}`);
571
+ throw await oauthError(response, "Token exchange failed");
533
572
  }
534
573
  return await response.json();
535
574
  }
@@ -634,5 +673,5 @@ function parseOrganizations(claim) {
634
673
  }
635
674
 
636
675
  export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, Discovery, FrontendApiError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook };
637
- //# sourceMappingURL=chunk-GZSLHMWN.js.map
638
- //# sourceMappingURL=chunk-GZSLHMWN.js.map
676
+ //# sourceMappingURL=chunk-TIIDIHOC.js.map
677
+ //# sourceMappingURL=chunk-TIIDIHOC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/pkce.ts","../src/vault.ts","../src/webhook.ts","../src/discovery.ts","../src/client.ts"],"names":["key"],"mappings":";;;AAIO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAA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CboxIdError) ... }` in one branch.\n */\nexport class CboxIdError extends Error {\n constructor(message: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\n/** The client is misconfigured (a required option is missing or empty). */\nexport class ConfigurationError extends CboxIdError {}\n\n/**\n * The login `state` did not match what was stored — the callback is forged or\n * stale. Treat as a fresh start, not an error to surface to the user.\n */\nexport class InvalidStateError extends CboxIdError {}\n\n/**\n * Login could not be completed: the provider returned an error, the callback was\n * missing a code, or a token / id_token failed verification.\n *\n * `error` carries the RFC 6749 §5.2 code the authorization server sent, when it sent one.\n * It used to be discarded at every back-channel boundary, leaving a single message string\n * for outcomes that need opposite responses: `invalid_grant` on a refresh means the\n * session is over and the person has to sign in again, while `temporarily_unavailable`\n * means try the same token in a moment. A caller reduced to matching on prose either\n * retries what can never succeed, or signs out somebody who did not need to be.\n */\nexport class AuthenticationError extends CboxIdError {\n constructor(\n message: string,\n /** RFC 6749 §5.2 error code, when the server sent a parseable one. */\n readonly error?: string,\n /** The server's `error_description`, verbatim. Not end-user copy. */\n readonly errorDescription?: string,\n /** HTTP status, for the cases where the body says nothing useful. */\n readonly status?: number,\n ) {\n super(message);\n }\n}\n\n/**\n * Read an OAuth error out of a failed token-endpoint response.\n *\n * Best-effort by design: a 502 from a proxy is HTML, a captive portal is worse, and the\n * caller still needs an error rather than a parse exception. What it must never do is\n * invent a code — an absent or unparseable `error` stays undefined, so\n * `e.error === 'invalid_grant'` is true only because the server said so.\n */\nexport async function oauthError(response: Response, fallback: string): Promise<AuthenticationError> {\n const body = await response.text().catch(() => '');\n\n let code: string | undefined;\n let description: string | undefined;\n\n try {\n const parsed: unknown = JSON.parse(body);\n\n if (typeof parsed === 'object' && parsed !== null) {\n const { error, error_description: errorDescription } = parsed as Record<string, unknown>;\n code = typeof error === 'string' ? error : undefined;\n description = typeof errorDescription === 'string' ? errorDescription : undefined;\n }\n } catch {\n // Not JSON. The status and the truncated body below are all there is to report.\n }\n\n const detail = code ?? (body.trim() === '' ? `HTTP ${response.status}` : body.slice(0, 200));\n\n return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status);\n}\n\n/**\n * The Frontend API refused, or could not be reached.\n *\n * Carries a `code` because the four ways this goes wrong need four different responses\n * from the caller, and telling them apart from a message string is the kind of thing\n * that works until somebody rewords the message:\n *\n * - `origin_not_allowed` — the overwhelmingly likely cause of a refusal, and a\n * configuration problem the developer fixes once in the console.\n * - `rate_limited` — back off; `retryAfter` says for how long, when the server said.\n * - `unavailable` — the network, or a 5xx. Transient by assumption; already retried.\n * - `malformed` — a 200 whose body is not the document we expect, which means something\n * between the page and us is rewriting responses (a proxy, an extension, a captive\n * portal). Worth distinguishing, because retrying it never helps.\n */\nexport class FrontendApiError extends CboxIdError {\n constructor(\n message: string,\n readonly code: 'origin_not_allowed' | 'rate_limited' | 'unavailable' | 'malformed',\n readonly status?: number,\n readonly retryAfter?: number,\n ) {\n super(message);\n }\n}\n","/**\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","import { AuthenticationError } 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\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 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 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 const response = await fetch(`${this.base}${path}`, init);\n if (!response.ok) {\n throw new AuthenticationError(`Vault ${method} ${path} failed with status ${response.status}.`);\n }\n return response;\n } finally {\n clearTimeout(timer);\n }\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","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 = `${this.issuer.replace(/\\/$/, '')}/.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 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","import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';\nimport { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError, InvalidStateError, oauthError } from './errors.js';\nimport { challenge, createVerifier, randomToken } from './pkce.js';\nimport type {\n AuthorizationRequest,\n CboxIdConfig,\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\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 if (!config.redirectUri) {\n throw new ConfigurationError('Cbox ID config `redirectUri` is required.');\n }\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: {\n scopes?: string[];\n redirectUri?: string;\n state?: string;\n prompt?: string;\n loginHint?: string;\n maxAge?: number;\n } = {}): Promise<AuthorizationRequest> {\n const codeVerifier = createVerifier();\n const state = options.state ?? randomToken(16);\n const nonce = randomToken(16);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: this.config.clientId,\n redirect_uri: options.redirectUri ?? this.config.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 (options.prompt) {\n params.set('prompt', options.prompt);\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\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 };\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 throw new AuthenticationError(\n `Cbox ID returned an error: ${params.error}${params.error_description ? ` (${params.error_description})` : ''}`,\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 claims: Record<string, unknown> = {};\n if (tokens.id_token) {\n claims = await this.verifyIdToken(tokens.id_token, stored.nonce, stored.maxAge);\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 // Enrich with userinfo (email/name/org a minimal id_token may omit).\n claims = { ...claims, ...(await this.userinfo(tokens.access_token)) };\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 // 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 * 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 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 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 body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri ?? this.config.redirectUri,\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 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/** 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"]}
@@ -317,12 +317,23 @@ declare class CboxIdClient {
317
317
  */
318
318
  introspect(token: string): Promise<Record<string, unknown>>;
319
319
  /**
320
- * RFC 7009 token revocation (confidential-client auth). Revokes an access or
321
- * refresh token; revoking a refresh token also drops the whole token family, so
322
- * this is what a real "sign out everywhere" does. Requires a secret.
320
+ * RFC 7009 token revocation. Revokes an access or refresh token; revoking a refresh
321
+ * token drops the whole token family, so this is what a real "sign out everywhere" does.
322
+ *
323
+ * **PUBLIC CLIENTS TOO.** This demanded a secret and threw `ConfigurationError` without
324
+ * one — so the clients that most need it were the ones that could not call it. A PKCE
325
+ * browser or native app authenticates with `none`, holds no secret, and is exactly the
326
+ * case where a refresh token sits in storage on a device somebody has just signed out
327
+ * of. Cbox ID's revocation endpoint accepts a public client, and its discovery document
328
+ * advertises `none` among the revocation auth methods; RFC 7009 §2.1 scopes every
329
+ * revocation to the calling client, so the only capability here is "destroy a token you
330
+ * are already holding". The SDK was the half saying no.
331
+ *
332
+ * A confidential client still authenticates with Basic; a public one names itself in the
333
+ * body, the same shape {@link exchange} already uses for the token endpoint.
323
334
  *
324
335
  * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so
325
- * a successful call means "the token is not valid any more", not "it existed".
336
+ * success means "this token is not valid any more", not "it existed".
326
337
  *
327
338
  * @param tokenTypeHint which store to search first — only a hint, never required.
328
339
  */
@@ -317,12 +317,23 @@ declare class CboxIdClient {
317
317
  */
318
318
  introspect(token: string): Promise<Record<string, unknown>>;
319
319
  /**
320
- * RFC 7009 token revocation (confidential-client auth). Revokes an access or
321
- * refresh token; revoking a refresh token also drops the whole token family, so
322
- * this is what a real "sign out everywhere" does. Requires a secret.
320
+ * RFC 7009 token revocation. Revokes an access or refresh token; revoking a refresh
321
+ * token drops the whole token family, so this is what a real "sign out everywhere" does.
322
+ *
323
+ * **PUBLIC CLIENTS TOO.** This demanded a secret and threw `ConfigurationError` without
324
+ * one — so the clients that most need it were the ones that could not call it. A PKCE
325
+ * browser or native app authenticates with `none`, holds no secret, and is exactly the
326
+ * case where a refresh token sits in storage on a device somebody has just signed out
327
+ * of. Cbox ID's revocation endpoint accepts a public client, and its discovery document
328
+ * advertises `none` among the revocation auth methods; RFC 7009 §2.1 scopes every
329
+ * revocation to the calling client, so the only capability here is "destroy a token you
330
+ * are already holding". The SDK was the half saying no.
331
+ *
332
+ * A confidential client still authenticates with Basic; a public one names itself in the
333
+ * body, the same shape {@link exchange} already uses for the token endpoint.
323
334
  *
324
335
  * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so
325
- * a successful call means "the token is not valid any more", not "it existed".
336
+ * success means "this token is not valid any more", not "it existed".
326
337
  *
327
338
  * @param tokenTypeHint which store to search first — only a hint, never required.
328
339
  */
package/dist/index.cjs CHANGED
@@ -14,7 +14,32 @@ var ConfigurationError = class extends CboxIdError {
14
14
  var InvalidStateError = class extends CboxIdError {
15
15
  };
16
16
  var AuthenticationError = class extends CboxIdError {
17
+ constructor(message, error, errorDescription, status) {
18
+ super(message);
19
+ this.error = error;
20
+ this.errorDescription = errorDescription;
21
+ this.status = status;
22
+ }
23
+ error;
24
+ errorDescription;
25
+ status;
17
26
  };
27
+ async function oauthError(response, fallback) {
28
+ const body = await response.text().catch(() => "");
29
+ let code;
30
+ let description;
31
+ try {
32
+ const parsed = JSON.parse(body);
33
+ if (typeof parsed === "object" && parsed !== null) {
34
+ const { error, error_description: errorDescription } = parsed;
35
+ code = typeof error === "string" ? error : void 0;
36
+ description = typeof errorDescription === "string" ? errorDescription : void 0;
37
+ }
38
+ } catch {
39
+ }
40
+ const detail = code ?? (body.trim() === "" ? `HTTP ${response.status}` : body.slice(0, 200));
41
+ return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status);
42
+ }
18
43
  var FrontendApiError = class extends CboxIdError {
19
44
  constructor(message, code, status, retryAfter) {
20
45
  super(message);
@@ -768,7 +793,7 @@ var CboxIdClient = class {
768
793
  }
769
794
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
770
795
  if (!response.ok) {
771
- throw new AuthenticationError(`Token refresh failed: ${await response.text()}`);
796
+ throw await oauthError(response, "Token refresh failed");
772
797
  }
773
798
  const tokens = await response.json();
774
799
  if (!tokens.access_token) {
@@ -844,7 +869,7 @@ var CboxIdClient = class {
844
869
  }
845
870
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
846
871
  if (!response.ok) {
847
- throw new AuthenticationError(`Machine token request failed: ${await response.text()}`);
872
+ throw await oauthError(response, "Machine token request failed");
848
873
  }
849
874
  const json2 = await response.json();
850
875
  if (typeof json2.access_token !== "string") {
@@ -862,7 +887,7 @@ var CboxIdClient = class {
862
887
  headers: { authorization: `Bearer ${accessToken}` }
863
888
  });
864
889
  if (!response.ok) {
865
- throw new AuthenticationError("Userinfo request failed.");
890
+ throw await oauthError(response, "Userinfo request failed");
866
891
  }
867
892
  return await response.json();
868
893
  }
@@ -879,30 +904,44 @@ var CboxIdClient = class {
879
904
  { authorization: `Basic ${basic}` }
880
905
  );
881
906
  if (!response.ok) {
882
- throw new AuthenticationError("Introspection request failed.");
907
+ throw await oauthError(response, "Introspection request failed");
883
908
  }
884
909
  return await response.json();
885
910
  }
886
911
  /**
887
- * RFC 7009 token revocation (confidential-client auth). Revokes an access or
888
- * refresh token; revoking a refresh token also drops the whole token family, so
889
- * this is what a real "sign out everywhere" does. Requires a secret.
912
+ * RFC 7009 token revocation. Revokes an access or refresh token; revoking a refresh
913
+ * token drops the whole token family, so this is what a real "sign out everywhere" does.
914
+ *
915
+ * **PUBLIC CLIENTS TOO.** This demanded a secret and threw `ConfigurationError` without
916
+ * one — so the clients that most need it were the ones that could not call it. A PKCE
917
+ * browser or native app authenticates with `none`, holds no secret, and is exactly the
918
+ * case where a refresh token sits in storage on a device somebody has just signed out
919
+ * of. Cbox ID's revocation endpoint accepts a public client, and its discovery document
920
+ * advertises `none` among the revocation auth methods; RFC 7009 §2.1 scopes every
921
+ * revocation to the calling client, so the only capability here is "destroy a token you
922
+ * are already holding". The SDK was the half saying no.
923
+ *
924
+ * A confidential client still authenticates with Basic; a public one names itself in the
925
+ * body, the same shape {@link exchange} already uses for the token endpoint.
890
926
  *
891
927
  * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so
892
- * a successful call means "the token is not valid any more", not "it existed".
928
+ * success means "this token is not valid any more", not "it existed".
893
929
  *
894
930
  * @param tokenTypeHint which store to search first — only a hint, never required.
895
931
  */
896
932
  async revoke(token, tokenTypeHint) {
897
933
  const endpoint = await this.discovery.endpoint("revocation_endpoint");
898
- const basic = btoa(`${this.config.clientId}:${this.requireSecret()}`);
899
- const body = new URLSearchParams({ token });
934
+ const body = new URLSearchParams({ token, client_id: this.config.clientId });
900
935
  if (tokenTypeHint) {
901
936
  body.set("token_type_hint", tokenTypeHint);
902
937
  }
903
- const response = await this.post(endpoint, body, { authorization: `Basic ${basic}` });
938
+ const headers = {};
939
+ if (this.config.clientSecret) {
940
+ headers.authorization = `Basic ${btoa(`${this.config.clientId}:${this.config.clientSecret}`)}`;
941
+ }
942
+ const response = await this.post(endpoint, body, headers);
904
943
  if (!response.ok) {
905
- throw new AuthenticationError("Revocation request failed.");
944
+ throw await oauthError(response, "Revocation request failed");
906
945
  }
907
946
  }
908
947
  /** Verify a Cbox ID webhook / inline-action signature. See {@link verifyWebhook}. */
@@ -930,7 +969,7 @@ var CboxIdClient = class {
930
969
  }
931
970
  const response = await this.post(await this.discovery.endpoint("token_endpoint"), body);
932
971
  if (!response.ok) {
933
- throw new AuthenticationError(`Token exchange failed: ${await response.text()}`);
972
+ throw await oauthError(response, "Token exchange failed");
934
973
  }
935
974
  return await response.json();
936
975
  }