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