@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/CHANGELOG.md CHANGED
@@ -6,7 +6,181 @@ 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
+ ### Added
10
+
11
+ - `AtolBrowserAuth.canRestartLogin()` exposes a read-only capability for UI
12
+ recovery, and `restartLogin()` explicitly restarts only the exact
13
+ response-vault authorization captured by a rejected signed-out
14
+ initialization.
15
+
16
+ ### Security
17
+
18
+ - Cross-tab restart first owns and persists a new signed-out generation,
19
+ clears local session state, and exact-fences the abandoned reference,
20
+ binding, mode, full generation, and active slot. Ambiguous settlement,
21
+ contention, supersession before or during restart, and cleanup failure remain
22
+ fail-closed and start
23
+ no replacement authorization.
24
+
25
+ ## [0.3.0] - Staged, unpublished
26
+
27
+ This staged release consolidates every change since the last published version,
28
+ 0.1.2. It has no publication date or release tag because registry publication
29
+ and integrity verification have not completed.
30
+
31
+ ### Added
32
+
33
+ - `AtolBrowserAuth.cancelLogin()` exact-fences and rejects an abandoned
34
+ response-vault interactive authorization without performing RP logout
35
+ navigation or exposing browser custody. Login and cancellation are ordered
36
+ through one client-local queue, concurrent callers retain exact
37
+ single-flight promise identity, and retry custody persists an
38
+ `interactive_cancel` provenance that cannot match iframe renewal. Damaged
39
+ local key custody remains cancellable only when its durable source mode
40
+ proves an interactive grant, and destroy-cleanup ownership begins only after
41
+ the durable cancellation claim succeeds.
42
+ - Ordinary browser authorization protocol v2 now performs credentialless form
43
+ PAR before navigation, carries only the rooted `client_id` and
44
+ `request_uri` envelope through the browser, and supports byte-identical
45
+ pre-navigation cancellation plus proof-bound terminal settlement.
46
+ - `responseVault: true` enables the public response-vault v1 protocol:
47
+ JSON PAR and issuer-init requests, parameter-free authorize/callback
48
+ navigation, same-origin relay, capability acknowledgement and finalization,
49
+ and durable exact-family rejection.
50
+ - OIDC discovery publishes the registered v1 binding and bootstrap, PAR,
51
+ issuer-init, authorize, relay, acknowledgement, finalization, and rejection
52
+ endpoints.
53
+ - `beginLogin({ returnTo })` and `stepUp({ returnTo })` restore a canonical
54
+ same-origin application route after verified credentials commit. The route
55
+ is transaction-bound state and never changes the registered redirect URI.
56
+ - `postLogoutRedirectUri` separates the registered RP-initiated logout landing
57
+ page from the authorization callback. Response-vault mode requires it.
58
+ - `selectOrganization(organizationId)` starts a distinct `prompt=none`
59
+ organization grant and exposes the committed credential context as
60
+ `AtolSession.organizationId`.
61
+ - `DPoPKeyManager.thumbprint()` exposes the RFC 7638 thumbprint used to
62
+ validate access-token `cnf.jkt` binding.
63
+
64
+ ### Changed
65
+
66
+ - The optional device collector now passes an operation-scoped authorization
67
+ owner to the fingerprint SDK. It acquires a Bearer token or an inseparable
68
+ DPoP token/proof pair for the exact identify URL and retains neither.
69
+ - The optional device collector independently validates the exact identify
70
+ response, including device-mismatch and device-sharing signals. Missing,
71
+ unknown, or mistyped fields fail closed instead of being defaulted.
72
+ - Device identify responses require a non-null exact 13-field smart-signal
73
+ object. A caller-supplied non-secret credential generation makes every new
74
+ credential intent fence late responses from older in-flight requests.
75
+ - Device collection snapshots only the accepted generation and authorization
76
+ owner before asynchronous work. Invalidation permanently fences every
77
+ accepted generation, and dependency preloading cannot replace authenticated
78
+ device state.
79
+ - Every response-vault interactive, silent, organization-selection, and step-up
80
+ grant now creates a fresh non-extractable DPoP key. The matching key is
81
+ adopted only after the relayed tokens pass issuer, audience, nonce, subject,
82
+ organization, token-type, and `cnf.jkt` validation.
83
+ - Resource DPoP results now fence the exact token, key, and credential epoch
84
+ across asynchronous signing. Logout, renewal, organization selection, or
85
+ destroy cannot return a stale token/proof pair.
86
+ - Browser client teardown retries any channel or listener step that throws.
87
+ Partial teardown remains destroyed and surfaces only the closed
88
+ `browser_auth_cleanup_failed` diagnostic until every retained step closes.
89
+ A completed abandoned-login cancellation suppresses duplicate destroy
90
+ cleanup until a later explicit `beginLogin()` successfully establishes new
91
+ interactive custody.
92
+ - Interactive callbacks now consume oidc-client-ts state/PKCE through its
93
+ public APIs, use the SDK's DPoP-aware code exchange, and verify ID-token
94
+ signature, issuer, audience, required claims, and callback nonce.
95
+ - Token responses commit atomically only after access/ID subjects and
96
+ organization claims agree. Organization selection is isolated from older
97
+ generic renewal results.
98
+ - Cross-tab coordination is signal-only. Tokens never travel through
99
+ `BroadcastChannel`; each tab renews with its own DPoP key and grant.
100
+ - `AtolUser` no longer exposes organization, plan, or role claims. Selected
101
+ organization is credential context, not user identity.
102
+
103
+ ### Security
104
+
105
+ - Ordinary PAR accepts only an exact parameter-free `application/json`
106
+ response and every authenticated PAR, cancellation, or settlement outcome
107
+ requires the exposed `Atol-Browser-Authorization: v2` signal. Hidden
108
+ `Access-Control-Allow-Origin`, `Vary`, and
109
+ `Access-Control-Allow-Credentials` headers are never treated as browser
110
+ authority; missing, unexposed, repeated, or unequal signals preserve
111
+ custody.
112
+ - Logout now persists one atomic generation and signed-out authority record
113
+ before asynchronous teardown. Cold startup retries application-wide
114
+ response-vault cancellation, suppresses IdP-cookie silent restoration, and
115
+ stays signed out without `BroadcastChannel`; only explicit login installs a
116
+ fresh active generation.
117
+ - RP-initiated logout uses one-use validated callback state. Refresh-token
118
+ revocation, response-vault cleanup, local vault clearing, and end-session
119
+ navigation failures remain visible while the durable tombstone prevents
120
+ session resurrection.
121
+ - Response-vault authorization codes, OAuth state, OIDC nonce, PKCE material,
122
+ pushed request URI, transaction ID, and tokens no longer cross browser
123
+ navigation URLs or `postMessage`.
124
+ - Relay transport loss resumes the same durable transaction and key.
125
+ A random PAR idempotency key makes an ambiguous push return the exact same
126
+ transaction, and a separate cancellation capability settles it after
127
+ cookie and CSRF authority is cleared.
128
+ - Acknowledgement deletes the encrypted delivery and enters bounded
129
+ `publishing`; local credential commit is followed by a separate,
130
+ idempotently retryable finalization to `adopted`. Publication failure
131
+ compensates by revoking the exact family, including during the bounded
132
+ post-finalize window.
133
+ - `completePublication()` atomically changes local `adopted` custody to
134
+ `published` and releases the host-wide live slot. Ordinary crash scans
135
+ compensate abandoned `adopted` custody but exclude clean `published`
136
+ custody; explicit logout includes both.
137
+ - After a reload, an acknowledged success that is unavailable from memory is
138
+ rejected before one fresh silent grant is obtained. Durable terminal
139
+ settlements re-surface the exact typed OAuth error instead of using success
140
+ recovery. The validated return route remains behind one private, one-shot
141
+ recovery capability and is never retained on the public error. Bearer
142
+ material is never persisted.
143
+ - Invalid, stale, or navigation-failed response-vault grants persist rejection
144
+ before transport. Exact retries revoke any issued token family, consume the
145
+ server transaction, and never create another relay or grant.
146
+ - Random origin-wide logout and per-tab owner generations fence ordinary and
147
+ response-vault callbacks across reloads and missed broadcasts. A durable
148
+ client-origin slot gives concurrent starts across tabs and bindings one
149
+ winner.
150
+ - Protocol response bodies are consumed with a 32 KiB streaming cap under the
151
+ operation deadline. Lifecycle invalidation aborts outstanding fetches and
152
+ retry waits.
153
+ - Response-vault mode requires DPoP and a non-empty registered audience, and
154
+ rejects the incompatible `deriveEncryptionKey` URL-fragment flow.
155
+ - Token-endpoint `DPoP-Nonce` fields are parsed once using bounded RFC 9449
156
+ syntax. Comma-joined duplicates, whitespace, control characters, and
157
+ malformed values are rejected without replacing the last valid nonce. A
158
+ transport rejection or malformed header after an authorization code was
159
+ dispatched returns the closed `authorization_code_exchange_uncertain`
160
+ diagnostic, never a definite local failure.
161
+ - Response-vault cleanup failures collapse to one closed code and message.
162
+ Public errors retain neither raw caught values nor nested error arrays.
163
+ Active-custody recovery reconstructs only named authorization diagnostics;
164
+ decorated errors, storage, WebCrypto, and hostile caught values collapse to
165
+ clean diagnostics. An earlier cleanup failure remains authoritative when
166
+ grant rejection also fails.
167
+ - Response-vault Web Locks are physically released after IndexedDB failures,
168
+ fence assertion failures, and lifecycle-cancelled retry waits. Durable
169
+ custody is never deleted by that release; a new contender must reacquire the
170
+ same browser lock and revalidate the persisted fence. When operation and
171
+ cleanup both fail, the original failure remains primary while internal
172
+ diagnostics retain the ordered cleanup failures outside public error fields.
173
+ - DPoP responses now require `token_type=DPoP` and an access-token `cnf.jkt`
174
+ matching the active tab key. `{ dpop: { required: true } }` fails init when
175
+ WebCrypto cannot create that key.
176
+ - Access tokens are verified as signed `at+jwt` credentials for the configured
177
+ resource before their subject, organization, or DPoP binding is trusted.
178
+ - Interactive callback state without a nonce is rejected. Callback completion
179
+ is single-flight, owns bounded failure cleanup, and cannot commit after the
180
+ client is destroyed.
181
+ - Only typed transport failures are retried; configuration, URL, and WebCrypto
182
+ `TypeError` failures surface immediately.
183
+ - Package type checking now includes all tests and protocol mocks.
10
184
 
11
185
  ## [0.1.2] - 2026-07-08
12
186
 
@@ -28,8 +202,8 @@ No unreleased changes yet.
28
202
 
29
203
  - `seedTestSession(tokens)` on the browser auth client, gated behind a new
30
204
  `allowTestSessions` config flag (default `false`). It establishes an
31
- authenticated session directly from a token response — bypassing the OIDC
32
- redirect/callback and signature/state/nonce checks — so browser e2e tests
205
+ authenticated session directly from a token response -- bypassing the OIDC
206
+ redirect/callback and signature/state/nonce checks -- so browser e2e tests
33
207
  can bootstrap a logged-in session against the in-memory token store without
34
208
  a live IdP. Adopted through the same `applyTokens` path as a real login, so
35
209
  `onSessionChange` subscribers flip to authenticated. Deny-by-default: it
@@ -61,10 +235,12 @@ Initial release. Framework-agnostic browser security core extracted from
61
235
  grant, and revokes the refresh token on logout. Same-site apps (a console
62
236
  on a subdomain of the IdP) should leave it `false`.
63
237
  - Lower-level primitives: `createDPoPKeyManager` (RFC 9449),
64
- `verifyIdToken` (JWKS), `createUserManager` / `silentAuthorize` /
65
- `exchangeCode` / `refreshTokenGrant` / `revokeToken`,
238
+ `verifyIdToken` (JWKS), `createUserManager` / `exchangeCode` /
239
+ `refreshTokenGrant` / `revokeToken`,
66
240
  `createTokenBroadcast`, `withTabLock`, `loadPermissions`, `KEKVault` +
67
241
  zero-knowledge encryption helpers, and JWT claim helpers.
242
+ - Browser authorization, including `prompt=none` iframe renewal, is admitted
243
+ through durable ordinary PAR before navigation.
68
244
  - Optional `@atol-sh/js/device` subpath: `DeviceCollector` and device
69
245
  intelligence types, isolating the optional `@atol-sh/fingerprint` peer
70
246
  dependency from the core bundle.
@@ -72,5 +248,7 @@ Initial release. Framework-agnostic browser security core extracted from
72
248
  - Tokens are memory-only: access/ID/refresh tokens never touch Web Storage;
73
249
  `sessionStorage` holds only the OIDC state/PKCE verifier.
74
250
 
75
- [Unreleased]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.0...HEAD
251
+ [Unreleased]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.2...HEAD
252
+ [0.1.2]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.1...v0.1.2
253
+ [0.1.1]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.0...v0.1.1
76
254
  [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.