@atol-sh/js 0.1.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,877 @@
1
+ import { JWTPayload } from 'jose';
2
+ import { UserManager, User } from 'oidc-client-ts';
3
+
4
+ /**
5
+ * Framework-agnostic shared types for the Atol browser security core.
6
+ *
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.
11
+ */
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
+ /** Organization ID (atol:org_id claim). */
23
+ orgId: string;
24
+ /** Organization's subscription plan (atol:plan claim). */
25
+ plan: string;
26
+ /** User's roles within the organization (atol:roles claim). */
27
+ roles: string[];
28
+ /** How the user authenticated (atol:auth_method claim). */
29
+ authMethod: string;
30
+ /** Whether multi-factor auth was completed (atol:mfa_verified claim). */
31
+ mfaVerified: boolean;
32
+ }
33
+ /** A permission check to evaluate. */
34
+ interface PermissionCheck {
35
+ /** Action to check (e.g. "edit", "view", "manage"). */
36
+ action: string;
37
+ /** Resource to check against (e.g. "publication", "team:team-123"). */
38
+ resource: string;
39
+ }
40
+ /** Result of a permission check. */
41
+ interface PermissionResult {
42
+ action: string;
43
+ resource: string;
44
+ allowed: boolean;
45
+ }
46
+ /**
47
+ * Result of `signDPoPProof` / a DPoP-aware token accessor: the current
48
+ * access token plus, when DPoP is active, a matching resource-server
49
+ * proof JWT.
50
+ */
51
+ interface DPoPProofResult {
52
+ /** The current (freshly-renewed) access token. */
53
+ token: string;
54
+ /**
55
+ * A DPoP proof JWT (RFC 9449) for the requested (method, url), bound to
56
+ * `token` via its `ath` claim. Undefined when DPoP is not active
57
+ * (`useDPoP` off or WebCrypto unavailable) -- the caller then presents
58
+ * `token` as a plain `Authorization: Bearer` credential.
59
+ */
60
+ proof?: string;
61
+ }
62
+
63
+ /**
64
+ * createAtolBrowserAuth: the config-driven browser auth client.
65
+ *
66
+ * This is the keystone of @atol-sh/js. It wraps oidc-client-ts with the
67
+ * proven Atol logic that previously lived only inside the React provider:
68
+ * PKCE authorization-code login, in-memory token storage, DPoP-aware token
69
+ * access, proactive + on-demand silent renewal with single-flight
70
+ * coordination, cross-tab rotation broadcast (authenticated via JWKS), and
71
+ * RP-initiated logout with refresh-token revocation.
72
+ *
73
+ * Framework bindings (React, Vue, ...) become thin wrappers over this: they
74
+ * subscribe with `onSessionChange` and render, delegating every credential
75
+ * decision here.
76
+ *
77
+ * Storage policy: tokens are MEMORY-ONLY. The oidc-client-ts user store is
78
+ * `InMemoryWebStorage`; sessionStorage holds only the OIDC state/PKCE
79
+ * verifier needed to survive the login redirect. A page reload starts with
80
+ * an empty store, and the client recovers via a silent renew against the
81
+ * IdP session cookie.
82
+ */
83
+
84
+ /** DPoP configuration: a boolean toggle or an object with `required`. */
85
+ type DPoPConfig = boolean | {
86
+ required?: boolean;
87
+ };
88
+ /** Configuration for {@link createAtolBrowserAuth}. */
89
+ interface AtolBrowserAuthConfig {
90
+ /** OIDC issuer URL (e.g. https://auth.atol.sh). */
91
+ issuer: string;
92
+ /** Publishable OIDC client id / key id (atol_kid_...). Safe for the browser. */
93
+ clientId: string;
94
+ /** API audience identifier. Optional. */
95
+ audience?: string;
96
+ /** OIDC scopes. Default: "openid profile email". */
97
+ scopes?: string;
98
+ /** URL to redirect to after login (and after logout). */
99
+ redirectUri: string;
100
+ /**
101
+ * Request DPoP-bound tokens (RFC 9449). `true` (or `{ required: true }`)
102
+ * generates a per-tab non-exportable ES256 keypair on init and attaches a
103
+ * proof to every token-endpoint call. `false` (default) uses Bearer.
104
+ */
105
+ dpop?: DPoPConfig;
106
+ /**
107
+ * Silent renewal strategy. Default (false): hidden-iframe silent
108
+ * authentication against the IdP session cookie (prompt=none) - no
109
+ * refresh token is requested or stored. The iframe path
110
+ * relies on the IdP session cookie being sent from a third-party context,
111
+ * which Safari ITP blocks and Chrome's third-party-cookie phase-out
112
+ * removes, so it fails UNCONDITIONALLY for a cross-site app (one served on
113
+ * a different registrable domain than the IdP). Cross-site apps MUST set
114
+ * this true: it requests offline_access and renews via the refresh-token
115
+ * grant (memory-only, rotated, DPoP-bound when dpop is on). Same-site apps
116
+ * (e.g. an admin console on a subdomain of the IdP) reach the first-party
117
+ * session cookie in the iframe and leave this false.
118
+ */
119
+ useRefreshTokens?: boolean;
120
+ /**
121
+ * When useRefreshTokens is true, fall back to the hidden-iframe silent
122
+ * authentication if a refresh-token grant fails transiently (network /
123
+ * transient server error), instead of only backing off. No effect when
124
+ * useRefreshTokens is false (iframe is already the path).
125
+ */
126
+ useRefreshTokensFallback?: boolean;
127
+ /**
128
+ * Request the zero-knowledge encryption-key claim. When true, the client
129
+ * appends `derive_encryption_key=true` to the login authorize request and
130
+ * to every silent (iframe) renew, so the issuer emits the
131
+ * `atol:wrapped_dek` claim on the ID token consistently across the
132
+ * session. The client itself does no crypto with the claim; a framework
133
+ * binding reads it from {@link AtolBrowserAuth.getIdToken} and derives the
134
+ * data-encryption key. Defaults to false.
135
+ */
136
+ deriveEncryptionKey?: boolean;
137
+ /**
138
+ * Token storage backend. Only `'memory'` is supported: tokens live in an
139
+ * in-memory oidc-client-ts store and are never written to Web Storage.
140
+ * Accepted as a config knob for forward-compat and to make the guarantee
141
+ * explicit at the call site.
142
+ */
143
+ storage?: 'memory';
144
+ }
145
+ /** The current auth session, delivered to `onSessionChange` subscribers. */
146
+ interface AtolSession {
147
+ /** Whether a user is currently authenticated. */
148
+ isAuthenticated: boolean;
149
+ /** The authenticated user, or null. */
150
+ user: AtolUser | null;
151
+ /**
152
+ * The unwrapped zero-knowledge data-encryption key (DEK), when
153
+ * `deriveEncryptionKey` is enabled and the KEK/wrapped-DEK derivation
154
+ * succeeded for the current session. `undefined` when the feature is off,
155
+ * when there is no session, or when derivation failed (see
156
+ * {@link AtolSession.encryptionError}). Framework bindings consume this
157
+ * instead of re-deriving the key themselves.
158
+ */
159
+ encryptionKey?: Uint8Array;
160
+ /**
161
+ * Non-`undefined` when `deriveEncryptionKey` is enabled but the expected
162
+ * DEK could not be unwrapped: a wrong KEK, a tampered wrapped-DEK
163
+ * (AES-GCM auth-tag failure), or a vault error. Surfaced so the app can
164
+ * deny encrypted operations instead of silently treating a failure as
165
+ * "encryption off" -- an auth-tag failure must never present as a
166
+ * silently-wrong key. Mutually exclusive with a present
167
+ * {@link AtolSession.encryptionKey}.
168
+ */
169
+ encryptionError?: Error;
170
+ }
171
+ /** Options for {@link AtolBrowserAuth.getAccessToken}. */
172
+ interface GetAccessTokenOptions {
173
+ /**
174
+ * When present, and DPoP is active, the returned result carries a proof
175
+ * JWT bound (via `ath`) to the returned access token for the given
176
+ * (method, url). When DPoP is inactive the proof is omitted.
177
+ */
178
+ dpop?: {
179
+ method: string;
180
+ url: string;
181
+ };
182
+ }
183
+ /** Options for {@link AtolBrowserAuth.beginLogin}. */
184
+ interface BeginLoginOptions {
185
+ /** Same-origin path to return to after login (overrides the redirect URI). */
186
+ returnTo?: string;
187
+ /**
188
+ * OIDC `prompt` value (e.g. `'login'` to force re-authentication, `'none'`
189
+ * for silent). Sent as an authorize-request parameter.
190
+ */
191
+ prompt?: string;
192
+ /**
193
+ * OIDC `max_age` (seconds): the maximum acceptable age of the End-User's
194
+ * authentication. `0` forces a fresh login.
195
+ */
196
+ maxAge?: number;
197
+ /** OIDC `acr_values`: requested authentication assurance level(s). */
198
+ acrValues?: string;
199
+ }
200
+ /** Options for {@link AtolBrowserAuth.stepUp}. */
201
+ interface StepUpOptions {
202
+ /** Same-origin path to return to after the step-up re-authentication. */
203
+ returnTo?: string;
204
+ /**
205
+ * OIDC `max_age` (seconds). Defaults to `0` (force a brand-new login). Set a
206
+ * small positive value to accept a very recent existing authentication.
207
+ */
208
+ maxAge?: number;
209
+ /** OIDC `acr_values`. Defaults to `'mfa'`. */
210
+ acrValues?: string;
211
+ }
212
+ /** The browser auth client returned by {@link createAtolBrowserAuth}. */
213
+ interface AtolBrowserAuth {
214
+ /**
215
+ * Initialize the client: install the DPoP key (if enabled), wire the
216
+ * cross-tab broadcast, and attempt to restore a session (handling a
217
+ * redirect callback if the current URL is one). Idempotent; safe to call
218
+ * once at startup. Resolves once the initial session state is settled.
219
+ */
220
+ init(): Promise<AtolSession>;
221
+ /**
222
+ * Begin an authorization-code + PKCE login by redirecting the browser to
223
+ * the Atol authorize endpoint. `returnTo` (a same-origin path) overrides
224
+ * the post-login redirect target for this call. `prompt` / `maxAge` /
225
+ * `acrValues` are forwarded as OIDC authorize-request parameters (used by
226
+ * {@link AtolBrowserAuth.stepUp} to force re-authentication).
227
+ */
228
+ beginLogin(options?: BeginLoginOptions): Promise<void>;
229
+ /**
230
+ * Force a step-up re-authentication: redirect to the authorize endpoint with
231
+ * `prompt=login` + `max_age=0` (and `acr_values=mfa` by default) so the
232
+ * issuer mints a token with a fresh `auth_time` and a completed second
233
+ * factor. Use this when a sensitive management operation returns a
234
+ * "step_up_required" challenge; after the redirect completes, retry the
235
+ * operation. Overridable via {@link StepUpOptions}.
236
+ */
237
+ stepUp(options?: StepUpOptions): Promise<void>;
238
+ /**
239
+ * Complete a login redirect: exchange the authorization code for tokens,
240
+ * verify the ID token, and establish the session. Call on the redirect
241
+ * URI page. A no-op returning the current session when the URL is not a
242
+ * callback. `init()` calls this automatically.
243
+ */
244
+ completeLogin(): Promise<AtolSession>;
245
+ /**
246
+ * Return the current access token, renewing it when it is inside the 60s
247
+ * expiry window. With `opts.dpop` and DPoP active, also returns a bound
248
+ * proof. Resolves to `undefined` when there is no session.
249
+ */
250
+ getAccessToken(opts?: GetAccessTokenOptions): Promise<{
251
+ token: string;
252
+ proof?: string;
253
+ } | undefined>;
254
+ /**
255
+ * The current raw ID token (the JWT), or `undefined` when there is no
256
+ * session. Exposed so framework bindings can read issuer-specific ID
257
+ * token claims the parsed {@link AtolUser} does not carry (e.g. an
258
+ * app-specific encryption-key claim) without re-implementing token
259
+ * storage. Read-only; the client owns renewal and rotation.
260
+ */
261
+ getIdToken(): string | undefined;
262
+ /**
263
+ * The current unwrapped zero-knowledge data-encryption key (DEK), or
264
+ * `undefined`. Only ever non-`undefined` when `deriveEncryptionKey` is
265
+ * enabled and derivation succeeded for the active session. Framework
266
+ * bindings read this (or the {@link AtolSession.encryptionKey} field on
267
+ * the session-change payload) instead of re-deriving the key. The
268
+ * returned array is the client's live buffer; do not mutate it.
269
+ */
270
+ getEncryptionKey(): Uint8Array | undefined;
271
+ /**
272
+ * The last zero-knowledge key-derivation error, or `undefined`. Set when
273
+ * `deriveEncryptionKey` is enabled but the DEK could not be unwrapped
274
+ * (wrong KEK, tampered wrapped-DEK auth-tag failure, or vault error), so
275
+ * the caller can fail loud rather than treat a tamper as "encryption
276
+ * off". Cleared on the next successful derivation and on logout/destroy.
277
+ */
278
+ getEncryptionError(): Error | undefined;
279
+ /**
280
+ * Sign out via OIDC RP-Initiated Logout: revoke the refresh token
281
+ * (best-effort), clear local state, then redirect to the end_session
282
+ * endpoint with `id_token_hint` + `post_logout_redirect_uri`.
283
+ */
284
+ logout(): Promise<void>;
285
+ /**
286
+ * Force an immediate silent renew, bypassing the freshness check.
287
+ * Resolves to the new access token, or undefined on failure.
288
+ */
289
+ forceRenew(): Promise<string | undefined>;
290
+ /**
291
+ * Sign a DPoP resource-server proof (RFC 9449 §7) for a request to your
292
+ * own protected resource. Fetches a fresh token first so `ath` binds to
293
+ * the token actually presented. Resolves undefined when there is no
294
+ * session; `proof` is undefined when DPoP is inactive.
295
+ */
296
+ signDPoPProof(method: string, url: string): Promise<DPoPProofResult | undefined>;
297
+ /** Whether DPoP is active (enabled AND WebCrypto produced a key manager). */
298
+ isDPoPActive(): boolean;
299
+ /**
300
+ * Subscribe to session changes (login, logout, renewal, cross-tab
301
+ * rotation). The callback fires immediately with the current session, and
302
+ * again on every subsequent change. Returns an unsubscribe function.
303
+ */
304
+ onSessionChange(cb: (session: AtolSession) => void): () => void;
305
+ /** Tear down timers, the broadcast channel, and subscriptions. */
306
+ destroy(): void;
307
+ }
308
+ /**
309
+ * Create a framework-agnostic Atol browser auth client. See
310
+ * {@link AtolBrowserAuthConfig} for options. Call {@link AtolBrowserAuth.init}
311
+ * once at startup.
312
+ */
313
+ declare function createAtolBrowserAuth(config: AtolBrowserAuthConfig): AtolBrowserAuth;
314
+
315
+ /**
316
+ * Parse Atol custom claims from a JWT token (ID token or access token).
317
+ * Decodes the payload without verifying the signature — verification is
318
+ * done by the OIDC library. This just extracts the user-facing fields.
319
+ */
320
+ declare function parseAtolUser(token: string): AtolUser;
321
+ /** Decode a JWT payload (the middle base64url segment) to a plain object. */
322
+ declare function decodeJWTPayload(token: string): Record<string, unknown>;
323
+ /**
324
+ * Parse the `exp` claim from a JWT without verifying the signature.
325
+ * Returns the absolute expiry in milliseconds, or null when the token is
326
+ * malformed or carries no numeric `exp`. Single source of truth for all
327
+ * expiry math in the SDK (renew scheduling, stale checks, broadcasts).
328
+ */
329
+ declare function getTokenExpiry(token: string): number | null;
330
+
331
+ /**
332
+ * DPoP (RFC 9449) client implementation.
333
+ *
334
+ * This module owns the per-tab ES256 keypair used for sender-constrained
335
+ * tokens, plus the proof-JWT builder that clients send on every
336
+ * /auth/token call (and, in future, on every resource-server request).
337
+ *
338
+ * Design choices:
339
+ * - Keys are non-exportable CryptoKey objects (`extractable: false`).
340
+ * XSS can use them to sign but cannot exfiltrate the private bytes.
341
+ * - Keys are regenerated per-tab on provider mount. A page reload ==
342
+ * a new keypair. The cost is one extra round-trip after reload;
343
+ * the benefit is no persistence surface for key material at all.
344
+ * - ES256 / P-256 only. Universal WebCrypto support, matches what the
345
+ * server's DPoP validator accepts first.
346
+ *
347
+ * The module is a no-op fallback when WebCrypto is unavailable (SSR,
348
+ * extremely old browsers). Callers treat a null manager as "Bearer mode".
349
+ */
350
+ /** Optional per-proof inputs (RFC 9449 resource access + server nonce). */
351
+ interface DPoPProofOptions {
352
+ /**
353
+ * Access token being presented. When set, the proof carries an `ath`
354
+ * claim (base64url(SHA-256(accessToken))) binding the proof to that
355
+ * token, as required for DPoP-authenticated resource-server requests
356
+ * (RFC 9449 §4.3 / §7). Omit at the token endpoint.
357
+ */
358
+ accessToken?: string;
359
+ /**
360
+ * Server-issued nonce (RFC 9449 §8). When the AS/RS rejects a proof
361
+ * with `use_dpop_nonce` + a `DPoP-Nonce` header, re-sign with that
362
+ * nonce and retry.
363
+ */
364
+ nonce?: string;
365
+ }
366
+ interface DPoPKeyManager {
367
+ /** Sign a proof for a specific (method, url) pair, plus optional ath/nonce. */
368
+ signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>;
369
+ /** Public JWK -- used by the server to compute `cnf.jkt`. */
370
+ publicJWK(): Promise<JsonWebKey>;
371
+ }
372
+ /**
373
+ * Create a per-tab DPoP key manager. Returns null when WebCrypto is not
374
+ * available -- the caller should fall back to Bearer mode silently.
375
+ */
376
+ declare function createDPoPKeyManager(): Promise<DPoPKeyManager | null>;
377
+
378
+ /**
379
+ * JWT signature verification against the IdP's JWKS.
380
+ *
381
+ * Used to authenticate tokens that arrive over an UNTRUSTED in-browser
382
+ * channel -- specifically the cross-tab `BroadcastChannel` (see the
383
+ * browser auth client). BroadcastChannel is same-origin but not
384
+ * same-trust: any script running on the origin (a third-party widget, an
385
+ * XSS payload) can post to a channel whose name is derivable from the
386
+ * public `authority` + `clientId`. Without verification a follower tab
387
+ * would adopt attacker-supplied tokens and rebuild its identity from a
388
+ * forged ID token.
389
+ *
390
+ * Verification is delegated to `jose` (RFC 7515/7517/7519). The JWKS is
391
+ * fetched from the issuer's discovery document and cached with rotation
392
+ * handling by `createRemoteJWKSet`.
393
+ */
394
+
395
+ /**
396
+ * Verify an ID token's signature, issuer, and audience against the IdP.
397
+ * Resolves to the verified claims, or rejects when the token is forged,
398
+ * expired, for a different issuer/audience, or carries no `sub`.
399
+ *
400
+ * `audience` is the OIDC `client_id` (the publishable key ID): an ID
401
+ * token's `aud` is always the client it was issued for.
402
+ */
403
+ declare function verifyIdToken(idToken: string, opts: {
404
+ authority: string;
405
+ clientId: string;
406
+ }): Promise<JWTPayload>;
407
+ /** Test-only: drop the discovery cache so a test can re-stub the IdP. */
408
+ declare function _resetDiscoveryCache(): void;
409
+
410
+ /**
411
+ * Token renewal error classification.
412
+ *
413
+ * The provider's `renewOnce` has three possible reactions to a failed
414
+ * renewal: retry (transient), force re-auth (terminal auth failure,
415
+ * local state is out of sync with the server), or surface (programmer
416
+ * error the caller should see). Spreading those decisions across every
417
+ * catch block drifts; centralizing them here keeps the contract auditable.
418
+ *
419
+ * The classification is deliberately conservative: anything we don't
420
+ * recognize surfaces, rather than silently forcing re-auth or looping.
421
+ */
422
+ /**
423
+ * OAuth 2.0 / OIDC protocol error surfaced by the authorization server.
424
+ * Carries the machine-readable `error` code from the token / authorize
425
+ * endpoint response so the recovery layer can act on it precisely.
426
+ */
427
+ declare class OAuthProtocolError extends Error {
428
+ code: string;
429
+ description?: string;
430
+ constructor(code: string, description?: string);
431
+ }
432
+ /**
433
+ * Re-auth-class protocol errors -- login_required, consent_required,
434
+ * interaction_required. Subclass of OAuthProtocolError so existing
435
+ * `instanceof LoginRequiredError` checks keep working AND `instanceof
436
+ * OAuthProtocolError` matches the broader classification.
437
+ */
438
+ declare class LoginRequiredError extends OAuthProtocolError {
439
+ constructor(description?: string);
440
+ }
441
+ /**
442
+ * Transport / network layer failure -- `fetch` rejected, DNS miss, TLS
443
+ * error, CORS block. Surfaced as retry because the authorization server
444
+ * never saw the request.
445
+ */
446
+ declare class NetworkError extends Error {
447
+ cause?: unknown;
448
+ constructor(message: string, cause?: unknown);
449
+ }
450
+ /**
451
+ * What the caller should do when a renewal throws.
452
+ *
453
+ * Retry -- transient (network blip, 5xx). Backoff and try again.
454
+ * ForceReauth -- terminal (stale refresh token, revoked client, session
455
+ * gone). Wipe local state and return the user to the
456
+ * signed-out screen. Don't loop.
457
+ * Surface -- programmer error (invalid_scope, unsupported_grant_type).
458
+ * Throw to the caller so they can see it during dev.
459
+ */
460
+ declare enum RecoveryAction {
461
+ Retry = "retry",
462
+ ForceReauth = "force_reauth",
463
+ Surface = "surface"
464
+ }
465
+ /**
466
+ * Classify a renewal error into a recovery action. The full mapping,
467
+ * grouped by cause:
468
+ *
469
+ * Terminal auth (ForceReauth):
470
+ * invalid_grant refresh token expired / revoked / rotated-reused
471
+ * invalid_request stale or malformed token at /auth/token
472
+ * (also what the server returns after a lost HMAC secret)
473
+ * invalid_client client was deleted / secret changed server-side
474
+ * unauthorized_client client no longer permitted this grant
475
+ * login_required prompt=none could not silently re-auth
476
+ * consent_required user consent missing
477
+ * interaction_required user action required
478
+ *
479
+ * Transient (Retry):
480
+ * server_error 500-class error on the authz server
481
+ * temporarily_unavailable documented OAuth retry signal
482
+ * NetworkError fetch rejection, DNS, TLS, CORS
483
+ *
484
+ * Programmer error (Surface):
485
+ * invalid_scope misconfigured scope list
486
+ * unsupported_grant_type wrong grant wiring
487
+ * unsupported_response_type
488
+ * Unknown OAuth codes -- conservative default
489
+ * Unknown Error subclass -- ditto
490
+ */
491
+ declare function classifyRenewalError(err: unknown): RecoveryAction;
492
+ /**
493
+ * Exponential backoff with full jitter. Cheap, deterministic test
494
+ * surface -- callers can swap out `Math.random` via the seed arg.
495
+ *
496
+ * attempt 0 -> [0, 500) ms
497
+ * attempt 1 -> [0, 1000) ms
498
+ * attempt 2 -> [0, 2000) ms
499
+ * attempt 3 -> [0, 4000) ms
500
+ * attempt N -> [0, 30_000) ms (capped)
501
+ *
502
+ * The cap matters: without it an always-failing transient error fires a
503
+ * renewal an hour later and the user thinks the app is frozen.
504
+ */
505
+ declare function backoffDelay(attempt: number, rand?: () => number): number;
506
+
507
+ /**
508
+ * Silent token renewal via web_message response mode.
509
+ *
510
+ * Opens a hidden iframe to the authorization endpoint with response_mode=web_message
511
+ * and prompt=none. The server validates the session cookie and returns an HTML page
512
+ * that sends the authorization response via postMessage. No SPA loading in the iframe.
513
+ *
514
+ * Spec: draft-sakimura-oauth-wmrm-01
515
+ */
516
+
517
+ interface SilentRenewOptions {
518
+ authority: string;
519
+ clientId: string;
520
+ redirectUri: string;
521
+ scope: string;
522
+ audience?: string;
523
+ /**
524
+ * When true, asks the server to include `atol:wrapped_dek` on the renewed
525
+ * ID token. The KEK is NOT re-delivered (the password isn't available
526
+ * during silent renew), but carrying the wrapped DEK claim keeps it
527
+ * consistently present across every token in the session, so app code
528
+ * that re-reads it after a renewal (tab rehydrate, multi-tab sync) finds
529
+ * the same DEK material it saw at login.
530
+ */
531
+ deriveEncryptionKey?: boolean;
532
+ /**
533
+ * Milliseconds to wait for the iframe's postMessage before rejecting.
534
+ * Defaults to 60s. An earlier 10s value was too tight on
535
+ * slow networks and caused the "return stale token" fallback to fire
536
+ * unnecessarily, producing `token is expired (exp)` errors on the server.
537
+ */
538
+ timeoutMs?: number;
539
+ }
540
+ /** Default iframe timeout for silent authorization. */
541
+ declare const DEFAULT_AUTHORIZE_TIMEOUT_MS = 60000;
542
+ /** Default retry count for silent authorize on transient errors. */
543
+ declare const DEFAULT_SILENT_RENEW_RETRY_COUNT = 3;
544
+ /**
545
+ * Perform a silent authorization request via web_message.
546
+ * Returns the authorization code + state, or throws on error.
547
+ */
548
+ declare function silentAuthorize(opts: SilentRenewOptions): Promise<{
549
+ code: string;
550
+ state: string;
551
+ codeVerifier: string;
552
+ }>;
553
+ /**
554
+ * silentAuthorize with bounded retry on transient errors (default 3
555
+ * attempts). `login_required` and similar
556
+ * re-auth errors are fatal and bypass the retry loop.
557
+ */
558
+ declare function silentAuthorizeWithRetry(opts: SilentRenewOptions, retries?: number): Promise<{
559
+ code: string;
560
+ state: string;
561
+ codeVerifier: string;
562
+ }>;
563
+ /** Shape of a successful /auth/token response. */
564
+ interface TokenResponse {
565
+ access_token: string;
566
+ id_token?: string;
567
+ refresh_token?: string;
568
+ token_type: string;
569
+ expires_in: number;
570
+ scope?: string;
571
+ }
572
+ /**
573
+ * Optional per-request DPoP signer. When provided, token-endpoint calls
574
+ * attach a signed proof header (RFC 9449). When omitted, calls run Bearer-
575
+ * only and the server issues un-bound tokens. The provider wires this
576
+ * through from its DPoPKeyManager when `useDPoP: true`.
577
+ */
578
+ interface DPoPSigner {
579
+ signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>;
580
+ }
581
+ /**
582
+ * Exchange an authorization code for tokens via the token endpoint.
583
+ */
584
+ declare function exchangeCode(authority: string, clientId: string, code: string, redirectUri: string, codeVerifier: string, dpop?: DPoPSigner): Promise<TokenResponse>;
585
+ /**
586
+ * Renew tokens using a refresh token grant (RFC 6749 §6). This is the
587
+ * `useRefreshTokens: true` path -- a direct POST to the token
588
+ * endpoint, no iframe, no cross-site cookies. Works under Chrome's third-
589
+ * party cookie phaseout, Safari ITP, and Firefox ETP without the user
590
+ * needing to grant Storage Access.
591
+ *
592
+ * The server may rotate the refresh token on each use (RFC 6749 §10.4);
593
+ * callers must read `refresh_token` from the response and replace their
594
+ * stored copy before the next renew.
595
+ *
596
+ * An expired or revoked refresh token surfaces as `LoginRequiredError` so
597
+ * the caller can force a re-auth, matching the semantics of the iframe
598
+ * path for login_required.
599
+ */
600
+ declare function refreshTokenGrant(authority: string, clientId: string, refreshToken: string, scope?: string, audience?: string, dpop?: DPoPSigner): Promise<TokenResponse>;
601
+ /**
602
+ * Revoke a token via the RFC 7009 revocation endpoint. Used on logout to
603
+ * proactively invalidate the refresh token server-side rather than waiting
604
+ * for it to expire. A best-effort call: revocation failures are surfaced
605
+ * to the caller, which typically swallows them (the RP-initiated logout
606
+ * still kills the session cookie).
607
+ *
608
+ * `tokenTypeHint` defaults to `refresh_token` -- the token most worth
609
+ * revoking, since it can mint new access tokens.
610
+ */
611
+ declare function revokeToken(authority: string, clientId: string, token: string, tokenTypeHint?: 'refresh_token' | 'access_token'): Promise<void>;
612
+
613
+ /**
614
+ * Create an oidc-client-ts UserManager configured for Atol.
615
+ *
616
+ * Storage policy:
617
+ * - `userStore` is IN-MEMORY. The full User object (access token, ID
618
+ * token, and -- when `useRefreshTokens` is on -- the refresh token)
619
+ * never touches sessionStorage or localStorage, so an XSS payload
620
+ * cannot read persisted credentials after the fact. The cost is that
621
+ * a page reload starts with an empty store; the provider recovers by
622
+ * attempting a silent renew against the IdP session cookie.
623
+ * - `stateStore` stays in sessionStorage. It only holds the OIDC
624
+ * state/PKCE verifier, which must survive the same-tab redirect to
625
+ * the Atol login page and back, and is worthless to an attacker
626
+ * after the code exchange completes.
627
+ */
628
+ declare function createUserManager(authority: string, clientId: string, redirectUri: string, scope: string, audience?: string): UserManager;
629
+ /** Extract the access token from an oidc-client-ts User. */
630
+ declare function getAccessToken(user: User | null): string | undefined;
631
+ /** Extract the ID token from an oidc-client-ts User. */
632
+ declare function getIdToken(user: User | null): string | undefined;
633
+ /**
634
+ * Build an oidc-client-ts User from a raw /auth/token response. Used to
635
+ * write renewed tokens back into the UserManager store so `mgr.getUser()`
636
+ * and React state never disagree (e.g. a rotated-away refresh token
637
+ * lingering in the store).
638
+ *
639
+ * `expires_at` prefers the access token's own `exp` claim; falls back to
640
+ * `expires_in` relative to now when the token is opaque.
641
+ */
642
+ declare function userFromTokenResponse(tokens: TokenResponse): User;
643
+
644
+ /**
645
+ * Cross-tab mutual exclusion for renewal work.
646
+ *
647
+ * Uses the native Web Locks API (navigator.locks) for cross-tab mutual
648
+ * exclusion. A leader tab acquires the lock and runs the critical
649
+ * section; followers block until the leader releases, then re-enter the lock
650
+ * themselves (at which point they typically find the state the leader
651
+ * produced and short-circuit).
652
+ *
653
+ * In environments without `navigator.locks` (jsdom under vitest, old Safari,
654
+ * workers with no locks API) we fall through to running `fn` directly. That
655
+ * matches the existing intra-tab dedup semantics -- no regression, just no
656
+ * cross-tab guarantee.
657
+ */
658
+ /**
659
+ * Run `fn` under a cross-tab exclusive lock identified by `name`.
660
+ *
661
+ * The `ms` argument bounds the total wait time for acquiring the lock; if
662
+ * the leader stalls beyond this, we abort and fall through to running `fn`
663
+ * directly rather than deadlocking the caller. A 5s default -- leaders that
664
+ * stall longer are almost certainly broken, and a
665
+ * second POST to /auth/token is preferable to a forever-hung tab.
666
+ *
667
+ * The lock is per-origin (Web Locks is same-origin by construction), so the
668
+ * lock name should include the authority + clientId to avoid cross-tenant
669
+ * contention when multiple atol apps share an origin.
670
+ */
671
+ declare function withTabLock<T>(name: string, ms: number, fn: () => Promise<T>): Promise<T>;
672
+ /** Whether the current environment supports cross-tab locks. Useful for tests. */
673
+ declare function hasTabLockSupport(): boolean;
674
+
675
+ /**
676
+ * Cross-tab token rotation broadcast.
677
+ *
678
+ * When the leader tab rotates tokens, it publishes the new access/id/refresh
679
+ * tokens to a shared `BroadcastChannel`. Follower tabs subscribe to the
680
+ * channel and apply the rotated tokens without running their own renewal,
681
+ * so concurrent open tabs collapse to a single /auth/token POST per cycle.
682
+ *
683
+ * Refresh tokens are deliberately broadcast because the server rotates them
684
+ * on every use (RFC 6749 §10.4). A follower whose refresh token is stale
685
+ * will hit `invalid_grant` on its next renew -- which, under the server's
686
+ * refresh-token reuse detection, invalidates the whole family and signs every
687
+ * tab out. Sharing
688
+ * the rotated value prevents that chain reaction.
689
+ *
690
+ * The channel stays same-origin by construction. If `BroadcastChannel` is
691
+ * unavailable (old Safari, some sandboxed iframes), the helper degrades to
692
+ * a no-op: publish swallows, subscribe never fires. That's a graceful
693
+ * regression to per-tab behavior, not a failure.
694
+ */
695
+ interface TokenRotatedMessage {
696
+ type: "token-rotated";
697
+ /** Access token sent as the Authorization header; always present. */
698
+ accessToken: string;
699
+ /** ID token if one was issued on this grant. */
700
+ idToken?: string;
701
+ /** Rotated refresh token if the server returned one. */
702
+ refreshToken?: string;
703
+ /** ms-since-epoch at which the access token expires; followers compute their own timers off this. */
704
+ expiresAt: number;
705
+ /** ms-since-epoch when the message was sent. Lets followers discard stale broadcasts. */
706
+ sentAt: number;
707
+ }
708
+ interface SessionExpiredMessage {
709
+ type: "session-expired";
710
+ sentAt: number;
711
+ }
712
+ type BroadcastMessage = TokenRotatedMessage | SessionExpiredMessage;
713
+ interface TokenBroadcast {
714
+ publish(message: BroadcastMessage): void;
715
+ subscribe(handler: (message: BroadcastMessage) => void): () => void;
716
+ close(): void;
717
+ }
718
+ /**
719
+ * Create a token broadcast wrapper for the given channel name. Callers must
720
+ * invoke `close()` when the provider unmounts so the underlying channel
721
+ * stops holding a reference.
722
+ */
723
+ declare function createTokenBroadcast(name: string): TokenBroadcast;
724
+ /** Whether the current environment supports cross-tab broadcast. Useful for tests. */
725
+ declare function hasBroadcastSupport(): boolean;
726
+
727
+ /** Inputs for a bulk permission load. */
728
+ interface LoadPermissionsOptions {
729
+ /**
730
+ * Control-plane API base URL (e.g. https://api.atol.sh). This is the
731
+ * Connect-RPC host that serves AccessService -- NOT the OIDC issuer
732
+ * (`authority`), which only mints tokens. Mixing them up sends the
733
+ * authorization check to the wrong host.
734
+ */
735
+ apiUrl: string;
736
+ /** Publishable key ID (atol_kid_...). */
737
+ keyId: string;
738
+ /** Bearer access token for the call. */
739
+ accessToken: string;
740
+ /** Authenticated user's ID (JWT sub). */
741
+ userId: string;
742
+ /** Authenticated user's org ID. */
743
+ orgId: string;
744
+ /** Permission checks to evaluate. */
745
+ checks: PermissionCheck[];
746
+ /**
747
+ * Optional DPoP signer. When the access token is DPoP-bound (`cnf.jkt`),
748
+ * the resource server expects the `DPoP` auth scheme plus a proof whose
749
+ * `ath` claim hashes the access token (RFC 9449 §4.3). Without this a
750
+ * bound token is presented as plain Bearer and a strict server rejects
751
+ * it -- or, worse, the sender-constraint is silently lost on the most
752
+ * security-sensitive call in the SDK.
753
+ */
754
+ dpop?: DPoPSigner;
755
+ }
756
+ /**
757
+ * Bulk-load permissions from the Atol control plane.
758
+ * Uses the batch-check endpoint with the user's JWT + publishable key.
759
+ * Returns a Map keyed by "action:resource" -> boolean.
760
+ */
761
+ declare function loadPermissions(opts: LoadPermissionsOptions): Promise<Map<string, boolean>>;
762
+ /** Build the permission map key from action + resource. */
763
+ declare function permissionKey(action: string, resource: string): string;
764
+
765
+ /**
766
+ * KEKVault is stateless by design -- construction is cheap and every
767
+ * method opens its own IndexedDB transaction. That avoids holding long-
768
+ * lived handles and plays cleanly with tab unload / page hide.
769
+ */
770
+ declare class KEKVault {
771
+ /**
772
+ * Stash the KEK under a fresh device key, then unwrap the DEK and
773
+ * return its bytes. Call this on the first login-callback of a
774
+ * session, when the KEK arrived in the URL fragment.
775
+ *
776
+ * Overwrites any existing vault record (key rotation, password change,
777
+ * or user-switch on the same device all land here).
778
+ *
779
+ * `kekBytes` is zeroed after use. Callers should also drop their
780
+ * local reference.
781
+ */
782
+ provision(kekBytes: Uint8Array, wrappedDEKBase64: string): Promise<Uint8Array>;
783
+ /**
784
+ * Rehydrate the DEK from the vault on silent-auth or page reload.
785
+ * Returns null when there's no prior vault record -- caller falls
786
+ * back to `signinRedirect` with `prompt=login` to repopulate.
787
+ *
788
+ * Returns null (rather than throwing) for the missing-state case
789
+ * because it's a normal branch: new browser, cleared data, freshly
790
+ * installed device. Actual errors (corrupted record, auth-tag fail
791
+ * on the stored KEK) DO throw -- those indicate tampering or a bug
792
+ * and the caller should escalate.
793
+ */
794
+ rehydrate(wrappedDEKBase64: string): Promise<Uint8Array | null>;
795
+ /**
796
+ * Wipe the vault. Call from the logout path after `signoutRedirect`
797
+ * so the next visit to this origin won't silently rehydrate the
798
+ * previous user's DEK.
799
+ *
800
+ * Idempotent: a missing record is fine.
801
+ */
802
+ clear(): Promise<void>;
803
+ /**
804
+ * Non-destructive "does the vault have a record?" predicate. The
805
+ * provider uses this to decide whether a silent refresh can succeed
806
+ * or it needs to kick a `prompt=login`.
807
+ */
808
+ hasRecord(): Promise<boolean>;
809
+ }
810
+
811
+ /**
812
+ * Zero-knowledge encryption primitives.
813
+ *
814
+ * The KEK (Key Encryption Key) is delivered via URL fragment by the Atol
815
+ * authorize endpoint. The wrapped DEK (Data Encryption Key) arrives as
816
+ * an ID token claim. The client unwraps the DEK locally and hands the
817
+ * KEK to the vault (see `./kek-vault.ts`) so silent-auth refreshes can
818
+ * rehydrate the DEK without a password prompt.
819
+ *
820
+ * This module stays intentionally small: fragment parsing, byte
821
+ * conversion helpers, and the one-shot unwrap. DEK persistence is the
822
+ * vault's job, not this module's.
823
+ */
824
+ /**
825
+ * Extract the KEK from the URL fragment and clean up immediately.
826
+ * The fragment is set by the Atol authorize endpoint: `#atol_enc_key=base64(kek)`.
827
+ * Returns null when not present.
828
+ */
829
+ declare function extractKEKFromFragment(): string | null;
830
+ /**
831
+ * Decode a base64 / base64url string into raw bytes. Accepts either
832
+ * the "+/" standard alphabet or the "-_" URL-safe alphabet, with or
833
+ * without padding. The Atol authorize endpoint emits base64url without
834
+ * padding; older servers may emit padded base64.
835
+ *
836
+ * Thin alias over the shared decoder in `./base64url` -- kept exported
837
+ * under this name because it is part of the public API.
838
+ */
839
+ declare function kekBase64ToBytes(b64: string): Uint8Array;
840
+ /**
841
+ * Unwrap a DEK using the KEK via AES-256-GCM (Web Crypto API). The
842
+ * `wrappedDEK` format is `base64(nonce12bytes || ciphertext || tag)`,
843
+ * matching the wire format the Atol authorize endpoint emits.
844
+ *
845
+ * Kept as a public utility so callers that prefer to own DEK lifetime
846
+ * themselves (e.g. tests, or frontends that intentionally avoid
847
+ * persisting the DEK across reloads) can unwrap without pulling in the
848
+ * vault machinery.
849
+ */
850
+ declare function unwrapDEK(kekBase64: string, wrappedDEKBase64: string): Promise<Uint8Array>;
851
+
852
+ /**
853
+ * Shared base64 / base64url helpers.
854
+ *
855
+ * Single source of truth for byte <-> base64 conversion across the SDK
856
+ * (encryption, KEK vault, PKCE, DPoP). The decoder accepts both the
857
+ * standard "+/" alphabet and the URL-safe "-_" alphabet, with or without
858
+ * padding, because the Atol server emits unpadded base64url while older
859
+ * tooling may emit padded standard base64.
860
+ */
861
+ /** Encode raw bytes as unpadded base64url. */
862
+ declare function bytesToBase64Url(bytes: Uint8Array): string;
863
+ /** Encode a UTF-8 string as unpadded base64url. */
864
+ declare function stringToBase64Url(input: string): string;
865
+ /**
866
+ * Decode a base64 or base64url string (padded or not) into raw bytes.
867
+ *
868
+ * This is the trust boundary for attacker-influenceable inputs (the KEK
869
+ * from the URL fragment, the wrapped DEK from a token claim, DPoP
870
+ * signatures). Validate the alphabet and reject impossible lengths
871
+ * explicitly so behavior is deterministic across engines instead of
872
+ * relying on the historically-lenient browser `atob` (which silently
873
+ * strips whitespace and tolerates trailing bits on some implementations).
874
+ */
875
+ declare function base64ToBytes(b64: string): Uint8Array;
876
+
877
+ 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 };