@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/bind.js
ADDED
|
@@ -0,0 +1,1384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DOM binding helpers — drive a `session.request(...)` from a
|
|
3
|
+
* page's existing form elements.
|
|
4
|
+
*
|
|
5
|
+
* Two entry points:
|
|
6
|
+
*
|
|
7
|
+
* * [`bindInput`] — for a single `<input>` / `<textarea>` /
|
|
8
|
+
* `<select>` element. Reads the element's `type`, `name`,
|
|
9
|
+
* `placeholder`, `required`, `min`/`max`/`minlength`/`maxlength`
|
|
10
|
+
* /`pattern`, and (for `<select>`) `<option>` children. Returns
|
|
11
|
+
* a controller whose `.request()` method synthesises a single
|
|
12
|
+
* `kind: "input"` request and, on a successful wallet reply,
|
|
13
|
+
* writes the value back into the element and dispatches
|
|
14
|
+
* `input` + `change` events so reactive frameworks pick it up.
|
|
15
|
+
*
|
|
16
|
+
* * [`bindForm`] — for a `<form>` (or any container holding
|
|
17
|
+
* inputs). Walks descendant `<input>`/`<textarea>`/`<select>`
|
|
18
|
+
* elements in document order, synthesises one
|
|
19
|
+
* `kind: "input-form"` request carrying every field, opens
|
|
20
|
+
* a single wallet drawer that paginates prev / next / send,
|
|
21
|
+
* fills every element on reply, and (when the bind target is
|
|
22
|
+
* a `<form>`) calls `requestSubmit()` so the page's existing
|
|
23
|
+
* submit handlers fire.
|
|
24
|
+
*
|
|
25
|
+
* Neither helper auto-fires. The host wires the controller's
|
|
26
|
+
* `.request()` to whatever trigger they prefer — a button click,
|
|
27
|
+
* focus, route change, etc. Keeps the SDK out of UX decisions
|
|
28
|
+
* about WHEN to ask.
|
|
29
|
+
*/
|
|
30
|
+
import { closeAllOverlays, findNearestClickableInOverlay, isSelectOverlayActive, openSelectOverlay, setOverlaySnap, } from "./select_overlay.js";
|
|
31
|
+
import { closePointPhoneOverlay, openPointPhoneOverlay, } from "./point_phone_overlay.js";
|
|
32
|
+
/**
|
|
33
|
+
* Bind to a single input-shaped element. Accepted nodes:
|
|
34
|
+
*
|
|
35
|
+
* * `<input>` (type ∈ text/search/email/tel/url/number/password
|
|
36
|
+
* — falls back to `text` for unsupported types like `date`),
|
|
37
|
+
* * `<textarea>` (treated as a `text` input),
|
|
38
|
+
* * `<select>` (with `<option>` children).
|
|
39
|
+
*
|
|
40
|
+
* The element's `aria-label`, label-for, or closest `<label>` text
|
|
41
|
+
* becomes the wallet's prompt label. `placeholder` rides through.
|
|
42
|
+
* Numeric / pattern constraints become wallet-side validation.
|
|
43
|
+
*
|
|
44
|
+
* Reply: the wallet's `value` is written via `element.value = ...`
|
|
45
|
+
* + `input` + `change` events. For `<select>`, the value is matched
|
|
46
|
+
* against the option `value` attributes.
|
|
47
|
+
*/
|
|
48
|
+
export function bindInput(session, element) {
|
|
49
|
+
return {
|
|
50
|
+
async request(opts) {
|
|
51
|
+
// Passwords and one-time codes never cross the live channel, in
|
|
52
|
+
// either direction: whoever holds the phone end may not be the
|
|
53
|
+
// person at this screen (see isSensitiveField).
|
|
54
|
+
if (isSensitiveField(element))
|
|
55
|
+
return { ok: false, error: "unsupported" };
|
|
56
|
+
const req = inputRequestFromElement(element, opts?.reason);
|
|
57
|
+
const reply = await session.request(req, opts);
|
|
58
|
+
if (reply.ok)
|
|
59
|
+
writeValueIntoElement(element, reply.value);
|
|
60
|
+
return reply;
|
|
61
|
+
},
|
|
62
|
+
dispose() { },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Bind to a `<form>` or any container element. Walks descendant
|
|
67
|
+
* input-shaped elements in document order, sends ONE
|
|
68
|
+
* `kind: "input-form"` request, and on reply fills every matching
|
|
69
|
+
* field + dispatches events.
|
|
70
|
+
*
|
|
71
|
+
* Field name resolution:
|
|
72
|
+
*
|
|
73
|
+
* 1. `element.name` — the canonical key.
|
|
74
|
+
* 2. `element.id` — fallback for label-less inputs.
|
|
75
|
+
* 3. `_field_<index>` — synthetic fallback so the reply still
|
|
76
|
+
* finds its target.
|
|
77
|
+
*
|
|
78
|
+
* If the bound container IS a `<form>`, a successful reply also
|
|
79
|
+
* fires `form.requestSubmit()` so the host's existing submit
|
|
80
|
+
* handler picks up. Containers that aren't forms skip the submit
|
|
81
|
+
* step.
|
|
82
|
+
*
|
|
83
|
+
* Buttons/checkboxes/hidden inputs are ignored on purpose — they
|
|
84
|
+
* don't fit the kiosk-input shape and confuse the wallet drawer.
|
|
85
|
+
*/
|
|
86
|
+
export function bindForm(session, container) {
|
|
87
|
+
return {
|
|
88
|
+
async request(opts) {
|
|
89
|
+
const elements = collectFieldElements(container);
|
|
90
|
+
if (elements.length === 0) {
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
error: "unsupported",
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
// Single-element shortcut — friendlier UX (one focused drawer,
|
|
97
|
+
// smaller envelope) than wrapping a lone input in an input-form.
|
|
98
|
+
if (elements.length === 1) {
|
|
99
|
+
const reply = await session.request(inputRequestFromElement(elements[0], opts?.reason), opts);
|
|
100
|
+
if (reply.ok)
|
|
101
|
+
writeValueIntoElement(elements[0], reply.value);
|
|
102
|
+
if (reply.ok && container instanceof HTMLFormElement) {
|
|
103
|
+
tryRequestSubmit(container);
|
|
104
|
+
}
|
|
105
|
+
return reply;
|
|
106
|
+
}
|
|
107
|
+
const fields = elements.map((el, i) => fieldFromElement(el, i));
|
|
108
|
+
const req = {
|
|
109
|
+
kind: "input-form",
|
|
110
|
+
fields,
|
|
111
|
+
submitLabel: container instanceof HTMLFormElement ? "Send" : "Done",
|
|
112
|
+
reason: opts?.reason,
|
|
113
|
+
};
|
|
114
|
+
const reply = await session.request(req, opts);
|
|
115
|
+
if (reply.ok && reply.value && typeof reply.value === "object") {
|
|
116
|
+
const values = reply.value;
|
|
117
|
+
for (const el of elements) {
|
|
118
|
+
const name = nameForElement(el, elements.indexOf(el));
|
|
119
|
+
if (name in values)
|
|
120
|
+
writeValueIntoElement(el, values[name]);
|
|
121
|
+
}
|
|
122
|
+
if (container instanceof HTMLFormElement)
|
|
123
|
+
tryRequestSubmit(container);
|
|
124
|
+
}
|
|
125
|
+
return reply;
|
|
126
|
+
},
|
|
127
|
+
dispose() { },
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
// ─── DOM → request synthesis ───────────────────────────────────────
|
|
131
|
+
function inputRequestFromElement(el, reason) {
|
|
132
|
+
if (el instanceof HTMLSelectElement) {
|
|
133
|
+
return {
|
|
134
|
+
kind: "input",
|
|
135
|
+
inputType: "select",
|
|
136
|
+
label: resolveLabel(el),
|
|
137
|
+
options: readOptions(el),
|
|
138
|
+
defaultValue: el.value || undefined,
|
|
139
|
+
required: el.required,
|
|
140
|
+
reason,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const inputType = resolveInputType(el);
|
|
144
|
+
const base = {
|
|
145
|
+
kind: "input",
|
|
146
|
+
inputType,
|
|
147
|
+
label: resolveLabel(el),
|
|
148
|
+
placeholder: el.placeholder || undefined,
|
|
149
|
+
defaultValue: el.value || undefined,
|
|
150
|
+
required: el instanceof HTMLInputElement ? el.required : false,
|
|
151
|
+
reason,
|
|
152
|
+
};
|
|
153
|
+
return {
|
|
154
|
+
...base,
|
|
155
|
+
...textConstraints(el),
|
|
156
|
+
...(el instanceof HTMLInputElement && inputType === "number"
|
|
157
|
+
? numericConstraints(el)
|
|
158
|
+
: {}),
|
|
159
|
+
...(el instanceof HTMLInputElement && el.pattern
|
|
160
|
+
? { pattern: el.pattern }
|
|
161
|
+
: {}),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function fieldFromElement(el, index) {
|
|
165
|
+
const name = nameForElement(el, index);
|
|
166
|
+
if (el instanceof HTMLSelectElement) {
|
|
167
|
+
return {
|
|
168
|
+
name,
|
|
169
|
+
inputType: "select",
|
|
170
|
+
label: resolveLabel(el),
|
|
171
|
+
options: readOptions(el),
|
|
172
|
+
defaultValue: el.value || undefined,
|
|
173
|
+
required: el.required,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const inputType = resolveInputType(el);
|
|
177
|
+
return {
|
|
178
|
+
name,
|
|
179
|
+
inputType,
|
|
180
|
+
label: resolveLabel(el),
|
|
181
|
+
placeholder: el.placeholder || undefined,
|
|
182
|
+
defaultValue: el.value || undefined,
|
|
183
|
+
required: el instanceof HTMLInputElement ? el.required : false,
|
|
184
|
+
...textConstraints(el),
|
|
185
|
+
...(el instanceof HTMLInputElement && inputType === "number"
|
|
186
|
+
? numericConstraints(el)
|
|
187
|
+
: {}),
|
|
188
|
+
...(el instanceof HTMLInputElement && el.pattern
|
|
189
|
+
? { pattern: el.pattern }
|
|
190
|
+
: {}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function collectFieldElements(container) {
|
|
194
|
+
const out = [];
|
|
195
|
+
const all = container.querySelectorAll("input, textarea, select");
|
|
196
|
+
// Filter: skip non-bindable inputs (button, submit, hidden,
|
|
197
|
+
// checkbox, radio, file). Those don't map to the kiosk pattern
|
|
198
|
+
// and would confuse the drawer's prev/next navigation.
|
|
199
|
+
const SKIPPED = new Set([
|
|
200
|
+
"button",
|
|
201
|
+
"submit",
|
|
202
|
+
"reset",
|
|
203
|
+
"image",
|
|
204
|
+
"hidden",
|
|
205
|
+
"file",
|
|
206
|
+
"checkbox",
|
|
207
|
+
"radio",
|
|
208
|
+
]);
|
|
209
|
+
for (let i = 0; i < all.length; i++) {
|
|
210
|
+
const el = all[i];
|
|
211
|
+
if (isSensitiveField(el))
|
|
212
|
+
continue; // passwords / one-time codes stay on this page
|
|
213
|
+
if (el instanceof HTMLInputElement) {
|
|
214
|
+
const t = (el.type || "text").toLowerCase();
|
|
215
|
+
if (SKIPPED.has(t))
|
|
216
|
+
continue;
|
|
217
|
+
if (el.disabled || el.readOnly)
|
|
218
|
+
continue;
|
|
219
|
+
out.push(el);
|
|
220
|
+
}
|
|
221
|
+
else if (el instanceof HTMLTextAreaElement) {
|
|
222
|
+
if (el.disabled || el.readOnly)
|
|
223
|
+
continue;
|
|
224
|
+
out.push(el);
|
|
225
|
+
}
|
|
226
|
+
else if (el instanceof HTMLSelectElement) {
|
|
227
|
+
if (el.disabled)
|
|
228
|
+
continue;
|
|
229
|
+
out.push(el);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Fields whose value must never travel over the live channel: password
|
|
236
|
+
* inputs and anything marked `autocomplete` current-password /
|
|
237
|
+
* new-password / one-time-code. Anyone who scans a sign-in code first
|
|
238
|
+
* holds the phone end of the channel, so the SDK neither mirrors these
|
|
239
|
+
* values to the phone nor lets the phone fill them: bindInput refuses,
|
|
240
|
+
* bindForm and remote navigation skip them.
|
|
241
|
+
*/
|
|
242
|
+
export function isSensitiveField(el) {
|
|
243
|
+
const tokens = (el.getAttribute("autocomplete") ?? "").toLowerCase().split(/\s+/);
|
|
244
|
+
if (tokens.some((t) => t === "current-password" || t === "new-password" || t === "one-time-code"))
|
|
245
|
+
return true;
|
|
246
|
+
if (typeof HTMLInputElement !== "undefined" && el instanceof HTMLInputElement) {
|
|
247
|
+
return (el.type || "text").toLowerCase() === "password";
|
|
248
|
+
}
|
|
249
|
+
return (el.getAttribute("type") ?? "").toLowerCase() === "password";
|
|
250
|
+
}
|
|
251
|
+
function resolveInputType(el) {
|
|
252
|
+
if (el instanceof HTMLTextAreaElement)
|
|
253
|
+
return "text";
|
|
254
|
+
const t = (el.type || "text").toLowerCase();
|
|
255
|
+
switch (t) {
|
|
256
|
+
case "text":
|
|
257
|
+
case "search":
|
|
258
|
+
case "email":
|
|
259
|
+
case "tel":
|
|
260
|
+
case "url":
|
|
261
|
+
case "number":
|
|
262
|
+
case "password":
|
|
263
|
+
return t;
|
|
264
|
+
// HTML5 types we don't have a wallet-side keyboard for — fall
|
|
265
|
+
// back to `text` so the drawer still renders something useful.
|
|
266
|
+
case "date":
|
|
267
|
+
case "datetime-local":
|
|
268
|
+
case "time":
|
|
269
|
+
case "month":
|
|
270
|
+
case "week":
|
|
271
|
+
case "color":
|
|
272
|
+
case "range":
|
|
273
|
+
default:
|
|
274
|
+
return "text";
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function resolveLabel(el) {
|
|
278
|
+
// Priority: aria-label > <label for> > parent <label> text >
|
|
279
|
+
// placeholder > name > tag-name.
|
|
280
|
+
const aria = el.getAttribute("aria-label");
|
|
281
|
+
if (aria && aria.trim())
|
|
282
|
+
return aria.trim();
|
|
283
|
+
if (el.id) {
|
|
284
|
+
const lbl = el.ownerDocument.querySelector(`label[for="${cssEscape(el.id)}"]`);
|
|
285
|
+
if (lbl && lbl.textContent && lbl.textContent.trim()) {
|
|
286
|
+
return lbl.textContent.trim();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const closestLabel = el.closest("label");
|
|
290
|
+
if (closestLabel && closestLabel.textContent) {
|
|
291
|
+
// Strip the input's own text content from the label string
|
|
292
|
+
// so a wrapping `<label>Email <input></label>` doesn't include
|
|
293
|
+
// the input's value.
|
|
294
|
+
const ownText = "value" in el && typeof el.value === "string"
|
|
295
|
+
? el.value
|
|
296
|
+
: (el.textContent ?? "");
|
|
297
|
+
const raw = closestLabel.textContent.replace(ownText, "").trim();
|
|
298
|
+
if (raw)
|
|
299
|
+
return raw;
|
|
300
|
+
}
|
|
301
|
+
if ("placeholder" in el &&
|
|
302
|
+
el.placeholder &&
|
|
303
|
+
el.placeholder.trim()) {
|
|
304
|
+
return el.placeholder.trim();
|
|
305
|
+
}
|
|
306
|
+
if (el.name)
|
|
307
|
+
return prettyName(el.name);
|
|
308
|
+
return prettyName(el.tagName.toLowerCase());
|
|
309
|
+
}
|
|
310
|
+
function readOptions(el) {
|
|
311
|
+
const out = [];
|
|
312
|
+
for (let i = 0; i < el.options.length; i++) {
|
|
313
|
+
const opt = el.options[i];
|
|
314
|
+
out.push({
|
|
315
|
+
value: opt.value,
|
|
316
|
+
label: opt.label || opt.textContent || opt.value,
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
function textConstraints(el) {
|
|
322
|
+
const out = {};
|
|
323
|
+
if ("minLength" in el && el.minLength > 0)
|
|
324
|
+
out.minLength = el.minLength;
|
|
325
|
+
if ("maxLength" in el && el.maxLength > 0)
|
|
326
|
+
out.maxLength = el.maxLength;
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
function numericConstraints(el) {
|
|
330
|
+
const out = {};
|
|
331
|
+
const minStr = el.getAttribute("min");
|
|
332
|
+
const maxStr = el.getAttribute("max");
|
|
333
|
+
if (minStr !== null && minStr !== "") {
|
|
334
|
+
const n = Number(minStr);
|
|
335
|
+
if (Number.isFinite(n))
|
|
336
|
+
out.min = n;
|
|
337
|
+
}
|
|
338
|
+
if (maxStr !== null && maxStr !== "") {
|
|
339
|
+
const n = Number(maxStr);
|
|
340
|
+
if (Number.isFinite(n))
|
|
341
|
+
out.max = n;
|
|
342
|
+
}
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
function nameForElement(el, index) {
|
|
346
|
+
if (el.name)
|
|
347
|
+
return el.name;
|
|
348
|
+
if (el.id)
|
|
349
|
+
return el.id;
|
|
350
|
+
return `_field_${index}`;
|
|
351
|
+
}
|
|
352
|
+
function prettyName(s) {
|
|
353
|
+
return s.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
|
|
354
|
+
}
|
|
355
|
+
// ─── Byte / encoding helpers ───────────────────────────────────────
|
|
356
|
+
/**
|
|
357
|
+
* Decode a base64url-padded chunk string into a fresh `Uint8Array`.
|
|
358
|
+
* Returns null on bad input so the receiver can drop the envelope
|
|
359
|
+
* without crashing. Used by the file-transfer reassembly path —
|
|
360
|
+
* each chunk is decoded once, written into the per-transfer
|
|
361
|
+
* `Uint8Array[]` slot, and the source string is dropped.
|
|
362
|
+
*/
|
|
363
|
+
function b64uToBytes(s) {
|
|
364
|
+
// Normalise to standard base64 with padding so `atob` accepts it.
|
|
365
|
+
const pad = (4 - (s.length % 4)) % 4;
|
|
366
|
+
const std = (s + "=".repeat(pad)).replace(/-/g, "+").replace(/_/g, "/");
|
|
367
|
+
try {
|
|
368
|
+
const bin = atob(std);
|
|
369
|
+
const out = new Uint8Array(bin.length);
|
|
370
|
+
for (let i = 0; i < bin.length; i++)
|
|
371
|
+
out[i] = bin.charCodeAt(i);
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/** Hex-encode a Uint8Array (lowercase, no separators). */
|
|
379
|
+
function bytesToHex(b) {
|
|
380
|
+
let s = "";
|
|
381
|
+
for (let i = 0; i < b.length; i++)
|
|
382
|
+
s += b[i].toString(16).padStart(2, "0");
|
|
383
|
+
return s;
|
|
384
|
+
}
|
|
385
|
+
// ─── Reply → DOM ───────────────────────────────────────────────────
|
|
386
|
+
function writeValueIntoElement(el, value) {
|
|
387
|
+
if (value === undefined || value === null)
|
|
388
|
+
return;
|
|
389
|
+
const str = String(value);
|
|
390
|
+
if (el instanceof HTMLSelectElement) {
|
|
391
|
+
// Match by value first, then by visible label.
|
|
392
|
+
let matched = false;
|
|
393
|
+
for (let i = 0; i < el.options.length; i++) {
|
|
394
|
+
if (el.options[i].value === str) {
|
|
395
|
+
el.selectedIndex = i;
|
|
396
|
+
matched = true;
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (!matched) {
|
|
401
|
+
for (let i = 0; i < el.options.length; i++) {
|
|
402
|
+
if (el.options[i].label === str) {
|
|
403
|
+
el.selectedIndex = i;
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
el.value = str;
|
|
411
|
+
}
|
|
412
|
+
// Reactive frameworks (React, Vue, etc.) listen for `input` /
|
|
413
|
+
// `change` to pick up the new value. Dispatch both so we don't
|
|
414
|
+
// miss either bucket.
|
|
415
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
416
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
417
|
+
}
|
|
418
|
+
function tryRequestSubmit(form) {
|
|
419
|
+
// `requestSubmit` runs the form's existing submit handler +
|
|
420
|
+
// validation; `submit` skips both. Always prefer
|
|
421
|
+
// `requestSubmit` when available — guards against pre-2020
|
|
422
|
+
// browsers via the typeof check.
|
|
423
|
+
if (typeof form.requestSubmit === "function") {
|
|
424
|
+
form.requestSubmit();
|
|
425
|
+
}
|
|
426
|
+
else {
|
|
427
|
+
form.submit();
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Wire up **remote navigation**. Pushes the page's currently-focused
|
|
432
|
+
* input to the wallet (metadata + current value) and applies inbound
|
|
433
|
+
* `nav` / `value` / `logout` commands as the user interacts with the
|
|
434
|
+
* wallet's persistent navigation banner.
|
|
435
|
+
*
|
|
436
|
+
* Wiring summary:
|
|
437
|
+
*
|
|
438
|
+
* * `focusin` on any tabbable input → `session._sendFocus(focus)`.
|
|
439
|
+
* * `focusout` on the same → `session._sendFocus(null)`.
|
|
440
|
+
* * `input` on the focused element → push the new value to the
|
|
441
|
+
* wallet so the phone mirror stays in sync if the user typed on
|
|
442
|
+
* the desktop. Debounced to one frame to avoid flooding.
|
|
443
|
+
* * Inbound `nav: "prev" | "next"` → move DOM focus along the
|
|
444
|
+
* tabbable-input order from the focused element.
|
|
445
|
+
* * Inbound `nav: "submit"` → `form.requestSubmit()` on the closest
|
|
446
|
+
* enclosing form.
|
|
447
|
+
* * Inbound `value` → write to the focused element + dispatch
|
|
448
|
+
* `input` + `change`. Reactive frameworks pick it up.
|
|
449
|
+
* * Inbound `logout` → session already torn down by the dispatcher;
|
|
450
|
+
* helper just detaches.
|
|
451
|
+
*
|
|
452
|
+
* Call this once after `signIn()` resolves when you passed
|
|
453
|
+
* `remoteNavigation: true`. The returned controller's `dispose()` is
|
|
454
|
+
* idempotent and runs on `signed_out` automatically.
|
|
455
|
+
*/
|
|
456
|
+
export function enableRemoteNavigation(session, opts) {
|
|
457
|
+
const root = opts?.root ?? document.body;
|
|
458
|
+
let currentFocused = null;
|
|
459
|
+
let disposed = false;
|
|
460
|
+
function isBindable(el) {
|
|
461
|
+
// Passwords and one-time codes are never mirrored to the phone.
|
|
462
|
+
if (isSensitiveField(el))
|
|
463
|
+
return false;
|
|
464
|
+
if (el instanceof HTMLInputElement) {
|
|
465
|
+
const t = (el.type || "text").toLowerCase();
|
|
466
|
+
if (t === "hidden" || t === "submit" || t === "button" ||
|
|
467
|
+
t === "reset" || t === "image" ||
|
|
468
|
+
t === "checkbox" || t === "radio")
|
|
469
|
+
return false;
|
|
470
|
+
// `type="file"` IS bindable — the wallet shows a picker UI
|
|
471
|
+
// and streams the chosen bytes back. Handled by the
|
|
472
|
+
// file-transfer reassembly path in `_handleMessage`; the
|
|
473
|
+
// `readOnly` check below doesn't apply (file inputs ignore
|
|
474
|
+
// it but expose the property as `false` regardless).
|
|
475
|
+
if (t === "file")
|
|
476
|
+
return !el.disabled;
|
|
477
|
+
return !el.disabled && !el.readOnly;
|
|
478
|
+
}
|
|
479
|
+
if (el instanceof HTMLTextAreaElement) {
|
|
480
|
+
return !el.disabled && !el.readOnly;
|
|
481
|
+
}
|
|
482
|
+
if (el instanceof HTMLSelectElement) {
|
|
483
|
+
return !el.disabled;
|
|
484
|
+
}
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
/** Buttons + button-type inputs. Tracked separately from
|
|
488
|
+
* [isBindable] so prev/next navigation only walks the
|
|
489
|
+
* input-like pool, but focus envelopes still fire for buttons
|
|
490
|
+
* (so the wallet can show the Enter row). */
|
|
491
|
+
function isFocusableButton(el) {
|
|
492
|
+
if (el instanceof HTMLButtonElement)
|
|
493
|
+
return !el.disabled;
|
|
494
|
+
if (el instanceof HTMLInputElement) {
|
|
495
|
+
const t = (el.type || "text").toLowerCase();
|
|
496
|
+
return (t === "submit" || t === "button" || t === "reset") && !el.disabled;
|
|
497
|
+
}
|
|
498
|
+
return el.getAttribute("role") === "button";
|
|
499
|
+
}
|
|
500
|
+
function collectFields() {
|
|
501
|
+
if (opts?.collectFields)
|
|
502
|
+
return opts.collectFields().filter((el) => !isSensitiveField(el));
|
|
503
|
+
const out = [];
|
|
504
|
+
const all = root.querySelectorAll("input, textarea, select");
|
|
505
|
+
for (let i = 0; i < all.length; i++) {
|
|
506
|
+
const el = all[i];
|
|
507
|
+
if (isBindable(el))
|
|
508
|
+
out.push(el);
|
|
509
|
+
}
|
|
510
|
+
return out;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Compute the prev / next / submit / enter visibility hints the
|
|
514
|
+
* wallet's banner drawer needs to render only the buttons that
|
|
515
|
+
* make sense for the page's current state.
|
|
516
|
+
*
|
|
517
|
+
* Rules (mirrored on the wallet — see `_navigationRow`):
|
|
518
|
+
*
|
|
519
|
+
* * `hasPrev` — there's at least one bindable input *before*
|
|
520
|
+
* this one in the tabbing pool.
|
|
521
|
+
* * `hasNext` — there's at least one bindable input *after*
|
|
522
|
+
* this one.
|
|
523
|
+
* * `isLastInForm`— this element is the last bindable input
|
|
524
|
+
* inside its enclosing `<form>`. Mutually
|
|
525
|
+
* exclusive with `hasNext` when the form
|
|
526
|
+
* ends the bindable pool; only true for input-
|
|
527
|
+
* like elements, never for buttons.
|
|
528
|
+
* * `isButton` — the focused element is a click target
|
|
529
|
+
* (`<button>`, `<input type=submit|button>`,
|
|
530
|
+
* `role="button"`). The wallet shows an
|
|
531
|
+
* "Enter" button that dispatches `nav: "submit"`,
|
|
532
|
+
* and the helper here treats that action as a
|
|
533
|
+
* synthetic click rather than a form submit.
|
|
534
|
+
*/
|
|
535
|
+
function computeNavMeta(el) {
|
|
536
|
+
const isButton = el instanceof HTMLButtonElement ||
|
|
537
|
+
(el instanceof HTMLInputElement &&
|
|
538
|
+
(el.type === "submit" || el.type === "button" || el.type === "reset")) ||
|
|
539
|
+
el.getAttribute("role") === "button";
|
|
540
|
+
if (isButton) {
|
|
541
|
+
// A focused button has no concept of "prev/next input" — the
|
|
542
|
+
// wallet hides those rows entirely and shows just Enter.
|
|
543
|
+
return { hasPrev: false, hasNext: false, isLastInForm: false, isButton: true };
|
|
544
|
+
}
|
|
545
|
+
const fields = collectFields();
|
|
546
|
+
const idx = fields.indexOf(el);
|
|
547
|
+
const hasPrev = idx > 0;
|
|
548
|
+
const hasNext = idx >= 0 && idx < fields.length - 1;
|
|
549
|
+
let isLastInForm = false;
|
|
550
|
+
const form = el.closest?.("form");
|
|
551
|
+
if (form instanceof HTMLFormElement) {
|
|
552
|
+
const fieldsInForm = fields.filter((f) => f.closest("form") === form);
|
|
553
|
+
isLastInForm =
|
|
554
|
+
fieldsInForm.length > 0 &&
|
|
555
|
+
fieldsInForm[fieldsInForm.length - 1] === el;
|
|
556
|
+
}
|
|
557
|
+
return { hasPrev, hasNext, isLastInForm, isButton: false };
|
|
558
|
+
}
|
|
559
|
+
function focusPayloadFor(el) {
|
|
560
|
+
const name = nameForElement(el, 0);
|
|
561
|
+
const meta = computeNavMeta(el);
|
|
562
|
+
if (el instanceof HTMLButtonElement || (el instanceof HTMLInputElement &&
|
|
563
|
+
(el.type === "submit" || el.type === "button" || el.type === "reset"))) {
|
|
564
|
+
// Button focus — the wallet renders just the Enter row.
|
|
565
|
+
return {
|
|
566
|
+
name,
|
|
567
|
+
label: resolveLabel(el),
|
|
568
|
+
inputType: "button",
|
|
569
|
+
value: el instanceof HTMLButtonElement ? (el.textContent ?? "").trim() : el.value,
|
|
570
|
+
...meta,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
if (el instanceof HTMLSelectElement) {
|
|
574
|
+
return {
|
|
575
|
+
name,
|
|
576
|
+
label: resolveLabel(el),
|
|
577
|
+
inputType: "select",
|
|
578
|
+
value: el.value,
|
|
579
|
+
options: readOptions(el),
|
|
580
|
+
required: el.required,
|
|
581
|
+
...meta,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
if (el instanceof HTMLInputElement && el.type === "file") {
|
|
585
|
+
// File picker: surface `accept` / `multiple` / `capture` so the
|
|
586
|
+
// wallet UI can render the right entry points (camera vs
|
|
587
|
+
// gallery vs files) and validate the user's pick against the
|
|
588
|
+
// host's MIME filter. Value stays empty — we don't try to
|
|
589
|
+
// mirror the picked-file metadata back as text.
|
|
590
|
+
return {
|
|
591
|
+
name,
|
|
592
|
+
label: resolveLabel(el),
|
|
593
|
+
inputType: "file",
|
|
594
|
+
value: "",
|
|
595
|
+
required: el.required,
|
|
596
|
+
accept: el.accept || undefined,
|
|
597
|
+
multiple: el.multiple || undefined,
|
|
598
|
+
capture: el.getAttribute("capture") || undefined,
|
|
599
|
+
...meta,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
const inputType = resolveInputType(el);
|
|
603
|
+
return {
|
|
604
|
+
name,
|
|
605
|
+
label: resolveLabel(el),
|
|
606
|
+
inputType,
|
|
607
|
+
value: el.value,
|
|
608
|
+
placeholder: "placeholder" in el ? el.placeholder || undefined : undefined,
|
|
609
|
+
required: el instanceof HTMLInputElement ? el.required : false,
|
|
610
|
+
...textConstraints(el),
|
|
611
|
+
...(el instanceof HTMLInputElement && inputType === "number"
|
|
612
|
+
? numericConstraints(el)
|
|
613
|
+
: {}),
|
|
614
|
+
...(el instanceof HTMLInputElement && el.pattern
|
|
615
|
+
? { pattern: el.pattern }
|
|
616
|
+
: {}),
|
|
617
|
+
...meta,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
// Debounced "current value changed locally" notifier — keeps the
|
|
621
|
+
// wallet mirror in sync if the user types on the desktop while the
|
|
622
|
+
// wallet drawer is open. requestAnimationFrame caps push rate
|
|
623
|
+
// at ~60 Hz which is well below the wallet's processing budget.
|
|
624
|
+
let pendingFrame = null;
|
|
625
|
+
function scheduleValuePush() {
|
|
626
|
+
if (pendingFrame !== null)
|
|
627
|
+
return;
|
|
628
|
+
pendingFrame = requestAnimationFrame(() => {
|
|
629
|
+
pendingFrame = null;
|
|
630
|
+
if (disposed || !currentFocused)
|
|
631
|
+
return;
|
|
632
|
+
void session._sendFocus(focusPayloadFor(currentFocused));
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
function onFocusIn(ev) {
|
|
636
|
+
const t = ev.target;
|
|
637
|
+
if (!(t instanceof Element))
|
|
638
|
+
return;
|
|
639
|
+
if (isSensitiveField(t)) {
|
|
640
|
+
// Focus moved to a password / one-time code: clear the phone's
|
|
641
|
+
// mirror, and don't let a `value` from the phone land here.
|
|
642
|
+
if (currentFocused)
|
|
643
|
+
void session._sendFocus(null);
|
|
644
|
+
currentFocused = null;
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (isBindable(t)) {
|
|
648
|
+
currentFocused = t;
|
|
649
|
+
void session._sendFocus(focusPayloadFor(t));
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (isFocusableButton(t)) {
|
|
653
|
+
currentFocused = t;
|
|
654
|
+
void session._sendFocus(focusPayloadFor(t));
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function onFocusOut(ev) {
|
|
658
|
+
const t = ev.target;
|
|
659
|
+
if (t !== currentFocused)
|
|
660
|
+
return;
|
|
661
|
+
currentFocused = null;
|
|
662
|
+
void session._sendFocus(null);
|
|
663
|
+
}
|
|
664
|
+
function onInputChange(ev) {
|
|
665
|
+
if (ev.target !== currentFocused)
|
|
666
|
+
return;
|
|
667
|
+
scheduleValuePush();
|
|
668
|
+
}
|
|
669
|
+
function applyNav(action) {
|
|
670
|
+
if (action === "submit") {
|
|
671
|
+
// Two semantics on one wire action:
|
|
672
|
+
//
|
|
673
|
+
// * focused element IS a button → click it. Wallet shows
|
|
674
|
+
// this as "Enter" when [isButton: true] in the focus
|
|
675
|
+
// envelope, and the user expects pressing it on the
|
|
676
|
+
// phone to fire the button's click handler.
|
|
677
|
+
// * else → submit the enclosing form. Wallet shows this as
|
|
678
|
+
// "Submit" when [isLastInForm: true].
|
|
679
|
+
//
|
|
680
|
+
// We use one nav action for both so the wire grammar stays
|
|
681
|
+
// narrow; the contextual UX is decided on the wallet side
|
|
682
|
+
// (different label / icon) and the dispatch routes correctly
|
|
683
|
+
// by inspecting `currentFocused`.
|
|
684
|
+
const focused = currentFocused;
|
|
685
|
+
if (focused instanceof HTMLButtonElement ||
|
|
686
|
+
(focused instanceof HTMLInputElement &&
|
|
687
|
+
(focused.type === "submit" ||
|
|
688
|
+
focused.type === "button" ||
|
|
689
|
+
focused.type === "reset")) ||
|
|
690
|
+
focused?.getAttribute("role") === "button") {
|
|
691
|
+
try {
|
|
692
|
+
focused.click();
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
/* swallow */
|
|
696
|
+
}
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
const form = currentFocused?.closest("form") ?? root.querySelector("form");
|
|
700
|
+
if (form instanceof HTMLFormElement)
|
|
701
|
+
tryRequestSubmit(form);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
const fields = collectFields();
|
|
705
|
+
if (fields.length === 0)
|
|
706
|
+
return;
|
|
707
|
+
let idx = currentFocused ? fields.indexOf(currentFocused) : -1;
|
|
708
|
+
if (idx === -1)
|
|
709
|
+
idx = action === "prev" ? fields.length : -1;
|
|
710
|
+
const target = action === "next"
|
|
711
|
+
? fields[(idx + 1) % fields.length]
|
|
712
|
+
: fields[(idx - 1 + fields.length) % fields.length];
|
|
713
|
+
target.focus();
|
|
714
|
+
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
|
715
|
+
const len = target.value.length;
|
|
716
|
+
try {
|
|
717
|
+
target.setSelectionRange(len, len);
|
|
718
|
+
}
|
|
719
|
+
catch { /* select-type inputs don't support it */ }
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
function applyValue(value) {
|
|
723
|
+
if (!currentFocused || isSensitiveField(currentFocused))
|
|
724
|
+
return;
|
|
725
|
+
// Value pushes only make sense for input-like fields. If a
|
|
726
|
+
// button is focused (no editable value) just drop the push.
|
|
727
|
+
if (currentFocused instanceof HTMLInputElement ||
|
|
728
|
+
currentFocused instanceof HTMLTextAreaElement ||
|
|
729
|
+
currentFocused instanceof HTMLSelectElement) {
|
|
730
|
+
writeValueIntoElement(currentFocused, value);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const unsubscribe = session._setRemoteNavListener((envelope) => {
|
|
734
|
+
if (envelope.msg === "nav")
|
|
735
|
+
applyNav(envelope.action);
|
|
736
|
+
else if (envelope.msg === "value")
|
|
737
|
+
applyValue(envelope.value);
|
|
738
|
+
else if (envelope.msg === "logout")
|
|
739
|
+
dispose();
|
|
740
|
+
});
|
|
741
|
+
const transfers = new Map();
|
|
742
|
+
const offFile = session._setFileEnvelopeHandler((envelope) => {
|
|
743
|
+
const reqId = envelope.requestId;
|
|
744
|
+
if (!reqId)
|
|
745
|
+
return;
|
|
746
|
+
if (envelope.msg === "file-begin") {
|
|
747
|
+
const begin = envelope.fileBegin;
|
|
748
|
+
if (!begin)
|
|
749
|
+
return;
|
|
750
|
+
// Resolve the target input AT BEGIN time so a focusout that
|
|
751
|
+
// races the transfer doesn't leave us assigning to a
|
|
752
|
+
// disposed element.
|
|
753
|
+
const target = currentFocused instanceof HTMLInputElement && currentFocused.type === "file"
|
|
754
|
+
? currentFocused
|
|
755
|
+
: null;
|
|
756
|
+
transfers.set(reqId, {
|
|
757
|
+
name: begin.name,
|
|
758
|
+
mimeType: begin.mimeType,
|
|
759
|
+
size: begin.size,
|
|
760
|
+
totalChunks: begin.totalChunks,
|
|
761
|
+
received: 0,
|
|
762
|
+
parts: new Array(begin.totalChunks),
|
|
763
|
+
targetInput: target,
|
|
764
|
+
});
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
if (envelope.msg === "file-chunk") {
|
|
768
|
+
const xfer = transfers.get(reqId);
|
|
769
|
+
const chunk = envelope.fileChunk;
|
|
770
|
+
if (!xfer || !chunk)
|
|
771
|
+
return;
|
|
772
|
+
const bytes = b64uToBytes(chunk.data);
|
|
773
|
+
if (!bytes)
|
|
774
|
+
return;
|
|
775
|
+
// Slot the chunk in by index — chunks arrive in order through
|
|
776
|
+
// the ack-tracked layer but indexing defensively keeps the
|
|
777
|
+
// contract obvious to a reader (and would survive a future
|
|
778
|
+
// sliding-window sender).
|
|
779
|
+
xfer.parts[chunk.index] = bytes;
|
|
780
|
+
xfer.received += 1;
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
if (envelope.msg === "file-end") {
|
|
784
|
+
const xfer = transfers.get(reqId);
|
|
785
|
+
const end = envelope.fileEnd;
|
|
786
|
+
if (!xfer || !end)
|
|
787
|
+
return;
|
|
788
|
+
transfers.delete(reqId);
|
|
789
|
+
void assembleAndCommit(xfer, end.sha256);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
async function assembleAndCommit(xfer, expectedSha256Hex) {
|
|
794
|
+
if (xfer.received !== xfer.totalChunks)
|
|
795
|
+
return;
|
|
796
|
+
// Blob does NOT copy its parts; this is the only assembly step.
|
|
797
|
+
// The `as unknown as BlobPart[]` cast sidesteps an over-strict
|
|
798
|
+
// type definition where `Uint8Array<ArrayBufferLike>` is not
|
|
799
|
+
// recognised as `BlobPart` even though it always is at runtime.
|
|
800
|
+
const blob = new Blob(xfer.parts, { type: xfer.mimeType });
|
|
801
|
+
// Verify SHA-256. `crypto.subtle.digest` runs over the Blob's
|
|
802
|
+
// ArrayBuffer — one transient allocation, then the buffer is
|
|
803
|
+
// released back to the GC.
|
|
804
|
+
const buf = await blob.arrayBuffer();
|
|
805
|
+
const digestBuf = await crypto.subtle.digest("SHA-256", buf);
|
|
806
|
+
const actual = bytesToHex(new Uint8Array(digestBuf));
|
|
807
|
+
if (actual !== expectedSha256Hex.toLowerCase()) {
|
|
808
|
+
// Hash mismatch — drop silently. A future revision can
|
|
809
|
+
// surface this to the host via an event; today the wallet's
|
|
810
|
+
// ack-tracked retransmit covers the common error case (a
|
|
811
|
+
// dropped chunk).
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
const target = xfer.targetInput;
|
|
815
|
+
if (!target || disposed)
|
|
816
|
+
return;
|
|
817
|
+
const file = new File([blob], xfer.name, {
|
|
818
|
+
type: xfer.mimeType,
|
|
819
|
+
lastModified: Date.now(),
|
|
820
|
+
});
|
|
821
|
+
// `HTMLInputElement.files` is read-only by default — the
|
|
822
|
+
// standard idiom is to build a `DataTransfer`, attach the
|
|
823
|
+
// file(s), and assign the `.files` reference.
|
|
824
|
+
try {
|
|
825
|
+
const dt = new DataTransfer();
|
|
826
|
+
dt.items.add(file);
|
|
827
|
+
target.files = dt.files;
|
|
828
|
+
}
|
|
829
|
+
catch {
|
|
830
|
+
// Browsers without `DataTransfer` (very old) can't accept a
|
|
831
|
+
// programmatic file. Nothing else we can do.
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
// Dispatch `input` + `change` so reactive frameworks pick the
|
|
835
|
+
// selection up. Bubbles + cancelable matches the native
|
|
836
|
+
// dispatch profile.
|
|
837
|
+
target.dispatchEvent(new Event("input", { bubbles: true }));
|
|
838
|
+
target.dispatchEvent(new Event("change", { bubbles: true }));
|
|
839
|
+
}
|
|
840
|
+
// `signed_out` cleanup — the dispatcher's `logout` case also tears
|
|
841
|
+
// the session down; this catches every other terminal path (TTL,
|
|
842
|
+
// wallet-side revoke, transport loss).
|
|
843
|
+
const offSignedOut = session.on("signed_out", () => dispose());
|
|
844
|
+
root.addEventListener("focusin", onFocusIn, true);
|
|
845
|
+
root.addEventListener("focusout", onFocusOut, true);
|
|
846
|
+
root.addEventListener("input", onInputChange, true);
|
|
847
|
+
root.addEventListener("change", onInputChange, true);
|
|
848
|
+
function dispose() {
|
|
849
|
+
if (disposed)
|
|
850
|
+
return;
|
|
851
|
+
disposed = true;
|
|
852
|
+
if (pendingFrame !== null)
|
|
853
|
+
cancelAnimationFrame(pendingFrame);
|
|
854
|
+
pendingFrame = null;
|
|
855
|
+
root.removeEventListener("focusin", onFocusIn, true);
|
|
856
|
+
root.removeEventListener("focusout", onFocusOut, true);
|
|
857
|
+
root.removeEventListener("input", onInputChange, true);
|
|
858
|
+
root.removeEventListener("change", onInputChange, true);
|
|
859
|
+
unsubscribe();
|
|
860
|
+
offFile();
|
|
861
|
+
offSignedOut();
|
|
862
|
+
transfers.clear();
|
|
863
|
+
}
|
|
864
|
+
return { dispose };
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Bind a virtual mouse to the session. Opens a `kind: "mouse"`
|
|
868
|
+
* request on the wallet, then subscribes to the streamed
|
|
869
|
+
* `mouse-update` envelopes and applies them to a CSS-positioned
|
|
870
|
+
* cursor on top of the page.
|
|
871
|
+
*
|
|
872
|
+
* Two modes (the wallet may toggle them mid-session):
|
|
873
|
+
*
|
|
874
|
+
* * `"touch"` — the phone is a touchpad. Drag = move (delta in
|
|
875
|
+
* CSS px), tap = click, double-tap = double-click, two-finger
|
|
876
|
+
* drag = scroll.
|
|
877
|
+
* * `"magic"` — phone gyro + accelerometer drive a "magic wand".
|
|
878
|
+
* Tap on the phone = click; swipe up/down = scroll.
|
|
879
|
+
*
|
|
880
|
+
* The cursor is a `<div>` fixed-positioned at z-index `2147483647`
|
|
881
|
+
* (the max 32-bit signed int — same trick browser extension
|
|
882
|
+
* overlays use to outrank page chrome). `pointer-events: none` so
|
|
883
|
+
* it never intercepts real clicks; we use `elementFromPoint` +
|
|
884
|
+
* synthetic events to forward clicks to the page underneath.
|
|
885
|
+
*
|
|
886
|
+
* Returns a [`BindController`] — call `dispose()` to detach the
|
|
887
|
+
* cursor and stop applying frames. The wallet drawer stays open
|
|
888
|
+
* until the user closes it; disposing the controller silently
|
|
889
|
+
* drops further frames but doesn't tell the wallet to stop.
|
|
890
|
+
*
|
|
891
|
+
* @example
|
|
892
|
+
* const mouse = bindMouse(session, { mode: "touch" });
|
|
893
|
+
* await mouse.request();
|
|
894
|
+
* // later
|
|
895
|
+
* mouse.dispose();
|
|
896
|
+
*/
|
|
897
|
+
export function bindMouse(session, opts) {
|
|
898
|
+
const mode = opts?.mode ?? "touch";
|
|
899
|
+
const size = Math.max(6, opts?.size ?? 28);
|
|
900
|
+
const color = opts?.color ?? "rgba(59, 130, 246, 0.65)";
|
|
901
|
+
const onMove = opts?.onMove;
|
|
902
|
+
const onClick = opts?.onClick;
|
|
903
|
+
// DOM-side state. The cursor element is created lazily on the
|
|
904
|
+
// first `request()` call so a host that builds the controller
|
|
905
|
+
// up-front but never calls request doesn't pollute the page.
|
|
906
|
+
let cursor = null;
|
|
907
|
+
let pos = opts?.initialPosition ?? {
|
|
908
|
+
x: typeof window !== "undefined" ? window.innerWidth / 2 : 0,
|
|
909
|
+
y: typeof window !== "undefined" ? window.innerHeight / 2 : 0,
|
|
910
|
+
};
|
|
911
|
+
let disposed = false;
|
|
912
|
+
/**
|
|
913
|
+
* The currently-previewed snap target, if any. Only populated
|
|
914
|
+
* while magic mode is active — every move frame finds the
|
|
915
|
+
* nearest interactive element and rewires this state so the
|
|
916
|
+
* page can style "what would be clicked if I tapped now":
|
|
917
|
+
*
|
|
918
|
+
* [data-prson-magic-snap] { outline: 2px solid #3b82f6; }
|
|
919
|
+
*
|
|
920
|
+
* The data-attribute is the public contract; the corresponding
|
|
921
|
+
* class is added too as a convenience for selector-shy host
|
|
922
|
+
* stylesheets. Cleared on dispose / mode-change so a left-over
|
|
923
|
+
* highlight can't outlive the controller.
|
|
924
|
+
*/
|
|
925
|
+
let snapTarget = null;
|
|
926
|
+
/** Active mode for the current frame stream — kept in sync with
|
|
927
|
+
* `mouse.mode` on every applied envelope so snap-preview turns
|
|
928
|
+
* itself off when the wallet flips back to touch. */
|
|
929
|
+
let activeMode = mode;
|
|
930
|
+
// Install the ambient mouse-update handler so wallet-initiated
|
|
931
|
+
// streams (the pre-grant flow — `signIn({mouseControl: true})`)
|
|
932
|
+
// land on `applyFrame` even when there's no pending
|
|
933
|
+
// `requestMouse` promise to key the subscriber by. `bindMouse`
|
|
934
|
+
// owns the handler for its lifetime; `dispose()` removes it.
|
|
935
|
+
// The handler is installed eagerly (not on first `request()`) so
|
|
936
|
+
// the wallet can start streaming the moment the user taps
|
|
937
|
+
// Touchpad / Magic on the banner drawer — even if the host hasn't
|
|
938
|
+
// called `.request()` at all.
|
|
939
|
+
// Window focus → `control-status` for the wallet. When the page
|
|
940
|
+
// tab loses focus the wallet drops into a "Remote control paused"
|
|
941
|
+
// state so the user can see, on the phone, that motion isn't
|
|
942
|
+
// landing anywhere. Listeners are torn down in `detach()`.
|
|
943
|
+
function onWindowBlur() {
|
|
944
|
+
if (disposed)
|
|
945
|
+
return;
|
|
946
|
+
void session._sendControlStatus(true);
|
|
947
|
+
}
|
|
948
|
+
function onWindowFocus() {
|
|
949
|
+
if (disposed)
|
|
950
|
+
return;
|
|
951
|
+
void session._sendControlStatus(false);
|
|
952
|
+
// Real OS focus also implies the user is back at the keyboard
|
|
953
|
+
// → drop the "point your phone" hint if it was still up.
|
|
954
|
+
closePointPhoneOverlay();
|
|
955
|
+
}
|
|
956
|
+
if (typeof window !== "undefined") {
|
|
957
|
+
window.addEventListener("blur", onWindowBlur);
|
|
958
|
+
window.addEventListener("focus", onWindowFocus);
|
|
959
|
+
// Initial state — fire once so a session created while the tab
|
|
960
|
+
// is hidden lands on the wallet correctly.
|
|
961
|
+
if (typeof document !== "undefined" && document.hasFocus && !document.hasFocus()) {
|
|
962
|
+
void session._sendControlStatus(true);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
const offAmbient = session._setAmbientMouseHandler((mouseBody) => {
|
|
966
|
+
if (disposed)
|
|
967
|
+
return;
|
|
968
|
+
// `begin` / `end` are protocol pairing tokens — they just need to
|
|
969
|
+
// make sure the cursor element exists (so the first real `move`
|
|
970
|
+
// frame doesn't race the lazy initialiser) and are otherwise
|
|
971
|
+
// no-ops. **Every other event** — including the visibility
|
|
972
|
+
// toggles `show` / `hide` — must be forwarded to `applyFrame`,
|
|
973
|
+
// which is what opens / closes the "point your phone" overlay
|
|
974
|
+
// and re-centres the cursor on resume.
|
|
975
|
+
if (mouseBody.event === "begin" || mouseBody.event === "end") {
|
|
976
|
+
ensureCursor();
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
applyFrame(mouseBody);
|
|
980
|
+
});
|
|
981
|
+
function ensureCursor() {
|
|
982
|
+
if (cursor)
|
|
983
|
+
return cursor;
|
|
984
|
+
// Dedupe across multiple `bindMouse` calls. If another instance
|
|
985
|
+
// already created a cursor (e.g. the long-lived ambient bind
|
|
986
|
+
// from sign-in + a per-request bind from a host button click),
|
|
987
|
+
// adopt the existing element instead of stacking a second one.
|
|
988
|
+
// We still own its position state from this controller — the
|
|
989
|
+
// last `bindMouse` to call `ensureCursor` becomes the visible
|
|
990
|
+
// owner. (Prior owners just stop applying frames.)
|
|
991
|
+
const existing = document.querySelector('[data-prson-virtual-cursor]');
|
|
992
|
+
if (existing) {
|
|
993
|
+
cursor = existing;
|
|
994
|
+
// Update size/colour to match our opts so a second mount can
|
|
995
|
+
// restyle the cursor without flicker.
|
|
996
|
+
existing.style.width = `${size}px`;
|
|
997
|
+
existing.style.height = `${size}px`;
|
|
998
|
+
existing.style.background = color;
|
|
999
|
+
existing.style.display = "block";
|
|
1000
|
+
applyCursorPosition(existing, pos);
|
|
1001
|
+
return existing;
|
|
1002
|
+
}
|
|
1003
|
+
const el = document.createElement("div");
|
|
1004
|
+
el.setAttribute("data-prson-virtual-cursor", "");
|
|
1005
|
+
el.style.position = "fixed";
|
|
1006
|
+
el.style.width = `${size}px`;
|
|
1007
|
+
el.style.height = `${size}px`;
|
|
1008
|
+
el.style.borderRadius = "50%";
|
|
1009
|
+
el.style.background = color;
|
|
1010
|
+
el.style.border = "2px solid rgba(255, 255, 255, 0.9)";
|
|
1011
|
+
el.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.25)";
|
|
1012
|
+
el.style.pointerEvents = "none";
|
|
1013
|
+
el.style.zIndex = "2147483647";
|
|
1014
|
+
el.style.transform = "translate(-50%, -50%)";
|
|
1015
|
+
el.style.transition = "background 120ms ease, opacity 120ms ease";
|
|
1016
|
+
applyCursorPosition(el, pos);
|
|
1017
|
+
document.body.appendChild(el);
|
|
1018
|
+
cursor = el;
|
|
1019
|
+
return el;
|
|
1020
|
+
}
|
|
1021
|
+
function applyCursorPosition(el, p) {
|
|
1022
|
+
el.style.left = `${p.x}px`;
|
|
1023
|
+
el.style.top = `${p.y}px`;
|
|
1024
|
+
}
|
|
1025
|
+
function clamp(value, min, max) {
|
|
1026
|
+
return value < min ? min : value > max ? max : value;
|
|
1027
|
+
}
|
|
1028
|
+
function setSnapTarget(next) {
|
|
1029
|
+
if (next === snapTarget)
|
|
1030
|
+
return;
|
|
1031
|
+
if (snapTarget) {
|
|
1032
|
+
snapTarget.removeAttribute("data-prson-magic-snap");
|
|
1033
|
+
snapTarget.classList.remove("prson-magic-snap");
|
|
1034
|
+
}
|
|
1035
|
+
snapTarget = next;
|
|
1036
|
+
if (snapTarget) {
|
|
1037
|
+
snapTarget.setAttribute("data-prson-magic-snap", "");
|
|
1038
|
+
snapTarget.classList.add("prson-magic-snap");
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
function applyFrame(mouse) {
|
|
1042
|
+
if (disposed)
|
|
1043
|
+
return;
|
|
1044
|
+
const el = ensureCursor();
|
|
1045
|
+
// The wallet may toggle mode mid-stream. Track the active mode
|
|
1046
|
+
// here so move frames know whether to maintain the snap-target
|
|
1047
|
+
// highlight (magic) or drop it (touch).
|
|
1048
|
+
if (mouse.mode === "touch" || mouse.mode === "magic") {
|
|
1049
|
+
if (mouse.mode !== activeMode) {
|
|
1050
|
+
activeMode = mouse.mode;
|
|
1051
|
+
if (activeMode === "touch")
|
|
1052
|
+
setSnapTarget(null);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
switch (mouse.event) {
|
|
1056
|
+
case "move": {
|
|
1057
|
+
pos = {
|
|
1058
|
+
x: clamp(pos.x + (mouse.dx ?? 0), 0, window.innerWidth),
|
|
1059
|
+
y: clamp(pos.y + (mouse.dy ?? 0), 0, window.innerHeight),
|
|
1060
|
+
};
|
|
1061
|
+
applyCursorPosition(el, pos);
|
|
1062
|
+
if (onMove) {
|
|
1063
|
+
try {
|
|
1064
|
+
onMove(pos);
|
|
1065
|
+
}
|
|
1066
|
+
catch { /* swallow */ }
|
|
1067
|
+
}
|
|
1068
|
+
// Magic-mode snap preview. Refreshed on every move frame so
|
|
1069
|
+
// the highlight tracks the cursor. The DOM query + N rect
|
|
1070
|
+
// measurements run at most once per browser repaint
|
|
1071
|
+
// (`mouse-update` is already wallet-throttled to ~60 Hz),
|
|
1072
|
+
// which is acceptable on every page we ship for.
|
|
1073
|
+
if (activeMode === "magic") {
|
|
1074
|
+
if (isSelectOverlayActive()) {
|
|
1075
|
+
// Page-side highlight stays cleared; the snap visual
|
|
1076
|
+
// lives inside the overlay's own shadow root (the page
|
|
1077
|
+
// can't reach it, and the page's selector can't
|
|
1078
|
+
// accidentally override the option styling).
|
|
1079
|
+
setSnapTarget(null);
|
|
1080
|
+
setOverlaySnap(findNearestClickableInOverlay(pos.x, pos.y));
|
|
1081
|
+
}
|
|
1082
|
+
else {
|
|
1083
|
+
setOverlaySnap(null);
|
|
1084
|
+
setSnapTarget(findNearestClickable(pos.x, pos.y));
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
break;
|
|
1088
|
+
}
|
|
1089
|
+
case "click":
|
|
1090
|
+
case "double-click": {
|
|
1091
|
+
// Visual feedback — briefly pulse the cursor so the user
|
|
1092
|
+
// sees the click landed even if the underlying element
|
|
1093
|
+
// doesn't repaint.
|
|
1094
|
+
const prev = el.style.background;
|
|
1095
|
+
el.style.background = "rgba(59, 130, 246, 1)";
|
|
1096
|
+
setTimeout(() => { if (cursor === el)
|
|
1097
|
+
el.style.background = prev; }, 140);
|
|
1098
|
+
// Custom-overlay route. While a select overlay is open the
|
|
1099
|
+
// page beneath is non-interactive — clicks land ONLY on
|
|
1100
|
+
// overlay elements (close button, page-up / page-down,
|
|
1101
|
+
// option buttons). The overlay's shadow-DOM listener
|
|
1102
|
+
// handles the actual semantics (close vs. paginate vs.
|
|
1103
|
+
// commit option); we just need to dispatch a click event
|
|
1104
|
+
// on the right inner element.
|
|
1105
|
+
if (isSelectOverlayActive()) {
|
|
1106
|
+
const overlayTarget = (snapTarget && snapTarget.closest?.("[data-prson-select-close],[data-prson-select-page],[data-prson-select-option]")) ??
|
|
1107
|
+
findNearestClickableInOverlay(pos.x, pos.y);
|
|
1108
|
+
if (overlayTarget) {
|
|
1109
|
+
const init = {
|
|
1110
|
+
bubbles: true,
|
|
1111
|
+
cancelable: true,
|
|
1112
|
+
composed: true,
|
|
1113
|
+
clientX: pos.x,
|
|
1114
|
+
clientY: pos.y,
|
|
1115
|
+
view: window,
|
|
1116
|
+
};
|
|
1117
|
+
overlayTarget.dispatchEvent(new MouseEvent("mousedown", init));
|
|
1118
|
+
overlayTarget.dispatchEvent(new MouseEvent("mouseup", init));
|
|
1119
|
+
overlayTarget.dispatchEvent(new MouseEvent("click", init));
|
|
1120
|
+
}
|
|
1121
|
+
break;
|
|
1122
|
+
}
|
|
1123
|
+
// Click-area enlargement: a virtual cursor is harder to land
|
|
1124
|
+
// precisely than a touch finger or a mouse, especially for a
|
|
1125
|
+
// gyro-driven wand. Search for the NEAREST interactive
|
|
1126
|
+
// element within [SNAP_RADIUS_PX] of the cursor and target
|
|
1127
|
+
// that, even if the cursor isn't strictly on top of it.
|
|
1128
|
+
// Falls back to whatever's at the cursor coordinate when no
|
|
1129
|
+
// candidate is within range (so clicks on free space, scroll
|
|
1130
|
+
// areas, etc. still work normally).
|
|
1131
|
+
//
|
|
1132
|
+
// Magic mode already maintains `snapTarget` via the move-
|
|
1133
|
+
// frame preview; touch mode skips the highlight but still
|
|
1134
|
+
// gets snap-on-click. Re-query in touch mode so the click
|
|
1135
|
+
// semantic stays identical across modes.
|
|
1136
|
+
const snapped = activeMode === "magic"
|
|
1137
|
+
? snapTarget
|
|
1138
|
+
: findNearestClickable(pos.x, pos.y);
|
|
1139
|
+
// Native <select>s open an OS-drawn list that the virtual
|
|
1140
|
+
// cursor can't reach. Replace the click with a custom
|
|
1141
|
+
// shadow-DOM overlay the cursor CAN drive.
|
|
1142
|
+
if (snapped instanceof HTMLSelectElement) {
|
|
1143
|
+
openSelectOverlay(snapped);
|
|
1144
|
+
// Clear the page-side snap highlight on the select so the
|
|
1145
|
+
// overlay's own snap visuals take over cleanly.
|
|
1146
|
+
setSnapTarget(null);
|
|
1147
|
+
break;
|
|
1148
|
+
}
|
|
1149
|
+
const direct = document.elementFromPoint(pos.x, pos.y);
|
|
1150
|
+
const target = snapped ?? direct;
|
|
1151
|
+
// When we snapped, dispatch at the SNAPPED element's centre
|
|
1152
|
+
// so any positional logic inside the page (e.g. a custom
|
|
1153
|
+
// dropdown computing position from `clientX`) sees a hit
|
|
1154
|
+
// ON the element rather than in dead space next to it.
|
|
1155
|
+
const clickPoint = snapped
|
|
1156
|
+
? rectCenter(snapped.getBoundingClientRect())
|
|
1157
|
+
: { x: pos.x, y: pos.y };
|
|
1158
|
+
let allowDefault = true;
|
|
1159
|
+
if (onClick) {
|
|
1160
|
+
try {
|
|
1161
|
+
const ret = onClick(target);
|
|
1162
|
+
if (ret === false)
|
|
1163
|
+
allowDefault = false;
|
|
1164
|
+
}
|
|
1165
|
+
catch { /* swallow */ }
|
|
1166
|
+
}
|
|
1167
|
+
if (allowDefault && target) {
|
|
1168
|
+
const init = {
|
|
1169
|
+
bubbles: true,
|
|
1170
|
+
cancelable: true,
|
|
1171
|
+
clientX: clickPoint.x,
|
|
1172
|
+
clientY: clickPoint.y,
|
|
1173
|
+
view: window,
|
|
1174
|
+
};
|
|
1175
|
+
target.dispatchEvent(new MouseEvent("mousedown", init));
|
|
1176
|
+
target.dispatchEvent(new MouseEvent("mouseup", init));
|
|
1177
|
+
target.dispatchEvent(new MouseEvent("click", init));
|
|
1178
|
+
if (mouse.event === "double-click") {
|
|
1179
|
+
target.dispatchEvent(new MouseEvent("dblclick", init));
|
|
1180
|
+
}
|
|
1181
|
+
// Inputs and other focusable elements don't always auto-
|
|
1182
|
+
// focus from synthetic `mousedown`. Explicitly focus the
|
|
1183
|
+
// snapped target so the page sees the same focus state it
|
|
1184
|
+
// would after a real touch.
|
|
1185
|
+
if (snapped &&
|
|
1186
|
+
typeof target.focus === "function") {
|
|
1187
|
+
try {
|
|
1188
|
+
target.focus({ preventScroll: true });
|
|
1189
|
+
}
|
|
1190
|
+
catch {
|
|
1191
|
+
/* swallow — some host elements throw on focus */
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
case "scroll": {
|
|
1198
|
+
// `dy` matches WheelEvent.deltaY — positive = scroll down.
|
|
1199
|
+
window.scrollBy({ left: mouse.dx ?? 0, top: mouse.dy ?? 0 });
|
|
1200
|
+
break;
|
|
1201
|
+
}
|
|
1202
|
+
case "hide": {
|
|
1203
|
+
// Wallet's pose detector says the phone is no longer
|
|
1204
|
+
// pointing at the screen. Pull the cursor off the page so
|
|
1205
|
+
// the user gets immediate feedback, and surface a soft
|
|
1206
|
+
// blue-glow + "point your phone" pill so they know how to
|
|
1207
|
+
// resume. The overlay auto-dismisses after 15 s or on real
|
|
1208
|
+
// OS mouse movement (whichever first).
|
|
1209
|
+
if (cursor) {
|
|
1210
|
+
cursor.style.opacity = "0";
|
|
1211
|
+
cursor.style.pointerEvents = "none";
|
|
1212
|
+
}
|
|
1213
|
+
setSnapTarget(null);
|
|
1214
|
+
setOverlaySnap(null);
|
|
1215
|
+
openPointPhoneOverlay();
|
|
1216
|
+
break;
|
|
1217
|
+
}
|
|
1218
|
+
case "show": {
|
|
1219
|
+
// Wand pose restored — bring the cursor back and clear the
|
|
1220
|
+
// "point your phone" hint regardless of which trigger
|
|
1221
|
+
// (timeout / mousemove / show) wins the race.
|
|
1222
|
+
//
|
|
1223
|
+
// **Re-centre the cursor.** After a pause the user has lost
|
|
1224
|
+
// mental track of where the cursor was; pinning it at the
|
|
1225
|
+
// viewport centre gives them a known starting point and
|
|
1226
|
+
// matches the "wand on / wand off" mental model (each
|
|
1227
|
+
// session begins at the middle). Position resets via
|
|
1228
|
+
// `applyCursorPosition` so subsequent move frames integrate
|
|
1229
|
+
// from the centre.
|
|
1230
|
+
const el = ensureCursor();
|
|
1231
|
+
el.style.opacity = "1";
|
|
1232
|
+
if (typeof window !== "undefined") {
|
|
1233
|
+
pos = {
|
|
1234
|
+
x: window.innerWidth / 2,
|
|
1235
|
+
y: window.innerHeight / 2,
|
|
1236
|
+
};
|
|
1237
|
+
applyCursorPosition(el, pos);
|
|
1238
|
+
}
|
|
1239
|
+
closePointPhoneOverlay();
|
|
1240
|
+
break;
|
|
1241
|
+
}
|
|
1242
|
+
case "begin":
|
|
1243
|
+
case "end": {
|
|
1244
|
+
// Wallet-side stream lifecycle markers (pre-grant flow).
|
|
1245
|
+
// Nothing for the cursor renderer to do — `_setAmbientMouseHandler`
|
|
1246
|
+
// already calls `ensureCursor()` on these so a real `move`
|
|
1247
|
+
// frame doesn't race the lazy initialiser.
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
function detach() {
|
|
1253
|
+
if (cursor) {
|
|
1254
|
+
cursor.remove();
|
|
1255
|
+
cursor = null;
|
|
1256
|
+
}
|
|
1257
|
+
// Clear any lingering magic-mode highlight so the page doesn't
|
|
1258
|
+
// keep a `data-prson-magic-snap` attribute on whichever input
|
|
1259
|
+
// happened to be the last preview target.
|
|
1260
|
+
setSnapTarget(null);
|
|
1261
|
+
setOverlaySnap(null);
|
|
1262
|
+
// Close any active select overlay so a disposing cursor doesn't
|
|
1263
|
+
// leave the dropdown orphaned on the page.
|
|
1264
|
+
closeAllOverlays();
|
|
1265
|
+
closePointPhoneOverlay();
|
|
1266
|
+
// Drop window-focus listeners so a torn-down controller doesn't
|
|
1267
|
+
// keep pushing control-status envelopes onto a closed channel.
|
|
1268
|
+
if (typeof window !== "undefined") {
|
|
1269
|
+
window.removeEventListener("blur", onWindowBlur);
|
|
1270
|
+
window.removeEventListener("focus", onWindowFocus);
|
|
1271
|
+
}
|
|
1272
|
+
// Tear down the ambient subscription so the session stops
|
|
1273
|
+
// holding a ref to our (now-disposed) handler.
|
|
1274
|
+
offAmbient();
|
|
1275
|
+
}
|
|
1276
|
+
return {
|
|
1277
|
+
async request(callerOpts) {
|
|
1278
|
+
if (disposed)
|
|
1279
|
+
return { ok: false, error: "session-closed" };
|
|
1280
|
+
ensureCursor();
|
|
1281
|
+
// `requestMouse` atomically registers the subscriber under the
|
|
1282
|
+
// requestId before the envelope leaves the wire, so the very
|
|
1283
|
+
// first `mouse-update` frame can never race ahead of us. The
|
|
1284
|
+
// session also drops the subscriber on the terminating
|
|
1285
|
+
// `response` so we don't need to manage that side ourselves.
|
|
1286
|
+
// Mouse requests stay open as long as the user is driving the
|
|
1287
|
+
// wallet's controller — that can easily be longer than the
|
|
1288
|
+
// generic `request()` default of 60 s. Pick the smaller of
|
|
1289
|
+
// (a) the session's hard expiry and (b) the `setTimeout`
|
|
1290
|
+
// int32 ceiling (~24.8 days). The credential's exp can sit
|
|
1291
|
+
// weeks out, but `setTimeout(fn, > 2^31-1)` overflows and
|
|
1292
|
+
// fires on the next tick — exactly the bug that caused
|
|
1293
|
+
// `bindMouse` to resolve with `error: "timeout"` the moment
|
|
1294
|
+
// it was awaited.
|
|
1295
|
+
const MAX_SAFE_TIMEOUT = 2147483000;
|
|
1296
|
+
const credentialBudget = session.expiresAt - Date.now() + 1000;
|
|
1297
|
+
const sessionEndMs = Math.max(60000, Math.min(credentialBudget, MAX_SAFE_TIMEOUT));
|
|
1298
|
+
const reply = await session.requestMouse({ kind: "mouse", mode, reason: callerOpts?.reason ?? opts?.reason }, applyFrame, { timeoutMs: sessionEndMs, ...callerOpts });
|
|
1299
|
+
// Drawer closed (or timed out) — pull the cursor off the page
|
|
1300
|
+
// so it doesn't sit there orphaned. Host can call request()
|
|
1301
|
+
// again to spawn another session.
|
|
1302
|
+
if (!disposed) {
|
|
1303
|
+
if (cursor) {
|
|
1304
|
+
cursor.remove();
|
|
1305
|
+
cursor = null;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return reply;
|
|
1309
|
+
},
|
|
1310
|
+
dispose() {
|
|
1311
|
+
disposed = true;
|
|
1312
|
+
detach();
|
|
1313
|
+
},
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
// ─── Click-area enlargement (virtual-cursor snap) ──────────────────
|
|
1317
|
+
//
|
|
1318
|
+
// CSS selector covering every realistic click target on a page —
|
|
1319
|
+
// form controls + anchor-style affordances. The query runs once per
|
|
1320
|
+
// click (low frequency relative to move frames), so the cost is
|
|
1321
|
+
// acceptable even on a long page; we do NOT walk the DOM on every
|
|
1322
|
+
// move frame.
|
|
1323
|
+
const SNAP_SELECTOR = 'input:not([type="hidden"]):not([disabled]),' +
|
|
1324
|
+
'textarea:not([disabled]),' +
|
|
1325
|
+
'select:not([disabled]),' +
|
|
1326
|
+
'button:not([disabled]),' +
|
|
1327
|
+
'a[href],' +
|
|
1328
|
+
'[role="button"],' +
|
|
1329
|
+
'[role="link"],' +
|
|
1330
|
+
'[role="checkbox"],' +
|
|
1331
|
+
'[role="radio"],' +
|
|
1332
|
+
'label[for],' +
|
|
1333
|
+
'[tabindex]:not([tabindex="-1"])';
|
|
1334
|
+
/** Snap radius in CSS pixels. A click further than this from any
|
|
1335
|
+
* interactive element falls through to whatever's at the cursor
|
|
1336
|
+
* coordinate. Tuned so a comfortable wand flick lands in the
|
|
1337
|
+
* right input without over-reaching across the page. */
|
|
1338
|
+
const SNAP_RADIUS_PX = 60;
|
|
1339
|
+
function rectCenter(r) {
|
|
1340
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Find the closest interactive element to the cursor whose bounding
|
|
1344
|
+
* box lies within [SNAP_RADIUS_PX]. Distance is measured to the
|
|
1345
|
+
* nearest edge of the element's rect (0 if inside), so wide elements
|
|
1346
|
+
* "win" over narrow ones at the same centre distance. Returns null
|
|
1347
|
+
* when nothing qualifies — the caller then falls back to
|
|
1348
|
+
* `document.elementFromPoint`.
|
|
1349
|
+
*
|
|
1350
|
+
* If multiple inputs sit equally close (tie), the one earliest in
|
|
1351
|
+
* the DOM wins — `querySelectorAll` iterates in document order, so
|
|
1352
|
+
* the strictly-less-than comparison preserves it.
|
|
1353
|
+
*/
|
|
1354
|
+
function findNearestClickable(x, y) {
|
|
1355
|
+
if (typeof document === "undefined")
|
|
1356
|
+
return null;
|
|
1357
|
+
const candidates = document.querySelectorAll(SNAP_SELECTOR);
|
|
1358
|
+
let best = null;
|
|
1359
|
+
let bestDist = Infinity;
|
|
1360
|
+
for (const el of Array.from(candidates)) {
|
|
1361
|
+
const rect = el.getBoundingClientRect();
|
|
1362
|
+
if (rect.width === 0 || rect.height === 0)
|
|
1363
|
+
continue; // hidden / collapsed
|
|
1364
|
+
// Distance from (x,y) to rect: 0 if inside, else Euclidean from
|
|
1365
|
+
// the nearest edge / corner.
|
|
1366
|
+
const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;
|
|
1367
|
+
const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;
|
|
1368
|
+
const dist = Math.sqrt(dx * dx + dy * dy);
|
|
1369
|
+
if (dist < bestDist) {
|
|
1370
|
+
bestDist = dist;
|
|
1371
|
+
best = el;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
return bestDist <= SNAP_RADIUS_PX ? best : null;
|
|
1375
|
+
}
|
|
1376
|
+
// `CSS.escape` polyfill — older Safari versions sometimes ship
|
|
1377
|
+
// without it. Hand-rolled escape covers our identifier characters.
|
|
1378
|
+
function cssEscape(s) {
|
|
1379
|
+
if (typeof CSS !== "undefined" &&
|
|
1380
|
+
typeof CSS.escape === "function") {
|
|
1381
|
+
return CSS.escape(s);
|
|
1382
|
+
}
|
|
1383
|
+
return s.replace(/(["\\#.>+~*$^|=:()\[\] ])/g, "\\$1");
|
|
1384
|
+
}
|