@prson/login-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1455 @@
1
+ import { boxToWallet, decryptEnvelope } from "./crypto.js";
2
+ import { verifyPresentation } from "./verify.js";
3
+ import { RequestController, } from "./requests.js";
4
+ /** RTT above this (ms) flips connectionStatus to `unstable`. */
5
+ const CONNECTION_UNSTABLE_THRESHOLD_MS = 1000;
6
+ /** No pong observed for this long (ms) flips status to `offline`. */
7
+ const CONNECTION_OFFLINE_AFTER_MS = 5000;
8
+ /** Cadence of the local ping loop (ms). */
9
+ const PING_INTERVAL_MS = 2000;
10
+ /** Delay before retransmitting an ack-required envelope (ms). */
11
+ const ACK_RETRY_DELAY_MS = 2000;
12
+ /** Maximum retransmissions before giving up on an ack-required envelope. */
13
+ const ACK_MAX_ATTEMPTS = 3;
14
+ /** LRU cap on the seen-id dedupe set. ~500 ids ≈ 16 min of pings
15
+ * on the 2 s loop, far longer than any realistic re-send window. */
16
+ const SEEN_IDS_CAPACITY = 500;
17
+ /**
18
+ * Generate a UUID v4. Browsers shipping `crypto.randomUUID` use it
19
+ * directly; older engines fall back to a `getRandomValues`-based
20
+ * implementation that produces the same on-the-wire shape.
21
+ */
22
+ /**
23
+ * Detach a timer handle from Node's "keep the event loop alive"
24
+ * accounting. In browsers `setTimeout` / `setInterval` return a
25
+ * number with no `unref` method, so the test is a harmless no-op.
26
+ * In Node the returned `Timeout` object has `unref()` and this is
27
+ * what stops unit tests from hanging until their hour-scale expiry
28
+ * timer would otherwise fire.
29
+ */
30
+ function _unrefTimer(t) {
31
+ if (t === null)
32
+ return;
33
+ const maybe = t;
34
+ if (typeof maybe.unref === "function")
35
+ maybe.unref();
36
+ }
37
+ /**
38
+ * Map a transport-layer close reason string onto the SDK's typed
39
+ * [ExpiryReason]. The transport emits a small vocabulary:
40
+ *
41
+ * * `"ttl_reached"` — Worker DO alarm fired at session TTL
42
+ * * `"wallet_signed_out"` — wallet sent a `peer-gone` signaling
43
+ * message (revoked) before the wire
44
+ * died
45
+ * * `"network_loss"` — anything else (signaling WS dropped
46
+ * for a transport reason, data channel
47
+ * closed on its own, etc.)
48
+ *
49
+ * Anything we don't recognise degrades to `network_loss` —
50
+ * preserving the host's invariant that a `signed_out` event always
51
+ * carries a known reason.
52
+ */
53
+ function _mapTransportCloseReason(reason) {
54
+ if (reason === "ttl_reached")
55
+ return "ttl_reached";
56
+ if (reason === "wallet_signed_out")
57
+ return "wallet_signed_out";
58
+ if (reason === "user_revoked")
59
+ return "user_revoked";
60
+ if (reason === "credential_revoked")
61
+ return "credential_revoked";
62
+ return "network_loss";
63
+ }
64
+ function uuidv4() {
65
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
66
+ return crypto.randomUUID();
67
+ }
68
+ const buf = new Uint8Array(16);
69
+ crypto.getRandomValues(buf);
70
+ buf[6] = (buf[6] & 0x0f) | 0x40; // version 4
71
+ buf[8] = (buf[8] & 0x3f) | 0x80; // variant 10
72
+ const h = [];
73
+ for (let i = 0; i < 16; i++)
74
+ h.push(buf[i].toString(16).padStart(2, "0"));
75
+ return (h.slice(0, 4).join("") +
76
+ "-" +
77
+ h.slice(4, 6).join("") +
78
+ "-" +
79
+ h.slice(6, 8).join("") +
80
+ "-" +
81
+ h.slice(8, 10).join("") +
82
+ "-" +
83
+ h.slice(10, 16).join(""));
84
+ }
85
+ export class PrsonLoginSession {
86
+ constructor(opts) {
87
+ this._expiryTimer = null;
88
+ this._closed = false;
89
+ /**
90
+ * Wallet's session X25519 public key, PINNED from the verified
91
+ * sign-in presentation (its KB-JWT `prson_wsk` claim, signed by the
92
+ * cnf key). Every inbound envelope must be boxed by this key or it is
93
+ * dropped, and every outbound one is boxed to it. It changes only when
94
+ * a verified `renewal` presentation carries a new `prson_wsk`. Null
95
+ * when the wallet published none — calls to `request()` then resolve
96
+ * with `{ ok: false, error: "no-active-session" }`.
97
+ */
98
+ this._walletSessionPk = null;
99
+ /**
100
+ * True when the sign-in presentation didn't bind a session key (a
101
+ * wallet older than envelope v2). The sender of inbound envelopes
102
+ * can't be checked then, so envelopes that act on the page (`nav`,
103
+ * `value`, `mouse-update`, file transfer) and request replies
104
+ * (`response`) are ignored, `request()` resolves with
105
+ * `{ ok: false, error: "unsupported" }` and no field values are sent
106
+ * (`focus`). Sign-in, renewals and claim updates (all verified
107
+ * presentations) and sign-out still work. See SECURITY.md §4.
108
+ */
109
+ this._legacyChannel = false;
110
+ /** `iat` of the newest verified presentation (sign-in or renewal).
111
+ * A renewal / claim-update must be strictly newer. */
112
+ this._lastPresentationIat = 0;
113
+ /** SHA-256 of every presentation this session accepted, so a replay
114
+ * of an earlier one (even with a still-fresh `iat`) is refused. */
115
+ this._seenPresentations = new Set();
116
+ /** Pairs outbound `request` envelopes with inbound `response`s. */
117
+ this._requestController = new RequestController();
118
+ /**
119
+ * Per-`requestId` mouse-update subscribers. Populated by
120
+ * [`bindMouse`] when it opens a `kind: "mouse"` request and torn
121
+ * down when the controller disposes or the wallet's final
122
+ * `response` arrives. Keys are RFC-4122 v4 UUIDs (the request id);
123
+ * values get a stream of decoded `mouse` bodies.
124
+ */
125
+ this._mouseSubscribers = new Map();
126
+ /**
127
+ * Ambient mouse-update handler. Used when the wallet starts a
128
+ * mouse stream WITHOUT a prior `kind: "mouse"` request — i.e.
129
+ * the pre-grant flow enabled by [SignInOptions.mouseControl].
130
+ * [`bindMouse`] registers itself here; any inbound
131
+ * `mouse-update` frame whose `requestId` doesn't match a
132
+ * specific subscriber falls through to this handler so the
133
+ * cursor moves regardless of who initiated the stream.
134
+ *
135
+ * Null when no [`bindMouse`] is mounted; only one ambient
136
+ * handler is active at a time (last call wins, mirroring the
137
+ * remote-nav listener semantics).
138
+ */
139
+ this._ambientMouseHandler = null;
140
+ /**
141
+ * File-transfer envelope handler. [`enableRemoteNavigation`]
142
+ * installs one of these to receive `file-begin` / `file-chunk` /
143
+ * `file-end` envelopes and reassemble the bytes into a `File`
144
+ * the focused `<input type="file">` accepts. The session layer
145
+ * just dispatches — assembly logic lives in `bind.ts` so the
146
+ * DOM dependency stays out of the protocol layer.
147
+ */
148
+ this._fileEnvelopeHandler = null;
149
+ /**
150
+ * Remote-navigation listener — installed by
151
+ * [`enableRemoteNavigation`]. Receives every inbound `nav`,
152
+ * `value`, and `logout` envelope. Only one listener at a time
153
+ * (later registrations replace the prior). Null when remote-nav
154
+ * is not active for this session.
155
+ */
156
+ this._remoteNavListener = null;
157
+ /**
158
+ * User's preferred UI language as a BCP-47 tag. Captured from the
159
+ * initial `presentation` envelope's `preferredLanguage` field;
160
+ * updated whenever a fresh envelope arrives with a new value.
161
+ * Null until the first envelope lands. The host page reads this
162
+ * to localise its own UI without an extra round-trip.
163
+ */
164
+ this._preferredLanguage = null;
165
+ /**
166
+ * Public-profile display name (cosmetic — host should treat as
167
+ * untrusted). Seeded from the wallet's initial `presentation`
168
+ * envelope and updated via `display-update` envelopes; mirrored
169
+ * by the `display_name_changed` event.
170
+ */
171
+ this._displayName = null;
172
+ /**
173
+ * Public-profile avatar pointer (cosmetic). Same trust model as
174
+ * `_displayName`. Updated via `display-update` envelopes; mirrored
175
+ * by `avatar_changed`.
176
+ */
177
+ this._avatar = null;
178
+ /** Per-type listener map. */
179
+ this._listeners = new Map();
180
+ /** "Fire on every event" subscribers — for logging / telemetry. */
181
+ this._anyListeners = new Set();
182
+ // ─── Transport-layer reliability state ───────────────────────────
183
+ //
184
+ // Mirrors the wallet's LoginSession protocol (see
185
+ // mobile-app/.../login_session_service.dart):
186
+ //
187
+ // * `_seenIds` + `_seenIdsOrder` — LRU dedupe of inbound `id`s.
188
+ // * `_pendingAcks` — outbound ack-tracked sends.
189
+ // * `_pingSendTimes` — RTT correlation by ping id.
190
+ // * `_pingTimer` + `_offlineTimer` — liveness loop.
191
+ //
192
+ // Browser-side critical sends are: `request`, `focus`, `ack`,
193
+ // `pong`. Of those only `request` already has its own
194
+ // RequestController/timeout contract; the rest are fire-and-forget
195
+ // today. To keep the surface small AND match the wallet, we add
196
+ // ack tracking on outbound `focus` only (high signal-to-noise for
197
+ // remote-nav UX). `request` keeps its existing semantics; `ack`
198
+ // and `pong` are never themselves ack-tracked (would loop).
199
+ this._seenIds = new Set();
200
+ this._seenIdsOrder = [];
201
+ this._pendingAcks = new Map();
202
+ this._pingSendTimes = new Map();
203
+ this._pingTimer = null;
204
+ this._offlineTimer = null;
205
+ this._connectionStatus = "unknown";
206
+ this._lastRttMs = null;
207
+ this._connectionListeners = new Set();
208
+ /**
209
+ * `pagehide` handler reference. Held so we can deregister at
210
+ * teardown without anchoring `this` to the global listener
211
+ * forever — important because the SDK can outlive multiple
212
+ * sign-in / sign-out cycles in a single tab.
213
+ */
214
+ this._onPageHide = null;
215
+ this._cnf = opts.cnf;
216
+ this._expiresAt = opts.credential.expiresAt;
217
+ this._transport = opts.transport;
218
+ this._ephKeys = opts.ephKeys;
219
+ this._verifierContext = opts.verifierContext;
220
+ this._claimsSnapshot = { ...(opts.initialClaims ?? {}) };
221
+ this._walletSessionPk = opts.walletSessionPk ?? null;
222
+ this._legacyChannel = opts.legacyChannel === true;
223
+ if (opts.initialPresentation) {
224
+ this._lastPresentationIat = opts.initialPresentation.iat;
225
+ void presentationDigest(opts.initialPresentation.presentation).then((d) => this._seenPresentations.add(d));
226
+ }
227
+ this._preferredLanguage = opts.initialPreferredLanguage ?? null;
228
+ this._displayName = opts.initialDisplayName ?? null;
229
+ this._avatar = opts.initialAvatar ?? null;
230
+ this._armExpiryTimer();
231
+ this._installUnloadGuard();
232
+ this._transport.onMessage((raw) => void this._handleMessage(raw));
233
+ // Transport teardown fan-out → `signed_out`. The credential's
234
+ // exp timer (`_armExpiryTimer`) covers credential-side TTL, but
235
+ // the Worker's session DO has a separate, MUCH shorter TTL —
236
+ // when its alarm fires, both signaling WSes close with code
237
+ // 4000 / reason `ttl_reached`, the data channel goes silent,
238
+ // and without this hook the host would keep showing "signed
239
+ // in" forever. The transport collapses every termination
240
+ // (signaling close, peer-gone, DC close) onto one notification;
241
+ // we map the reason string to the SDK's `ExpiryReason` union
242
+ // and tear down.
243
+ this._transport.onClose((reason) => {
244
+ if (this._closed)
245
+ return;
246
+ const mapped = _mapTransportCloseReason(reason);
247
+ this._teardown(mapped);
248
+ });
249
+ // Start the wallet→browser liveness loop. The wallet runs the
250
+ // same loop on its side; either peer's ping triggers a pong on
251
+ // the other. Both sides independently track their own RTT view.
252
+ this._pingTimer = setInterval(() => this._sendPing(), PING_INTERVAL_MS);
253
+ _unrefTimer(this._pingTimer);
254
+ // Fire `signed_in` via microtask so listeners attached
255
+ // synchronously after `await signIn()` still receive it.
256
+ // Without the microtask the event would race against the
257
+ // caller's first `on()` registration.
258
+ if (opts.initialSignedInResult) {
259
+ const result = opts.initialSignedInResult;
260
+ queueMicrotask(() => this._dispatch({ type: "signed_in", result }));
261
+ }
262
+ }
263
+ // ─── Public getters ──────────────────────────────────────────────
264
+ get expiresAt() {
265
+ return this._expiresAt;
266
+ }
267
+ get cnf() {
268
+ return this._cnf;
269
+ }
270
+ /** Snapshot of the most recent verified claims (since last renew / update). */
271
+ get claims() {
272
+ return this._claimsSnapshot;
273
+ }
274
+ /**
275
+ * Who is signed in: the person's Prson ID for this site (`cnf.jwk.x`,
276
+ * the same value as `SignInResult.prsonId`). Show it — or a name your
277
+ * backend maps it to — on the page, so the person can see it's them
278
+ * and not someone who scanned the code first.
279
+ */
280
+ get prsonId() {
281
+ return this._cnf.jwk.x;
282
+ }
283
+ /** The wallet's pinned X25519 session key (base64url), or null. */
284
+ get walletSessionPk() {
285
+ return this._walletSessionPk;
286
+ }
287
+ /** User's preferred UI language (BCP-47 tag) or null if the
288
+ * wallet hasn't published one yet. */
289
+ get preferredLanguage() {
290
+ return this._preferredLanguage;
291
+ }
292
+ /** Public-profile display name from the wallet's identity record,
293
+ * or null if the wallet hasn't published one yet (anonymous
294
+ * identity, etc.). Cosmetic — do not gate privileged actions on
295
+ * this value. */
296
+ get displayName() {
297
+ return this._displayName;
298
+ }
299
+ /** Public-profile avatar pointer, or null. Same cosmetic-only
300
+ * trust model as [displayName]. */
301
+ get avatar() {
302
+ return this._avatar;
303
+ }
304
+ /** Coarse health of the wallet ↔ browser data channel as observed
305
+ * via the periodic ping/pong loop. `unknown` until the first pong
306
+ * lands; `offline` after 5 s of no pong; `unstable` when the most
307
+ * recent RTT crossed 1 s; otherwise `stable`. */
308
+ get connectionStatus() {
309
+ return this._connectionStatus;
310
+ }
311
+ /** Most recently observed RTT in milliseconds, or null until the
312
+ * first pong lands. */
313
+ get lastRttMs() {
314
+ return this._lastRttMs;
315
+ }
316
+ /** Subscribe to connection-status changes. Fires on every transition
317
+ * with the new status + the RTT that triggered it (null on the
318
+ * `offline` transition). Returns an unsubscribe handle. */
319
+ onConnectionStatus(cb) {
320
+ this._connectionListeners.add(cb);
321
+ return () => this._connectionListeners.delete(cb);
322
+ }
323
+ // ─── Subscription API ────────────────────────────────────────────
324
+ /**
325
+ * Subscribe to a single event type. The callback is invoked with
326
+ * the typed event variant (TS narrows on the `type` discriminant).
327
+ * Returns an unsubscribe handle.
328
+ *
329
+ * const off = session.on("claim_updated", (e) => {
330
+ * if (e.name === "verification_level") refreshBadge(e.newValue);
331
+ * });
332
+ * // later:
333
+ * off();
334
+ */
335
+ on(type, cb) {
336
+ let set = this._listeners.get(type);
337
+ if (!set) {
338
+ set = new Set();
339
+ this._listeners.set(type, set);
340
+ }
341
+ const wrapped = cb;
342
+ set.add(wrapped);
343
+ return () => set.delete(wrapped);
344
+ }
345
+ /** Subscribe to every event. Returns an unsubscribe handle. */
346
+ onAny(cb) {
347
+ this._anyListeners.add(cb);
348
+ return () => this._anyListeners.delete(cb);
349
+ }
350
+ // ─── Back-compat shims ───────────────────────────────────────────
351
+ //
352
+ // The original SDK exposed `onRenewed(cb)` and `onExpiry(cb)`.
353
+ // We keep them as thin wrappers around the typed `on()` so
354
+ // existing host pages compile without changes. New code should
355
+ // prefer `on()` / `onAny()`.
356
+ /** @deprecated Use `on("renewed", e => cb(e.result))` instead. */
357
+ onRenewed(cb) {
358
+ return this.on("renewed", (e) => cb(e.result));
359
+ }
360
+ /** @deprecated Use `on("signed_out", e => cb(e.reason))` instead. */
361
+ onExpiry(cb) {
362
+ return this.on("signed_out", (e) => cb(e.reason));
363
+ }
364
+ close() {
365
+ this._teardown("user_revoked");
366
+ }
367
+ // ─── Request channel ─────────────────────────────────────────────
368
+ /**
369
+ * Send a [request] to the wallet and resolve with the wallet's
370
+ * reply. The wallet shows a bottom drawer for the user to
371
+ * approve / decline / pick a matching fragment or document; the
372
+ * promise resolves when the user acts (or the [timeoutMs]
373
+ * elapses, or the session closes).
374
+ *
375
+ * Common error codes:
376
+ * * `no-active-session` — request issued before the wallet has
377
+ * published its session pk (race against the initial
378
+ * `presentation` envelope) or after the session closed.
379
+ * * `declined` — user tapped Decline in the wallet drawer.
380
+ * * `not-present` — no matching fragment / document on the
381
+ * device AND the user declined to acquire one.
382
+ * * `queue-full` — wallet is sitting at the 5-in-flight cap and
383
+ * isn't accepting more requests. Try later.
384
+ * * `rate-limited` — wallet's 1-request-per-second throttle
385
+ * rejected this one.
386
+ * * `timeout` — the [timeoutMs] elapsed before the wallet
387
+ * replied. Defaults to 60 s.
388
+ * * `session-closed` — the session shut down with this request
389
+ * in flight.
390
+ * * `unsupported` — the wallet predates envelope v2 (it bound no
391
+ * session key into the sign-in), so its replies couldn't be told
392
+ * apart from anyone else's. Nothing is sent to it.
393
+ *
394
+ * Wire grammar: outbound envelope shape is
395
+ * `{ v, msg: "request", issuedAt, domain, requestId, kind, ...kindFields }`,
396
+ * NaCl-boxed to the wallet's session pk. Reply is a matching
397
+ * `{ msg: "response", requestId, result | error }`.
398
+ */
399
+ async request(req, opts) {
400
+ return this._sendRequest(req, opts);
401
+ }
402
+ /**
403
+ * Streaming variant of [request] for `kind: "mouse"`. Identical
404
+ * to `request()` except [onFrame] is invoked for every
405
+ * `mouse-update` envelope the wallet emits against the request's
406
+ * UUID until the terminating `response` arrives. The returned
407
+ * promise resolves with the final response (i.e. when the user
408
+ * closes the wallet drawer). Used by [`bindMouse`].
409
+ *
410
+ * Separated from `request()` because the subscriber MUST be
411
+ * attached against the requestId BEFORE the envelope is sent —
412
+ * otherwise the first `mouse-update` frame can race ahead of the
413
+ * subscription. `request()` doesn't expose its requestId, so we
414
+ * provide this dedicated entry point rather than leak the id.
415
+ */
416
+ async requestMouse(req, onFrame, opts) {
417
+ return this._sendRequest(req, opts, onFrame);
418
+ }
419
+ /**
420
+ * Push the currently-focused input's metadata + value to the
421
+ * wallet so the user can edit it on the phone. Pass `null` to
422
+ * clear the wallet's focus mirror (blur, page change, etc.).
423
+ *
424
+ * Used by [`enableRemoteNavigation`]; not part of the documented
425
+ * public API but exposed so the helper lives in a separate module
426
+ * without reaching into private fields. NaCl-boxed to the wallet's
427
+ * session pk on the way out.
428
+ *
429
+ * @internal
430
+ */
431
+ async _sendFocus(focus) {
432
+ if (this._closed)
433
+ return;
434
+ if (!this._walletSessionPk)
435
+ return;
436
+ // A legacy wallet's key isn't bound to the sign-in, and its edits
437
+ // (`value`) are ignored anyway: don't send it the page's fields.
438
+ if (this._legacyChannel)
439
+ return;
440
+ // Focus updates drive the wallet drawer's mirrored input — the
441
+ // user can't edit a value the wallet never received, so we
442
+ // ack-track these. The promise is awaited only by tests; the
443
+ // common path (remote-nav helper firing on DOM focus events) is
444
+ // fire-and-forget.
445
+ await this._sendWithAck({
446
+ msg: "focus",
447
+ focus,
448
+ });
449
+ }
450
+ /**
451
+ * Install a `pagehide` listener that fires a synchronous
452
+ * `browser-revoke` envelope at the wallet right before the tab
453
+ * closes / refreshes / navigates away. Without this the wallet
454
+ * has to wait for the slower transport-collapse pathway
455
+ * (`peer-gone` over the signaling WS + ICE failure on the data
456
+ * channel) to learn the browser is gone — long enough for the
457
+ * connection-status dot to oscillate and any in-flight ack
458
+ * promises to time out.
459
+ *
460
+ * `pagehide` is preferred over `beforeunload` because:
461
+ * * it fires for bfcache evictions (back/forward navigation
462
+ * on iOS Safari), tab closes, AND refreshes
463
+ * * `beforeunload` is increasingly restricted by browsers
464
+ * for non-blocking-prompt use
465
+ *
466
+ * The envelope itself rides through the same NaCl box as every
467
+ * other browser→wallet message. We can't await the ack — the
468
+ * page is being torn down — so this is a true fire-and-forget;
469
+ * the wallet's [LoginSession.inbound] handler treats receipt
470
+ * as the trigger to close.
471
+ */
472
+ _installUnloadGuard() {
473
+ if (typeof window === "undefined")
474
+ return;
475
+ this._onPageHide = (_e) => {
476
+ if (this._closed || !this._walletSessionPk)
477
+ return;
478
+ const body = JSON.stringify({
479
+ v: "prson_vp_v1",
480
+ msg: "browser-revoke",
481
+ issuedAt: Math.floor(Date.now() / 1000),
482
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
483
+ reason: "page_unload",
484
+ });
485
+ try {
486
+ this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));
487
+ }
488
+ catch {
489
+ /* swallow — the channel is on its way out anyway */
490
+ }
491
+ };
492
+ window.addEventListener("pagehide", this._onPageHide);
493
+ }
494
+ /**
495
+ * Browser→wallet pause-state notification. The wallet's mouse
496
+ * controller dims its surface + shows "Remote control paused"
497
+ * while the page is in the background. Fire-and-forget over
498
+ * NaCl-box to the wallet's session pk; loss is acceptable
499
+ * (we re-fire on every focus / blur).
500
+ *
501
+ * @internal
502
+ */
503
+ async _sendControlStatus(paused) {
504
+ if (this._closed)
505
+ return;
506
+ if (!this._walletSessionPk)
507
+ return;
508
+ const payload = JSON.stringify({
509
+ v: "prson_vp_v1",
510
+ msg: "control-status",
511
+ issuedAt: Math.floor(Date.now() / 1000),
512
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
513
+ paused,
514
+ });
515
+ try {
516
+ this._transport.send(boxToWallet(this._walletSessionPk, payload, this._ephKeys));
517
+ }
518
+ catch {
519
+ /* swallow — channel down */
520
+ }
521
+ }
522
+ /**
523
+ * Install the ambient `mouse-update` handler. Mirrors
524
+ * [`_setRemoteNavListener`] — only one ambient subscriber at a
525
+ * time (last call wins). Used by [`bindMouse`] when the
526
+ * session was pre-granted mouse control at sign-in
527
+ * ([SignInOptions.mouseControl]).
528
+ *
529
+ * @internal
530
+ */
531
+ _setAmbientMouseHandler(cb) {
532
+ this._ambientMouseHandler = cb;
533
+ return () => {
534
+ if (this._ambientMouseHandler === cb)
535
+ this._ambientMouseHandler = null;
536
+ };
537
+ }
538
+ /**
539
+ * Install the file-envelope handler. Mirrors
540
+ * [`_setAmbientMouseHandler`] — only one handler at a time;
541
+ * [`enableRemoteNavigation`] owns it during its lifetime and
542
+ * tears it down on disposal so the next mount can install a
543
+ * fresh one. The handler receives `file-begin` / `file-chunk` /
544
+ * `file-end` envelopes in arrival order; assembly + DOM
545
+ * dispatch lives in [`bind.ts`].
546
+ *
547
+ * @internal
548
+ */
549
+ _setFileEnvelopeHandler(cb) {
550
+ this._fileEnvelopeHandler = cb;
551
+ return () => {
552
+ if (this._fileEnvelopeHandler === cb)
553
+ this._fileEnvelopeHandler = null;
554
+ };
555
+ }
556
+ /**
557
+ * Install the remote-navigation listener. Replaces any prior
558
+ * listener — only one is active at a time. Returns an unsubscribe
559
+ * handle. Used by [`enableRemoteNavigation`].
560
+ *
561
+ * @internal
562
+ */
563
+ _setRemoteNavListener(cb) {
564
+ this._remoteNavListener = cb;
565
+ return () => {
566
+ if (this._remoteNavListener === cb)
567
+ this._remoteNavListener = null;
568
+ };
569
+ }
570
+ async _sendRequest(req, opts, onMouseFrame) {
571
+ if (this._closed)
572
+ return { ok: false, error: "session-closed" };
573
+ // A legacy session can't check who sent a `response` (no session
574
+ // key bound in the presentation), so anyone able to box to us could
575
+ // answer. Refuse the request instead of trusting the reply.
576
+ if (this._legacyChannel)
577
+ return { ok: false, error: "unsupported" };
578
+ const recipientPk = this._walletSessionPk;
579
+ if (!recipientPk)
580
+ return { ok: false, error: "no-active-session" };
581
+ const timeoutMs = opts?.timeoutMs ?? 60000;
582
+ const { requestId, promise } = this._requestController.enqueue(timeoutMs);
583
+ // Attach the streaming subscriber BEFORE sending so the first
584
+ // mouse-update frame can never race ahead of the subscription.
585
+ if (onMouseFrame)
586
+ this._mouseSubscribers.set(requestId, onMouseFrame);
587
+ const envelope = {
588
+ v: "prson_vp_v1",
589
+ msg: "request",
590
+ issuedAt: Math.floor(Date.now() / 1000),
591
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
592
+ requestId,
593
+ kind: req.kind,
594
+ };
595
+ // Per-kind body — flat keys for simplicity, matches the wallet's
596
+ // existing wire-decoder pattern.
597
+ switch (req.kind) {
598
+ case "claim-value":
599
+ envelope.name = req.name;
600
+ if (req.reason)
601
+ envelope.reason = req.reason;
602
+ break;
603
+ case "fragment-check":
604
+ envelope.fragmentName = req.fragmentName;
605
+ // `format` selects the wire shape the wallet asks the notary
606
+ // for (native / vc+jwt / vc+sd-jwt). Omitted means native, so
607
+ // we only put it on the envelope when the host opted in — the
608
+ // wallet treats an absent field as legacy behaviour.
609
+ if (req.format)
610
+ envelope.format = req.format;
611
+ if (req.reason)
612
+ envelope.reason = req.reason;
613
+ break;
614
+ case "document-presence":
615
+ if (req.type)
616
+ envelope.type = req.type;
617
+ if (req.country)
618
+ envelope.country = req.country;
619
+ if (req.reason)
620
+ envelope.reason = req.reason;
621
+ break;
622
+ case "document-sign":
623
+ // Bytes get base64'd in the envelope; large docs should use
624
+ // `uploadUrl` to keep the WebRTC message size down.
625
+ if ("bytes" in req.document) {
626
+ envelope.document = {
627
+ bytes: u8ToB64(req.document.bytes),
628
+ };
629
+ }
630
+ else {
631
+ envelope.document = req.document;
632
+ }
633
+ if (req.visibleCue)
634
+ envelope.visibleCue = req.visibleCue;
635
+ if (req.reason)
636
+ envelope.reason = req.reason;
637
+ break;
638
+ case "input":
639
+ envelope.inputType = req.inputType;
640
+ envelope.label = req.label;
641
+ if (req.placeholder !== undefined)
642
+ envelope.placeholder = req.placeholder;
643
+ // A password's current value never goes to the phone.
644
+ if (req.defaultValue !== undefined && req.inputType !== "password")
645
+ envelope.defaultValue = req.defaultValue;
646
+ if (req.minLength !== undefined)
647
+ envelope.minLength = req.minLength;
648
+ if (req.maxLength !== undefined)
649
+ envelope.maxLength = req.maxLength;
650
+ if (req.min !== undefined)
651
+ envelope.min = req.min;
652
+ if (req.max !== undefined)
653
+ envelope.max = req.max;
654
+ if (req.pattern !== undefined)
655
+ envelope.pattern = req.pattern;
656
+ if (req.required !== undefined)
657
+ envelope.required = req.required;
658
+ if (req.options !== undefined)
659
+ envelope.options = req.options;
660
+ if (req.reason)
661
+ envelope.reason = req.reason;
662
+ break;
663
+ case "input-form":
664
+ envelope.fields = req.fields.map((f) => f.inputType === "password" && f.defaultValue !== undefined ? { ...f, defaultValue: undefined } : f);
665
+ if (req.submitLabel !== undefined)
666
+ envelope.submitLabel = req.submitLabel;
667
+ if (req.reason)
668
+ envelope.reason = req.reason;
669
+ break;
670
+ case "mouse":
671
+ envelope.mode = req.mode;
672
+ if (req.reason)
673
+ envelope.reason = req.reason;
674
+ break;
675
+ }
676
+ try {
677
+ const boxed = boxToWallet(recipientPk, JSON.stringify(envelope), this._ephKeys);
678
+ this._transport.send(boxed);
679
+ }
680
+ catch {
681
+ // Network down, channel closed, encoding bug — surface as
682
+ // session-closed; the timeout would also fire eventually.
683
+ if (onMouseFrame)
684
+ this._mouseSubscribers.delete(requestId);
685
+ return { ok: false, error: "session-closed" };
686
+ }
687
+ return promise;
688
+ }
689
+ // ─── internals ───────────────────────────────────────────────────
690
+ /**
691
+ * Fire a single event to per-type listeners + onAny subscribers.
692
+ * Listener errors are swallowed so one buggy host listener can't
693
+ * break the rest of the dispatch (or close the session).
694
+ */
695
+ _dispatch(event) {
696
+ const set = this._listeners.get(event.type);
697
+ if (set) {
698
+ for (const cb of set) {
699
+ try {
700
+ cb(event);
701
+ }
702
+ catch {
703
+ /* swallow — host bug shouldn't bring down the session */
704
+ }
705
+ }
706
+ }
707
+ for (const cb of this._anyListeners) {
708
+ try {
709
+ cb(event);
710
+ }
711
+ catch {
712
+ /* swallow */
713
+ }
714
+ }
715
+ }
716
+ _armExpiryTimer() {
717
+ if (this._expiryTimer)
718
+ clearTimeout(this._expiryTimer);
719
+ const delta = this._expiresAt - Date.now();
720
+ // 60-second skew/sanity budget on BOTH sides:
721
+ //
722
+ // * If `expiresAt === 0`: the credential's JWS had no numeric
723
+ // `exp`. Skip the timer.
724
+ // * If `delta` is in `[-60_000, +60_000]`: the credential
725
+ // "expires" within a one-minute window of "now". Almost
726
+ // always one of: clock skew between server and browser,
727
+ // network latency between issuance and verify, or a
728
+ // server-side TTL bug that issued an essentially-zero-TTL
729
+ // credential. Tearing down on this signal causes a visible
730
+ // "signed_in immediately followed by signed_out" UX bug;
731
+ // skip the timer and let the wallet (or host) close.
732
+ // * Otherwise: legitimate future expiry — arm the timer.
733
+ // * Otherwise (genuinely past, >60s ago): real expiry,
734
+ // teardown immediately.
735
+ const skewBudgetMs = 60000;
736
+ if (this._expiresAt <= 0 || Math.abs(delta) < skewBudgetMs) {
737
+ // eslint-disable-next-line no-console
738
+ console.warn(`[@prson/login-sdk] credential expiresAt ${this._expiresAt <= 0
739
+ ? "missing/zero"
740
+ : delta < 0
741
+ ? `${(-delta / 1000).toFixed(1)}s in the past`
742
+ : `only ${(delta / 1000).toFixed(1)}s in the future`} — leaving session open without a TTL timer.` +
743
+ " Host should set its own deadline.");
744
+ return;
745
+ }
746
+ if (delta <= 0) {
747
+ this._teardown("ttl_reached");
748
+ return;
749
+ }
750
+ // `setTimeout` clamps delays > 2^31-1 ms (~24.8 days) to a 32-bit
751
+ // int and effectively fires immediately. A verified-human VC has
752
+ // a 90-day TTL — delta is ~7.8 billion ms — so a naive
753
+ // `setTimeout(..., delta)` would trip the teardown on the very
754
+ // next tick. Re-arm in chunks ≤ MAX_TIMEOUT and re-evaluate.
755
+ const MAX_TIMEOUT = 2147483000; // a hair under int32 max
756
+ const chunk = delta > MAX_TIMEOUT ? MAX_TIMEOUT : delta;
757
+ this._expiryTimer = setTimeout(() => {
758
+ if (this._closed)
759
+ return;
760
+ // Re-check against the current clock — if we still haven't
761
+ // reached `_expiresAt`, re-arm. Otherwise teardown.
762
+ if (Date.now() >= this._expiresAt) {
763
+ this._teardown("ttl_reached");
764
+ }
765
+ else {
766
+ this._armExpiryTimer();
767
+ }
768
+ }, chunk);
769
+ _unrefTimer(this._expiryTimer);
770
+ }
771
+ async _handleMessage(raw) {
772
+ if (this._closed)
773
+ return;
774
+ let envelope;
775
+ try {
776
+ // Only the pinned wallet key may talk to us. A legacy session (no
777
+ // key bound in the presentation) can't check the sender, so it
778
+ // accepts any box and ignores page-acting messages instead.
779
+ envelope = await decryptEnvelope(raw, this._ephKeys, this._legacyChannel ? undefined : (this._walletSessionPk ?? undefined));
780
+ }
781
+ catch {
782
+ // Garbage on the wire, or a box from a key other than the pinned
783
+ // wallet key (an injected envelope) — ignore it.
784
+ return;
785
+ }
786
+ // ── Transport-layer protocol: dedupe + auto-ack + ping/pong ──
787
+ if (typeof envelope.id === "string") {
788
+ if (this._seenIds.has(envelope.id)) {
789
+ // Duplicate — our prior ack likely got lost. Re-ack so the
790
+ // wallet stops retransmitting, then drop locally.
791
+ void this._sendAckFor(envelope);
792
+ return;
793
+ }
794
+ this._markSeen(envelope.id);
795
+ void this._sendAckFor(envelope);
796
+ }
797
+ if (envelope.msg === "ack") {
798
+ this._handleAck(envelope.ackOf);
799
+ return;
800
+ }
801
+ if (envelope.msg === "ping") {
802
+ void this._sendPong(envelope);
803
+ return;
804
+ }
805
+ if (envelope.msg === "pong") {
806
+ this._handlePong(envelope);
807
+ return;
808
+ }
809
+ await this._dispatchDecryptedForTest(envelope);
810
+ }
811
+ // ─── Transport-layer protocol helpers ─────────────────────────────
812
+ _markSeen(id) {
813
+ this._seenIds.add(id);
814
+ this._seenIdsOrder.push(id);
815
+ if (this._seenIdsOrder.length > SEEN_IDS_CAPACITY) {
816
+ const evict = this._seenIdsOrder.shift();
817
+ if (evict)
818
+ this._seenIds.delete(evict);
819
+ }
820
+ }
821
+ /** Auto-ack any inbound envelope that carries an `id`, except
822
+ * protocol primitives. `ping` is implicitly acked by `pong`;
823
+ * `pong` and `ack` would loop. */
824
+ async _sendAckFor(envelope) {
825
+ if (typeof envelope.id !== "string")
826
+ return;
827
+ if (envelope.msg === "ack" || envelope.msg === "ping" || envelope.msg === "pong") {
828
+ return;
829
+ }
830
+ if (!this._walletSessionPk)
831
+ return;
832
+ const body = JSON.stringify({
833
+ v: "prson_vp_v1",
834
+ msg: "ack",
835
+ ackOf: envelope.id,
836
+ issuedAt: Math.floor(Date.now() / 1000),
837
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
838
+ });
839
+ try {
840
+ this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));
841
+ }
842
+ catch {
843
+ /* channel down — wallet will time out its retry budget */
844
+ }
845
+ }
846
+ _handleAck(ackOf) {
847
+ if (!ackOf)
848
+ return;
849
+ const pending = this._pendingAcks.get(ackOf);
850
+ if (!pending)
851
+ return;
852
+ if (pending.timer)
853
+ clearTimeout(pending.timer);
854
+ this._pendingAcks.delete(ackOf);
855
+ }
856
+ async _sendPing() {
857
+ if (this._closed)
858
+ return;
859
+ if (!this._walletSessionPk)
860
+ return;
861
+ const id = uuidv4();
862
+ const ts = Date.now();
863
+ this._pingSendTimes.set(id, ts);
864
+ const body = JSON.stringify({
865
+ v: "prson_vp_v1",
866
+ msg: "ping",
867
+ id,
868
+ ts,
869
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
870
+ });
871
+ try {
872
+ this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));
873
+ }
874
+ catch {
875
+ /* swallow */
876
+ }
877
+ this._armOfflineTimer();
878
+ }
879
+ async _sendPong(ping) {
880
+ if (!this._walletSessionPk)
881
+ return;
882
+ if (typeof ping.id !== "string")
883
+ return;
884
+ const body = JSON.stringify({
885
+ v: "prson_vp_v1",
886
+ msg: "pong",
887
+ ackOf: ping.id,
888
+ ts: ping.ts,
889
+ recvTs: Date.now(),
890
+ domain: this._verifierContext.expectedAudience.replace(/^https?:\/\//, ""),
891
+ });
892
+ try {
893
+ this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));
894
+ }
895
+ catch {
896
+ /* swallow */
897
+ }
898
+ }
899
+ _handlePong(envelope) {
900
+ if (typeof envelope.ackOf !== "string")
901
+ return;
902
+ const sent = this._pingSendTimes.get(envelope.ackOf);
903
+ if (sent === undefined)
904
+ return;
905
+ this._pingSendTimes.delete(envelope.ackOf);
906
+ const rtt = Date.now() - sent;
907
+ this._lastRttMs = rtt;
908
+ if (this._offlineTimer) {
909
+ clearTimeout(this._offlineTimer);
910
+ this._offlineTimer = null;
911
+ }
912
+ this._setConnectionStatus(rtt > CONNECTION_UNSTABLE_THRESHOLD_MS ? "unstable" : "stable", rtt);
913
+ }
914
+ _armOfflineTimer() {
915
+ if (this._offlineTimer)
916
+ clearTimeout(this._offlineTimer);
917
+ this._offlineTimer = setTimeout(() => {
918
+ if (this._closed)
919
+ return;
920
+ this._setConnectionStatus("offline", null);
921
+ }, CONNECTION_OFFLINE_AFTER_MS);
922
+ _unrefTimer(this._offlineTimer);
923
+ }
924
+ _setConnectionStatus(s, rttMs) {
925
+ if (this._connectionStatus === s && this._lastRttMs === rttMs)
926
+ return;
927
+ this._connectionStatus = s;
928
+ if (rttMs !== null)
929
+ this._lastRttMs = rttMs;
930
+ for (const cb of this._connectionListeners) {
931
+ try {
932
+ cb(s, rttMs);
933
+ }
934
+ catch {
935
+ /* swallow — host bug shouldn't kill the loop */
936
+ }
937
+ }
938
+ }
939
+ /** Send a JSON envelope with ack tracking + retry. Stamps a fresh
940
+ * `id` onto [body] and retransmits every [ACK_RETRY_DELAY_MS]
941
+ * until the matching ack lands or [ACK_MAX_ATTEMPTS] is reached.
942
+ * Resolves with `true` on ack, `false` on exhaustion. */
943
+ async _sendWithAck(body) {
944
+ if (this._closed)
945
+ return false;
946
+ if (!this._walletSessionPk)
947
+ return false;
948
+ const id = uuidv4();
949
+ body.id = id;
950
+ body.v = body.v ?? "prson_vp_v1";
951
+ body.issuedAt = body.issuedAt ?? Math.floor(Date.now() / 1000);
952
+ body.domain =
953
+ body.domain ?? this._verifierContext.expectedAudience.replace(/^https?:\/\//, "");
954
+ const encoded = JSON.stringify(body);
955
+ const pending = { encoded, attempts: 0, timer: null };
956
+ this._pendingAcks.set(id, pending);
957
+ return new Promise((resolve) => {
958
+ const attempt = () => {
959
+ if (this._closed) {
960
+ this._pendingAcks.delete(id);
961
+ resolve(false);
962
+ return;
963
+ }
964
+ pending.attempts += 1;
965
+ try {
966
+ this._transport.send(boxToWallet(this._walletSessionPk, encoded, this._ephKeys));
967
+ }
968
+ catch {
969
+ /* channel down — keep retrying; offline timer will fire */
970
+ }
971
+ pending.timer = setTimeout(() => {
972
+ if (!this._pendingAcks.has(id)) {
973
+ // Ack already arrived between attempts; the success path
974
+ // cleared the map entry.
975
+ resolve(true);
976
+ return;
977
+ }
978
+ if (pending.attempts >= ACK_MAX_ATTEMPTS) {
979
+ this._pendingAcks.delete(id);
980
+ resolve(false);
981
+ return;
982
+ }
983
+ attempt();
984
+ }, ACK_RETRY_DELAY_MS);
985
+ _unrefTimer(pending.timer);
986
+ };
987
+ attempt();
988
+ });
989
+ }
990
+ /**
991
+ * Pure dispatch entry-point — takes an already-decrypted envelope
992
+ * and routes it through the same per-message handlers
993
+ * `_handleMessage` does after decryption. Public-but-prefixed so
994
+ * unit tests can exercise the dispatch contract without
995
+ * constructing real NaCl-boxed ciphertext.
996
+ *
997
+ * NOT part of the documented public API; treat as @internal.
998
+ */
999
+ async _dispatchDecryptedForTest(envelope) {
1000
+ if (this._closed)
1001
+ return;
1002
+ // `walletSessionPk` on an envelope is NOT trusted: the key is pinned
1003
+ // from the signed presentation and only a verified renewal can
1004
+ // rotate it (see _handleRenewal).
1005
+ // Same treatment for the user's preferred language — the wallet
1006
+ // re-stamps this on every envelope so a mid-session locale
1007
+ // change propagates without an explicit event.
1008
+ if (typeof envelope.preferredLanguage === "string") {
1009
+ this._preferredLanguage = envelope.preferredLanguage;
1010
+ }
1011
+ switch (envelope.msg) {
1012
+ case "revoke":
1013
+ this._teardown("wallet_signed_out");
1014
+ return;
1015
+ case "presentation":
1016
+ case "renewal":
1017
+ await this._handleRenewal(envelope);
1018
+ return;
1019
+ case "claim-update":
1020
+ await this._handleClaimUpdate(envelope);
1021
+ return;
1022
+ case "display-update":
1023
+ this._handleDisplayUpdate(envelope);
1024
+ return;
1025
+ case "credential-revoked":
1026
+ this._handleCredentialRevoked(envelope);
1027
+ return;
1028
+ case "response":
1029
+ // Legacy sessions never send requests (see _sendRequest); a
1030
+ // `response` there is unauthenticated, so it resolves nothing.
1031
+ if (this._legacyChannel)
1032
+ return;
1033
+ // Wallet replied to an outbound `request`. Match by UUID
1034
+ // and resolve the matching promise. Late replies (after
1035
+ // timeout) silently no-op — the controller already
1036
+ // delivered the timeout error.
1037
+ this._requestController.resolve(envelope);
1038
+ // If the request was a streaming `mouse` request, the final
1039
+ // `response` also closes the stream — drop the subscriber so
1040
+ // the controller can be reused.
1041
+ if (envelope.requestId)
1042
+ this._mouseSubscribers.delete(envelope.requestId);
1043
+ return;
1044
+ case "mouse-update":
1045
+ // An unauthenticated sender must not drive the page.
1046
+ if (this._legacyChannel)
1047
+ return;
1048
+ // Wallet is streaming pointer events. Two routing paths:
1049
+ //
1050
+ // 1. **Per-request** — there's a pending `requestMouse`
1051
+ // subscriber keyed by this `requestId`. Used when the
1052
+ // host explicitly opened a `kind: "mouse"` request.
1053
+ //
1054
+ // 2. **Ambient** — no such subscriber exists. Used by the
1055
+ // pre-grant flow (`SignInOptions.mouseControl: true`)
1056
+ // where the wallet's banner drawer starts a stream
1057
+ // with a wallet-minted id the host never saw. Falls
1058
+ // through to `_ambientMouseHandler`, which [`bindMouse`]
1059
+ // installs so its on-page cursor still moves.
1060
+ if (envelope.mouse) {
1061
+ const perRequest = envelope.requestId
1062
+ ? this._mouseSubscribers.get(envelope.requestId)
1063
+ : undefined;
1064
+ const target = perRequest ?? this._ambientMouseHandler;
1065
+ if (target) {
1066
+ try {
1067
+ target(envelope.mouse);
1068
+ }
1069
+ catch {
1070
+ /* swallow — host bug shouldn't kill the stream */
1071
+ }
1072
+ }
1073
+ }
1074
+ return;
1075
+ case "nav":
1076
+ case "logout":
1077
+ if (envelope.msg === "nav" && this._legacyChannel)
1078
+ return;
1079
+ // Remote-navigation commands from the wallet's persistent
1080
+ // banner. Without an installed listener (i.e. the host
1081
+ // didn't call `enableRemoteNavigation`), `nav` is silently
1082
+ // dropped and `logout` falls through to the default teardown
1083
+ // below — the user tapping logout MUST sign the session out
1084
+ // even if the host never wired the optional helper.
1085
+ if (this._remoteNavListener) {
1086
+ try {
1087
+ if (envelope.msg === "nav" && envelope.action) {
1088
+ this._remoteNavListener({ msg: "nav", action: envelope.action });
1089
+ return;
1090
+ }
1091
+ if (envelope.msg === "logout") {
1092
+ this._remoteNavListener({ msg: "logout" });
1093
+ // Logout also tears the session down — the helper may
1094
+ // have already done it, but tearing again is a no-op.
1095
+ this._teardown("user_revoked");
1096
+ return;
1097
+ }
1098
+ }
1099
+ catch {
1100
+ /* swallow */
1101
+ }
1102
+ }
1103
+ if (envelope.msg === "logout")
1104
+ this._teardown("user_revoked");
1105
+ return;
1106
+ case "value":
1107
+ if (this._legacyChannel)
1108
+ return;
1109
+ // Wallet edited the value of the focused field. The remote-
1110
+ // nav helper is the only consumer; without it the edit is
1111
+ // silently dropped (the host page never asked for remote
1112
+ // input control). `value: null` is "no change" — we ignore.
1113
+ if (this._remoteNavListener &&
1114
+ typeof envelope.value === "string") {
1115
+ try {
1116
+ this._remoteNavListener({ msg: "value", value: envelope.value });
1117
+ }
1118
+ catch {
1119
+ /* swallow */
1120
+ }
1121
+ }
1122
+ return;
1123
+ case "file-begin":
1124
+ case "file-chunk":
1125
+ case "file-end":
1126
+ if (this._legacyChannel)
1127
+ return;
1128
+ // File-transfer envelopes flow through the remote-nav
1129
+ // helper's file receiver — bytes are reassembled into a
1130
+ // `File` object that the focused `<input type="file">`
1131
+ // accepts. Without the helper mounted these envelopes are
1132
+ // silently dropped (the host page never asked for remote
1133
+ // file input).
1134
+ if (this._fileEnvelopeHandler) {
1135
+ try {
1136
+ this._fileEnvelopeHandler(envelope);
1137
+ }
1138
+ catch {
1139
+ /* swallow — one buggy receiver shouldn't kill the
1140
+ * channel for everyone */
1141
+ }
1142
+ }
1143
+ return;
1144
+ default:
1145
+ // Forward-compatible: unknown msg types are ignored, not
1146
+ // errors. A future wallet build can ship new events that
1147
+ // older SDK builds simply don't surface.
1148
+ return;
1149
+ }
1150
+ }
1151
+ async _handleRenewal(envelope) {
1152
+ if (!envelope.presentation)
1153
+ return;
1154
+ const verified = await this._verifyFresh(envelope.presentation);
1155
+ if (!verified)
1156
+ return;
1157
+ // Key rotation: only a verified renewal presentation can move the
1158
+ // pinned wallet key, and only to the key it signs (`prson_wsk`).
1159
+ // The next envelope must then come from the new key.
1160
+ const rotated = verified.binding.walletSessionPk;
1161
+ if (envelope.msg === "renewal" && rotated && !this._legacyChannel) {
1162
+ this._walletSessionPk = rotated;
1163
+ }
1164
+ this._expiresAt = verified.credential.expiresAt;
1165
+ this._claimsSnapshot = { ...verified.claims };
1166
+ this._armExpiryTimer();
1167
+ const fresh = {
1168
+ sdJwtVc: envelope.presentation,
1169
+ // The wallet picks a renewal's nonce, so a backend can't have issued it.
1170
+ nonce: verified.binding.nonce,
1171
+ prsonId: verified.cnf.jwk.x,
1172
+ claims: verified.claims,
1173
+ cnf: verified.cnf,
1174
+ credential: verified.credential,
1175
+ session: this,
1176
+ };
1177
+ this._dispatch({ type: "renewed", result: fresh });
1178
+ }
1179
+ /**
1180
+ * Verify a renewal / claim-update presentation and enforce in-session
1181
+ * anti-replay: same holder key, a holder-signed `iat` strictly newer
1182
+ * than the last accepted presentation, and never a presentation this
1183
+ * session already accepted. Returns null (drop it) otherwise.
1184
+ */
1185
+ async _verifyFresh(presentation) {
1186
+ const verifierOpts = {
1187
+ ...this._verifierContext,
1188
+ // The wallet signs the sign-in nonce again, or one of its own; the
1189
+ // freshness checks below are what stop a replay either way.
1190
+ expectedNonce: extractKbNonce(presentation) ?? this._verifierContext.expectedNonceFactory(),
1191
+ };
1192
+ const digest = await presentationDigest(presentation);
1193
+ if (this._seenPresentations.has(digest))
1194
+ return null;
1195
+ const verified = await verifyPresentation(presentation, verifierOpts);
1196
+ if (!verified.ok)
1197
+ return null;
1198
+ if (verified.cnf.jwk.x !== this._cnf.jwk.x)
1199
+ return null; // wallet swapped under us; ignore
1200
+ if (verified.binding.iat <= this._lastPresentationIat)
1201
+ return null;
1202
+ if (this._closed || this._seenPresentations.has(digest))
1203
+ return null;
1204
+ this._seenPresentations.add(digest);
1205
+ this._lastPresentationIat = verified.binding.iat;
1206
+ return verified;
1207
+ }
1208
+ /**
1209
+ * Verify the embedded presentation, then diff its claims against
1210
+ * the cached snapshot and emit name-only per-claim events. The
1211
+ * actual claim values land in `this._claimsSnapshot` (accessible
1212
+ * via `session.claims`) but **never** in the event payloads —
1213
+ * see the privacy note on the [LoginEvent] type.
1214
+ *
1215
+ * Re-verifies against the same audience + accepted-VCT set as the
1216
+ * initial sign-in. A `claim-update` whose presentation fails
1217
+ * verification is dropped silently — fail-closed. Same for a
1218
+ * cnf-mismatch (the wallet swapped per-domain key under us).
1219
+ *
1220
+ * The wire-level `envelope.delta` is intentionally ignored — we
1221
+ * recompute the diff from the verified SD-JWT so a malicious
1222
+ * wallet can't lie about which claim changed. The wallet should
1223
+ * not include values in `envelope.delta` at all (the wire
1224
+ * grammar in `crypto.ts` documents this as name-only); we'd
1225
+ * ignore them even if it did.
1226
+ */
1227
+ async _handleClaimUpdate(envelope) {
1228
+ if (!envelope.presentation)
1229
+ return;
1230
+ const verified = await this._verifyFresh(envelope.presentation);
1231
+ if (!verified)
1232
+ return;
1233
+ const oldClaims = this._claimsSnapshot;
1234
+ const newClaims = verified.claims;
1235
+ this._claimsSnapshot = { ...newClaims };
1236
+ // Added + updated — emit name + canonical hash of the new
1237
+ // value (NOT the raw value). The host reads the actual value
1238
+ // via `session.claims[name]` when needed; the hash lets
1239
+ // callers do an `==`-style check against a precomputed digest
1240
+ // ("did verification_level become 5?") without ever letting
1241
+ // the raw value cross the event surface.
1242
+ for (const [name, newValue] of Object.entries(newClaims)) {
1243
+ if (!(name in oldClaims)) {
1244
+ this._dispatch({
1245
+ type: "claim_added",
1246
+ name,
1247
+ newHash: await canonicalSha256Hex(newValue),
1248
+ });
1249
+ }
1250
+ else if (!_deepEqual(oldClaims[name], newValue)) {
1251
+ this._dispatch({
1252
+ type: "claim_updated",
1253
+ name,
1254
+ newHash: await canonicalSha256Hex(newValue),
1255
+ });
1256
+ }
1257
+ }
1258
+ // Removed
1259
+ for (const name of Object.keys(oldClaims)) {
1260
+ if (!(name in newClaims)) {
1261
+ this._dispatch({ type: "claim_removed", name });
1262
+ }
1263
+ }
1264
+ }
1265
+ /**
1266
+ * Display-only update. Fires `display_name_changed` and/or
1267
+ * `avatar_changed` based on which fields the envelope carries.
1268
+ * NOT cryptographically verified — partner sites should treat
1269
+ * the payload as advisory (refresh the cosmetic UI) and not
1270
+ * grant any privileged access on the basis of these values.
1271
+ */
1272
+ _handleDisplayUpdate(envelope) {
1273
+ if (envelope.displayName !== undefined) {
1274
+ // Mirror onto the session getter so a host that reads
1275
+ // `session.displayName` lazily after the update event sees
1276
+ // the new value.
1277
+ this._displayName = envelope.displayName;
1278
+ this._dispatch({
1279
+ type: "display_name_changed",
1280
+ displayName: envelope.displayName,
1281
+ });
1282
+ }
1283
+ if (envelope.avatar !== undefined) {
1284
+ this._avatar = envelope.avatar;
1285
+ this._dispatch({ type: "avatar_changed", avatar: envelope.avatar });
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Credential-revoked. Fires `credential_revoked` with the
1290
+ * wallet-supplied reason, then tears the session down with
1291
+ * `signed_out / reason="credential_revoked"`. Both events land
1292
+ * before the transport closes.
1293
+ */
1294
+ _handleCredentialRevoked(envelope) {
1295
+ const reason = envelope.reason ?? "user_revoked";
1296
+ this._dispatch({ type: "credential_revoked", reason });
1297
+ this._teardown("credential_revoked");
1298
+ }
1299
+ _teardown(reason) {
1300
+ if (this._closed)
1301
+ return;
1302
+ this._closed = true;
1303
+ if (this._expiryTimer)
1304
+ clearTimeout(this._expiryTimer);
1305
+ if (this._pingTimer)
1306
+ clearInterval(this._pingTimer);
1307
+ if (this._offlineTimer)
1308
+ clearTimeout(this._offlineTimer);
1309
+ if (this._onPageHide && typeof window !== "undefined") {
1310
+ window.removeEventListener("pagehide", this._onPageHide);
1311
+ this._onPageHide = null;
1312
+ }
1313
+ for (const p of this._pendingAcks.values()) {
1314
+ if (p.timer)
1315
+ clearTimeout(p.timer);
1316
+ }
1317
+ this._pendingAcks.clear();
1318
+ this._pingSendTimes.clear();
1319
+ try {
1320
+ this._transport.close();
1321
+ }
1322
+ catch {
1323
+ /* */
1324
+ }
1325
+ // Reject every in-flight request so callers awaiting
1326
+ // `session.request(...)` don't hang past the teardown.
1327
+ this._requestController.closeAll("session-closed");
1328
+ // Drop any open mouse-update subscribers — the wallet won't be
1329
+ // sending more frames, and `bindMouse` will clean up its
1330
+ // DOM-side state via the `signed_out` event.
1331
+ this._mouseSubscribers.clear();
1332
+ this._dispatch({ type: "signed_out", reason });
1333
+ // Clear listener sets after dispatch so a host that calls
1334
+ // `session.on(...)` after teardown doesn't accumulate forever.
1335
+ this._listeners.clear();
1336
+ this._anyListeners.clear();
1337
+ this._connectionListeners.clear();
1338
+ }
1339
+ }
1340
+ /**
1341
+ * Best-effort nonce extraction from a KB-JWT. Used at renewal /
1342
+ * update time so we accept the wallet's fresh nonce without forcing
1343
+ * a coordination round-trip. The verifier still checks aud +
1344
+ * sd_hash + Ed25519 signature — nonce skew only relaxes anti-replay
1345
+ * across the session.
1346
+ */
1347
+ function extractKbNonce(presentation) {
1348
+ // SD-JWT: the KB-JWT is the last `~` part. Anonymous credential: one
1349
+ // plain JWS, whose payload carries the nonce itself.
1350
+ const parts = presentation.split("~");
1351
+ const last = parts[parts.length - 1];
1352
+ if (!last || !last.includes("."))
1353
+ return undefined;
1354
+ const [, kbP] = last.split(".");
1355
+ if (!kbP)
1356
+ return undefined;
1357
+ try {
1358
+ const pad = (4 - (kbP.length % 4)) % 4;
1359
+ const std = (kbP + "=".repeat(pad)).replace(/-/g, "+").replace(/_/g, "/");
1360
+ const decoded = JSON.parse(atob(std));
1361
+ return decoded.nonce;
1362
+ }
1363
+ catch {
1364
+ return undefined;
1365
+ }
1366
+ }
1367
+ /** SHA-256 (hex) of a presentation string — the replay-set key. */
1368
+ async function presentationDigest(presentation) {
1369
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(presentation));
1370
+ const view = new Uint8Array(digest);
1371
+ let out = "";
1372
+ for (let i = 0; i < view.length; i++)
1373
+ out += view[i].toString(16).padStart(2, "0");
1374
+ return out;
1375
+ }
1376
+ /**
1377
+ * `Uint8Array` → standard base64 (with `=` padding) for inclusion
1378
+ * inside a JSON envelope. Used by the request channel's
1379
+ * `document-sign` payload when the document arrives as raw bytes.
1380
+ */
1381
+ function u8ToB64(bytes) {
1382
+ let s = "";
1383
+ for (let i = 0; i < bytes.length; i++)
1384
+ s += String.fromCharCode(bytes[i]);
1385
+ return btoa(s);
1386
+ }
1387
+ /**
1388
+ * Canonical-JSON encoder: stable key ordering at every nesting
1389
+ * depth, no whitespace, arrays preserve insertion order. Used as
1390
+ * the input to the SHA-256 that becomes `claim_added.newHash` /
1391
+ * `claim_updated.newHash`. Matches the wallet's
1392
+ * `canonicalStringify` byte-for-byte, so both sides hash to the
1393
+ * same digest — the host can precompute a known-value digest and
1394
+ * compare.
1395
+ */
1396
+ function canonicalJson(value) {
1397
+ if (value === undefined)
1398
+ return "null";
1399
+ if (value === null)
1400
+ return "null";
1401
+ if (typeof value === "string")
1402
+ return JSON.stringify(value);
1403
+ if (typeof value === "number" || typeof value === "boolean") {
1404
+ return JSON.stringify(value);
1405
+ }
1406
+ if (Array.isArray(value)) {
1407
+ return "[" + value.map(canonicalJson).join(",") + "]";
1408
+ }
1409
+ if (typeof value === "object") {
1410
+ const obj = value;
1411
+ const keys = Object.keys(obj).sort();
1412
+ return ("{" +
1413
+ keys
1414
+ .map((k) => JSON.stringify(k) + ":" + canonicalJson(obj[k]))
1415
+ .join(",") +
1416
+ "}");
1417
+ }
1418
+ return JSON.stringify(String(value));
1419
+ }
1420
+ /**
1421
+ * SHA-256 over `canonicalJson(value)` returned as 64-char lowercase
1422
+ * hex. Uses the browser-native WebCrypto API — no dependency. Async
1423
+ * because `crypto.subtle.digest` is async.
1424
+ */
1425
+ async function canonicalSha256Hex(value) {
1426
+ const bytes = new TextEncoder().encode(canonicalJson(value));
1427
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
1428
+ const view = new Uint8Array(digest);
1429
+ let s = "";
1430
+ for (let i = 0; i < view.length; i++) {
1431
+ s += view[i].toString(16).padStart(2, "0");
1432
+ }
1433
+ return s;
1434
+ }
1435
+ /**
1436
+ * Structural equality for claim values. The verifier emits plain
1437
+ * JSON shapes (strings, numbers, booleans, arrays of those, objects
1438
+ * of those) so a value-equal comparison via JSON round-trip is
1439
+ * correct and ~25 ns for the sizes we see in practice. Avoids
1440
+ * pulling in a deep-equal dep for one call site.
1441
+ */
1442
+ function _deepEqual(a, b) {
1443
+ if (a === b)
1444
+ return true;
1445
+ if (typeof a !== "object" || typeof b !== "object")
1446
+ return false;
1447
+ if (a === null || b === null)
1448
+ return false;
1449
+ try {
1450
+ return JSON.stringify(a) === JSON.stringify(b);
1451
+ }
1452
+ catch {
1453
+ return false;
1454
+ }
1455
+ }