@blogmcp/sdk 0.13.0 → 0.14.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.
Files changed (61) hide show
  1. package/dist/community/links.d.ts +6 -0
  2. package/dist/community/links.js +9 -1
  3. package/dist/community/outcome.d.ts +1 -1
  4. package/dist/community/outcome.js +60 -23
  5. package/dist/community/private/browser.d.ts +18 -0
  6. package/dist/community/private/browser.js +17 -0
  7. package/dist/community/private/client.d.ts +259 -0
  8. package/dist/community/private/client.js +98 -0
  9. package/dist/community/private/dm.d.ts +547 -0
  10. package/dist/community/private/dm.js +852 -0
  11. package/dist/community/private/dpop.d.ts +59 -0
  12. package/dist/community/private/dpop.js +46 -0
  13. package/dist/community/private/encoding.d.ts +17 -0
  14. package/dist/community/private/encoding.js +50 -0
  15. package/dist/community/private/host-state.d.ts +20 -0
  16. package/dist/community/private/host-state.js +15 -0
  17. package/dist/community/private/index.d.ts +51 -0
  18. package/dist/community/private/index.js +71 -0
  19. package/dist/community/private/keystore.d.ts +73 -0
  20. package/dist/community/private/keystore.js +91 -0
  21. package/dist/community/private/marker.d.ts +17 -0
  22. package/dist/community/private/marker.js +11 -0
  23. package/dist/community/private/private-routes.d.ts +6 -0
  24. package/dist/community/private/private-routes.js +72 -0
  25. package/dist/community/private/promise.d.ts +65 -0
  26. package/dist/community/private/promise.js +39 -0
  27. package/dist/community/private/realtime.d.ts +127 -0
  28. package/dist/community/private/realtime.js +199 -0
  29. package/dist/community/private/session.d.ts +175 -0
  30. package/dist/community/private/session.js +441 -0
  31. package/dist/community/private/transport.d.ts +47 -0
  32. package/dist/community/private/transport.js +65 -0
  33. package/dist/community/server/grant-handoff.d.ts +53 -0
  34. package/dist/community/server/grant-handoff.js +96 -0
  35. package/dist/community/server/grant.d.ts +100 -0
  36. package/dist/community/server/grant.js +165 -0
  37. package/dist/community/server/index.d.ts +4 -0
  38. package/dist/community/server/index.js +20 -16
  39. package/dist/community/shapes.d.ts +27 -1
  40. package/dist/community/shapes.js +27 -17
  41. package/package.json +7 -3
  42. package/src/community/links.ts +8 -0
  43. package/src/community/outcome.ts +37 -0
  44. package/src/community/private/browser.ts +31 -0
  45. package/src/community/private/client.ts +304 -0
  46. package/src/community/private/dm.ts +1687 -0
  47. package/src/community/private/dpop.ts +110 -0
  48. package/src/community/private/encoding.ts +71 -0
  49. package/src/community/private/host-state.ts +37 -0
  50. package/src/community/private/index.ts +169 -0
  51. package/src/community/private/keystore.ts +179 -0
  52. package/src/community/private/marker.ts +28 -0
  53. package/src/community/private/private-routes.ts +80 -0
  54. package/src/community/private/promise.ts +125 -0
  55. package/src/community/private/realtime.ts +431 -0
  56. package/src/community/private/session.ts +848 -0
  57. package/src/community/private/transport.ts +125 -0
  58. package/src/community/server/grant-handoff.ts +179 -0
  59. package/src/community/server/grant.ts +292 -0
  60. package/src/community/server/index.ts +6 -0
  61. package/src/community/shapes.ts +46 -1
@@ -0,0 +1,848 @@
1
+ /**
2
+ * The private session in the browser (docs/internal/m4-contracts.md §6.1, §5.9).
3
+ *
4
+ * **Getting a session.** `ensureSession()`: the device key (keystore.ts) → a refresh with a proof when the record
5
+ * holds a refresh token, or else a grant from the host's `grantPath` (the host's server turns its own member session
6
+ * into a one-minute grant for this key: `createPrivateGrantHandler`) redeemed at `private/session`. The access token
7
+ * lives in this tab's memory only (one per tab; a refresh adds a token on kb-api and invalidates none, §5.9).
8
+ *
9
+ * **Many tabs.** Every refresh and every grant runs inside `navigator.locks.request('blogmcp-private-<memberHash>')`
10
+ * and re-reads the record from IndexedDB after taking the lock, so a burst of tabs never refreshes past kb-api's cap of
11
+ * eight access tokens per session. Before it refreshes, a tab takes the newest access token another tab of the same
12
+ * member already holds, through a `BroadcastChannel` of the same name: every tab announces the token it obtained, and
13
+ * a tab with none asks once. So nine tabs open over fifteen minutes cause one refresh per token lifetime between them,
14
+ * and no new session.
15
+ *
16
+ * **The recovery rule.** `UNAUTHORIZED` on a call triggers one refresh under the lock; only `UNAUTHORIZED` on the
17
+ * refresh triggers one grant. A grant opens a new `sessions` row on kb-api, so a grant per failed call would orphan
18
+ * sessions. `DEVICE_REMOVED` deletes the record and makes a new key: a new, pending device at the next grant.
19
+ *
20
+ * **The proof's two retries** (dpop.ts): one on `DPOP_NONCE` with the nonce the refusal carried, one on `DPOP_INVALID`
21
+ * when the refusal's `serverTime` shows the clock was more than 60 s off.
22
+ *
23
+ * **The host's session decides** (§5.9). `start()` asks the host for its current member (the `me/get` it reads anyway):
24
+ * for every stored record of another member — a shared browser where B now signs in after A — and for every record
25
+ * when the host has no member at all, it unsubscribes that device's private push (so the shared push endpoint stops
26
+ * pinging for the previous member), ends the private session and deletes the refresh token, keeping the key (that
27
+ * member's device). `privateSignOut()` unsubscribes the device's private push, ends the session and deletes the
28
+ * refresh token; the hosts call it in their sign-out flows, before or after ending their own session (when the host's
29
+ * member is already gone it ends the record this tab used and every stored tenant session, as `start()` would on the
30
+ * next load). `forget()` removes the device on kb-api (`devices/forget`) and deletes the record.
31
+ *
32
+ * **Under `provider_page`** (the account host's `/zpravy`, §6.4) there is no `me/get` and no grant path: every load
33
+ * starts with the hand-off (handoff.ts), the record is keyed by the hand-off's `memberRef`, and the refresh token is
34
+ * kept in this tab's `sessionStorage` only, never in IndexedDB. A sign-out on the site therefore ends the private view
35
+ * at the next load, and the next person on a shared browser never reaches the previous member's session. A load that
36
+ * finds this tab's previous refresh token ends that session before it opens the new one, so reloading the page does not
37
+ * leave one live session per load behind.
38
+ *
39
+ * Nothing here logs, tracks or reports: the private entry imports no error tracker, analytics or RUM (§9.3).
40
+ */
41
+
42
+ import type { CommunityApiCode } from '../outcome'
43
+ import { assertPrivateBrowser } from './browser'
44
+ import { createDpopClock, signDpopProof, type DpopClock } from './dpop'
45
+ import { randomBase64url } from './encoding'
46
+ import { isUnboundRecordId, privateRecordId, unboundRecordId, createPrivateKeystore, type PrivateKeyRecord, type PrivateKeystore, type PrivateRendering } from './keystore'
47
+ import { PRIVATE_BASE_PATH, PRIVATE_TIMEOUT_MS, PrivateTransportError, createPrivateTransport, kbOriginOf, privateBaseOf, type PrivateTransport } from './transport'
48
+
49
+ assertPrivateBrowser()
50
+
51
+ // ───────────────────────── outcomes ─────────────────────────
52
+
53
+ /** The SDK's own codes besides kb-api's (`CommunityApiCode`, `UNKNOWN_PATH`). */
54
+ export type PrivateClientCode =
55
+ /** The host has no member session (tenant rendering): sign in on the site first. */
56
+ | 'NO_MEMBER'
57
+ /** `provider_page`: no session in this tab — the page starts the hand-off. */
58
+ | 'HANDOFF_REQUIRED'
59
+ /** `provider_page`: the hand-off's fragment is not the one this tab started (a foreign `state`, a stale link). */
60
+ | 'HANDOFF_INVALID'
61
+ /** `provider_page`: the hand-off named another member; the page navigated to repeat it with that member's key. */
62
+ | 'HANDOFF_REPEATED'
63
+ /** No answer: the network, a timeout, a refused redirect, CORS. */
64
+ | 'NETWORK'
65
+ /** An answer that is not kb-api's or the host's (a gateway's page, a malformed grant). */
66
+ | 'BAD_ANSWER'
67
+
68
+ export type PrivateCode = CommunityApiCode | 'UNKNOWN_PATH' | PrivateClientCode
69
+
70
+ export interface PrivateFailure {
71
+ ok: false
72
+ code: PrivateCode
73
+ /** The HTTP status, or null when there was none. */
74
+ status: number | null
75
+ }
76
+
77
+ /** What every private call resolves to; nothing here throws on a refusal. */
78
+ export type PrivateOutcome<T> = { ok: true; value: T } | PrivateFailure
79
+
80
+ const fail = (code: PrivateCode, status: number | null = null): PrivateFailure => ({ ok: false, code, status })
81
+
82
+ /** What `private/session` says of the device, the address and the activation (§5.9). */
83
+ export interface PrivateSessionOpened {
84
+ readonly device: { readonly state: 'first' | 'pending' | 'approved'; readonly label: string | null }
85
+ readonly address: { readonly state: 'none' | 'pending' | 'verified' }
86
+ /**
87
+ * kb-api's activation vocabulary (`ActivationStateValue` of PS4's activation service), the same values as the
88
+ * client's `PrivateActivation['state']`: one field, one set of values, whichever route answers it.
89
+ */
90
+ readonly activation: { readonly state: 'active' | 'needed' | 'refused' }
91
+ }
92
+
93
+ /** `ensureSession()`'s value: whether this call opened a new session (then with its answer) or reused one. */
94
+ export type PrivateSessionInfo = { readonly opened: false } | ({ readonly opened: true } & PrivateSessionOpened)
95
+
96
+ // ───────────────────────── configuration ─────────────────────────
97
+
98
+ /** The part of the Web Locks API the session uses. */
99
+ export interface PrivateLocks {
100
+ request<T>(name: string, callback: () => Promise<T>): Promise<T>
101
+ }
102
+
103
+ /** The part of BroadcastChannel the session uses. */
104
+ export interface PrivateChannel {
105
+ postMessage(message: unknown): void
106
+ addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void
107
+ close(): void
108
+ }
109
+
110
+ export interface PrivateSessionConfig {
111
+ /** kb-api's public origin (`https://<slug>.blogmcp.ai`): the key's scope and the only origin a private base may have. */
112
+ kbOrigin: string
113
+ /** `tenant` (default) or `provider_page` (the account host's `/zpravy`). */
114
+ rendering?: PrivateRendering
115
+ /** Tenant rendering: the host's grant route on its own origin (`/komunita/grant`, `/blog/community/grant`). */
116
+ grantPath?: string
117
+ /**
118
+ * Tenant rendering: the host's current member id (`me/get`'s `member.memberId`), or null without a member session.
119
+ * Read on every `ensureSession()` and by `start()`.
120
+ */
121
+ member?: () => Promise<string | null>
122
+ /** The fetch for kb-api and the host's grant route (a test stub; default the page's fetch). */
123
+ fetch?: () => typeof fetch
124
+ /** Default `navigator.locks`; without it an in-tab mutex (Safari before 15.4). */
125
+ locks?: PrivateLocks
126
+ /** Default `new BroadcastChannel(name)`; null turns the sharing between tabs off. */
127
+ channel?: ((name: string) => PrivateChannel) | null
128
+ indexedDB?: () => IDBFactory
129
+ sessionStorage?: () => Storage
130
+ /** Default `navigator.storage.persist()`. */
131
+ persist?: () => Promise<boolean>
132
+ /** This browser's push endpoint, for `push/unsubscribe` of another member's device (default the service worker's). */
133
+ pushEndpoint?: () => Promise<string | null>
134
+ now?: () => number
135
+ timeoutMs?: number
136
+ /** How long a tab without a token waits for another tab's answer before it refreshes (default 40 ms). */
137
+ askWaitMs?: number
138
+ /** `provider_page`: navigate the tab (default `location.assign`). */
139
+ navigate?: (url: string) => void
140
+ }
141
+
142
+ /** Refresh when less than this is left of an access token (it lives 600 s). */
143
+ export const PRIVATE_REFRESH_MARGIN_MS = 60_000
144
+
145
+ /** The `sessionStorage` keys under `provider_page`. */
146
+ export const PRIVATE_SESSION_STORAGE = Object.freeze({
147
+ refreshPrefix: 'blogmcp-private-refresh:',
148
+ current: 'blogmcp-private-current',
149
+ handoff: 'blogmcp-private-handoff',
150
+ })
151
+
152
+ const GRANT_RE = /^kbpg_[A-Za-z0-9_-]{16,256}$/
153
+ const ACCESS_RE = /^kbpa_[A-Za-z0-9_-]{16,256}$/
154
+ const REFRESH_RE = /^kbpr_[A-Za-z0-9_-]{16,256}$/
155
+ const MEMBER_REF_RE = /^[A-Za-z0-9_-]{16,64}$/
156
+ const STATE_RE = /^[A-Za-z0-9_-]{32,128}$/
157
+ /** A refusal code as kb-api and the hand-off route spell them. */
158
+ const CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
159
+ /** A path on the host's own origin: one leading `/`, no `//`, no backslash, query or fragment. */
160
+ const SITE_PATH_RE = /^\/(?![/\\])[^\s\\?#]*$/
161
+
162
+ /** The lock and channel name of one member's key (the record id is already a hash). */
163
+ export const privateLockName = (recordId: string): string => `blogmcp-private-${recordId}`
164
+
165
+ interface AccessToken {
166
+ jkt: string
167
+ token: string
168
+ /** Local epoch ms. */
169
+ exp: number
170
+ }
171
+
172
+ interface Signed {
173
+ status: number | null
174
+ body: Record<string, unknown> | null
175
+ code: PrivateCode | null
176
+ }
177
+
178
+ interface GrantAnswer {
179
+ grant: string
180
+ privateBase: string
181
+ dpopNonce: unknown
182
+ serverTime: unknown
183
+ }
184
+
185
+ /** An in-tab mutex per name, for a browser without the Web Locks API. */
186
+ function localLocks(): PrivateLocks {
187
+ const tails = new Map<string, Promise<unknown>>()
188
+ return {
189
+ request(name, callback) {
190
+ const prev = tails.get(name) ?? Promise.resolve()
191
+ const run = prev.then(callback, callback)
192
+ tails.set(name, run.catch(() => undefined))
193
+ return run
194
+ },
195
+ }
196
+ }
197
+
198
+ function defaultLocks(): PrivateLocks {
199
+ const nav = (globalThis as { navigator?: { locks?: { request?: unknown } } }).navigator
200
+ const locks = nav?.locks
201
+ if (locks && typeof locks.request === 'function') {
202
+ return { request: (name, cb) => (locks as unknown as PrivateLocks).request(name, cb) }
203
+ }
204
+ return localLocks()
205
+ }
206
+
207
+ async function defaultPushEndpoint(): Promise<string | null> {
208
+ try {
209
+ const sw = (globalThis as { navigator?: Navigator }).navigator?.serviceWorker
210
+ if (!sw) return null
211
+ const reg = await sw.getRegistration()
212
+ const sub = reg ? await reg.pushManager.getSubscription() : null
213
+ return sub?.endpoint ?? null
214
+ } catch {
215
+ return null
216
+ }
217
+ }
218
+
219
+ const isRecordObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
220
+
221
+ /** The answer's code: kb-api's `code`, the unknown-path answer by its status, else BAD_ANSWER. */
222
+ function codeOfAnswer(status: number, body: Record<string, unknown> | null): PrivateCode | null {
223
+ if (status === 200 && body?.ok === true) return null
224
+ if (body && typeof body.code === 'string' && CODE_RE.test(body.code)) return body.code as PrivateCode
225
+ return status === 404 ? 'UNKNOWN_PATH' : 'BAD_ANSWER'
226
+ }
227
+
228
+ /** An answer's data without the envelope (`ok`, `serverTime`). */
229
+ function dataOf(body: Record<string, unknown>): Record<string, unknown> {
230
+ const { ok: _ok, serverTime: _time, ...rest } = body
231
+ return rest
232
+ }
233
+
234
+ export interface PrivateSession {
235
+ readonly kbOrigin: string
236
+ readonly rendering: PrivateRendering
237
+ /** A usable access token for this tab (refreshed or granted when needed). */
238
+ ensureSession(): Promise<PrivateOutcome<PrivateSessionInfo>>
239
+ /** One private operation with this session: the recovery rule and the proof's retries applied. */
240
+ call<T = Record<string, unknown>>(op: string, body?: Record<string, unknown>): Promise<PrivateOutcome<T>>
241
+ /**
242
+ * `push/unsubscribe` and `session/end`, then the refresh token deleted; the key stays (it is this member's device).
243
+ * Safe before or after the host ends its own session: without a host member it ends the record this tab used and
244
+ * every stored tenant session.
245
+ */
246
+ privateSignOut(): Promise<PrivateOutcome<null>>
247
+ /** `devices/forget`, then the record deleted (key and refresh token). */
248
+ forget(): Promise<PrivateOutcome<null>>
249
+ /** The host-session check (tenant rendering): ends every stored session that is not the host's current member's. */
250
+ start(): Promise<PrivateOutcome<{ ended: number }>>
251
+ /** After an activation: ask the browser to keep this origin's storage (fewer lapses into a new pending device). */
252
+ activated(): Promise<boolean>
253
+ /** `provider_page`: navigate to the site's hand-off route with this tab's key (see handoff.ts). */
254
+ beginHandoff(handoffUrl: string): Promise<PrivateOutcome<null>>
255
+ /** `provider_page`: read the hand-off's fragment and open the session (see handoff.ts). */
256
+ completeHandoff(hash: string, handoffUrl: string): Promise<PrivateOutcome<PrivateSessionInfo>>
257
+ /** For tests and the elements: the current record's thumbprint, or null. */
258
+ currentJkt(): Promise<string | null>
259
+ /** Stop listening on the channels (an unmounted view). */
260
+ close(): void
261
+ }
262
+
263
+ export function createPrivateSession(config: PrivateSessionConfig): PrivateSession {
264
+ const kbOrigin = kbOriginOf(config?.kbOrigin)
265
+ if (kbOrigin === null) throw new TypeError('[blogmcp-sdk] createPrivateSession needs kbOrigin: kb-api’s https origin, e.g. https://tenant.blogmcp.ai')
266
+ const rendering: PrivateRendering = config.rendering === 'provider_page' ? 'provider_page' : 'tenant'
267
+ if (rendering === 'tenant') {
268
+ if (typeof config.grantPath !== 'string' || !SITE_PATH_RE.test(config.grantPath)) {
269
+ throw new TypeError('[blogmcp-sdk] createPrivateSession needs grantPath: the host’s grant route on its own origin, e.g. /komunita/grant')
270
+ }
271
+ if (typeof config.member !== 'function') throw new TypeError('[blogmcp-sdk] createPrivateSession needs member(): the host’s current member id')
272
+ }
273
+ const now = config.now ?? Date.now
274
+ const keystore: PrivateKeystore = createPrivateKeystore({ kbOrigin, indexedDB: config.indexedDB, now })
275
+ const transport: PrivateTransport = createPrivateTransport({ fetch: config.fetch, timeoutMs: config.timeoutMs })
276
+ const fetchFn = (): typeof fetch => (typeof config.fetch === 'function' ? config.fetch() : globalThis.fetch)
277
+ const locks = config.locks ?? defaultLocks()
278
+ const channelFactory =
279
+ config.channel === null
280
+ ? null
281
+ : (config.channel ?? (typeof BroadcastChannel === 'function' ? (name: string) => new BroadcastChannel(name) as unknown as PrivateChannel : null))
282
+ const storage = (): Storage | null => {
283
+ try {
284
+ return config.sessionStorage ? config.sessionStorage() : (globalThis.sessionStorage ?? null)
285
+ } catch {
286
+ return null
287
+ }
288
+ }
289
+ const askWaitMs = config.askWaitMs ?? 40
290
+ const clock: DpopClock = createDpopClock(now)
291
+
292
+ /** Access tokens by record id: this tab's own and the newest another tab announced. */
293
+ const tokens = new Map<string, AccessToken>()
294
+ const channels = new Map<string, PrivateChannel>()
295
+ const asked = new Set<string>()
296
+ /** `provider_page`: the record the hand-off selected for this tab. */
297
+ let currentId: string | null = null
298
+ /** Tenant rendering: the record this tab last used, so a sign-out after the host's own still finds it. */
299
+ let lastTenantId: string | null = null
300
+
301
+ const usable = (t: AccessToken | undefined, jkt: string): t is AccessToken => !!t && t.jkt === jkt && t.exp - now() > PRIVATE_REFRESH_MARGIN_MS
302
+
303
+ function keepToken(recordId: string, t: AccessToken): void {
304
+ const held = tokens.get(recordId)
305
+ if (!held || held.jkt !== t.jkt || held.exp < t.exp) tokens.set(recordId, t)
306
+ }
307
+
308
+ function channelOf(recordId: string): PrivateChannel | null {
309
+ if (!channelFactory) return null
310
+ let ch = channels.get(recordId)
311
+ if (ch) return ch
312
+ try {
313
+ ch = channelFactory(privateLockName(recordId))
314
+ } catch {
315
+ return null
316
+ }
317
+ ch.addEventListener('message', (event) => {
318
+ const m = event.data as { t?: unknown; jkt?: unknown; token?: unknown; exp?: unknown }
319
+ if (!isRecordObject(m)) return
320
+ if (m.t === 'token' && typeof m.jkt === 'string' && typeof m.token === 'string' && ACCESS_RE.test(m.token) && typeof m.exp === 'number') {
321
+ keepToken(recordId, { jkt: m.jkt, token: m.token, exp: m.exp })
322
+ } else if (m.t === 'ask' && typeof m.jkt === 'string') {
323
+ const t = tokens.get(recordId)
324
+ if (usable(t, m.jkt)) ch!.postMessage({ t: 'token', jkt: t.jkt, token: t.token, exp: t.exp })
325
+ } else if (m.t === 'gone') {
326
+ tokens.delete(recordId)
327
+ }
328
+ })
329
+ channels.set(recordId, ch)
330
+ return ch
331
+ }
332
+
333
+ function announce(recordId: string, t: AccessToken): void {
334
+ channelOf(recordId)?.postMessage({ t: 'token', jkt: t.jkt, token: t.token, exp: t.exp })
335
+ }
336
+
337
+ function announceGone(recordId: string): void {
338
+ tokens.delete(recordId)
339
+ channelOf(recordId)?.postMessage({ t: 'gone' })
340
+ }
341
+
342
+ /** Once per tab and member: ask the other tabs for their token, and give their answers a moment. */
343
+ async function askOtherTabs(record: PrivateKeyRecord): Promise<void> {
344
+ const ch = channelOf(record.id)
345
+ if (!ch || asked.has(record.id)) return
346
+ asked.add(record.id)
347
+ ch.postMessage({ t: 'ask', jkt: record.jkt })
348
+ await new Promise((resolve) => setTimeout(resolve, askWaitMs))
349
+ }
350
+
351
+ // ── the refresh token's home: the record (tenant) or this tab's sessionStorage (provider_page) ──
352
+
353
+ function refreshTokenOf(record: PrivateKeyRecord): string | null {
354
+ if (record.rendering === 'tenant') return record.refreshToken
355
+ const value = storage()?.getItem(PRIVATE_SESSION_STORAGE.refreshPrefix + record.id) ?? null
356
+ return value !== null && REFRESH_RE.test(value) ? value : null
357
+ }
358
+
359
+ async function setRefreshToken(record: PrivateKeyRecord, refreshToken: string | null, privateBase?: string): Promise<PrivateKeyRecord> {
360
+ let next: PrivateKeyRecord = { ...record, usedAt: now(), ...(privateBase !== undefined ? { privateBase } : {}) }
361
+ if (record.rendering === 'tenant') next = { ...next, refreshToken }
362
+ else {
363
+ const s = storage()
364
+ if (refreshToken === null) s?.removeItem(PRIVATE_SESSION_STORAGE.refreshPrefix + record.id)
365
+ else s?.setItem(PRIVATE_SESSION_STORAGE.refreshPrefix + record.id, refreshToken)
366
+ next = { ...next, refreshToken: null }
367
+ }
368
+ await keystore.put(next)
369
+ return next
370
+ }
371
+
372
+ // ── signed requests ──
373
+
374
+ /** One private operation, signed; the nonce retry and the clock retry, once each. */
375
+ async function signed(record: PrivateKeyRecord, base: string, op: string, body: unknown, accessToken: string | null): Promise<Signed> {
376
+ let nonceRetried = false
377
+ let clockRetried = false
378
+ const htu = `${base}/${op}`
379
+ for (;;) {
380
+ const proof = await signDpopProof({
381
+ privateKey: record.keyPair.privateKey,
382
+ jwk: record.publicJwk,
383
+ htm: 'POST',
384
+ htu,
385
+ nonce: clock.nonce(kbOrigin!, record.jkt),
386
+ accessToken,
387
+ iat: clock.iat(),
388
+ })
389
+ const headers: Record<string, string> = { DPoP: proof }
390
+ if (accessToken) headers.Authorization = `DPoP ${accessToken}`
391
+ let answer
392
+ try {
393
+ answer = await transport(base, kbOrigin!, op, body, headers)
394
+ } catch (err) {
395
+ return { status: null, body: null, code: err instanceof PrivateTransportError && err.reason === 'refused_base' ? 'BAD_ANSWER' : 'NETWORK' }
396
+ }
397
+ clock.setNonce(kbOrigin!, record.jkt, answer.nonce)
398
+ const clockWasOff = clock.observe(answer.body?.serverTime)
399
+ const code = codeOfAnswer(answer.status, answer.body)
400
+ if (code === 'DPOP_NONCE' && !nonceRetried) {
401
+ nonceRetried = true
402
+ continue
403
+ }
404
+ if (code === 'DPOP_INVALID' && clockWasOff && !clockRetried) {
405
+ clockRetried = true
406
+ continue
407
+ }
408
+ return { status: answer.status, body: answer.body, code }
409
+ }
410
+ }
411
+
412
+ // ── the record of the current member ──
413
+
414
+ /**
415
+ * The current member's record as stored, without making one: null when this browser holds no key for them.
416
+ * Signing out, forgetting and reading the thumbprint use this, so they never leave a fresh key in IndexedDB (or,
417
+ * through a grant, a new pending device on kb-api) for a member who never opened the private view.
418
+ */
419
+ async function storedRecord(): Promise<PrivateOutcome<{ id: string; record: PrivateKeyRecord | null }>> {
420
+ if (rendering === 'provider_page') {
421
+ const id = currentId
422
+ const record = id ? await keystore.get(id) : null
423
+ return record ? { ok: true, value: { id: record.id, record } } : fail('HANDOFF_REQUIRED')
424
+ }
425
+ let memberId: string | null
426
+ try {
427
+ memberId = await config.member!()
428
+ } catch {
429
+ return fail('NETWORK')
430
+ }
431
+ if (typeof memberId !== 'string' || memberId === '') return fail('NO_MEMBER')
432
+ const id = await privateRecordId(kbOrigin!, memberId)
433
+ const record = await keystore.get(id)
434
+ if (record) lastTenantId = record.id
435
+ return { ok: true, value: { id, record } }
436
+ }
437
+
438
+ /** The current member's record, made when missing: only a session or a call needs a key to exist. */
439
+ async function currentRecord(): Promise<PrivateOutcome<PrivateKeyRecord>> {
440
+ const stored = await storedRecord()
441
+ if (!stored.ok) return stored
442
+ if (stored.value.record !== null) return { ok: true, value: stored.value.record }
443
+ // Only tenant rendering gets here: provider_page answers HANDOFF_REQUIRED without a record.
444
+ const id = stored.value.id
445
+ // A new key is made under the member's lock: two tabs opening at once must not each make one and overwrite.
446
+ const record = await locks.request(privateLockName(id), async () => (await keystore.get(id)) ?? keystore.create(id, 'tenant'))
447
+ lastTenantId = record.id
448
+ return { ok: true, value: record }
449
+ }
450
+
451
+ async function reread(record: PrivateKeyRecord): Promise<PrivateKeyRecord> {
452
+ return (await keystore.get(record.id)) ?? (await keystore.create(record.id, record.rendering))
453
+ }
454
+
455
+ /** A removed device: forget its key, its tokens and its nonce; a new key under the same id (a new, pending device). */
456
+ async function replaceKey(record: PrivateKeyRecord): Promise<PrivateKeyRecord> {
457
+ clock.forgetKey(record.jkt)
458
+ storage()?.removeItem(PRIVATE_SESSION_STORAGE.refreshPrefix + record.id)
459
+ announceGone(record.id)
460
+ return keystore.create(record.id, record.rendering)
461
+ }
462
+
463
+ // ── grant, open, refresh ──
464
+
465
+ async function requestGrant(record: PrivateKeyRecord): Promise<PrivateOutcome<GrantAnswer>> {
466
+ // The same timeout as the private transport: this request runs inside the member's lock, so a host route that
467
+ // never answers would otherwise hold every tab of the member. The signal covers the body as well as the headers.
468
+ const signal = AbortSignal.timeout(config.timeoutMs ?? PRIVATE_TIMEOUT_MS)
469
+ let res: Response
470
+ try {
471
+ res = await fetchFn()(config.grantPath!, {
472
+ method: 'POST',
473
+ headers: { 'Content-Type': 'application/json' },
474
+ body: JSON.stringify({ jkt: record.jkt }),
475
+ mode: 'same-origin',
476
+ credentials: 'same-origin',
477
+ redirect: 'error',
478
+ cache: 'no-store',
479
+ signal,
480
+ })
481
+ } catch {
482
+ return fail('NETWORK')
483
+ }
484
+ let body: Record<string, unknown> | null = null
485
+ try {
486
+ const value: unknown = await res.json()
487
+ body = isRecordObject(value) ? value : null
488
+ } catch {
489
+ body = null
490
+ }
491
+ const code = codeOfAnswer(res.status, body)
492
+ if (code !== null) return fail(code, res.status)
493
+ const privateBase = privateBaseOf(body!.privateBase, kbOrigin!)
494
+ if (typeof body!.grant !== 'string' || !GRANT_RE.test(body!.grant) || privateBase === null) return fail('BAD_ANSWER', res.status)
495
+ return { ok: true, value: { grant: body!.grant, privateBase, dpopNonce: body!.dpopNonce, serverTime: body!.serverTime } }
496
+ }
497
+
498
+ /** `private/session` with a grant; on DEVICE_REMOVED (tenant rendering) a new key and one more grant. */
499
+ async function openWithGrant(record: PrivateKeyRecord, grant: GrantAnswer, retried = false): Promise<PrivateOutcome<PrivateSessionInfo>> {
500
+ clock.observe(grant.serverTime)
501
+ clock.setNonce(kbOrigin!, record.jkt, grant.dpopNonce)
502
+ const out = await signed(record, grant.privateBase, 'session', { grant: grant.grant }, null)
503
+ if (out.code === 'DEVICE_REMOVED' && rendering === 'tenant' && !retried) {
504
+ const fresh = await replaceKey(record)
505
+ const again = await requestGrant(fresh)
506
+ return again.ok ? openWithGrant(fresh, again.value, true) : again
507
+ }
508
+ if (out.code !== null) {
509
+ if (out.code === 'DEVICE_REMOVED') await replaceKey(record)
510
+ return fail(out.code, out.status)
511
+ }
512
+ const b = out.body!
513
+ if (typeof b.accessToken !== 'string' || !ACCESS_RE.test(b.accessToken) || typeof b.refreshToken !== 'string' || !REFRESH_RE.test(b.refreshToken)) {
514
+ return fail('BAD_ANSWER', out.status)
515
+ }
516
+ const stored = await setRefreshToken(record, b.refreshToken, grant.privateBase)
517
+ const t: AccessToken = { jkt: stored.jkt, token: b.accessToken, exp: now() + expiresInMs(b.expiresIn) }
518
+ keepToken(stored.id, t)
519
+ announce(stored.id, t)
520
+ const data = dataOf(b)
521
+ return {
522
+ ok: true,
523
+ value: {
524
+ opened: true,
525
+ device: data.device as PrivateSessionOpened['device'],
526
+ address: data.address as PrivateSessionOpened['address'],
527
+ activation: data.activation as PrivateSessionOpened['activation'],
528
+ },
529
+ }
530
+ }
531
+
532
+ const expiresInMs = (value: unknown): number =>
533
+ typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 3600 ? value * 1000 : 600_000
534
+
535
+ /** A refresh with the record's refresh token: a new access token, or the failure (UNAUTHORIZED: the token is gone). */
536
+ async function refresh(record: PrivateKeyRecord): Promise<PrivateOutcome<AccessToken> | null> {
537
+ const refreshToken = refreshTokenOf(record)
538
+ if (refreshToken === null || record.privateBase === null) return null
539
+ const out = await signed(record, record.privateBase, 'session/refresh', { refreshToken }, null)
540
+ if (out.code === 'UNAUTHORIZED') {
541
+ await setRefreshToken(record, null)
542
+ return fail('UNAUTHORIZED', out.status)
543
+ }
544
+ if (out.code === 'DEVICE_REMOVED') {
545
+ await replaceKey(record)
546
+ return fail('DEVICE_REMOVED', out.status)
547
+ }
548
+ if (out.code !== null) return fail(out.code, out.status)
549
+ const token = out.body!.accessToken
550
+ if (typeof token !== 'string' || !ACCESS_RE.test(token)) return fail('BAD_ANSWER', out.status)
551
+ const t: AccessToken = { jkt: record.jkt, token, exp: now() + expiresInMs(out.body!.expiresIn) }
552
+ keepToken(record.id, t)
553
+ announce(record.id, t)
554
+ return { ok: true, value: t }
555
+ }
556
+
557
+ /**
558
+ * Inside the lock: another tab's token, else a refresh, else (tenant rendering, and only when the refresh is
559
+ * impossible or answered UNAUTHORIZED) one grant. `notToken`: a token a call just had refused.
560
+ */
561
+ async function obtain(record0: PrivateKeyRecord, notToken: string | null): Promise<PrivateOutcome<{ record: PrivateKeyRecord; token: AccessToken; info: PrivateSessionInfo }>> {
562
+ let record = await reread(record0)
563
+ const held = tokens.get(record.id)
564
+ if (usable(held, record.jkt) && held.token !== notToken) return { ok: true, value: { record, token: held, info: { opened: false } } }
565
+ if (!tokens.has(record.id)) {
566
+ await askOtherTabs(record)
567
+ const shared = tokens.get(record.id)
568
+ if (usable(shared, record.jkt) && shared.token !== notToken) return { ok: true, value: { record, token: shared, info: { opened: false } } }
569
+ }
570
+ const refreshed = await refresh(record)
571
+ if (refreshed?.ok) return { ok: true, value: { record, token: refreshed.value, info: { opened: false } } }
572
+ if (refreshed && refreshed.code !== 'UNAUTHORIZED' && refreshed.code !== 'DEVICE_REMOVED') return refreshed
573
+ if (rendering === 'provider_page') return fail('HANDOFF_REQUIRED')
574
+ record = await reread(record)
575
+ const grant = await requestGrant(record)
576
+ if (!grant.ok) return grant
577
+ const opened = await openWithGrant(record, grant.value)
578
+ if (!opened.ok) return opened
579
+ record = await reread(record)
580
+ const t = tokens.get(record.id)
581
+ if (!usable(t, record.jkt)) return fail('BAD_ANSWER')
582
+ return { ok: true, value: { record, token: t, info: opened.value } }
583
+ }
584
+
585
+ async function session(notToken: string | null = null): Promise<PrivateOutcome<{ record: PrivateKeyRecord; token: AccessToken; info: PrivateSessionInfo }>> {
586
+ const current = await currentRecord()
587
+ if (!current.ok) return current
588
+ const held = tokens.get(current.value.id)
589
+ if (notToken === null && usable(held, current.value.jkt) && current.value.privateBase !== null) {
590
+ return { ok: true, value: { record: current.value, token: held, info: { opened: false } } }
591
+ }
592
+ return locks.request(privateLockName(current.value.id), () => obtain(current.value, notToken))
593
+ }
594
+
595
+ async function call<T>(op: string, body: Record<string, unknown> = {}): Promise<PrivateOutcome<T>> {
596
+ let s = await session()
597
+ if (!s.ok) return s
598
+ let out = await signed(s.value.record, s.value.record.privateBase!, op, body, s.value.token.token)
599
+ if (out.code === 'UNAUTHORIZED') {
600
+ // The recovery rule: one refresh under the lock (or a newer token of another tab); a grant only if that fails.
601
+ tokens.delete(s.value.record.id)
602
+ s = await session(s.value.token.token)
603
+ if (!s.ok) return s
604
+ out = await signed(s.value.record, s.value.record.privateBase!, op, body, s.value.token.token)
605
+ }
606
+ if (out.code === 'DEVICE_REMOVED') await replaceKey(s.value.record)
607
+ if (out.code !== null) return fail(out.code, out.status)
608
+ return { ok: true, value: dataOf(out.body!) as T }
609
+ }
610
+
611
+ /**
612
+ * End one record's session with what it holds (no grant): push unsubscribed first when asked, refresh token deleted.
613
+ * The caller holds the member's lock (Web Locks are not re-entrant, so this never takes it itself).
614
+ */
615
+ async function endHeld(record0: PrivateKeyRecord, unsubscribePush: boolean): Promise<boolean> {
616
+ const record = await reread(record0)
617
+ let ended = false
618
+ try {
619
+ let t = tokens.get(record.id)
620
+ if (!usable(t, record.jkt)) {
621
+ const refreshed = await refresh(record)
622
+ t = refreshed?.ok ? refreshed.value : undefined
623
+ }
624
+ if (t && record.privateBase !== null) {
625
+ if (unsubscribePush) {
626
+ const endpoint = await (config.pushEndpoint ?? defaultPushEndpoint)()
627
+ if (typeof endpoint === 'string' && endpoint !== '') await signed(record, record.privateBase, 'push/unsubscribe', { endpoint }, t.token)
628
+ }
629
+ const out = await signed(record, record.privateBase, 'session/end', {}, t.token)
630
+ ended = out.code === null
631
+ }
632
+ } finally {
633
+ const latest = (await keystore.get(record.id)) ?? record
634
+ if (refreshTokenOf(latest) !== null) await setRefreshToken(latest, null)
635
+ announceGone(record.id)
636
+ }
637
+ return ended
638
+ }
639
+
640
+ /** `endHeld` under the member's lock. */
641
+ async function endRecord(record: PrivateKeyRecord, unsubscribePush: boolean): Promise<boolean> {
642
+ return locks.request(privateLockName(record.id), () => endHeld(record, unsubscribePush))
643
+ }
644
+
645
+ return {
646
+ kbOrigin,
647
+ rendering,
648
+ async ensureSession() {
649
+ const s = await session()
650
+ return s.ok ? { ok: true, value: s.value.info } : s
651
+ },
652
+ call,
653
+ async privateSignOut() {
654
+ // The private push goes too: after a sign-out the browser's shared push endpoint must stop pinging for this
655
+ // member (the next member's start() cannot do it once the refresh token is gone); the private view re-posts its
656
+ // subscription on its next start (B-55).
657
+ // Read only: a member without a key in this browser has no private session to end, and signing out must not
658
+ // make one.
659
+ const current = await storedRecord()
660
+ if (current.ok) {
661
+ if (current.value.record !== null) await endRecord(current.value.record, true)
662
+ return { ok: true, value: null }
663
+ }
664
+ if (rendering === 'provider_page') return current.code === 'HANDOFF_REQUIRED' ? { ok: true, value: null } : current
665
+ // The host's member is gone (its own sign-out ran first) or unreadable: end the record this tab used, and with no
666
+ // member at all every stored tenant session, as start() would on the next load. Signing out never needs to know
667
+ // who is signed in now.
668
+ const ids = new Set<string>(lastTenantId !== null ? [lastTenantId] : [])
669
+ if (current.code === 'NO_MEMBER') {
670
+ for (const record of await keystore.list()) if (record.rendering === 'tenant' && record.refreshToken !== null) ids.add(record.id)
671
+ }
672
+ if (ids.size === 0) return current.code === 'NO_MEMBER' ? { ok: true, value: null } : current
673
+ for (const id of ids) {
674
+ const record = await keystore.get(id)
675
+ if (record) await endRecord(record, true)
676
+ }
677
+ lastTenantId = null
678
+ return { ok: true, value: null }
679
+ },
680
+ async forget() {
681
+ const current = await storedRecord()
682
+ if (!current.ok) return current
683
+ const record = current.value.record
684
+ if (record === null) {
685
+ // No key in this browser: kb-api knows no device of it to forget, and a grant here would register one first.
686
+ storage()?.removeItem(PRIVATE_SESSION_STORAGE.refreshPrefix + current.value.id)
687
+ tokens.delete(current.value.id)
688
+ return { ok: true, value: null }
689
+ }
690
+ const out = await call('devices/forget', {})
691
+ clock.forgetKey(record.jkt)
692
+ storage()?.removeItem(PRIVATE_SESSION_STORAGE.refreshPrefix + record.id)
693
+ await keystore.delete(record.id)
694
+ announceGone(record.id)
695
+ if (rendering === 'provider_page') currentId = null
696
+ return out.ok ? { ok: true, value: null } : out
697
+ },
698
+ async start() {
699
+ if (rendering !== 'tenant') return { ok: true, value: { ended: 0 } }
700
+ let memberId: string | null
701
+ try {
702
+ memberId = await config.member!()
703
+ } catch {
704
+ return fail('NETWORK')
705
+ }
706
+ const currentRecordId = typeof memberId === 'string' && memberId !== '' ? await privateRecordId(kbOrigin, memberId) : null
707
+ let ended = 0
708
+ for (const record of await keystore.list()) {
709
+ if (record.rendering !== 'tenant' || record.id === currentRecordId || record.refreshToken === null) continue
710
+ if (await endRecord(record, true)) ended++
711
+ }
712
+ return { ok: true, value: { ended } }
713
+ },
714
+ async activated() {
715
+ try {
716
+ const persist = config.persist ?? (() => (globalThis as { navigator?: Navigator }).navigator?.storage?.persist?.() ?? Promise.resolve(false))
717
+ return await persist()
718
+ } catch {
719
+ return false
720
+ }
721
+ },
722
+ async beginHandoff(handoffUrl) {
723
+ return beginHandoff(handoffUrl, false)
724
+ },
725
+ async completeHandoff(hash, handoffUrl) {
726
+ return completeHandoff(hash, handoffUrl)
727
+ },
728
+ async currentJkt() {
729
+ if (rendering === 'provider_page') return currentId ? ((await keystore.get(currentId))?.jkt ?? null) : null
730
+ const r = await storedRecord()
731
+ return r.ok ? (r.value.record?.jkt ?? null) : null
732
+ },
733
+ close() {
734
+ for (const ch of channels.values()) ch.close()
735
+ channels.clear()
736
+ },
737
+ }
738
+
739
+ // ───────────────────────── the hand-off (provider_page, §6.4) ─────────────────────────
740
+
741
+ function handoffTarget(handoffUrl: string): string | null {
742
+ try {
743
+ const url = new URL(handoffUrl)
744
+ if ((url.protocol !== 'https:' && url.protocol !== 'http:') || url.search || url.hash || url.username || url.password) return null
745
+ return url.href
746
+ } catch {
747
+ return null
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Navigate to the site's hand-off route with a key of this browser: the one this tab used last, else the most
753
+ * recently used `provider_page` key, else a new key bound to nobody yet. The `state` is random and kept in this
754
+ * tab's sessionStorage; the fragment that comes back must carry it.
755
+ */
756
+ async function beginHandoff(handoffUrl: string, repeat: boolean, preferId: string | null = null): Promise<PrivateOutcome<null>> {
757
+ if (rendering !== 'provider_page') return fail('HANDOFF_INVALID')
758
+ const target = handoffTarget(handoffUrl)
759
+ const s = storage()
760
+ if (target === null || s === null) return fail('HANDOFF_INVALID')
761
+ const records = (await keystore.list()).filter((r) => r.rendering === 'provider_page')
762
+ const wanted = preferId ?? currentId ?? s.getItem(PRIVATE_SESSION_STORAGE.current)
763
+ let record = records.find((r) => r.id === wanted) ?? [...records].sort((a, b) => b.usedAt - a.usedAt)[0]
764
+ record ??= await keystore.create(unboundRecordId(), 'provider_page')
765
+ const state = randomBase64url(32)
766
+ s.setItem(PRIVATE_SESSION_STORAGE.handoff, JSON.stringify({ state, recordId: record.id, jkt: record.jkt, repeat }))
767
+ const url = new URL(target)
768
+ url.searchParams.set('jkt', record.jkt)
769
+ url.searchParams.set('state', state)
770
+ ;(config.navigate ?? ((u: string) => globalThis.location.assign(u)))(url.href)
771
+ return { ok: true, value: null }
772
+ }
773
+
774
+ async function completeHandoff(hash: string, handoffUrl: string): Promise<PrivateOutcome<PrivateSessionInfo>> {
775
+ if (rendering !== 'provider_page') return fail('HANDOFF_INVALID')
776
+ const s = storage()
777
+ const raw = typeof hash === 'string' ? hash.replace(/^#/, '') : ''
778
+ const params = new URLSearchParams(raw)
779
+ // The fragment leaves the address bar at once, whatever it holds.
780
+ try {
781
+ const loc = globalThis.location
782
+ if (loc && raw !== '') globalThis.history?.replaceState(null, '', `${loc.pathname}${loc.search}`)
783
+ } catch {
784
+ // A page without history (a test) keeps going.
785
+ }
786
+ const pendingText = s?.getItem(PRIVATE_SESSION_STORAGE.handoff) ?? null
787
+ s?.removeItem(PRIVATE_SESSION_STORAGE.handoff)
788
+ const pending = pendingHandoffOf(pendingText)
789
+ const state = params.get('state')
790
+ const grant = params.get('grant')
791
+ const memberRef = params.get('memberRef')
792
+ const error = params.get('error')
793
+ if (!pending || typeof pending.state !== 'string' || state === null || !STATE_RE.test(state) || state !== pending.state) return fail('HANDOFF_INVALID')
794
+ // The hand-off route's refusal (no session on the site, PRIVATE_IDENTITY, ACTIVATION_REQUIRED, …): its code, once
795
+ // the state shows this tab started it, so the account page can say what to do.
796
+ if (grant === null && error !== null && CODE_RE.test(error)) return fail(error as PrivateCode)
797
+ if (grant === null || !GRANT_RE.test(grant) || memberRef === null || !MEMBER_REF_RE.test(memberRef) || typeof pending.recordId !== 'string') {
798
+ return fail('HANDOFF_INVALID')
799
+ }
800
+ const sent = await keystore.get(pending.recordId)
801
+ if (!sent || sent.jkt !== pending.jkt) return fail('HANDOFF_INVALID')
802
+ const targetId = await privateRecordId(kbOrigin!, memberRef)
803
+ let record: PrivateKeyRecord
804
+ if (sent.id === targetId) record = sent
805
+ else if (isUnboundRecordId(sent.id) && !(await keystore.get(targetId))) {
806
+ // A key made before the member was known: it is now this member's (the grant is for its jkt).
807
+ record = { ...sent, id: targetId }
808
+ await keystore.put(record)
809
+ await keystore.delete(sent.id)
810
+ } else {
811
+ // The key sent was another member's (a shared browser): select or make this member's key, and repeat once.
812
+ if (pending.repeat === true) return fail('HANDOFF_INVALID')
813
+ // The previous member's session in this tab ends with their private push: the site now has another member.
814
+ if (refreshTokenOf(sent) !== null) await locks.request(privateLockName(sent.id), () => endHeld(sent, true))
815
+ const mine = (await keystore.get(targetId)) ?? (await keystore.create(targetId, 'provider_page'))
816
+ if (isUnboundRecordId(sent.id)) await keystore.delete(sent.id)
817
+ const again = await beginHandoff(handoffUrl, true, mine.id)
818
+ return again.ok ? fail('HANDOFF_REPEATED') : again
819
+ }
820
+ currentId = record.id
821
+ s?.setItem(PRIVATE_SESSION_STORAGE.current, record.id)
822
+ // The fragment carries no private base (§6.4 fixes its fields): the account page is kb-api's own, on the origin
823
+ // the page was configured with.
824
+ const privateBase = `${kbOrigin}${PRIVATE_BASE_PATH}`
825
+ const serverTime = Number(params.get('serverTime'))
826
+ return locks.request(privateLockName(record.id), async () => {
827
+ // A reload: this tab's previous session ends (best effort) before the grant opens a new one, or every load of
828
+ // the page would leave a live session behind until its 14-day lapse. The member is the same, so the push stays.
829
+ if (refreshTokenOf(record) !== null) {
830
+ await endHeld(record, false)
831
+ // That refresh may have learnt that the device was removed and replaced its key: the grant is for the old one.
832
+ if ((await keystore.get(record.id))?.jkt !== record.jkt) return fail('DEVICE_REMOVED')
833
+ }
834
+ return openWithGrant(record, { grant, privateBase, dpopNonce: params.get('dpopNonce'), serverTime: Number.isFinite(serverTime) ? serverTime : null })
835
+ })
836
+ }
837
+ }
838
+
839
+ /** The hand-off this tab started, as beginHandoff stored it, or null. */
840
+ function pendingHandoffOf(text: string | null): { state?: unknown; recordId?: unknown; jkt?: unknown; repeat?: unknown } | null {
841
+ if (text === null) return null
842
+ try {
843
+ const value: unknown = JSON.parse(text)
844
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
845
+ } catch {
846
+ return null
847
+ }
848
+ }