@atol-sh/js 0.1.2 → 0.4.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/README.md CHANGED
@@ -8,8 +8,7 @@ Framework-agnostic browser security core for [Atol](https://atol.sh): a
8
8
  single config-driven client for OIDC authentication (Authorization Code +
9
9
  PKCE), DPoP sender-constrained tokens (RFC 9449), silent renewal, cross-tab
10
10
  coordination, and permission loading. `@atol-sh/react` is the React
11
- binding, built as a thin wrapper over this same core -- future Vue,
12
- Svelte, and vanilla-JS bindings will share it too.
11
+ binding, built as a thin wrapper over this same core.
13
12
 
14
13
  Building a React app? Use [`@atol-sh/react`](https://github.com/atol-sh/atol-sdk-react)
15
14
  instead, the React binding over this core. Either way you'll need a
@@ -35,26 +34,33 @@ const auth = createAtolBrowserAuth({
35
34
  audience: 'https://api.example.com', // optional API audience
36
35
  scopes: 'openid profile email', // optional; used verbatim (no offline_access by default)
37
36
  redirectUri: 'https://app.example.com/callback',
37
+ postLogoutRedirectUri: 'https://app.example.com/logout',
38
38
  dpop: true, // optional RFC 9449 sender-constrained tokens
39
39
  useRefreshTokens: false, // default (same-site); REQUIRED true for cross-site apps
40
40
  storage: 'memory', // tokens are always memory-only
41
41
  })
42
42
 
43
- const unsubscribe = auth.onSessionChange(({ isAuthenticated, user }) => {
44
- render(isAuthenticated, user)
43
+ const unsubscribe = auth.onSessionChange(({ isAuthenticated, user, organizationId }) => {
44
+ render(isAuthenticated, user, organizationId)
45
45
  })
46
46
 
47
47
  // On startup: handles a redirect callback, or silently restores a session
48
48
  // from the IdP session cookie.
49
49
  await auth.init()
50
50
 
51
- // Start a login (redirects the browser):
52
- await auth.beginLogin()
51
+ // Start a login. returnTo is transaction-bound application state; it never
52
+ // changes the registered redirect URI. After verified credentials commit,
53
+ // the SDK restores it with same-origin history navigation.
54
+ await auth.beginLogin({ returnTo: '/dashboard' })
53
55
 
54
56
  // On the redirect URI page: exchange the code for tokens. init() calls
55
57
  // this automatically, so most apps never call it directly.
56
58
  await auth.completeLogin()
57
59
 
60
+ // Switch the credential context after the user chooses an organization.
61
+ // This mints a new access/ID-token pair; it is not a generic token refresh.
62
+ await auth.selectOrganization('01KV4BNVVNZ4TNY0PP0CVXPZWP')
63
+
58
64
  // Get a token for an API call (DPoP-aware: pass the request you're about
59
65
  // to make so the proof's `htm`/`htu` bind to it):
60
66
  const result = await auth.getAccessToken({
@@ -70,14 +76,66 @@ if (result) {
70
76
  await auth.logout()
71
77
  ```
72
78
 
79
+ ### Response-vault v1
80
+
81
+ Registered clients can opt into the public response-vault protocol when their
82
+ authorization server and same-origin relay support it:
83
+
84
+ ```ts
85
+ const auth = createAtolBrowserAuth({
86
+ issuer: 'https://id.example.com',
87
+ clientId: 'example-spa',
88
+ audience: 'https://api.example.com',
89
+ scopes: 'openid profile email',
90
+ redirectUri: 'https://app.example.com/callback',
91
+ postLogoutRedirectUri: 'https://app.example.com/logout',
92
+ dpop: { required: true },
93
+ responseVault: true,
94
+ })
95
+ ```
96
+
97
+ `responseVault: true` pushes authorization parameters in JSON request bodies,
98
+ navigates to a parameter-free `/auth/authorize`, and redeems the server-held
99
+ code through the same-origin client relay. Authorization codes, state, nonce,
100
+ PKCE material, request URIs, transaction IDs, and tokens never appear in a
101
+ navigation URL or `postMessage`. Every grant gets a fresh non-extractable DPoP
102
+ key, and tokens are validated before the one-use result is acknowledged.
103
+ Invalid or superseded grants are durably rejected, revoking any exact token
104
+ family relay already issued instead of leaving a server-side orphan.
105
+
106
+ The server publishes its v1 endpoints and registered binding in OIDC
107
+ discovery. A random PAR idempotency key makes an ambiguous push exactly
108
+ retryable, while a separate cancellation capability authorizes settlement
109
+ after mutable cookie and CSRF authority is cleared. Acknowledgement deletes
110
+ the delivery and enters a bounded `publishing` state; the SDK publishes
111
+ validated credentials locally, finalizes server adoption, then atomically
112
+ marks local custody `published` and releases its slot. Failure before that
113
+ last local transition rejects and revokes the exact family within the
114
+ compensation window.
115
+
116
+ Response-vault v1 requires a non-empty audience, mandatory DPoP, a clean
117
+ callback URL, and a distinct same-origin post-logout URL. It does not support
118
+ `deriveEncryptionKey`, whose URL-fragment delivery is incompatible with a
119
+ parameter-free callback. See [RESPONSE_VAULT_PROTOCOL.md](./RESPONSE_VAULT_PROTOCOL.md)
120
+ for the supported v1 contract.
121
+
73
122
  Other methods on the returned client: `forceRenew()` bypasses the
74
123
  freshness check and renews immediately; `stepUp()` forces re-authentication
75
124
  (`prompt=login`, `max_age=0`, `acr_values=mfa` by default) for a sensitive
76
- operation that requires a fresh auth; `signDPoPProof(method, url)` signs a
125
+ operation that requires a fresh auth; `selectOrganization(id)` starts a
126
+ distinct silent organization grant and exposes the selected ID on
127
+ `AtolSession.organizationId`; `restartLogin()` explicitly settles the exact
128
+ response-vault authorization that made signed-out initialization fail, then
129
+ starts one fresh login; `canRestartLogin()` reports whether this runtime holds
130
+ the hidden exact authority required for that operation;
131
+ `signDPoPProof(method, url)` signs a
77
132
  standalone RFC 9449 proof for a request to your own protected resource;
78
133
  `isDPoPActive()` reports whether DPoP is actually in effect (it can be
79
134
  `false` even when `dpop: true` was requested, if WebCrypto is unavailable);
80
- `destroy()` tears down timers and subscriptions.
135
+ `destroy()` tears down timers and subscriptions. If a browser resource close
136
+ throws, the client stays destroyed, retains only that cleanup ownership, and
137
+ throws `AtolBrowserAuthCleanupError`; calling `destroy()` again retries the
138
+ incomplete step.
81
139
 
82
140
  ## Lower-level primitives
83
141
 
@@ -86,11 +144,15 @@ own flows:
86
144
 
87
145
  - **DPoP** - `createDPoPKeyManager` (per-tab non-exportable ES256 key,
88
146
  RFC 9449 proofs).
89
- - **Verification** - `verifyIdToken` (JWKS signature + issuer + audience,
90
- the trust gate for cross-tab token adoption).
91
- - **OIDC / PKCE** - `createUserManager`, `silentAuthorize`,
92
- `silentAuthorizeWithRetry`, `exchangeCode`, `refreshTokenGrant`,
93
- `revokeToken`.
147
+ - **Verification** - `verifyIdToken` (JWKS signature + issuer + audience +
148
+ required OIDC claims and callback nonce).
149
+ - **OIDC / PKCE** - `createUserManager`, `exchangeCode`,
150
+ `refreshTokenGrant`, `revokeToken`. Browser authorization, including
151
+ `prompt=none` iframe renewal, is admitted through durable ordinary PAR
152
+ before navigation. Once `exchangeCode` dispatches the single-use code,
153
+ transport loss or an incomplete response rejects with
154
+ `AuthorizationCodeExchangeUncertainError` and code
155
+ `authorization_code_exchange_uncertain`.
94
156
  - **Cross-tab** - `createTokenBroadcast`, `hasBroadcastSupport`,
95
157
  `withTabLock`, `hasTabLockSupport`.
96
158
  - **Permissions** - `loadPermissions`, `permissionKey`.
@@ -108,10 +170,57 @@ This is a security library first. Key properties:
108
170
 
109
171
  - **Memory-only tokens.** Access, ID, and (when opted in) refresh tokens
110
172
  live in an in-memory store and are never written to `localStorage` or
111
- `sessionStorage`. `sessionStorage` holds only the transient OIDC
112
- state/PKCE verifier needed to survive the login redirect. A page reload
113
- starts with an empty store; the client recovers by silently renewing
114
- against the IdP session cookie.
173
+ `sessionStorage`. `sessionStorage` holds transient OIDC state/PKCE plus
174
+ non-secret tab ownership and, in response-vault mode, one opaque active
175
+ reference. `localStorage` holds only the non-secret credential generation
176
+ and signed-out status. A page reload starts with an empty token store; the
177
+ client recovers by silently renewing against the IdP session cookie unless
178
+ durable local authority records that the application is signed out.
179
+ - **Ordinary redirect custody.** A DPoP authorization key staged before an
180
+ ordinary full-page redirect remains in IndexedDB for the SDK's explicit
181
+ 15-minute browser-ceremony window plus the full 10-minute exchange lifetime
182
+ of a code issued at that boundary. OIDC state cleanup and callback
183
+ validation use the same checked 25-minute custody window; equality is
184
+ expired. This is a fail-closed client custody policy, not authorization
185
+ server authority. Response-vault mode instead has one server-enforced
186
+ 10-minute whole-transaction deadline and stores its key in that separate
187
+ transaction record.
188
+ - **Ordinary authorization protocol v2.** Discovery must publish the nested v2
189
+ PAR, pre-navigation cancellation, and settlement endpoints. The SDK sends
190
+ one canonical credentialless form request, persists its cancellation
191
+ capability before transport, and navigates with only `client_id` and the
192
+ admitted `request_uri`. If it cannot durably adopt the PAR response, it
193
+ resubmits the byte-identical form to the pre-navigation endpoint before
194
+ removing custody. PAR responses require exact `application/json`, and
195
+ settlement requests require exact `application/json`, both without
196
+ media-type parameters. The SDK authenticates a cross-origin response only
197
+ through the browser-visible `Atol-Browser-Authorization: v2` header. It does
198
+ not use hidden CORS response headers as authority. Missing, unexposed,
199
+ repeated, or unequal signals retain or settle custody and never authorize
200
+ navigation or cleanup.
201
+ - **Response vault.** A response-vault client stores a bounded authorization
202
+ transaction and non-extractable key handle in IndexedDB, with
203
+ only an opaque same-tab reference in `sessionStorage`. One durable
204
+ client-origin slot admits exactly one transaction across tabs and registered
205
+ bindings. PAR and issuer-init use POST bodies; authorize and callback
206
+ navigations are parameter-free. The same-origin relay supports exact
207
+ redelivery after an ambiguous network loss. Capability acknowledgement
208
+ deletes the delivery and opens bounded compensation, local publication
209
+ installs validated credentials, and capability finalization confirms
210
+ adoption. A crash that loses an acknowledged success rejects the exact
211
+ unavailable family before obtaining one fresh silent grant; terminal errors
212
+ retain and re-surface their exact classification. Bearer material is never
213
+ persisted for recovery. Validation and authority failures enter an
214
+ idempotently retryable rejection lineage that revokes and consumes the exact
215
+ transaction, including a finalized transaction during the compensation
216
+ window. Finalization reaches local `adopted`; `completePublication()`
217
+ atomically changes it to `published` and releases the live origin slot.
218
+ Ordinary crash scans compensate abandoned `adopted` custody and exclude
219
+ clean `published` custody, while explicit logout includes both.
220
+ Delivery-recovery routes remain private one-shot custody, and cleanup
221
+ diagnostics retain no caught browser or transport errors. Active-custody
222
+ recovery exposes only named binding, invalidation, busy, rejection, and
223
+ cleanup diagnostics; unknown storage or WebCrypto values are discarded.
115
224
  - **Iframe-default renewal, refresh required for cross-site.** By default
116
225
  the client renews in a hidden iframe against the IdP session cookie
117
226
  (`prompt=none`) and requests no refresh token, so there is no long-lived
@@ -129,19 +238,63 @@ This is a security library first. Key properties:
129
238
  attached to every token-endpoint call and to `getAccessToken({ dpop })`
130
239
  results. A stolen access token cannot be replayed from another client
131
240
  without the private key, which never leaves the browser's WebCrypto
132
- keystore.
241
+ keystore. Every token response is rejected unless `token_type=DPoP` and
242
+ the access token's `cnf.jkt` matches that tab key. Use
243
+ `dpop: { required: true }` to fail initialization when key creation is
244
+ unavailable instead of permitting the boolean option's Bearer fallback.
133
245
  - **PKCE + nonce + ID token verification.** Login uses OIDC Authorization
134
246
  Code with PKCE (no implicit flow, no client secret in the browser).
135
- Cross-tab token adoption over `BroadcastChannel` is untrusted by default:
136
- a rotated token is only adopted after its ID token is verified against
137
- the issuer's JWKS (signature, issuer, audience) and the subject is
138
- pinned to the current session, so a same-origin script cannot forge a
139
- session takeover.
140
- - **RP-initiated logout + refresh-token revocation.** `logout()`
141
- best-effort revokes the refresh token (RFC 7009) when one exists (the
142
- refresh opt-in) before redirecting to the issuer's `end_session` endpoint
143
- with `id_token_hint` and `post_logout_redirect_uri`, so the IdP session
144
- is torn down, not just the local one.
247
+ Callback state and PKCE are consumed through oidc-client-ts, while the SDK
248
+ performs the DPoP-aware code exchange and verifies the ID token against
249
+ the issuer's JWKS, including the stored nonce when present.
250
+ - **Signal-only cross-tab coordination.** `BroadcastChannel` messages carry
251
+ only credential-invalidation and session-ended signals. Access, ID, and
252
+ refresh tokens never cross tabs; each receiving tab renews with its own
253
+ DPoP key and grant.
254
+ - **Durable RP-initiated logout.** `logout()` atomically rotates the
255
+ origin-wide credential generation into a non-secret signed-out tombstone
256
+ before asynchronous teardown. It attempts refresh-token revocation
257
+ (RFC 7009) and the issuer's `end_session` endpoint with a one-use callback
258
+ state, and surfaces either failure. Reloads and tabs without
259
+ `BroadcastChannel` remain signed out even if the IdP session cookie still
260
+ exists. Failed attempts retain exact in-memory revocation and ID-token-hint
261
+ custody for a same-runtime retry. Only an explicit `beginLogin()` clears
262
+ the tombstone under a fresh generation; successful `restartLogin()` does so
263
+ only after the abandoned authorization has been settled.
264
+ - **Exact abandoned-login cancellation.** In response-vault mode,
265
+ `cancelLogin()` is available only before client initialization on a
266
+ signed-out browser. It claims and rejects the exact pending interactive
267
+ generation, releases local custody, and never navigates to the issuer or
268
+ ends an established session. Ambiguous rejection remains durable for an
269
+ exact retry under an `interactive_cancel` provenance. Hidden-iframe renewal
270
+ custody and generic lifecycle rejection can never satisfy that provenance.
271
+ Damaged local key custody remains cancellable only when the durable source
272
+ mode still proves that the transaction was interactive. Cleanup ownership is
273
+ latched only after that durable cancellation claim succeeds. If rejection
274
+ releases custody before tab-owner rotation is persisted, a same-runtime
275
+ retry must replace and reread the retained local fence before it resolves.
276
+ `beginLogin()` and `cancelLogin()` execute in call order, and every
277
+ concurrent cancellation caller receives the same in-flight promise even if
278
+ logout or another precondition changes while it runs. A same-tick logout
279
+ therefore awaits an earlier queued cancellation; later cancellation
280
+ requests are unavailable until logout finishes. Destroy cleanup is re-armed
281
+ only after a later explicit login successfully establishes new interactive
282
+ custody. Unsupported modes and initialized clients reject.
283
+ - **Explicit closed-tab restart.** If `init()` rejects while a signed-out
284
+ replacement tab finds response-vault custody abandoned by a closed tab,
285
+ ordinary `cancelLogin()` remains same-tab scoped and returns a busy error
286
+ without sending rejection. `restartLogin()` first persists and rechecks a
287
+ new origin-wide signed-out generation owned by that restart only while the
288
+ captured generation is still current, clears local
289
+ session state, and then fences only the failure-time reference, binding,
290
+ mode, full old generation, and active slot. A fresh authorization starts
291
+ exactly once and only after `/reject` returns an empty 204 or an authenticated
292
+ terminal-only probe returns 410. Ambiguous responses, authenticated 409,
293
+ local cleanup failure, or a concurrently superseded logout generation retain
294
+ the initialization failure for an exact retry and start no new PAR.
295
+ `canRestartLogin()` is the read-only UI capability check; generic startup,
296
+ callback, logout, successful initialization, and destroyed states return
297
+ `false` and are never promoted into restart authority.
145
298
 
146
299
  Found a vulnerability? See [SECURITY.md](./SECURITY.md) for how to report
147
300
  it privately.
@@ -150,12 +303,37 @@ it privately.
150
303
 
151
304
  ```ts
152
305
  import { DeviceCollector } from '@atol-sh/js/device'
306
+
307
+ const collector = new DeviceCollector('https://api.atol.sh', publishState)
308
+ await collector.collect({
309
+ credentialGeneration: 1,
310
+ authorize: async ({ method, url }) => {
311
+ const credential = await auth.getAccessToken({ dpop: { method, url } })
312
+ if (!credential) throw new Error('No authenticated session')
313
+ return credential.proof
314
+ ? {
315
+ scheme: 'DPoP',
316
+ accessToken: credential.token,
317
+ dpopProof: credential.proof,
318
+ }
319
+ : { scheme: 'Bearer', accessToken: credential.token }
320
+ },
321
+ })
153
322
  ```
154
323
 
155
324
  The `@atol-sh/js/device` subpath is split out of the core barrel and
156
325
  dynamic-imports `@atol-sh/fingerprint` (an optional peer dependency) so
157
326
  consumers who don't use device intelligence never pull it into their
158
327
  bundle. Install `@atol-sh/fingerprint` alongside `@atol-sh/js` to use it.
328
+ The collector validates the complete identify response before publishing
329
+ device state; malformed or drifted success payloads produce a closed error
330
+ and never receive invented defaults. Its operation-scoped credential owner
331
+ acquires the access token and DPoP proof atomically for the exact identify
332
+ URL; neither value is stored by the collector. Increment the non-secret
333
+ `credentialGeneration` whenever the session credential rotates. A newer
334
+ generation immediately fences late responses from every older request. Call
335
+ `collector.invalidate()` on logout before releasing the collector; future
336
+ credentials must continue with a higher generation.
159
337
 
160
338
  ## Browser support
161
339
 
@@ -164,8 +342,8 @@ browsers (Chrome, Firefox, Safari, Edge) on both desktop and mobile.
164
342
  When WebCrypto is unavailable (for example, a non-browser or non-secure
165
343
  context), DPoP key generation returns `null` and the client falls back to
166
344
  plain Bearer tokens automatically -- `isDPoPActive()` reports `false` and
167
- no proof is attached, but authentication and token renewal continue to
168
- work.
345
+ no proof is attached for ordinary clients. Response-vault mode never falls
346
+ back: missing WebCrypto is a fatal authorization error.
169
347
 
170
348
  ## Troubleshooting
171
349