@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/CHANGELOG.md CHANGED
@@ -6,7 +6,179 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
- No unreleased changes yet.
9
+ ## [0.3.0] - Staged, unpublished
10
+
11
+ This staged release consolidates every change since the last published version,
12
+ 0.1.2. It has no publication date or release tag because registry publication
13
+ and integrity verification have not completed.
14
+
15
+ ### Added
16
+
17
+ - `AtolBrowserAuth.cancelLogin()` exact-fences and rejects an abandoned
18
+ response-vault interactive authorization without performing RP logout
19
+ navigation or exposing browser custody. Login and cancellation are ordered
20
+ through one client-local queue, concurrent callers retain exact
21
+ single-flight promise identity, and retry custody persists an
22
+ `interactive_cancel` provenance that cannot match iframe renewal. Damaged
23
+ local key custody remains cancellable only when its durable source mode
24
+ proves an interactive grant, and destroy-cleanup ownership begins only after
25
+ the durable cancellation claim succeeds.
26
+ - Ordinary browser authorization protocol v2 now performs credentialless form
27
+ PAR before navigation, carries only the rooted `client_id` and
28
+ `request_uri` envelope through the browser, and supports byte-identical
29
+ pre-navigation cancellation plus proof-bound terminal settlement.
30
+ - `responseVault: true` enables the public response-vault v1 protocol:
31
+ JSON PAR and issuer-init requests, parameter-free authorize/callback
32
+ navigation, same-origin relay, capability acknowledgement and finalization,
33
+ and durable exact-family rejection.
34
+ - OIDC discovery publishes the registered v1 binding and bootstrap, PAR,
35
+ issuer-init, authorize, relay, acknowledgement, finalization, and rejection
36
+ endpoints.
37
+ - `beginLogin({ returnTo })` and `stepUp({ returnTo })` restore a canonical
38
+ same-origin application route after verified credentials commit. The route
39
+ is transaction-bound state and never changes the registered redirect URI.
40
+ - `postLogoutRedirectUri` separates the registered RP-initiated logout landing
41
+ page from the authorization callback. Response-vault mode requires it.
42
+ - `selectOrganization(organizationId)` starts a distinct `prompt=none`
43
+ organization grant and exposes the committed credential context as
44
+ `AtolSession.organizationId`.
45
+ - `DPoPKeyManager.thumbprint()` exposes the RFC 7638 thumbprint used to
46
+ validate access-token `cnf.jkt` binding.
47
+
48
+ ### Changed
49
+
50
+ - The optional device collector now passes an operation-scoped authorization
51
+ owner to the fingerprint SDK. It acquires a Bearer token or an inseparable
52
+ DPoP token/proof pair for the exact identify URL and retains neither.
53
+ - The optional device collector independently validates the exact identify
54
+ response, including device-mismatch and device-sharing signals. Missing,
55
+ unknown, or mistyped fields fail closed instead of being defaulted.
56
+ - Device identify responses require a non-null exact 13-field smart-signal
57
+ object. A caller-supplied non-secret credential generation makes every new
58
+ credential intent fence late responses from older in-flight requests.
59
+ - Device collection snapshots only the accepted generation and authorization
60
+ owner before asynchronous work. Invalidation permanently fences every
61
+ accepted generation, and dependency preloading cannot replace authenticated
62
+ device state.
63
+ - Every response-vault interactive, silent, organization-selection, and step-up
64
+ grant now creates a fresh non-extractable DPoP key. The matching key is
65
+ adopted only after the relayed tokens pass issuer, audience, nonce, subject,
66
+ organization, token-type, and `cnf.jkt` validation.
67
+ - Resource DPoP results now fence the exact token, key, and credential epoch
68
+ across asynchronous signing. Logout, renewal, organization selection, or
69
+ destroy cannot return a stale token/proof pair.
70
+ - Browser client teardown retries any channel or listener step that throws.
71
+ Partial teardown remains destroyed and surfaces only the closed
72
+ `browser_auth_cleanup_failed` diagnostic until every retained step closes.
73
+ A completed abandoned-login cancellation suppresses duplicate destroy
74
+ cleanup until a later explicit `beginLogin()` successfully establishes new
75
+ interactive custody.
76
+ - Interactive callbacks now consume oidc-client-ts state/PKCE through its
77
+ public APIs, use the SDK's DPoP-aware code exchange, and verify ID-token
78
+ signature, issuer, audience, required claims, and callback nonce.
79
+ - Token responses commit atomically only after access/ID subjects and
80
+ organization claims agree. Organization selection is isolated from older
81
+ generic renewal results.
82
+ - Cross-tab coordination is signal-only. Tokens never travel through
83
+ `BroadcastChannel`; each tab renews with its own DPoP key and grant.
84
+ - `AtolUser` no longer exposes organization, plan, or role claims. Selected
85
+ organization is credential context, not user identity.
86
+
87
+ ### Security
88
+
89
+ - Ordinary PAR accepts only an exact parameter-free `application/json`
90
+ response and every authenticated PAR, cancellation, or settlement outcome
91
+ requires the exposed `Atol-Browser-Authorization: v2` signal. Hidden
92
+ `Access-Control-Allow-Origin`, `Vary`, and
93
+ `Access-Control-Allow-Credentials` headers are never treated as browser
94
+ authority; missing, unexposed, repeated, or unequal signals preserve
95
+ custody.
96
+ - Logout now persists one atomic generation and signed-out authority record
97
+ before asynchronous teardown. Cold startup retries application-wide
98
+ response-vault cancellation, suppresses IdP-cookie silent restoration, and
99
+ stays signed out without `BroadcastChannel`; only explicit login installs a
100
+ fresh active generation.
101
+ - RP-initiated logout uses one-use validated callback state. Refresh-token
102
+ revocation, response-vault cleanup, local vault clearing, and end-session
103
+ navigation failures remain visible while the durable tombstone prevents
104
+ session resurrection.
105
+ - Response-vault authorization codes, OAuth state, OIDC nonce, PKCE material,
106
+ pushed request URI, transaction ID, and tokens no longer cross browser
107
+ navigation URLs or `postMessage`.
108
+ - Relay transport loss resumes the same durable transaction and key.
109
+ A random PAR idempotency key makes an ambiguous push return the exact same
110
+ transaction, and a separate cancellation capability settles it after
111
+ cookie and CSRF authority is cleared.
112
+ - Acknowledgement deletes the encrypted delivery and enters bounded
113
+ `publishing`; local credential commit is followed by a separate,
114
+ idempotently retryable finalization to `adopted`. Publication failure
115
+ compensates by revoking the exact family, including during the bounded
116
+ post-finalize window.
117
+ - `completePublication()` atomically changes local `adopted` custody to
118
+ `published` and releases the host-wide live slot. Ordinary crash scans
119
+ compensate abandoned `adopted` custody but exclude clean `published`
120
+ custody; explicit logout includes both.
121
+ - After a reload, an acknowledged success that is unavailable from memory is
122
+ rejected before one fresh silent grant is obtained. Durable terminal
123
+ settlements re-surface the exact typed OAuth error instead of using success
124
+ recovery. The validated return route remains behind one private, one-shot
125
+ recovery capability and is never retained on the public error. Bearer
126
+ material is never persisted.
127
+ - Invalid, stale, or navigation-failed response-vault grants persist rejection
128
+ before transport. Exact retries revoke any issued token family, consume the
129
+ server transaction, and never create another relay or grant.
130
+ - Random origin-wide logout and per-tab owner generations fence ordinary and
131
+ response-vault callbacks across reloads and missed broadcasts. A durable
132
+ client-origin slot gives concurrent starts across tabs and bindings one
133
+ winner.
134
+ - Protocol response bodies are consumed with a 32 KiB streaming cap under the
135
+ operation deadline. Lifecycle invalidation aborts outstanding fetches and
136
+ retry waits.
137
+ - Response-vault mode requires DPoP and a non-empty registered audience, and
138
+ rejects the incompatible `deriveEncryptionKey` URL-fragment flow.
139
+ - Token-endpoint `DPoP-Nonce` fields are parsed once using bounded RFC 9449
140
+ syntax. Comma-joined duplicates, whitespace, control characters, and
141
+ malformed values are rejected without replacing the last valid nonce. A
142
+ transport rejection or malformed header after an authorization code was
143
+ dispatched returns the closed `authorization_code_exchange_uncertain`
144
+ diagnostic, never a definite local failure.
145
+ - Response-vault cleanup failures collapse to one closed code and message.
146
+ Public errors retain neither raw caught values nor nested error arrays.
147
+ Active-custody recovery reconstructs only named authorization diagnostics;
148
+ decorated errors, storage, WebCrypto, and hostile caught values collapse to
149
+ clean diagnostics. An earlier cleanup failure remains authoritative when
150
+ grant rejection also fails.
151
+ - Response-vault Web Locks are physically released after IndexedDB failures,
152
+ fence assertion failures, and lifecycle-cancelled retry waits. Durable
153
+ custody is never deleted by that release; a new contender must reacquire the
154
+ same browser lock and revalidate the persisted fence. When operation and
155
+ cleanup both fail, the original failure remains primary while internal
156
+ diagnostics retain the ordered cleanup failures outside public error fields.
157
+ - DPoP responses now require `token_type=DPoP` and an access-token `cnf.jkt`
158
+ matching the active tab key. `{ dpop: { required: true } }` fails init when
159
+ WebCrypto cannot create that key.
160
+ - Access tokens are verified as signed `at+jwt` credentials for the configured
161
+ resource before their subject, organization, or DPoP binding is trusted.
162
+ - Interactive callback state without a nonce is rejected. Callback completion
163
+ is single-flight, owns bounded failure cleanup, and cannot commit after the
164
+ client is destroyed.
165
+ - Only typed transport failures are retried; configuration, URL, and WebCrypto
166
+ `TypeError` failures surface immediately.
167
+ - Package type checking now includes all tests and protocol mocks.
168
+
169
+ ## [0.1.2] - 2026-07-08
170
+
171
+ ### Added
172
+
173
+ - `initialTestSession` config option (gated on `allowTestSessions`). When set,
174
+ `createAtolBrowserAuth(...).init()` adopts the given token response
175
+ deterministically and SKIPS the cold-load restore entirely -- no
176
+ redirect-callback handling, no hidden-iframe silent renew. The session settles
177
+ authenticated at first paint, race-free (unlike calling `seedTestSession`
178
+ after mount). This is the clean way to bootstrap a browser e2e session against
179
+ a stubbed backend with no IdP at the `issuer`, where the restore iframe would
180
+ otherwise block until it times out. Ignored unless `allowTestSessions: true`;
181
+ warns when the token has no future `exp`.
10
182
 
11
183
  ## [0.1.1] - 2026-07-08
12
184
 
@@ -14,8 +186,8 @@ No unreleased changes yet.
14
186
 
15
187
  - `seedTestSession(tokens)` on the browser auth client, gated behind a new
16
188
  `allowTestSessions` config flag (default `false`). It establishes an
17
- authenticated session directly from a token response — bypassing the OIDC
18
- redirect/callback and signature/state/nonce checks — so browser e2e tests
189
+ authenticated session directly from a token response -- bypassing the OIDC
190
+ redirect/callback and signature/state/nonce checks -- so browser e2e tests
19
191
  can bootstrap a logged-in session against the in-memory token store without
20
192
  a live IdP. Adopted through the same `applyTokens` path as a real login, so
21
193
  `onSessionChange` subscribers flip to authenticated. Deny-by-default: it
@@ -47,10 +219,12 @@ Initial release. Framework-agnostic browser security core extracted from
47
219
  grant, and revokes the refresh token on logout. Same-site apps (a console
48
220
  on a subdomain of the IdP) should leave it `false`.
49
221
  - Lower-level primitives: `createDPoPKeyManager` (RFC 9449),
50
- `verifyIdToken` (JWKS), `createUserManager` / `silentAuthorize` /
51
- `exchangeCode` / `refreshTokenGrant` / `revokeToken`,
222
+ `verifyIdToken` (JWKS), `createUserManager` / `exchangeCode` /
223
+ `refreshTokenGrant` / `revokeToken`,
52
224
  `createTokenBroadcast`, `withTabLock`, `loadPermissions`, `KEKVault` +
53
225
  zero-knowledge encryption helpers, and JWT claim helpers.
226
+ - Browser authorization, including `prompt=none` iframe renewal, is admitted
227
+ through durable ordinary PAR before navigation.
54
228
  - Optional `@atol-sh/js/device` subpath: `DeviceCollector` and device
55
229
  intelligence types, isolating the optional `@atol-sh/fingerprint` peer
56
230
  dependency from the core bundle.
@@ -58,5 +232,7 @@ Initial release. Framework-agnostic browser security core extracted from
58
232
  - Tokens are memory-only: access/ID/refresh tokens never touch Web Storage;
59
233
  `sessionStorage` holds only the OIDC state/PKCE verifier.
60
234
 
61
- [Unreleased]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.0...HEAD
235
+ [Unreleased]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.2...HEAD
236
+ [0.1.2]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.1...v0.1.2
237
+ [0.1.1]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.0...v0.1.1
62
238
  [0.1.0]: https://github.com/atol-sh/atol-sdk-js/releases/tag/v0.1.0
package/EXAMPLES.md ADDED
@@ -0,0 +1,316 @@
1
+ # Examples
2
+
3
+ Runnable, framework-agnostic snippets for `@atol-sh/js`. Every symbol here
4
+ is checked against `src/index.ts` -- if it's not exported, it's not shown.
5
+
6
+ Building a React app? Use [`@atol-sh/react`](https://github.com/atol-sh/atol-sdk-react)
7
+ instead; these patterns still apply underneath.
8
+
9
+ ## 1. Minimal login / logout
10
+
11
+ ```ts
12
+ import { createAtolBrowserAuth } from '@atol-sh/js'
13
+
14
+ const auth = createAtolBrowserAuth({
15
+ issuer: 'https://id.atol.sh',
16
+ clientId: 'atol_kid_abc123', // from console.atol.sh
17
+ redirectUri: 'https://app.example.com/callback',
18
+ postLogoutRedirectUri: 'https://app.example.com/logout',
19
+ })
20
+
21
+ // Subscribe before init() so you see the first snapshot too.
22
+ const unsubscribe = auth.onSessionChange(({ isAuthenticated, user }) => {
23
+ if (isAuthenticated) {
24
+ console.log('signed in as', user?.email)
25
+ } else {
26
+ console.log('signed out')
27
+ }
28
+ })
29
+
30
+ // Call once at startup. On the redirect URI page this also completes the
31
+ // login (see completeLogin below); everywhere else it tries a silent
32
+ // restore against the IdP session cookie.
33
+ await auth.init()
34
+
35
+ // Wire a "Log in" button:
36
+ document.querySelector('#login')?.addEventListener('click', () => {
37
+ void auth.beginLogin({ returnTo: '/dashboard' })
38
+ })
39
+
40
+ // Wire a "Log out" button:
41
+ document.querySelector('#logout')?.addEventListener('click', () => {
42
+ void auth.logout()
43
+ })
44
+ ```
45
+
46
+ On your redirect URI page, `init()` already calls `completeLogin()`
47
+ internally, so most apps never call it directly. Pass a same-origin absolute
48
+ path as `returnTo` when login starts. The SDK binds it to that authorization,
49
+ keeps the registered OAuth redirect URI fixed, and restores the route with
50
+ history navigation only after the response is verified and committed:
51
+
52
+ ```ts
53
+ await auth.beginLogin({ returnTo: '/dashboard?tab=welcome' })
54
+ ```
55
+
56
+ Do not perform a full-page redirect after `completeLogin()`: credentials are
57
+ memory-only, so reloading would intentionally discard them.
58
+
59
+ Clean up on teardown (e.g. a single-page app tearing down a route):
60
+
61
+ ```ts
62
+ unsubscribe()
63
+ auth.destroy()
64
+ ```
65
+
66
+ ## 2. Calling an API with `getAccessToken({ dpop })`
67
+
68
+ ```ts
69
+ const auth = createAtolBrowserAuth({
70
+ issuer: 'https://id.atol.sh',
71
+ clientId: 'atol_kid_abc123',
72
+ audience: 'https://api.example.com',
73
+ redirectUri: 'https://app.example.com/callback',
74
+ dpop: true, // RFC 9449 sender-constrained tokens
75
+ })
76
+
77
+ await auth.init()
78
+
79
+ async function fetchMe() {
80
+ const url = 'https://api.example.com/me'
81
+ const result = await auth.getAccessToken({ dpop: { method: 'GET', url } })
82
+ if (!result) {
83
+ throw new Error('not authenticated')
84
+ }
85
+
86
+ const headers: Record<string, string> = result.proof
87
+ ? { Authorization: `DPoP ${result.token}`, DPoP: result.proof }
88
+ : { Authorization: `Bearer ${result.token}` }
89
+
90
+ const res = await fetch(url, { headers })
91
+ return res.json()
92
+ }
93
+ ```
94
+
95
+ `getAccessToken` renews under the hood when the token is within 60s of
96
+ expiry, so callers never need to check expiry themselves. If DPoP was
97
+ requested but WebCrypto wasn't available, `result.proof` is simply
98
+ `undefined` and you fall back to Bearer -- check `auth.isDPoPActive()` if
99
+ you need to know which mode is in effect ahead of time.
100
+
101
+ ## 3. Refresh-token vs iframe renewal
102
+
103
+ Default (`useRefreshTokens: false`): renewal happens in a hidden iframe
104
+ against the IdP session cookie. No refresh token is requested or stored.
105
+ This only works for a **same-site** app (e.g. a console on a subdomain of
106
+ the issuer):
107
+
108
+ ```ts
109
+ const auth = createAtolBrowserAuth({
110
+ issuer: 'https://id.atol.sh',
111
+ clientId: 'atol_kid_abc123',
112
+ redirectUri: 'https://console.atol.sh/callback',
113
+ // useRefreshTokens defaults to false: iframe renewal.
114
+ })
115
+ ```
116
+
117
+ **Cross-site** apps (served on a different registrable domain than the
118
+ issuer) must opt into refresh tokens -- Safari ITP and Chrome's
119
+ third-party-cookie phase-out make the iframe path fail unconditionally:
120
+
121
+ ```ts
122
+ const auth = createAtolBrowserAuth({
123
+ issuer: 'https://id.atol.sh',
124
+ clientId: 'atol_kid_abc123',
125
+ redirectUri: 'https://app.example.com/callback',
126
+ useRefreshTokens: true, // appends offline_access, renews via refresh grant
127
+ useRefreshTokensFallback: true, // optional: fall back to iframe on a transient grant failure
128
+ })
129
+ ```
130
+
131
+ Refresh tokens are still memory-only, rotated on every use, and
132
+ DPoP-bound when `dpop: true`. `logout()` best-effort revokes the refresh
133
+ token (RFC 7009) before redirecting to `end_session`.
134
+
135
+ You can also force an immediate renewal outside of the normal
136
+ expiry-driven schedule:
137
+
138
+ ```ts
139
+ const newAccessToken = await auth.forceRenew()
140
+ ```
141
+
142
+ ## 4. Response-vault authorization
143
+
144
+ Use response-vault v1 when the registered client has both authorization-server
145
+ support and a same-origin relay:
146
+
147
+ ```ts
148
+ const auth = createAtolBrowserAuth({
149
+ issuer: 'https://id.example.com',
150
+ clientId: 'example-spa',
151
+ audience: 'https://api.example.com',
152
+ scopes: 'openid profile email',
153
+ redirectUri: 'https://app.example.com/callback',
154
+ postLogoutRedirectUri: 'https://app.example.com/logout',
155
+ dpop: { required: true },
156
+ responseVault: true,
157
+ })
158
+ ```
159
+
160
+ The registration pins the client, audience, client origin, and clean callback.
161
+ This mode uses no authorization response in query, fragment, form-post, or
162
+ `postMessage`; `init()` relays and validates the server-vault result before
163
+ publishing it. Ambiguous PAR and relay responses retry the exact server
164
+ transaction. Acknowledgement deletes the encrypted delivery and opens a
165
+ bounded compensation window; only after local credentials commit does
166
+ finalization confirm adoption. If a reload loses an acknowledged success, the
167
+ SDK rejects the unavailable family before obtaining one fresh silent grant
168
+ because tokens are intentionally never persisted client-side. Terminal errors
169
+ retain their exact typed classification. Invalid, superseded, or
170
+ publication-failed grants use the same cancellation capability to revoke and
171
+ consume the exact transaction.
172
+ The complete wire and recovery contract is documented in
173
+ [RESPONSE_VAULT_PROTOCOL.md](./RESPONSE_VAULT_PROTOCOL.md).
174
+
175
+ ## 5. Step-up re-auth with `stepUp()`
176
+
177
+ When a sensitive operation returns a `step_up_required` challenge (a fresh
178
+ authentication / second factor is needed), redirect through `stepUp()` and
179
+ retry the operation once the page comes back:
180
+
181
+ ```ts
182
+ async function deleteOrg(orgId: string) {
183
+ const result = await auth.getAccessToken()
184
+ const res = await fetch(`/api/orgs/${orgId}`, {
185
+ method: 'DELETE',
186
+ headers: { Authorization: `Bearer ${result?.token}` },
187
+ })
188
+
189
+ if (res.status === 403) {
190
+ const body = await res.json()
191
+ if (body.error === 'step_up_required') {
192
+ // Redirects the browser; forces prompt=login, max_age=0, acr_values=mfa.
193
+ await auth.stepUp({ returnTo: '/orgs' })
194
+ return
195
+ }
196
+ }
197
+ return res
198
+ }
199
+ ```
200
+
201
+ Override the assurance level or accept a very recent login instead of
202
+ forcing a brand-new one:
203
+
204
+ ```ts
205
+ await auth.stepUp({
206
+ returnTo: '/billing',
207
+ maxAge: 300,
208
+ acrValues: 'urn:example:loa:2',
209
+ })
210
+ ```
211
+
212
+ `returnTo` is same-origin transaction state; it never changes the registered
213
+ callback URI.
214
+
215
+ ## 6. Permission checks
216
+
217
+ ```ts
218
+ import { createAtolBrowserAuth, loadPermissions, permissionKey } from '@atol-sh/js'
219
+
220
+ const auth = createAtolBrowserAuth({
221
+ issuer: 'https://id.atol.sh',
222
+ clientId: 'atol_kid_abc123',
223
+ redirectUri: 'https://app.example.com/callback',
224
+ dpop: true,
225
+ })
226
+
227
+ await auth.init()
228
+
229
+ async function checkPermissions() {
230
+ const result = await auth.getAccessToken()
231
+ if (!result) return new Map<string, boolean>()
232
+
233
+ const user = /* the AtolUser from onSessionChange / session state */ null
234
+ if (!user) return new Map<string, boolean>()
235
+
236
+ return loadPermissions({
237
+ apiUrl: 'https://api.atol.sh', // control-plane API host, NOT the issuer
238
+ keyId: 'atol_kid_abc123',
239
+ accessToken: result.token,
240
+ userId: user.id,
241
+ orgId: user.orgId,
242
+ checks: [
243
+ { action: 'edit', resource: 'publication' },
244
+ { action: 'manage', resource: 'team:team-123' },
245
+ ],
246
+ // Pass a DPoP signer when the session is DPoP-bound so the resource
247
+ // server sees `DPoP` + a matching proof instead of a stolen-looking
248
+ // Bearer token. signDPoPProof() re-fetches the token itself, so this
249
+ // adapter only needs to forward the (method, url) pair.
250
+ dpop: auth.isDPoPActive()
251
+ ? {
252
+ signProof: async (method: string, url: string) => {
253
+ const r = await auth.signDPoPProof(method, url)
254
+ if (!r?.proof) throw new Error('DPoP proof unavailable')
255
+ return r.proof
256
+ },
257
+ }
258
+ : undefined,
259
+ })
260
+ }
261
+
262
+ const permissions = await checkPermissions()
263
+ const canEdit = permissions.get(permissionKey('edit', 'publication')) === true
264
+ ```
265
+
266
+ `loadPermissions` denies by default: a missing check, a malformed
267
+ response, or a shape mismatch between requested checks and returned
268
+ results throws rather than silently returning `true` for anything.
269
+ Treat a thrown error the same as "no permissions granted" in your UI.
270
+
271
+ ## 7. Device intelligence (`./device` subpath)
272
+
273
+ Optional, and only pulls in `@atol-sh/fingerprint` (an optional peer
274
+ dependency) when you actually import this subpath:
275
+
276
+ ```bash
277
+ npm install @atol-sh/js @atol-sh/fingerprint
278
+ ```
279
+
280
+ ```ts
281
+ import { DeviceCollector, DEFAULT_DEVICE_API_URL } from '@atol-sh/js/device'
282
+
283
+ const collector = new DeviceCollector(DEFAULT_DEVICE_API_URL, (state) => {
284
+ if (state.loading) return
285
+ if (state.error) {
286
+ console.error('device intelligence failed', state.error)
287
+ return
288
+ }
289
+ console.log('device', state.deviceId, 'known:', state.known, 'signals:', state.signals)
290
+ })
291
+
292
+ // The credential owner resolves the token and proof together for the exact
293
+ // request. Call prepare() first if you only want to pre-load the agent.
294
+ await collector.collect({
295
+ credentialGeneration: 1,
296
+ authorize: async ({ method, url }) => {
297
+ const result = await auth.getAccessToken({ dpop: { method, url } })
298
+ if (!result) throw new Error('No authenticated session')
299
+ return result.proof
300
+ ? {
301
+ scheme: 'DPoP',
302
+ accessToken: result.token,
303
+ dpopProof: result.proof,
304
+ }
305
+ : { scheme: 'Bearer', accessToken: result.token }
306
+ },
307
+ })
308
+ ```
309
+
310
+ `DeviceCollector` is framework-agnostic: it dedupes concurrent `collect()`
311
+ calls for the same non-secret credential generation. Increment that generation
312
+ whenever the session credential rotates; the new intent immediately suppresses
313
+ late state from older requests. After `invalidate()`, the next credential
314
+ generation must be strictly higher than every previously accepted generation.
315
+ A framework binding (like
316
+ `@atol-sh/react`'s device hook) wraps this in reactive state.