@atol-sh/js 0.1.1 → 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/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,62 @@ 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`; `signDPoPProof(method, url)` signs a
77
128
  standalone RFC 9449 proof for a request to your own protected resource;
78
129
  `isDPoPActive()` reports whether DPoP is actually in effect (it can be
79
130
  `false` even when `dpop: true` was requested, if WebCrypto is unavailable);
80
- `destroy()` tears down timers and subscriptions.
131
+ `destroy()` tears down timers and subscriptions. If a browser resource close
132
+ throws, the client stays destroyed, retains only that cleanup ownership, and
133
+ throws `AtolBrowserAuthCleanupError`; calling `destroy()` again retries the
134
+ incomplete step.
81
135
 
82
136
  ## Lower-level primitives
83
137
 
@@ -86,11 +140,15 @@ own flows:
86
140
 
87
141
  - **DPoP** - `createDPoPKeyManager` (per-tab non-exportable ES256 key,
88
142
  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`.
143
+ - **Verification** - `verifyIdToken` (JWKS signature + issuer + audience +
144
+ required OIDC claims and callback nonce).
145
+ - **OIDC / PKCE** - `createUserManager`, `exchangeCode`,
146
+ `refreshTokenGrant`, `revokeToken`. Browser authorization, including
147
+ `prompt=none` iframe renewal, is admitted through durable ordinary PAR
148
+ before navigation. Once `exchangeCode` dispatches the single-use code,
149
+ transport loss or an incomplete response rejects with
150
+ `AuthorizationCodeExchangeUncertainError` and code
151
+ `authorization_code_exchange_uncertain`.
94
152
  - **Cross-tab** - `createTokenBroadcast`, `hasBroadcastSupport`,
95
153
  `withTabLock`, `hasTabLockSupport`.
96
154
  - **Permissions** - `loadPermissions`, `permissionKey`.
@@ -108,10 +166,57 @@ This is a security library first. Key properties:
108
166
 
109
167
  - **Memory-only tokens.** Access, ID, and (when opted in) refresh tokens
110
168
  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.
169
+ `sessionStorage`. `sessionStorage` holds transient OIDC state/PKCE plus
170
+ non-secret tab ownership and, in response-vault mode, one opaque active
171
+ reference. `localStorage` holds only the non-secret credential generation
172
+ and signed-out status. A page reload starts with an empty token store; the
173
+ client recovers by silently renewing against the IdP session cookie unless
174
+ durable local authority records that the application is signed out.
175
+ - **Ordinary redirect custody.** A DPoP authorization key staged before an
176
+ ordinary full-page redirect remains in IndexedDB for the SDK's explicit
177
+ 15-minute browser-ceremony window plus the full 10-minute exchange lifetime
178
+ of a code issued at that boundary. OIDC state cleanup and callback
179
+ validation use the same checked 25-minute custody window; equality is
180
+ expired. This is a fail-closed client custody policy, not authorization
181
+ server authority. Response-vault mode instead has one server-enforced
182
+ 10-minute whole-transaction deadline and stores its key in that separate
183
+ transaction record.
184
+ - **Ordinary authorization protocol v2.** Discovery must publish the nested v2
185
+ PAR, pre-navigation cancellation, and settlement endpoints. The SDK sends
186
+ one canonical credentialless form request, persists its cancellation
187
+ capability before transport, and navigates with only `client_id` and the
188
+ admitted `request_uri`. If it cannot durably adopt the PAR response, it
189
+ resubmits the byte-identical form to the pre-navigation endpoint before
190
+ removing custody. PAR responses require exact `application/json`, and
191
+ settlement requests require exact `application/json`, both without
192
+ media-type parameters. The SDK authenticates a cross-origin response only
193
+ through the browser-visible `Atol-Browser-Authorization: v2` header. It does
194
+ not use hidden CORS response headers as authority. Missing, unexposed,
195
+ repeated, or unequal signals retain or settle custody and never authorize
196
+ navigation or cleanup.
197
+ - **Response vault.** A response-vault client stores a bounded authorization
198
+ transaction and non-extractable key handle in IndexedDB, with
199
+ only an opaque same-tab reference in `sessionStorage`. One durable
200
+ client-origin slot admits exactly one transaction across tabs and registered
201
+ bindings. PAR and issuer-init use POST bodies; authorize and callback
202
+ navigations are parameter-free. The same-origin relay supports exact
203
+ redelivery after an ambiguous network loss. Capability acknowledgement
204
+ deletes the delivery and opens bounded compensation, local publication
205
+ installs validated credentials, and capability finalization confirms
206
+ adoption. A crash that loses an acknowledged success rejects the exact
207
+ unavailable family before obtaining one fresh silent grant; terminal errors
208
+ retain and re-surface their exact classification. Bearer material is never
209
+ persisted for recovery. Validation and authority failures enter an
210
+ idempotently retryable rejection lineage that revokes and consumes the exact
211
+ transaction, including a finalized transaction during the compensation
212
+ window. Finalization reaches local `adopted`; `completePublication()`
213
+ atomically changes it to `published` and releases the live origin slot.
214
+ Ordinary crash scans compensate abandoned `adopted` custody and exclude
215
+ clean `published` custody, while explicit logout includes both.
216
+ Delivery-recovery routes remain private one-shot custody, and cleanup
217
+ diagnostics retain no caught browser or transport errors. Active-custody
218
+ recovery exposes only named binding, invalidation, busy, rejection, and
219
+ cleanup diagnostics; unknown storage or WebCrypto values are discarded.
115
220
  - **Iframe-default renewal, refresh required for cross-site.** By default
116
221
  the client renews in a hidden iframe against the IdP session cookie
117
222
  (`prompt=none`) and requests no refresh token, so there is no long-lived
@@ -129,19 +234,47 @@ This is a security library first. Key properties:
129
234
  attached to every token-endpoint call and to `getAccessToken({ dpop })`
130
235
  results. A stolen access token cannot be replayed from another client
131
236
  without the private key, which never leaves the browser's WebCrypto
132
- keystore.
237
+ keystore. Every token response is rejected unless `token_type=DPoP` and
238
+ the access token's `cnf.jkt` matches that tab key. Use
239
+ `dpop: { required: true }` to fail initialization when key creation is
240
+ unavailable instead of permitting the boolean option's Bearer fallback.
133
241
  - **PKCE + nonce + ID token verification.** Login uses OIDC Authorization
134
242
  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.
243
+ Callback state and PKCE are consumed through oidc-client-ts, while the SDK
244
+ performs the DPoP-aware code exchange and verifies the ID token against
245
+ the issuer's JWKS, including the stored nonce when present.
246
+ - **Signal-only cross-tab coordination.** `BroadcastChannel` messages carry
247
+ only credential-invalidation and session-ended signals. Access, ID, and
248
+ refresh tokens never cross tabs; each receiving tab renews with its own
249
+ DPoP key and grant.
250
+ - **Durable RP-initiated logout.** `logout()` atomically rotates the
251
+ origin-wide credential generation into a non-secret signed-out tombstone
252
+ before asynchronous teardown. It attempts refresh-token revocation
253
+ (RFC 7009) and the issuer's `end_session` endpoint with a one-use callback
254
+ state, and surfaces either failure. Reloads and tabs without
255
+ `BroadcastChannel` remain signed out even if the IdP session cookie still
256
+ exists. Failed attempts retain exact in-memory revocation and ID-token-hint
257
+ custody for a same-runtime retry. Only an explicit `beginLogin()` clears
258
+ the tombstone under a fresh generation.
259
+ - **Exact abandoned-login cancellation.** In response-vault mode,
260
+ `cancelLogin()` is available only before client initialization on a
261
+ signed-out browser. It claims and rejects the exact pending interactive
262
+ generation, releases local custody, and never navigates to the issuer or
263
+ ends an established session. Ambiguous rejection remains durable for an
264
+ exact retry under an `interactive_cancel` provenance. Hidden-iframe renewal
265
+ custody and generic lifecycle rejection can never satisfy that provenance.
266
+ Damaged local key custody remains cancellable only when the durable source
267
+ mode still proves that the transaction was interactive. Cleanup ownership is
268
+ latched only after that durable cancellation claim succeeds. If rejection
269
+ releases custody before tab-owner rotation is persisted, a same-runtime
270
+ retry must replace and reread the retained local fence before it resolves.
271
+ `beginLogin()` and `cancelLogin()` execute in call order, and every
272
+ concurrent cancellation caller receives the same in-flight promise even if
273
+ logout or another precondition changes while it runs. A same-tick logout
274
+ therefore awaits an earlier queued cancellation; later cancellation
275
+ requests are unavailable until logout finishes. Destroy cleanup is re-armed
276
+ only after a later explicit login successfully establishes new interactive
277
+ custody. Unsupported modes and initialized clients reject.
145
278
 
146
279
  Found a vulnerability? See [SECURITY.md](./SECURITY.md) for how to report
147
280
  it privately.
@@ -150,12 +283,37 @@ it privately.
150
283
 
151
284
  ```ts
152
285
  import { DeviceCollector } from '@atol-sh/js/device'
286
+
287
+ const collector = new DeviceCollector('https://api.atol.sh', publishState)
288
+ await collector.collect({
289
+ credentialGeneration: 1,
290
+ authorize: async ({ method, url }) => {
291
+ const credential = await auth.getAccessToken({ dpop: { method, url } })
292
+ if (!credential) throw new Error('No authenticated session')
293
+ return credential.proof
294
+ ? {
295
+ scheme: 'DPoP',
296
+ accessToken: credential.token,
297
+ dpopProof: credential.proof,
298
+ }
299
+ : { scheme: 'Bearer', accessToken: credential.token }
300
+ },
301
+ })
153
302
  ```
154
303
 
155
304
  The `@atol-sh/js/device` subpath is split out of the core barrel and
156
305
  dynamic-imports `@atol-sh/fingerprint` (an optional peer dependency) so
157
306
  consumers who don't use device intelligence never pull it into their
158
307
  bundle. Install `@atol-sh/fingerprint` alongside `@atol-sh/js` to use it.
308
+ The collector validates the complete identify response before publishing
309
+ device state; malformed or drifted success payloads produce a closed error
310
+ and never receive invented defaults. Its operation-scoped credential owner
311
+ acquires the access token and DPoP proof atomically for the exact identify
312
+ URL; neither value is stored by the collector. Increment the non-secret
313
+ `credentialGeneration` whenever the session credential rotates. A newer
314
+ generation immediately fences late responses from every older request. Call
315
+ `collector.invalidate()` on logout before releasing the collector; future
316
+ credentials must continue with a higher generation.
159
317
 
160
318
  ## Browser support
161
319
 
@@ -164,8 +322,8 @@ browsers (Chrome, Firefox, Safari, Edge) on both desktop and mobile.
164
322
  When WebCrypto is unavailable (for example, a non-browser or non-secure
165
323
  context), DPoP key generation returns `null` and the client falls back to
166
324
  plain Bearer tokens automatically -- `isDPoPActive()` reports `false` and
167
- no proof is attached, but authentication and token renewal continue to
168
- work.
325
+ no proof is attached for ordinary clients. Response-vault mode never falls
326
+ back: missing WebCrypto is a fatal authorization error.
169
327
 
170
328
  ## Troubleshooting
171
329