@atol-sh/js 0.1.2 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -2,51 +2,57 @@ import { JWTPayload } from 'jose';
2
2
  import { UserManager, User } from 'oidc-client-ts';
3
3
 
4
4
  /**
5
- * DPoP (RFC 9449) client implementation.
6
- *
7
- * This module owns the per-tab ES256 keypair used for sender-constrained
8
- * tokens, plus the proof-JWT builder that clients send on every
9
- * /auth/token call (and, in future, on every resource-server request).
10
- *
11
- * Design choices:
12
- * - Keys are non-exportable CryptoKey objects (`extractable: false`).
13
- * XSS can use them to sign but cannot exfiltrate the private bytes.
14
- * - Keys are regenerated per-tab on provider mount. A page reload ==
15
- * a new keypair. The cost is one extra round-trip after reload;
16
- * the benefit is no persistence surface for key material at all.
17
- * - ES256 / P-256 only. Universal WebCrypto support, matches what the
18
- * server's DPoP validator accepts first.
5
+ * Framework-agnostic shared types for the Atol browser security core.
19
6
  *
20
- * The module is a no-op fallback when WebCrypto is unavailable (SSR,
21
- * extremely old browsers). Callers treat a null manager as "Bearer mode".
7
+ * These are the wire-facing shapes the core produces and consumes:
8
+ * the parsed Atol user, permission checks, and the DPoP proof result.
9
+ * They carry no framework dependency, so both @atol-sh/react and any
10
+ * other binding layer re-export them unchanged.
22
11
  */
23
- /** Optional per-proof inputs (RFC 9449 resource access + server nonce). */
24
- interface DPoPProofOptions {
25
- /**
26
- * Access token being presented. When set, the proof carries an `ath`
27
- * claim (base64url(SHA-256(accessToken))) binding the proof to that
28
- * token, as required for DPoP-authenticated resource-server requests
29
- * (RFC 9449 §4.3 / §7). Omit at the token endpoint.
30
- */
31
- accessToken?: string;
32
- /**
33
- * Server-issued nonce (RFC 9449 §8). When the AS/RS rejects a proof
34
- * with `use_dpop_nonce` + a `DPoP-Nonce` header, re-sign with that
35
- * nonce and retry.
36
- */
37
- nonce?: string;
12
+ /** Authenticated user parsed from Atol JWT claims. */
13
+ interface AtolUser {
14
+ /** User ID (JWT sub claim). */
15
+ id: string;
16
+ /** User's email address. */
17
+ email: string;
18
+ /** Whether the user's email address is verified (email_verified claim). */
19
+ emailVerified: boolean;
20
+ /** User's display name. */
21
+ name: string;
22
+ /** How the user authenticated (atol:auth_method claim). */
23
+ authMethod: string;
24
+ /** Whether multi-factor auth was completed (atol:mfa_verified claim). */
25
+ mfaVerified: boolean;
38
26
  }
39
- interface DPoPKeyManager {
40
- /** Sign a proof for a specific (method, url) pair, plus optional ath/nonce. */
41
- signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>;
42
- /** Public JWK -- used by the server to compute `cnf.jkt`. */
43
- publicJWK(): Promise<JsonWebKey>;
27
+ /** A permission check to evaluate. */
28
+ interface PermissionCheck {
29
+ /** Action to check (e.g. "edit", "view", "manage"). */
30
+ action: string;
31
+ /** Resource to check against (e.g. "publication", "team:team-123"). */
32
+ resource: string;
33
+ }
34
+ /** Result of a permission check. */
35
+ interface PermissionResult {
36
+ action: string;
37
+ resource: string;
38
+ allowed: boolean;
44
39
  }
45
40
  /**
46
- * Create a per-tab DPoP key manager. Returns null when WebCrypto is not
47
- * available -- the caller should fall back to Bearer mode silently.
41
+ * Result of `signDPoPProof` / a DPoP-aware token accessor: the current
42
+ * access token plus, when DPoP is active, a matching resource-server
43
+ * proof JWT.
48
44
  */
49
- declare function createDPoPKeyManager(): Promise<DPoPKeyManager | null>;
45
+ interface DPoPProofResult {
46
+ /** The current (freshly-renewed) access token. */
47
+ token: string;
48
+ /**
49
+ * A DPoP proof JWT (RFC 9449) for the requested (method, url), bound to
50
+ * `token` via its `ath` claim. Undefined when DPoP is not active
51
+ * (`useDPoP` off or WebCrypto unavailable) -- the caller then presents
52
+ * `token` as a plain `Authorization: Bearer` credential.
53
+ */
54
+ proof?: string;
55
+ }
50
56
 
51
57
  /**
52
58
  * Token renewal error classification.
@@ -62,13 +68,15 @@ declare function createDPoPKeyManager(): Promise<DPoPKeyManager | null>;
62
68
  */
63
69
  /**
64
70
  * OAuth 2.0 / OIDC protocol error surfaced by the authorization server.
65
- * Carries the machine-readable `error` code from the token / authorize
66
- * endpoint response so the recovery layer can act on it precisely.
71
+ * Carries only a closed machine-readable code. Provider descriptions and
72
+ * unknown error names are untrusted diagnostic input and are never retained
73
+ * on a public Error object.
67
74
  */
75
+ declare const OAUTH_PROTOCOL_ERROR_CODES: readonly ["access_denied", "account_selection_required", "authorization_pending", "authorization_nonterminal", "authorization_terminal", "consent_required", "expired_token", "insufficient_scope", "interaction_required", "invalid_client", "invalid_dpop_proof", "invalid_grant", "invalid_request", "invalid_response", "invalid_scope", "invalid_token", "login_required", "server_error", "slow_down", "temporarily_unavailable", "unauthorized_client", "unsupported_grant_type", "unsupported_response_type", "use_dpop_nonce"];
76
+ type OAuthProtocolErrorCode = (typeof OAUTH_PROTOCOL_ERROR_CODES)[number];
68
77
  declare class OAuthProtocolError extends Error {
69
- code: string;
70
- description?: string;
71
- constructor(code: string, description?: string);
78
+ readonly code: OAuthProtocolErrorCode;
79
+ constructor(code: unknown, _description?: unknown);
72
80
  }
73
81
  /**
74
82
  * Re-auth-class protocol errors -- login_required, consent_required,
@@ -77,7 +85,7 @@ declare class OAuthProtocolError extends Error {
77
85
  * OAuthProtocolError` matches the broader classification.
78
86
  */
79
87
  declare class LoginRequiredError extends OAuthProtocolError {
80
- constructor(description?: string);
88
+ constructor(_description?: unknown);
81
89
  }
82
90
  /**
83
91
  * Transport / network layer failure -- `fetch` rejected, DNS miss, TLS
@@ -85,8 +93,16 @@ declare class LoginRequiredError extends OAuthProtocolError {
85
93
  * never saw the request.
86
94
  */
87
95
  declare class NetworkError extends Error {
88
- cause?: unknown;
89
- constructor(message: string, cause?: unknown);
96
+ constructor(message: string, _cause?: unknown);
97
+ }
98
+ /**
99
+ * The token request may have consumed an authorization code, but the browser
100
+ * did not obtain a complete usable response. Exact code replay is required so
101
+ * the authorization server can revoke any first family before local cleanup.
102
+ */
103
+ declare class AuthorizationCodeExchangeUncertainError extends NetworkError {
104
+ readonly code = "authorization_code_exchange_uncertain";
105
+ constructor(message: string, _cause?: unknown);
90
106
  }
91
107
  /**
92
108
  * What the caller should do when a renewal throws.
@@ -146,62 +162,55 @@ declare function classifyRenewalError(err: unknown): RecoveryAction;
146
162
  declare function backoffDelay(attempt: number, rand?: () => number): number;
147
163
 
148
164
  /**
149
- * Silent token renewal via web_message response mode.
165
+ * DPoP (RFC 9449) client implementation.
150
166
  *
151
- * Opens a hidden iframe to the authorization endpoint with response_mode=web_message
152
- * and prompt=none. The server validates the session cookie and returns an HTML page
153
- * that sends the authorization response via postMessage. No SPA loading in the iframe.
167
+ * This module owns the per-tab ES256 keypair used for sender-constrained
168
+ * tokens, plus the proof-JWT builder used for token-endpoint and protected
169
+ * resource requests.
154
170
  *
155
- * Spec: draft-sakimura-oauth-wmrm-01
171
+ * Design choices:
172
+ * - Keys are non-exportable CryptoKey objects (`extractable: false`).
173
+ * XSS can use them to sign but cannot exfiltrate the private bytes.
174
+ * - Every authorization gets a new key. A full redirect stages only its
175
+ * opaque CryptoKey handles in IndexedDB until the matching callback
176
+ * consumes them; iframe grants keep the key in memory.
177
+ * - ES256 / P-256 only. Universal WebCrypto support, matches what the
178
+ * server's DPoP validator accepts first.
179
+ *
180
+ * The module is a no-op fallback when WebCrypto is unavailable (SSR,
181
+ * extremely old browsers). Callers treat a null manager as "Bearer mode".
156
182
  */
157
-
158
- interface SilentRenewOptions {
159
- authority: string;
160
- clientId: string;
161
- redirectUri: string;
162
- scope: string;
163
- audience?: string;
183
+ /** Optional per-proof inputs (RFC 9449 resource access + server nonce). */
184
+ interface DPoPProofOptions {
164
185
  /**
165
- * When true, asks the server to include `atol:wrapped_dek` on the renewed
166
- * ID token. The KEK is NOT re-delivered (the password isn't available
167
- * during silent renew), but carrying the wrapped DEK claim keeps it
168
- * consistently present across every token in the session, so app code
169
- * that re-reads it after a renewal (tab rehydrate, multi-tab sync) finds
170
- * the same DEK material it saw at login.
186
+ * Access token being presented. When set, the proof carries an `ath`
187
+ * claim (base64url(SHA-256(accessToken))) binding the proof to that
188
+ * token, as required for DPoP-authenticated resource-server requests
189
+ * (RFC 9449 §4.3 / §7). Omit at the token endpoint.
171
190
  */
172
- deriveEncryptionKey?: boolean;
191
+ accessToken?: string;
173
192
  /**
174
- * Milliseconds to wait for the iframe's postMessage before rejecting.
175
- * Defaults to 60s. An earlier 10s value was too tight on
176
- * slow networks and caused the "return stale token" fallback to fire
177
- * unnecessarily, producing `token is expired (exp)` errors on the server.
193
+ * Server-issued nonce (RFC 9449 §8). When the AS/RS rejects a proof
194
+ * with `use_dpop_nonce` + a `DPoP-Nonce` header, re-sign with that
195
+ * nonce and retry.
178
196
  */
179
- timeoutMs?: number;
197
+ nonce?: string;
198
+ }
199
+ interface DPoPKeyManager {
200
+ /** Sign a proof for a specific (method, url) pair, plus optional ath/nonce. */
201
+ signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>;
202
+ /** Public JWK -- used by the server to compute `cnf.jkt`. */
203
+ publicJWK(): Promise<JsonWebKey>;
204
+ /** RFC 7638 SHA-256 thumbprint expected in a bound token's `cnf.jkt`. */
205
+ thumbprint(): Promise<string>;
180
206
  }
181
- /** Default iframe timeout for silent authorization. */
182
- declare const DEFAULT_AUTHORIZE_TIMEOUT_MS = 60000;
183
- /** Default retry count for silent authorize on transient errors. */
184
- declare const DEFAULT_SILENT_RENEW_RETRY_COUNT = 3;
185
- /**
186
- * Perform a silent authorization request via web_message.
187
- * Returns the authorization code + state, or throws on error.
188
- */
189
- declare function silentAuthorize(opts: SilentRenewOptions): Promise<{
190
- code: string;
191
- state: string;
192
- codeVerifier: string;
193
- }>;
194
207
  /**
195
- * silentAuthorize with bounded retry on transient errors (default 3
196
- * attempts). `login_required` and similar
197
- * re-auth errors are fatal and bypass the retry loop.
208
+ * Create a per-tab DPoP key manager. Returns null when WebCrypto is not
209
+ * available. The caller decides whether that means Bearer fallback or a
210
+ * fatal error according to its public configuration.
198
211
  */
199
- declare function silentAuthorizeWithRetry(opts: SilentRenewOptions, retries?: number): Promise<{
200
- code: string;
201
- state: string;
202
- codeVerifier: string;
203
- }>;
204
- /** Shape of a successful /auth/token response. */
212
+ declare function createDPoPKeyManager(): Promise<DPoPKeyManager | null>;
213
+
205
214
  interface TokenResponse {
206
215
  access_token: string;
207
216
  id_token?: string;
@@ -210,106 +219,37 @@ interface TokenResponse {
210
219
  expires_in: number;
211
220
  scope?: string;
212
221
  }
213
- /**
214
- * Optional per-request DPoP signer. When provided, token-endpoint calls
215
- * attach a signed proof header (RFC 9449). When omitted, calls run Bearer-
216
- * only and the server issues un-bound tokens. The provider wires this
217
- * through from its DPoPKeyManager when `useDPoP: true`.
218
- */
222
+
219
223
  interface DPoPSigner {
220
224
  signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>;
221
225
  }
222
- /**
223
- * Exchange an authorization code for tokens via the token endpoint.
224
- */
225
- declare function exchangeCode(authority: string, clientId: string, code: string, redirectUri: string, codeVerifier: string, dpop?: DPoPSigner): Promise<TokenResponse>;
226
- /**
227
- * Renew tokens using a refresh token grant (RFC 6749 §6). This is the
228
- * `useRefreshTokens: true` path -- a direct POST to the token
229
- * endpoint, no iframe, no cross-site cookies. Works under Chrome's third-
230
- * party cookie phaseout, Safari ITP, and Firefox ETP without the user
231
- * needing to grant Storage Access.
232
- *
233
- * The server may rotate the refresh token on each use (RFC 6749 §10.4);
234
- * callers must read `refresh_token` from the response and replace their
235
- * stored copy before the next renew.
236
- *
237
- * An expired or revoked refresh token surfaces as `LoginRequiredError` so
238
- * the caller can force a re-auth, matching the semantics of the iframe
239
- * path for login_required.
240
- */
226
+ declare function exchangeCode(authority: string, clientId: string, code: string, redirectUri: string, codeVerifier: string, dpop?: DPoPSigner, options?: {
227
+ signal?: AbortSignal;
228
+ }): Promise<TokenResponse>;
241
229
  declare function refreshTokenGrant(authority: string, clientId: string, refreshToken: string, scope?: string, audience?: string, dpop?: DPoPSigner): Promise<TokenResponse>;
242
- /**
243
- * Revoke a token via the RFC 7009 revocation endpoint. Used on logout to
244
- * proactively invalidate the refresh token server-side rather than waiting
245
- * for it to expire. A best-effort call: revocation failures are surfaced
246
- * to the caller, which typically swallows them (the RP-initiated logout
247
- * still kills the session cookie).
248
- *
249
- * `tokenTypeHint` defaults to `refresh_token` -- the token most worth
250
- * revoking, since it can mint new access tokens.
251
- */
252
230
  declare function revokeToken(authority: string, clientId: string, token: string, tokenTypeHint?: 'refresh_token' | 'access_token'): Promise<void>;
253
231
 
254
232
  /**
255
- * Framework-agnostic shared types for the Atol browser security core.
233
+ * Silent token renewal transport for a PAR-admitted web_message URL.
256
234
  *
257
- * These are the wire-facing shapes the core produces and consumes:
258
- * the parsed Atol user, permission checks, and the DPoP proof result.
259
- * They carry no framework dependency, so both @atol-sh/react and any
260
- * other binding layer re-export them unchanged.
261
- */
262
- /** Authenticated user parsed from Atol JWT claims. */
263
- interface AtolUser {
264
- /** User ID (JWT sub claim). */
265
- id: string;
266
- /** User's email address. */
267
- email: string;
268
- /** Whether the user's email address is verified (email_verified claim). */
269
- emailVerified: boolean;
270
- /** User's display name. */
271
- name: string;
272
- /** Organization ID (atol:org_id claim). */
273
- orgId: string;
274
- /** Organization's subscription plan (atol:plan claim). */
275
- plan: string;
276
- /** User's roles within the organization (atol:roles claim). */
277
- roles: string[];
278
- /** How the user authenticated (atol:auth_method claim). */
279
- authMethod: string;
280
- /** Whether multi-factor auth was completed (atol:mfa_verified claim). */
281
- mfaVerified: boolean;
282
- }
283
- /** A permission check to evaluate. */
284
- interface PermissionCheck {
285
- /** Action to check (e.g. "edit", "view", "manage"). */
286
- action: string;
287
- /** Resource to check against (e.g. "publication", "team:team-123"). */
288
- resource: string;
289
- }
290
- /** Result of a permission check. */
291
- interface PermissionResult {
292
- action: string;
293
- resource: string;
294
- allowed: boolean;
295
- }
296
- /**
297
- * Result of `signDPoPProof` / a DPoP-aware token accessor: the current
298
- * access token plus, when DPoP is active, a matching resource-server
299
- * proof JWT.
235
+ * The caller owns PAR admission and callback custody. This module validates
236
+ * and navigates only the resulting client_id + request_uri envelope.
237
+ *
238
+ * Spec: draft-sakimura-oauth-wmrm-01
300
239
  */
301
- interface DPoPProofResult {
302
- /** The current (freshly-renewed) access token. */
303
- token: string;
304
- /**
305
- * A DPoP proof JWT (RFC 9449) for the requested (method, url), bound to
306
- * `token` via its `ath` claim. Undefined when DPoP is not active
307
- * (`useDPoP` off or WebCrypto unavailable) -- the caller then presents
308
- * `token` as a plain `Authorization: Bearer` credential.
309
- */
310
- proof?: string;
240
+
241
+ /** Default iframe timeout for silent authorization. */
242
+ declare const DEFAULT_AUTHORIZE_TIMEOUT_MS = 60000;
243
+ /** Default retry count for silent authorize on transient errors. */
244
+ declare const DEFAULT_SILENT_RENEW_RETRY_COUNT = 3;
245
+
246
+ declare class AtolBrowserAuthCleanupError extends Error {
247
+ readonly code = "browser_auth_cleanup_failed";
248
+ constructor();
311
249
  }
312
250
 
251
+ declare function createAtolBrowserAuth(config: AtolBrowserAuthConfig): AtolBrowserAuth;
252
+
313
253
  /**
314
254
  * createAtolBrowserAuth: the config-driven browser auth client.
315
255
  *
@@ -317,8 +257,9 @@ interface DPoPProofResult {
317
257
  * proven Atol logic that previously lived only inside the React provider:
318
258
  * PKCE authorization-code login, in-memory token storage, DPoP-aware token
319
259
  * access, proactive + on-demand silent renewal with single-flight
320
- * coordination, cross-tab rotation broadcast (authenticated via JWKS), and
321
- * RP-initiated logout with refresh-token revocation.
260
+ * coordination, signal-only cross-tab invalidation, organization-scoped
261
+ * credential transactions, and RP-initiated logout with refresh-token
262
+ * revocation.
322
263
  *
323
264
  * Framework bindings (React, Vue, ...) become thin wrappers over this: they
324
265
  * subscribe with `onSessionChange` and render, delegating every credential
@@ -345,12 +286,29 @@ interface AtolBrowserAuthConfig {
345
286
  audience?: string;
346
287
  /** OIDC scopes. Default: "openid profile email". */
347
288
  scopes?: string;
348
- /** URL to redirect to after login (and after logout). */
289
+ /** Exact registered OIDC callback URL used only for authorization responses. */
349
290
  redirectUri: string;
291
+ /**
292
+ * Exact registered same-origin landing URL used after RP-initiated logout.
293
+ * Ordinary clients default to `redirectUri` for compatibility.
294
+ * Response-vault clients require an explicit, distinct value.
295
+ */
296
+ postLogoutRedirectUri?: string;
297
+ /**
298
+ * Enable the public response-vault v1 browser authorization protocol. Every
299
+ * interactive, silent, organization-selection, and step-up authorization
300
+ * uses PAR plus a parameter-free navigation and same-origin token relay.
301
+ * The client registration must support the protocol. A non-empty audience
302
+ * and mandatory DPoP are required.
303
+ */
304
+ responseVault?: boolean;
350
305
  /**
351
306
  * Request DPoP-bound tokens (RFC 9449). `true` (or `{ required: true }`)
352
307
  * generates a per-tab non-exportable ES256 keypair on init and attaches a
353
- * proof to every token-endpoint call. `false` (default) uses Bearer.
308
+ * proof to every token-endpoint call. `{ required: true }` also makes key
309
+ * creation failure fatal; boolean `true` retains a Bearer fallback where
310
+ * WebCrypto is unavailable. `false` (default) uses Bearer for ordinary
311
+ * clients. Response-vault mode always requires DPoP and rejects `false`.
354
312
  */
355
313
  dpop?: DPoPConfig;
356
314
  /**
@@ -394,9 +352,9 @@ interface AtolBrowserAuthConfig {
394
352
  /**
395
353
  * TEST ONLY. Enable {@link AtolBrowserAuth.seedTestSession}, which
396
354
  * establishes an authenticated session directly from a token response --
397
- * WITHOUT an OIDC redirect/callback, and without signature, state, or
398
- * nonce validation. Defaults to `false`; while `false`, `seedTestSession`
399
- * throws.
355
+ * WITHOUT an OIDC redirect/callback, and without signature, state, nonce,
356
+ * or DPoP-binding validation. Defaults to `false`; while `false`,
357
+ * `seedTestSession` throws.
400
358
  *
401
359
  * This exists so browser end-to-end tests (Cypress, Playwright) can
402
360
  * bootstrap a logged-in session against the in-memory token store without a
@@ -433,6 +391,8 @@ interface AtolSession {
433
391
  isAuthenticated: boolean;
434
392
  /** The authenticated user, or null. */
435
393
  user: AtolUser | null;
394
+ /** Organization to which the current credential pair is scoped. */
395
+ organizationId?: string;
436
396
  /**
437
397
  * The unwrapped zero-knowledge data-encryption key (DEK), when
438
398
  * `deriveEncryptionKey` is enabled and the KEK/wrapped-DEK derivation
@@ -467,7 +427,11 @@ interface GetAccessTokenOptions {
467
427
  }
468
428
  /** Options for {@link AtolBrowserAuth.beginLogin}. */
469
429
  interface BeginLoginOptions {
470
- /** Same-origin path to return to after login (overrides the redirect URI). */
430
+ /**
431
+ * Same-origin application route to restore only after the authorization
432
+ * response has been verified and committed. This is transaction-bound
433
+ * application state and never changes the registered OIDC redirect URI.
434
+ */
471
435
  returnTo?: string;
472
436
  /**
473
437
  * OIDC `prompt` value (e.g. `'login'` to force re-authentication, `'none'`
@@ -484,7 +448,10 @@ interface BeginLoginOptions {
484
448
  }
485
449
  /** Options for {@link AtolBrowserAuth.stepUp}. */
486
450
  interface StepUpOptions {
487
- /** Same-origin path to return to after the step-up re-authentication. */
451
+ /**
452
+ * Same-origin application route to restore after the verified step-up
453
+ * response commits. It never changes the registered OIDC redirect URI.
454
+ */
488
455
  returnTo?: string;
489
456
  /**
490
457
  * OIDC `max_age` (seconds). Defaults to `0` (force a brand-new login). Set a
@@ -505,17 +472,18 @@ interface AtolBrowserAuth {
505
472
  init(): Promise<AtolSession>;
506
473
  /**
507
474
  * Begin an authorization-code + PKCE login by redirecting the browser to
508
- * the Atol authorize endpoint. `returnTo` (a same-origin path) overrides
509
- * the post-login redirect target for this call. `prompt` / `maxAge` /
510
- * `acrValues` are forwarded as OIDC authorize-request parameters (used by
511
- * {@link AtolBrowserAuth.stepUp} to force re-authentication).
475
+ * the Atol authorize endpoint. The registered redirect URI is immutable;
476
+ * host applications keep any post-login route separately in same-tab state.
477
+ * `prompt` / `maxAge` / `acrValues` are forwarded as OIDC
478
+ * authorize-request parameters (used by {@link AtolBrowserAuth.stepUp} to
479
+ * force re-authentication).
512
480
  */
513
481
  beginLogin(options?: BeginLoginOptions): Promise<void>;
514
482
  /**
515
483
  * Force a step-up re-authentication: redirect to the authorize endpoint with
516
484
  * `prompt=login` + `max_age=0` (and `acr_values=mfa` by default) so the
517
485
  * issuer mints a token with a fresh `auth_time` and a completed second
518
- * factor. Use this when a sensitive management operation returns a
486
+ * factor. Use this when a sensitive operation returns a
519
487
  * "step_up_required" challenge; after the redirect completes, retry the
520
488
  * operation. Overridable via {@link StepUpOptions}.
521
489
  */
@@ -527,6 +495,13 @@ interface AtolBrowserAuth {
527
495
  * callback. `init()` calls this automatically.
528
496
  */
529
497
  completeLogin(): Promise<AtolSession>;
498
+ /**
499
+ * Mint a new credential pair scoped to `organizationId`. This is a
500
+ * distinct prompt=none authorization transaction, never an alias for a
501
+ * generic renewal. The previous credential pair remains active if the
502
+ * selection fails.
503
+ */
504
+ selectOrganization(organizationId: string): Promise<AtolSession>;
530
505
  /**
531
506
  * Return the current access token, renewing it when it is inside the 60s
532
507
  * expiry window. With `opts.dpop` and DPoP active, also returns a bound
@@ -562,9 +537,17 @@ interface AtolBrowserAuth {
562
537
  */
563
538
  getEncryptionError(): Error | undefined;
564
539
  /**
565
- * Sign out via OIDC RP-Initiated Logout: revoke the refresh token
566
- * (best-effort), clear local state, then redirect to the end_session
567
- * endpoint with `id_token_hint` + `post_logout_redirect_uri`.
540
+ * Cancel the response-vault interactive login owned by the current browser
541
+ * generation without ending an established session or navigating to the
542
+ * issuer. Resolves only after exact server rejection and local custody
543
+ * release. Unsupported auth modes and initialized/session states reject.
544
+ */
545
+ cancelLogin(): Promise<void>;
546
+ /**
547
+ * Persist durable signed-out authority, clear local state, attempt refresh
548
+ * revocation, then redirect to the end_session endpoint with a one-use
549
+ * callback state. Any observable teardown or navigation failure rejects
550
+ * while the tombstone continues to suppress silent restoration.
568
551
  */
569
552
  logout(): Promise<void>;
570
553
  /**
@@ -582,15 +565,16 @@ interface AtolBrowserAuth {
582
565
  /** Whether DPoP is active (enabled AND WebCrypto produced a key manager). */
583
566
  isDPoPActive(): boolean;
584
567
  /**
585
- * Subscribe to session changes (login, logout, renewal, cross-tab
586
- * rotation). The callback fires immediately with the current session, and
568
+ * Subscribe to session changes (login, logout, renewal, organization
569
+ * selection, or a cross-tab lifecycle signal). The callback fires
570
+ * immediately with the current session, and
587
571
  * again on every subsequent change. Returns an unsubscribe function.
588
572
  */
589
573
  onSessionChange(cb: (session: AtolSession) => void): () => void;
590
574
  /**
591
575
  * TEST ONLY. Establish an authenticated session directly from a raw token
592
576
  * response, bypassing the OIDC redirect/callback and all signature, state,
593
- * and nonce checks. Throws unless the client was created with
577
+ * nonce, and DPoP-binding checks. Throws unless the client was created with
594
578
  * `allowTestSessions: true` (see {@link AtolBrowserAuthConfig.allowTestSessions}).
595
579
  *
596
580
  * The tokens are adopted through the same path a real login/renewal uses:
@@ -604,15 +588,20 @@ interface AtolBrowserAuth {
604
588
  * still validated server-side by your API.
605
589
  */
606
590
  seedTestSession(tokens: TokenResponse): Promise<AtolSession>;
607
- /** Tear down timers, the broadcast channel, and subscriptions. */
591
+ /**
592
+ * Tear down timers, the broadcast channel, and subscriptions. A failed
593
+ * browser-resource close throws `AtolBrowserAuthCleanupError`; call again
594
+ * to retry only the retained cleanup ownership.
595
+ */
608
596
  destroy(): void;
609
597
  }
610
- /**
611
- * Create a framework-agnostic Atol browser auth client. See
612
- * {@link AtolBrowserAuthConfig} for options. Call {@link AtolBrowserAuth.init}
613
- * once at startup.
614
- */
615
- declare function createAtolBrowserAuth(config: AtolBrowserAuthConfig): AtolBrowserAuth;
598
+
599
+ interface CredentialGenerationSnapshot {
600
+ logout: string;
601
+ tabOwner: string;
602
+ }
603
+
604
+ declare const RESPONSE_VAULT_PROTOCOL_VERSION: 1;
616
605
 
617
606
  /**
618
607
  * Parse Atol custom claims from a JWT token (ID token or access token).
@@ -633,14 +622,8 @@ declare function getTokenExpiry(token: string): number | null;
633
622
  /**
634
623
  * JWT signature verification against the IdP's JWKS.
635
624
  *
636
- * Used to authenticate tokens that arrive over an UNTRUSTED in-browser
637
- * channel -- specifically the cross-tab `BroadcastChannel` (see the
638
- * browser auth client). BroadcastChannel is same-origin but not
639
- * same-trust: any script running on the origin (a third-party widget, an
640
- * XSS payload) can post to a channel whose name is derivable from the
641
- * public `authority` + `clientId`. Without verification a follower tab
642
- * would adopt attacker-supplied tokens and rebuild its identity from a
643
- * forged ID token.
625
+ * Used before an ID token from a callback or silent token exchange enters
626
+ * live session state. Cross-tab messages carry no tokens.
644
627
  *
645
628
  * Verification is delegated to `jose` (RFC 7515/7517/7519). The JWKS is
646
629
  * fetched from the issuer's discovery document and cached with rotation
@@ -648,7 +631,8 @@ declare function getTokenExpiry(token: string): number | null;
648
631
  */
649
632
 
650
633
  /**
651
- * Verify an ID token's signature, issuer, and audience against the IdP.
634
+ * Verify an ID token's signature, issuer, audience, required OIDC claims,
635
+ * and (when supplied) callback nonce against the IdP.
652
636
  * Resolves to the verified claims, or rejects when the token is forged,
653
637
  * expired, for a different issuer/audience, or carries no `sub`.
654
638
  *
@@ -658,10 +642,29 @@ declare function getTokenExpiry(token: string): number | null;
658
642
  declare function verifyIdToken(idToken: string, opts: {
659
643
  authority: string;
660
644
  clientId: string;
645
+ nonce?: string;
646
+ }): Promise<JWTPayload>;
647
+ /**
648
+ * Verify an Atol JWT access token before any proof-binding, subject, or
649
+ * organization claim is trusted. The audience is the protected resource,
650
+ * not the OIDC client id used for an ID token.
651
+ */
652
+ declare function verifyAccessToken(accessToken: string, opts: {
653
+ authority: string;
654
+ audience: string;
661
655
  }): Promise<JWTPayload>;
662
656
  /** Test-only: drop the discovery cache so a test can re-stub the IdP. */
663
657
  declare function _resetDiscoveryCache(): void;
664
658
 
659
+ /** Parsed, state-validated redirect result before the token exchange. */
660
+ interface AuthorizationCodeCallback {
661
+ code: string;
662
+ codeVerifier: string;
663
+ redirectUri: string;
664
+ nonce: string;
665
+ returnTo?: string;
666
+ credentialGeneration?: CredentialGenerationSnapshot;
667
+ }
665
668
  /**
666
669
  * Create an oidc-client-ts UserManager configured for Atol.
667
670
  *
@@ -678,6 +681,12 @@ declare function _resetDiscoveryCache(): void;
678
681
  * after the code exchange completes.
679
682
  */
680
683
  declare function createUserManager(authority: string, clientId: string, redirectUri: string, scope: string, audience?: string): UserManager;
684
+ /**
685
+ * Read a redirect callback without letting oidc-client-ts exchange the code.
686
+ * The matching state remains present until the caller definitively settles
687
+ * its code exchange.
688
+ */
689
+ declare function readAuthorizationCodeCallback(manager: UserManager, url: string): Promise<AuthorizationCodeCallback>;
681
690
  /** Extract the access token from an oidc-client-ts User. */
682
691
  declare function getAccessToken(user: User | null): string | undefined;
683
692
  /** Extract the ID token from an oidc-client-ts User. */
@@ -725,43 +734,30 @@ declare function withTabLock<T>(name: string, ms: number, fn: () => Promise<T>):
725
734
  declare function hasTabLockSupport(): boolean;
726
735
 
727
736
  /**
728
- * Cross-tab token rotation broadcast.
729
- *
730
- * When the leader tab rotates tokens, it publishes the new access/id/refresh
731
- * tokens to a shared `BroadcastChannel`. Follower tabs subscribe to the
732
- * channel and apply the rotated tokens without running their own renewal,
733
- * so concurrent open tabs collapse to a single /auth/token POST per cycle.
737
+ * Cross-tab credential lifecycle signals.
734
738
  *
735
- * Refresh tokens are deliberately broadcast because the server rotates them
736
- * on every use (RFC 6749 §10.4). A follower whose refresh token is stale
737
- * will hit `invalid_grant` on its next renew -- which, under the server's
738
- * refresh-token reuse detection, invalidates the whole family and signs every
739
- * tab out. Sharing
740
- * the rotated value prevents that chain reaction.
739
+ * Proof-bound tokens are tab-local because every tab owns a different DPoP
740
+ * key. The channel therefore carries signals only. A receiving tab renews
741
+ * with its own key and grant; it never adopts credential material minted for
742
+ * another tab.
741
743
  *
742
744
  * The channel stays same-origin by construction. If `BroadcastChannel` is
743
745
  * unavailable (old Safari, some sandboxed iframes), the helper degrades to
744
746
  * a no-op: publish swallows, subscribe never fires. That's a graceful
745
747
  * regression to per-tab behavior, not a failure.
746
748
  */
747
- interface TokenRotatedMessage {
748
- type: "token-rotated";
749
- /** Access token sent as the Authorization header; always present. */
750
- accessToken: string;
751
- /** ID token if one was issued on this grant. */
752
- idToken?: string;
753
- /** Rotated refresh token if the server returned one. */
754
- refreshToken?: string;
755
- /** ms-since-epoch at which the access token expires; followers compute their own timers off this. */
756
- expiresAt: number;
757
- /** ms-since-epoch when the message was sent. Lets followers discard stale broadcasts. */
749
+ interface CredentialsInvalidatedMessage {
750
+ type: "credentials-invalidated";
751
+ /** ms-since-epoch when the message was sent. */
758
752
  sentAt: number;
759
753
  }
760
- interface SessionExpiredMessage {
761
- type: "session-expired";
754
+ interface SessionEndedMessage {
755
+ type: "session-ended";
762
756
  sentAt: number;
757
+ /** Origin-wide logout generation resulting from the sender's invalidation. */
758
+ logoutGeneration: string;
763
759
  }
764
- type BroadcastMessage = TokenRotatedMessage | SessionExpiredMessage;
760
+ type BroadcastMessage = CredentialsInvalidatedMessage | SessionEndedMessage;
765
761
  interface TokenBroadcast {
766
762
  publish(message: BroadcastMessage): void;
767
763
  subscribe(handler: (message: BroadcastMessage) => void): () => void;
@@ -926,4 +922,4 @@ declare function stringToBase64Url(input: string): string;
926
922
  */
927
923
  declare function base64ToBytes(b64: string): Uint8Array;
928
924
 
929
- export { type AtolBrowserAuth, type AtolBrowserAuthConfig, type AtolSession, type AtolUser, type BeginLoginOptions, type BroadcastMessage, DEFAULT_AUTHORIZE_TIMEOUT_MS, DEFAULT_SILENT_RENEW_RETRY_COUNT, type DPoPConfig, type DPoPKeyManager, type DPoPProofOptions, type DPoPProofResult, type DPoPSigner, type GetAccessTokenOptions, KEKVault, type LoadPermissionsOptions, LoginRequiredError, NetworkError, OAuthProtocolError, type PermissionCheck, type PermissionResult, RecoveryAction, type SessionExpiredMessage, type StepUpOptions, type TokenBroadcast, type TokenResponse, type TokenRotatedMessage, _resetDiscoveryCache, backoffDelay, base64ToBytes, bytesToBase64Url, classifyRenewalError, createAtolBrowserAuth, createDPoPKeyManager, createTokenBroadcast, createUserManager, decodeJWTPayload, exchangeCode, extractKEKFromFragment, getAccessToken, getIdToken, getTokenExpiry, hasBroadcastSupport, hasTabLockSupport, kekBase64ToBytes, loadPermissions, parseAtolUser, permissionKey, refreshTokenGrant, revokeToken, silentAuthorize, silentAuthorizeWithRetry, stringToBase64Url, unwrapDEK, userFromTokenResponse, verifyIdToken, withTabLock };
925
+ export { type AtolBrowserAuth, AtolBrowserAuthCleanupError, type AtolBrowserAuthConfig, type AtolSession, type AtolUser, type AuthorizationCodeCallback, AuthorizationCodeExchangeUncertainError, type BeginLoginOptions, type BroadcastMessage, type CredentialsInvalidatedMessage, DEFAULT_AUTHORIZE_TIMEOUT_MS, DEFAULT_SILENT_RENEW_RETRY_COUNT, type DPoPConfig, type DPoPKeyManager, type DPoPProofOptions, type DPoPProofResult, type DPoPSigner, type GetAccessTokenOptions, KEKVault, type LoadPermissionsOptions, LoginRequiredError, NetworkError, OAuthProtocolError, type PermissionCheck, type PermissionResult, RESPONSE_VAULT_PROTOCOL_VERSION, RecoveryAction, type SessionEndedMessage, type StepUpOptions, type TokenBroadcast, type TokenResponse, _resetDiscoveryCache, backoffDelay, base64ToBytes, bytesToBase64Url, classifyRenewalError, createAtolBrowserAuth, createDPoPKeyManager, createTokenBroadcast, createUserManager, decodeJWTPayload, exchangeCode, extractKEKFromFragment, getAccessToken, getIdToken, getTokenExpiry, hasBroadcastSupport, hasTabLockSupport, kekBase64ToBytes, loadPermissions, parseAtolUser, permissionKey, readAuthorizationCodeCallback, refreshTokenGrant, revokeToken, stringToBase64Url, unwrapDEK, userFromTokenResponse, verifyAccessToken, verifyIdToken, withTabLock };