@verax-ai/body 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +4 -3
  2. package/dist/approval-signature.d.ts +19 -0
  3. package/dist/approval-signature.js +70 -5
  4. package/dist/approve-cli.js +20 -24
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.js +146 -14
  7. package/dist/config.d.ts +23 -0
  8. package/dist/config.js +41 -0
  9. package/dist/control-signature.d.ts +4 -0
  10. package/dist/control-signature.js +20 -5
  11. package/dist/definitions.d.ts +9 -0
  12. package/dist/definitions.js +53 -0
  13. package/dist/demo.js +15 -12
  14. package/dist/doctor.js +72 -0
  15. package/dist/downstream-pin.d.ts +9 -0
  16. package/dist/downstream-pin.js +273 -0
  17. package/dist/downstream.d.ts +22 -2
  18. package/dist/downstream.js +312 -44
  19. package/dist/heartbeat.d.ts +26 -2
  20. package/dist/heartbeat.js +90 -7
  21. package/dist/held-spend.d.ts +16 -0
  22. package/dist/held-spend.js +20 -0
  23. package/dist/http-io.d.ts +14 -0
  24. package/dist/http-io.js +46 -0
  25. package/dist/init-local.d.ts +11 -0
  26. package/dist/init-local.js +32 -3
  27. package/dist/install.d.ts +5 -0
  28. package/dist/install.js +37 -5
  29. package/dist/main.d.ts +1 -0
  30. package/dist/main.js +34 -5
  31. package/dist/operator-cli.d.ts +49 -1
  32. package/dist/operator-cli.js +132 -7
  33. package/dist/operator-credentials.d.ts +40 -1
  34. package/dist/operator-credentials.js +97 -7
  35. package/dist/operator-door-page.d.ts +3 -0
  36. package/dist/operator-door-page.js +819 -0
  37. package/dist/operator-door.d.ts +22 -0
  38. package/dist/operator-door.js +487 -0
  39. package/dist/operator-handlers.d.ts +28 -0
  40. package/dist/operator-handlers.js +221 -0
  41. package/dist/server.d.ts +2 -0
  42. package/dist/server.js +108 -255
  43. package/dist/verify-cli.js +30 -10
  44. package/dist/webauthn-verify.d.ts +48 -4
  45. package/dist/webauthn-verify.js +183 -25
  46. package/package.json +4 -4
@@ -0,0 +1,819 @@
1
+ /**
2
+ * The one page the operator door serves: its markup, its stylesheet and its
3
+ * script, each a string the door hands out under its own path.
4
+ *
5
+ * The door sends them under a policy that runs no inline script and applies
6
+ * no inline style, so the markup carries neither. The script writes every
7
+ * value the door gives it as text, and keeps the session token in a variable
8
+ * of its own: nothing a later page could read, and gone on reload.
9
+ *
10
+ * What a held call says comes from the agent. The terminal escapes every
11
+ * code point that draws nothing, draws over its neighbour, or has no glyph
12
+ * to rely on, before it prints one; the script escapes the same class, read
13
+ * from the same place. A real backslash is written as two characters first,
14
+ * so a written escape and the character it names do not look the same.
15
+ * Turkish and Latin letters, one code point each (NFC), stay as they are.
16
+ * Each value has its own direction, so text that runs right to left cannot
17
+ * rearrange what is beside it.
18
+ */
19
+ import { DISPLAY_ESCAPE_CLASS } from "@verax-ai/proxy";
20
+ export const DOOR_HTML = `<!doctype html>
21
+ <html lang="en" dir="ltr">
22
+ <head>
23
+ <meta charset="utf-8">
24
+ <meta name="viewport" content="width=device-width, initial-scale=1">
25
+ <meta name="color-scheme" content="light dark">
26
+ <title>Verax operator door</title>
27
+ <link rel="stylesheet" href="/door.css">
28
+ <script src="/door.js" defer></script>
29
+ </head>
30
+ <body>
31
+ <main data-test="door">
32
+ <header class="top">
33
+ <h1>Verax</h1>
34
+ <p class="dim">Operator door</p>
35
+ </header>
36
+
37
+ <p data-test="notice" class="notice" role="status" aria-live="polite" hidden></p>
38
+
39
+ <section data-test="screen-loading">
40
+ <p class="dim">Asking the door.</p>
41
+ </section>
42
+
43
+ <section data-test="screen-enroll" hidden>
44
+ <h2>Add this device</h2>
45
+ <p>Run <code>verax operator enroll</code> at the machine. It prints an 8-digit code that is good for five minutes.</p>
46
+ <label for="enroll-code">Pairing code</label>
47
+ <input id="enroll-code" data-test="enroll-code" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="8" spellcheck="false">
48
+ <button type="button" data-test="enroll-submit" class="primary">Enrol a passkey on this device</button>
49
+ <button type="button" data-test="goto-signin" class="plain" hidden>Back to sign-in</button>
50
+ </section>
51
+
52
+ <section data-test="screen-signin" hidden>
53
+ <h2>Sign in</h2>
54
+ <p>Signing in shows what is waiting. Each approval asks the passkey again.</p>
55
+ <button type="button" data-test="signin" class="primary">Sign in with a passkey</button>
56
+ <button type="button" data-test="goto-enroll" class="plain">Add a device with a pairing code</button>
57
+ </section>
58
+
59
+ <section data-test="screen-main" hidden>
60
+ <div class="bar">
61
+ <p class="dim">Signed in as <strong data-test="session-sub"></strong> until <span data-test="session-expires"></span></p>
62
+ <button type="button" data-test="signout" class="plain">Sign out</button>
63
+ </div>
64
+
65
+ <div class="card">
66
+ <p class="state"><span class="label">Body</span><strong data-test="halt-state" data-halted="false">Running</strong></p>
67
+ <p data-test="halt-since" class="dim" hidden></p>
68
+ <button type="button" data-test="halt" class="danger">Stop the body</button>
69
+ <button type="button" data-test="resume" class="primary" hidden>Resume with passkey</button>
70
+ </div>
71
+
72
+ <div class="bar">
73
+ <h2>Waiting <span data-test="waiting-count" class="count">0</span></h2>
74
+ <button type="button" data-test="refresh" class="plain">Refresh</button>
75
+ </div>
76
+ <p data-test="waiting-empty" class="dim">Nothing is waiting.</p>
77
+ <ul data-test="waiting-list" class="waiting"></ul>
78
+ </section>
79
+ </main>
80
+ </body>
81
+ </html>
82
+ `;
83
+ export const DOOR_CSS = `:root {
84
+ --paper: #f6f5f1;
85
+ --card: #ffffff;
86
+ --ink: #16181d;
87
+ --dim: #5b616e;
88
+ --line: #d9d7cf;
89
+ --go: #0b5cad;
90
+ --go-ink: #ffffff;
91
+ --stop: #b3261e;
92
+ --ok: #17643a;
93
+ --ok-paper: #e5f3ea;
94
+ --bad-paper: #fbe9e7;
95
+ }
96
+ @media (prefers-color-scheme: dark) {
97
+ :root {
98
+ --paper: #101216;
99
+ --card: #191c22;
100
+ --ink: #eceef2;
101
+ --dim: #9aa1ae;
102
+ --line: #2c313a;
103
+ --go: #7db7f5;
104
+ --go-ink: #0b1420;
105
+ --stop: #f28b82;
106
+ --ok: #81c995;
107
+ --ok-paper: #14261b;
108
+ --bad-paper: #2d1614;
109
+ }
110
+ }
111
+ [hidden] { display: none !important; }
112
+ * { box-sizing: border-box; }
113
+ html { -webkit-text-size-adjust: 100%; }
114
+ body {
115
+ margin: 0;
116
+ background: var(--paper);
117
+ color: var(--ink);
118
+ font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
119
+ }
120
+ main { max-width: 34rem; margin: 0 auto; padding: 20px 16px 48px; }
121
+ h1 { font-size: 1.25rem; margin: 0; letter-spacing: 0.02em; }
122
+ h2 { font-size: 1.1rem; margin: 0; }
123
+ p { margin: 0; }
124
+ section > * + * { margin-top: 14px; }
125
+ .top { display: flex; align-items: baseline; gap: 10px; margin-bottom: 18px; }
126
+ .dim { color: var(--dim); font-size: 0.9rem; }
127
+ .label { color: var(--dim); font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.06em; }
128
+ code, pre, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.85rem; }
129
+ /* Arguments and identifiers: one character after another, left to right, whatever script they are in. */
130
+ pre, .mono { direction: ltr; unicode-bidi: bidi-override; }
131
+ /* Every other value keeps its own direction to itself. */
132
+ bdi, [data-test="session-sub"], [data-test="session-expires"] { unicode-bidi: isolate; }
133
+ .notice { padding: 12px 14px; border-radius: 8px; border: 1px solid var(--line); margin-bottom: 16px; overflow-wrap: anywhere; }
134
+ .notice[data-kind="ok"] { background: var(--ok-paper); border-color: var(--ok); }
135
+ .notice[data-kind="error"] { background: var(--bad-paper); border-color: var(--stop); }
136
+ label { display: block; font-size: 0.9rem; color: var(--dim); }
137
+ input {
138
+ display: block; width: 100%; min-height: 52px; margin-top: 6px; padding: 8px 12px;
139
+ font: 1.6rem/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; letter-spacing: 0.3em;
140
+ color: var(--ink); background: var(--card); border: 1px solid var(--line); border-radius: 8px;
141
+ }
142
+ button {
143
+ display: block; width: 100%; min-height: 48px; padding: 10px 16px;
144
+ font: inherit; font-weight: 600; border-radius: 8px; border: 1px solid var(--line);
145
+ background: var(--card); color: var(--ink); cursor: pointer;
146
+ }
147
+ button:disabled { opacity: 0.5; cursor: default; }
148
+ button:focus-visible, input:focus-visible { outline: 3px solid var(--go); outline-offset: 2px; }
149
+ button.primary { background: var(--go); border-color: var(--go); color: var(--go-ink); }
150
+ button.danger { background: transparent; border-color: var(--stop); color: var(--stop); }
151
+ button.plain { width: auto; min-height: 44px; font-weight: 500; white-space: nowrap; flex: none; }
152
+ .bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
153
+ .card, .waiting li { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
154
+ .card > * + *, .waiting li > * + * { margin-top: 12px; }
155
+ .state { display: flex; align-items: baseline; gap: 10px; font-size: 1.15rem; }
156
+ [data-halted="true"] { color: var(--stop); }
157
+ [data-halted="false"] { color: var(--ok); }
158
+ .count { display: inline-block; min-width: 1.6em; padding: 0 0.4em; text-align: center; border: 1px solid var(--line); border-radius: 999px; font-size: 0.9rem; }
159
+ .waiting { list-style: none; margin: 14px 0 0; padding: 0; }
160
+ .waiting li + li { margin-top: 14px; }
161
+ .spend .amount { font-size: 1.9rem; font-weight: 700; line-height: 1.15; overflow-wrap: anywhere; }
162
+ .spend .amount small { font-size: 0.8rem; font-weight: 400; color: var(--dim); }
163
+ .spend .payee { font-size: 1.35rem; font-weight: 600; overflow-wrap: anywhere; }
164
+ .field { display: grid; grid-template-columns: 6.5rem 1fr; gap: 8px; align-items: baseline; }
165
+ .field > :last-child, pre { overflow-wrap: anywhere; white-space: pre-wrap; min-width: 0; }
166
+ pre { margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--paper); max-height: 16rem; overflow: auto; }
167
+ .confirm { border-top: 1px solid var(--line); padding-top: 12px; }
168
+ .confirm > * + * { margin-top: 10px; }
169
+ .confirm p { font-weight: 600; overflow-wrap: anywhere; }
170
+ `;
171
+ const SCRIPT = String.raw `(function () {
172
+ "use strict";
173
+
174
+ // The session. Held here and nowhere else; a reload ends it.
175
+ var token = null;
176
+ var expiryTimer = null;
177
+ var operatorKnown = false;
178
+ var unsupported = false;
179
+ var busy = false;
180
+
181
+ var SCREENS = ["loading", "enroll", "signin", "main"];
182
+ var TEXT = {
183
+ "enrolled": "This device is enrolled. Sign in to go on.",
184
+ "signed-in": "Signed in.",
185
+ "signed-out": "Signed out.",
186
+ "approved": "Approved.",
187
+ "halted": "The body is stopped.",
188
+ "halted-unsigned": "The body is stopped. The stop carries no passkey signature.",
189
+ "resumed": "The body is running again.",
190
+ "session-ended": "The session ended. Sign in again.",
191
+ "code-format": "The code is 8 digits.",
192
+ "pairing-refused": "That code was not accepted. Ask for a new one at the machine.",
193
+ "enroll-refused": "The door did not accept this passkey.",
194
+ "signin-refused": "The door did not accept this sign-in.",
195
+ "cloned-authenticator": "This passkey answered with an older counter than the door has seen. It was refused.",
196
+ "no-operator": "Nobody is enrolled yet. Add this device with a pairing code.",
197
+ "passkey-unsupported": "This browser has no passkeys. Open the door in one that does.",
198
+ "passkey-cancelled": "The passkey prompt was dismissed. Nothing was sent.",
199
+ "passkey-failed": "The passkey did not answer.",
200
+ "stale": "That request changed since it was listed. The list is fresh now; nothing was approved.",
201
+ "unknown-ref": "That request is no longer waiting. Nothing was approved.",
202
+ "approve-halted": "The body is stopped. Nothing is approved while it is.",
203
+ "resume-signature-required": "A resume needs the passkey.",
204
+ "origin-not-allowed": "This page was opened under a name the door does not answer for.",
205
+ "busy": "The door is busy. Try again in a few seconds.",
206
+ "network": "The door did not answer.",
207
+ "fault": "Something went wrong on this page. Reload it."
208
+ };
209
+
210
+ function Refusal(code, body) {
211
+ this.code = code;
212
+ this.body = body || {};
213
+ }
214
+
215
+ function at(name, root) {
216
+ return (root || document).querySelector('[data-test="' + name + '"]');
217
+ }
218
+
219
+ /**
220
+ * The page's own words as text, and each value among them in an element of
221
+ * its own direction: letters that run right to left stay inside the value
222
+ * and move nothing beside it.
223
+ */
224
+ function fill(el, parts) {
225
+ while (el.firstChild) el.removeChild(el.firstChild);
226
+ for (var i = 0; i < parts.length; i += 1) {
227
+ if (typeof parts[i] === "string") {
228
+ el.appendChild(document.createTextNode(parts[i]));
229
+ } else {
230
+ var value = document.createElement("bdi");
231
+ value.textContent = parts[i].value;
232
+ el.appendChild(value);
233
+ }
234
+ }
235
+ return el;
236
+ }
237
+
238
+ function show(name) {
239
+ SCREENS.forEach(function (screen) {
240
+ at("screen-" + screen).hidden = screen !== name;
241
+ });
242
+ }
243
+
244
+ function hush() {
245
+ var notice = at("notice");
246
+ notice.hidden = true;
247
+ notice.textContent = "";
248
+ ["data-kind", "data-code", "data-reason", "data-allow-ref"].forEach(function (name) {
249
+ notice.removeAttribute(name);
250
+ });
251
+ }
252
+
253
+ function say(kind, code, more) {
254
+ var notice = at("notice");
255
+ hush();
256
+ // The page's own sentence where it has one. A word of the door's it does not know is shown as a value.
257
+ var parts = [Object.prototype.hasOwnProperty.call(TEXT, code) ? TEXT[code] : { value: plain(code) }];
258
+ if (more && typeof more.reason === "string" && more.reason !== "") {
259
+ notice.setAttribute("data-reason", more.reason);
260
+ parts.push(" (", { value: plain(more.reason) }, ")");
261
+ }
262
+ if (more && typeof more.allowRef === "string") notice.setAttribute("data-allow-ref", more.allowRef);
263
+ notice.setAttribute("data-kind", kind);
264
+ notice.setAttribute("data-code", code);
265
+ fill(notice, parts);
266
+ notice.hidden = false;
267
+ }
268
+
269
+ function lock(on) {
270
+ var buttons = document.querySelectorAll("button");
271
+ for (var i = 0; i < buttons.length; i += 1) buttons[i].disabled = on;
272
+ if (!on && unsupported) {
273
+ at("signin").disabled = true;
274
+ at("enroll-submit").disabled = true;
275
+ }
276
+ }
277
+
278
+ // The class the terminal escapes in a held call: controls, format characters,
279
+ // combining marks, unassigned and private-use code points, surrogates, and
280
+ // the other code points that draw nothing or draw over a neighbour. One
281
+ // escape per UTF-16 unit. A real backslash is written as two characters
282
+ // first, so a written escape and the character it names do not look the
283
+ // same. Arguments arrive as JSON, which has already doubled every
284
+ // backslash; doubling those again would change the value, so that call
285
+ // passes keepLineBreaks and only the class is escaped.
286
+ var CONTROL = new RegExp("[" + "@@CONTROL_CLASS@@" + "]", "gu");
287
+
288
+ function plain(text, keepLineBreaks) {
289
+ var source = String(text);
290
+ if (!keepLineBreaks) source = source.replace(/\\/g, "\\\\");
291
+ return source.replace(CONTROL, function (ch) {
292
+ if (keepLineBreaks && ch === "\n") return ch;
293
+ var out = "";
294
+ for (var i = 0; i < ch.length; i += 1) out += "\\u" + ("000" + ch.charCodeAt(i).toString(16)).slice(-4);
295
+ return out;
296
+ });
297
+ }
298
+
299
+ function clock(ms) {
300
+ if (typeof ms !== "number" || !isFinite(ms)) return "—";
301
+ return new Date(ms).toLocaleString([], { dateStyle: "medium", timeStyle: "short" });
302
+ }
303
+
304
+ // ---- the door ----
305
+
306
+ function call(method, path, body, withSession) {
307
+ var headers = {};
308
+ if (body !== undefined) headers["content-type"] = "application/json";
309
+ if (withSession && token !== null) headers["authorization"] = "Bearer " + token;
310
+ var options = {
311
+ method: method,
312
+ headers: headers,
313
+ credentials: "omit",
314
+ cache: "no-store",
315
+ redirect: "error",
316
+ referrerPolicy: "no-referrer"
317
+ };
318
+ if (body !== undefined) options.body = JSON.stringify(body);
319
+ return fetch(path, options).then(
320
+ function (res) {
321
+ return res.text().then(function (text) {
322
+ var parsed = null;
323
+ try {
324
+ parsed = text === "" ? null : JSON.parse(text);
325
+ } catch (err) {
326
+ parsed = null;
327
+ }
328
+ return { ok: res.ok, status: res.status, body: parsed !== null && typeof parsed === "object" ? parsed : {} };
329
+ });
330
+ },
331
+ function () {
332
+ throw new Refusal("network");
333
+ }
334
+ );
335
+ }
336
+
337
+ /** The answer's body, or the door's refusal by its own word for it. */
338
+ function need(res) {
339
+ if (res.ok) return res.body;
340
+ var word = typeof res.body.error === "string" && res.body.error !== "" ? res.body.error : "http-" + res.status;
341
+ if (token !== null && (res.status === 401 || word === "no-operator")) throw new Refusal("session-ended");
342
+ throw new Refusal(word, res.body);
343
+ }
344
+
345
+ // ---- passkeys: base64url on the wire, bytes for the browser ----
346
+
347
+ function toBytes(value) {
348
+ var padded = String(value).replace(/-/g, "+").replace(/_/g, "/");
349
+ while (padded.length % 4 !== 0) padded += "=";
350
+ var binary = atob(padded);
351
+ var out = new Uint8Array(binary.length);
352
+ for (var i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
353
+ return out;
354
+ }
355
+
356
+ function toText(buffer) {
357
+ var bytes = new Uint8Array(buffer);
358
+ var binary = "";
359
+ for (var i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
360
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
361
+ }
362
+
363
+ function descriptors(list) {
364
+ var out = [];
365
+ if (!Array.isArray(list)) return out;
366
+ for (var i = 0; i < list.length; i += 1) {
367
+ if (list[i] && typeof list[i].id === "string") out.push({ type: "public-key", id: toBytes(list[i].id) });
368
+ }
369
+ return out;
370
+ }
371
+
372
+ function ceremony(make) {
373
+ return Promise.resolve()
374
+ .then(make)
375
+ .then(
376
+ function (made) {
377
+ if (!made) throw new Refusal("passkey-failed");
378
+ return made;
379
+ },
380
+ function (err) {
381
+ var name = err && err.name;
382
+ throw new Refusal(name === "NotAllowedError" || name === "AbortError" ? "passkey-cancelled" : "passkey-failed");
383
+ }
384
+ );
385
+ }
386
+
387
+ function assertion(options) {
388
+ return ceremony(function () {
389
+ return navigator.credentials.get({
390
+ publicKey: {
391
+ challenge: toBytes(options.challenge),
392
+ rpId: options.rpId,
393
+ allowCredentials: descriptors(options.allowCredentials),
394
+ userVerification: "required",
395
+ timeout: 60000
396
+ }
397
+ });
398
+ }).then(function (made) {
399
+ var id = toText(made.rawId);
400
+ return {
401
+ id: id,
402
+ rawId: id,
403
+ type: made.type,
404
+ response: {
405
+ clientDataJSON: toText(made.response.clientDataJSON),
406
+ authenticatorData: toText(made.response.authenticatorData),
407
+ signature: toText(made.response.signature)
408
+ },
409
+ clientExtensionResults: made.getClientExtensionResults()
410
+ };
411
+ });
412
+ }
413
+
414
+ // ---- what is drawn ----
415
+
416
+ function piece(tag, test, text, className) {
417
+ var el = document.createElement(tag);
418
+ if (test) el.setAttribute("data-test", test);
419
+ if (className) el.className = className;
420
+ if (text !== undefined) el.textContent = text;
421
+ return el;
422
+ }
423
+
424
+ /** A value in an element of its own direction: what runs right to left in it stays in it. */
425
+ function field(label, test, text, mono) {
426
+ var wrap = piece("div", null, undefined, "field");
427
+ wrap.appendChild(piece("span", null, label, "label"));
428
+ wrap.appendChild(piece("bdi", test, text, mono ? "mono" : ""));
429
+ return wrap;
430
+ }
431
+
432
+ function word(value) {
433
+ return value === null || value === undefined ? "" : String(value);
434
+ }
435
+
436
+ /** A value from the door, as it is put on the screen. */
437
+ function shown(value) {
438
+ return plain(word(value));
439
+ }
440
+
441
+ /** A sentence with values in it, each value apart from the words around it. */
442
+ function sentence(parts) {
443
+ return fill(document.createElement("p"), parts);
444
+ }
445
+
446
+ function drawRow(row) {
447
+ var item = piece("li", "waiting-row");
448
+ item.setAttribute("data-ref", word(row.ref));
449
+ var spend = row.spend && typeof row.spend === "object" ? row.spend : null;
450
+ var asked = ["Approve ", { value: shown(row.tool) }, "?"];
451
+ if (spend) {
452
+ var amountText = typeof spend.amountMinor === "number" ? String(spend.amountMinor) : "unreadable";
453
+ var box = piece("div", null, undefined, "spend");
454
+ var amount = piece("p", null, undefined, "amount");
455
+ amount.appendChild(piece("bdi", "row-amount", amountText));
456
+ amount.appendChild(document.createTextNode(" "));
457
+ amount.appendChild(piece("bdi", "row-currency", shown(spend.currency)));
458
+ amount.appendChild(document.createTextNode(" "));
459
+ amount.appendChild(piece("small", null, "minor units"));
460
+ box.appendChild(amount);
461
+ var payee = piece("p", null, undefined, "payee");
462
+ payee.appendChild(piece("span", null, "to ", "label"));
463
+ payee.appendChild(piece("bdi", "row-payee", shown(spend.payee)));
464
+ box.appendChild(payee);
465
+ box.appendChild(field("Reference", "row-reference", shown(spend.reference), false));
466
+ item.appendChild(box);
467
+ asked = [
468
+ "Approve ",
469
+ { value: amountText },
470
+ " ",
471
+ { value: shown(spend.currency) },
472
+ " (minor units) to ",
473
+ { value: shown(spend.payee) },
474
+ "?"
475
+ ];
476
+ }
477
+ item.appendChild(field("Tool", "row-tool", shown(row.tool), true));
478
+ item.appendChild(field("Agent", "row-agent", shown(row.agent), false));
479
+ item.appendChild(field("Rule", "row-rule", row.rule === null || row.rule === undefined ? "—" : shown(row.rule), false));
480
+ var held = "";
481
+ try {
482
+ held = JSON.stringify(row.args, null, 2);
483
+ } catch (err) {
484
+ held = "";
485
+ }
486
+ // The line breaks are the layout's own: JSON has already escaped any inside a value.
487
+ item.appendChild(piece("pre", "row-args", held === undefined ? "" : plain(held, true)));
488
+ item.appendChild(field("Held as", "row-ref", shown(row.ref), true));
489
+ item.appendChild(field("Request", "row-hash", shown(row.requestHash), true));
490
+ item.appendChild(field("Expires", "row-expires", clock(row.expiresAtMs), false));
491
+
492
+ var open = piece("button", "approve", "Approve", "primary");
493
+ open.type = "button";
494
+ var panel = piece("div", "approve-panel", undefined, "confirm");
495
+ panel.hidden = true;
496
+ panel.appendChild(sentence(asked));
497
+ var confirm = piece("button", "approve-confirm", "Approve with passkey", "primary");
498
+ confirm.type = "button";
499
+ var cancel = piece("button", "approve-cancel", "Cancel", "plain");
500
+ cancel.type = "button";
501
+ panel.appendChild(confirm);
502
+ panel.appendChild(cancel);
503
+ open.addEventListener("click", function () {
504
+ panel.hidden = false;
505
+ open.hidden = true;
506
+ });
507
+ cancel.addEventListener("click", function () {
508
+ panel.hidden = true;
509
+ open.hidden = false;
510
+ });
511
+ confirm.addEventListener("click", run(function () {
512
+ return approve(row);
513
+ }));
514
+ item.appendChild(open);
515
+ item.appendChild(panel);
516
+ return item;
517
+ }
518
+
519
+ function drawWaiting(rows) {
520
+ var list = at("waiting-list");
521
+ while (list.firstChild) list.removeChild(list.firstChild);
522
+ for (var i = 0; i < rows.length; i += 1) {
523
+ if (rows[i] && typeof rows[i] === "object") list.appendChild(drawRow(rows[i]));
524
+ }
525
+ at("waiting-count").textContent = String(list.children.length);
526
+ at("waiting-empty").hidden = list.children.length !== 0;
527
+ }
528
+
529
+ function drawHalt(state) {
530
+ var halted = state.halted === true;
531
+ var mark = at("halt-state");
532
+ mark.setAttribute("data-halted", halted ? "true" : "false");
533
+ mark.textContent = halted ? "Stopped" : "Running";
534
+ at("halt").hidden = halted;
535
+ at("resume").hidden = !halted;
536
+ var since = at("halt-since");
537
+ if (halted && state.since && typeof state.since === "object") {
538
+ fill(since, ["Stopped by ", { value: shown(state.since.by) }, ", " + clock(state.since.atMs)]);
539
+ since.hidden = false;
540
+ } else {
541
+ since.textContent = "";
542
+ since.hidden = true;
543
+ }
544
+ }
545
+
546
+ // ---- the session ----
547
+
548
+ function endSession() {
549
+ token = null;
550
+ clearTimeout(expiryTimer);
551
+ at("session-sub").textContent = "";
552
+ at("session-expires").textContent = "";
553
+ drawWaiting([]);
554
+ show("signin");
555
+ }
556
+
557
+ function beginSession(session) {
558
+ token = session.token;
559
+ at("session-sub").textContent = shown(session.sub);
560
+ at("session-expires").textContent = clock(session.expiresAtMs);
561
+ clearTimeout(expiryTimer);
562
+ // The door's clock decides when a session ends. This timer only saves a
563
+ // tap when the two clocks agree; when they do not, the next call finds out.
564
+ var left = session.expiresAtMs - Date.now();
565
+ if (typeof left === "number" && left > 0 && left < 15 * 60 * 1000) {
566
+ expiryTimer = setTimeout(function () {
567
+ if (token === null) return;
568
+ endSession();
569
+ say("error", "session-ended");
570
+ }, left);
571
+ }
572
+ }
573
+
574
+ function load() {
575
+ return call("GET", "/api/halt", undefined, true)
576
+ .then(function (res) {
577
+ drawHalt(need(res));
578
+ return call("GET", "/api/waiting", undefined, true);
579
+ })
580
+ .then(function (res) {
581
+ var listed = need(res);
582
+ drawWaiting(Array.isArray(listed.waiting) ? listed.waiting : []);
583
+ });
584
+ }
585
+
586
+ /** After something was done: a list that cannot be fetched must not hide that it was. */
587
+ function loadAfter() {
588
+ return load().catch(function (err) {
589
+ if (err instanceof Refusal && err.code === "session-ended") throw err;
590
+ });
591
+ }
592
+
593
+ // ---- what the buttons do ----
594
+
595
+ function enroll() {
596
+ var input = at("enroll-code");
597
+ var code = input.value.trim();
598
+ if (!/^[0-9]{8}$/.test(code)) return Promise.reject(new Refusal("code-format"));
599
+ return call("POST", "/api/enroll/options", { code: code })
600
+ .then(function (res) {
601
+ var options = need(res);
602
+ return ceremony(function () {
603
+ return navigator.credentials.create({
604
+ publicKey: {
605
+ challenge: toBytes(options.challenge),
606
+ rp: options.rp,
607
+ user: { id: toBytes(options.user.id), name: options.user.name, displayName: options.user.displayName },
608
+ pubKeyCredParams: options.pubKeyCredParams,
609
+ authenticatorSelection: options.authenticatorSelection,
610
+ attestation: options.attestation,
611
+ excludeCredentials: descriptors(options.excludeCredentials),
612
+ timeout: options.timeout
613
+ }
614
+ });
615
+ });
616
+ })
617
+ .then(function (made) {
618
+ var id = toText(made.rawId);
619
+ return call("POST", "/api/enroll", {
620
+ code: code,
621
+ response: {
622
+ id: id,
623
+ rawId: id,
624
+ type: made.type,
625
+ response: {
626
+ clientDataJSON: toText(made.response.clientDataJSON),
627
+ attestationObject: toText(made.response.attestationObject)
628
+ }
629
+ }
630
+ });
631
+ })
632
+ .then(function (res) {
633
+ need(res);
634
+ input.value = "";
635
+ operatorKnown = true;
636
+ show("signin");
637
+ say("ok", "enrolled");
638
+ });
639
+ }
640
+
641
+ function signIn() {
642
+ return call("POST", "/api/signin/options")
643
+ .then(function (res) {
644
+ return assertion(need(res));
645
+ })
646
+ .then(function (signed) {
647
+ return call("POST", "/api/signin", { assertion: signed });
648
+ })
649
+ .then(function (res) {
650
+ beginSession(need(res));
651
+ show("main");
652
+ return load();
653
+ })
654
+ .then(function () {
655
+ say("ok", "signed-in");
656
+ });
657
+ }
658
+
659
+ function signOut() {
660
+ return call("POST", "/api/signout", undefined, true)
661
+ .catch(function () {
662
+ return null;
663
+ })
664
+ .then(function () {
665
+ endSession();
666
+ say("ok", "signed-out");
667
+ });
668
+ }
669
+
670
+ function approve(row) {
671
+ var done = null;
672
+ return call("GET", "/api/approve/challenge?ref=" + encodeURIComponent(word(row.ref)), undefined, true)
673
+ .then(function (res) {
674
+ return assertion(need(res));
675
+ })
676
+ .then(function (signed) {
677
+ // The request hash that was on the screen: if something else is waiting now, the door says so.
678
+ return call("POST", "/api/approve", { ref: row.ref, requestHash: row.requestHash, assertion: signed }, true);
679
+ })
680
+ .then(function (res) {
681
+ done = need(res);
682
+ return loadAfter();
683
+ })
684
+ .then(function () {
685
+ say("ok", "approved", { allowRef: word(done.allowRef) });
686
+ });
687
+ }
688
+
689
+ function halt() {
690
+ // Stopping is the safe direction. A passkey that does not answer does not keep the body running.
691
+ return call("GET", "/api/halt/challenge", undefined, true)
692
+ .then(function (res) {
693
+ return assertion(need(res));
694
+ })
695
+ .then(
696
+ function (signed) {
697
+ return { assertion: signed };
698
+ },
699
+ function (err) {
700
+ if (err instanceof Refusal && err.code === "session-ended") throw err;
701
+ return {};
702
+ }
703
+ )
704
+ .then(function (sent) {
705
+ return call("POST", "/api/halt", sent, true).then(function (res) {
706
+ var state = need(res);
707
+ drawHalt(state);
708
+ say("ok", sent.assertion && !state.signatureRefused ? "halted" : "halted-unsigned");
709
+ });
710
+ });
711
+ }
712
+
713
+ function resume() {
714
+ return call("GET", "/api/resume/challenge", undefined, true)
715
+ .then(function (res) {
716
+ return assertion(need(res));
717
+ })
718
+ .then(function (signed) {
719
+ return call("POST", "/api/resume", { assertion: signed }, true);
720
+ })
721
+ .then(function (res) {
722
+ drawHalt(need(res));
723
+ say("ok", "resumed");
724
+ });
725
+ }
726
+
727
+ /** One thing at a time, every button shut while it runs, and whatever went wrong said by its code. */
728
+ function run(action) {
729
+ return function () {
730
+ if (busy) return;
731
+ busy = true;
732
+ lock(true);
733
+ hush();
734
+ Promise.resolve()
735
+ .then(action)
736
+ .catch(function (err) {
737
+ var refusal = err instanceof Refusal ? err : new Refusal("fault");
738
+ var after = Promise.resolve();
739
+ if (refusal.code === "session-ended") {
740
+ endSession();
741
+ } else if (refusal.code === "no-operator") {
742
+ operatorKnown = false;
743
+ at("goto-signin").hidden = true;
744
+ show("enroll");
745
+ } else if (token !== null && (refusal.code === "stale" || refusal.code === "unknown-ref")) {
746
+ after = load().catch(function (again) {
747
+ if (again instanceof Refusal && again.code === "session-ended") {
748
+ endSession();
749
+ refusal = again;
750
+ }
751
+ });
752
+ }
753
+ return after.then(function () {
754
+ say("error", refusal.code, refusal.code === "enroll-refused" ? { reason: refusal.body.reason } : null);
755
+ });
756
+ })
757
+ .then(function () {
758
+ busy = false;
759
+ lock(false);
760
+ });
761
+ };
762
+ }
763
+
764
+ function start() {
765
+ at("enroll-submit").addEventListener("click", run(enroll));
766
+ at("enroll-code").addEventListener("keydown", function (event) {
767
+ if (event.key === "Enter") at("enroll-submit").click();
768
+ });
769
+ at("signin").addEventListener("click", run(signIn));
770
+ at("signout").addEventListener("click", run(signOut));
771
+ at("refresh").addEventListener("click", run(load));
772
+ at("halt").addEventListener("click", run(halt));
773
+ at("resume").addEventListener("click", run(resume));
774
+ at("goto-enroll").addEventListener("click", function () {
775
+ hush();
776
+ at("goto-signin").hidden = !operatorKnown;
777
+ show("enroll");
778
+ });
779
+ at("goto-signin").addEventListener("click", function () {
780
+ hush();
781
+ show("signin");
782
+ });
783
+
784
+ if (!window.PublicKeyCredential || !navigator.credentials) {
785
+ unsupported = true;
786
+ lock(false);
787
+ show("signin");
788
+ say("error", "passkey-unsupported");
789
+ return;
790
+ }
791
+ // Whether anyone is enrolled decides the first screen. The challenge this
792
+ // returns is not kept: a sign-in asks for its own.
793
+ call("POST", "/api/signin/options").then(
794
+ function (res) {
795
+ if (res.ok) {
796
+ operatorKnown = true;
797
+ show("signin");
798
+ return;
799
+ }
800
+ if (res.body.error === "no-operator") {
801
+ operatorKnown = false;
802
+ at("goto-signin").hidden = true;
803
+ show("enroll");
804
+ return;
805
+ }
806
+ show("signin");
807
+ say("error", typeof res.body.error === "string" && res.body.error !== "" ? res.body.error : "http-" + res.status);
808
+ },
809
+ function (err) {
810
+ show("signin");
811
+ say("error", err instanceof Refusal ? err.code : "fault");
812
+ }
813
+ );
814
+ }
815
+
816
+ start();
817
+ })();
818
+ `;
819
+ export const DOOR_JS = SCRIPT.replace('"@@CONTROL_CLASS@@"', () => JSON.stringify(DISPLAY_ESCAPE_CLASS));