sideora 0.0.1-alpha.0 → 0.1.0-alpha.2

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 (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
package/src/relay.js ADDED
@@ -0,0 +1,876 @@
1
+ // The Mac's side of the relay: the web app reached from another device, with nothing let in to this Mac.
2
+ //
3
+ // This Mac dials out to a relay (a small server on the internet: relay/ in this repository) and keeps one
4
+ // connection to it. A browser paired with this Mac talks to the relay, which passes on what it cannot read:
5
+ // everything a browser asks and everything it is answered is sealed between that browser and this Mac
6
+ // (src/relay-seal.js). The relay knows who may talk, never what is said.
7
+ //
8
+ // sideora relay join <url> <invitation> this Mac becomes an instance of that relay (its two keys are made here)
9
+ // sideora relay pair a link (and a QR code) that pairs a browser, good once, ten minutes
10
+ // sideora relay devices | forget <id|all> the paired browsers; one forgotten is refused at once, here and at the relay
11
+ // sideora relay leave the membership is closed
12
+ // `sideora web` keeps the connection for as long as it runs.
13
+ //
14
+ // Kept in $SIDEORA_HOME/relay.json (mode 600): the relay's address, this instance's id, the paired browsers'
15
+ // public keys. The secrets (the membership token, the private halves of the two keys) are in the Keychain.
16
+ //
17
+ // Pairing: the link carries a code and the fingerprint of this Mac's key, after the #: neither reaches the relay.
18
+ // The browser seals the code to this Mac's key, so the relay cannot read the code nor pair a browser of its own.
19
+ // A request: { n, at, e, op, args } sealed for "req.<device>"; fresh (five minutes), used once, and of this run of
20
+ // the Mac (`e`, its epoch: a number made as this process starts, so a request kept by the relay and sent again
21
+ // after a restart is of another run, and refused). Its answer is sealed for "res.<device>.<n>": an answer to
22
+ // another request, or to another browser, does not open. The pushes of one subscription are sealed for
23
+ // "ev.<device>.<s>" (s: a number the page made for that subscription) and numbered: one kept and sent again, out
24
+ // of order, or left out shows.
25
+ //
26
+ // What this does not cover: the page's own code comes from the relay. A relay that served other code than this
27
+ // repository's could read what the page shows. One's own relay, or one run by someone trusted, is the answer to that.
28
+
29
+ import crypto from 'node:crypto';
30
+ import fs from 'node:fs';
31
+ import os from 'node:os';
32
+ import path from 'node:path';
33
+ import { HOME_DIR, keychainReadStrict, keychainWrite, keychainDelete } from './config.js';
34
+ import { withFileLock } from './file-lock.js';
35
+ import { OPS, runOp, follow } from './panel-ops.js';
36
+ import * as passkeys from './relay-passkey.js';
37
+ import * as seals from './relay-seal.js';
38
+ import * as access from './web-access.js';
39
+ import { AT_THE_MAC, EACH_OPS, FULL_OPS, NOT_FROM_AFAR, RELAY_OPS, TOUCH_OPS } from './op-registry.js';
40
+
41
+ export const RELAY_PATH = path.join(HOME_DIR, 'relay.json');
42
+ const KEY_SERVICE = 'sideora-relay';
43
+ const KEY_ACCOUNT = 'membership';
44
+ /** Characters of JSON text in one frame to the relay (as the relay's relay/src/instance.ts, in sideorahq/cloud, cuts its own). */
45
+ export const PART = 256 * 1024;
46
+ const FRESH_MS = 5 * 60 * 1000;
47
+ const MAX_DEVICES = 20;
48
+ /** At once, for one device: more would be the relay asking again and again with one ticket. */
49
+ const MAX_STREAMS = 4;
50
+ /** Parts of long requests waiting for their last one: no more than this is kept, nor for longer. */
51
+ const MAX_PARTS_BYTES = 96 * 1024 * 1024;
52
+ const PARTS_MS = 120_000;
53
+ /** The JSON text of one answer: what the relay holds of one (relay/src/instance.ts in sideorahq/cloud, MAX_ANSWER), less a little. */
54
+ const MAX_ANSWER = 15 * 1024 * 1024;
55
+ /** A device unused for this long is no longer paired (a phone lost and never forgotten by hand). */
56
+ const IDLE_MS = 30 * 24 * 60 * 60 * 1000;
57
+
58
+ /**
59
+ * What a device may ask through the relay (RELAY_OPS), what a device given full access at the Mac may ask besides
60
+ * (FULL_OPS: a device paired with `sideora relay pair` (not --limited), or given it by `relay admin <device>`, at the Mac, never asked
61
+ * for from afar), what neither may (NOT_FROM_AFAR for a device without full access; AT_THE_MAC for any), and the
62
+ * passkey touch each takes (TOUCH_OPS, EACH_OPS): src/op-registry.js, where each op is named once and why it is
63
+ * reached as it is. Never an op that changes accounts without full access; never more than the web app serves.
64
+ * Whoever holds a device with full access, and whoever serves its page (the relay), can do on this Mac what its
65
+ * owner can do in the panel.
66
+ */
67
+ export { AT_THE_MAC, EACH_OPS, FULL_OPS, NOT_FROM_AFAR, RELAY_OPS, TOUCH_OPS };
68
+ /**
69
+ * Of the AI settings' messages, those answered from afar: seeing the connections, choosing one, its models, a turn.
70
+ * Adding or changing a connection, and signing in to a provider, are done at the Mac (the page there, the
71
+ * extension): they make this Mac reach an address of the asker's choosing.
72
+ */
73
+ const AI_FROM_AFAR = new Set(['ai-get', 'ai-set-active', 'ai-chat', 'ai-list-models']);
74
+ /**
75
+ * A device's passkey (src/relay-passkey.js): made on the device, checked here. A device that has one is locked
76
+ * until its passkey opens it, and again once nothing was done on it for LOCK_MS: locked, it is told nothing but
77
+ * that it is, and its pushes end. What its page asks by itself (a list read again as a mail arrives) is not
78
+ * something done on it: each request says how long ago a key or a finger last touched the page.
79
+ * Then, with a passkey: what reaches other people (TOUCH_OPS) and what full access adds are asked with a touch of
80
+ * the passkey no older than TOUCH_MS; what changes this Mac's rules, accounts and AI connections (EACH_OPS, and
81
+ * saving or removing a connection) with a touch made for that very asking, good once.
82
+ * A device without a passkey is as it was (paired, never locked), and full access waits until it has one.
83
+ * Opening hands the page a name for that opening, which each request then carries: what was paired and copied
84
+ * elsewhere (the browser's storage, taken while locked or long ago) is not opened by the device being opened.
85
+ */
86
+ export const LOCK_MS = 15 * 60 * 1000;
87
+ /** How long unused before it locks, as each device may have it (minutes; chosen on the device, with its passkey): never longer than an opening lasts. */
88
+ export const LOCK_CHOICES = [15, 60, 240, 720];
89
+ export const TOUCH_MS = 5 * 60 * 1000;
90
+ /** However much it is used, an opening lasts this long at most: then the passkey is asked for again. */
91
+ export const OPEN_MS = 12 * 60 * 60 * 1000;
92
+ const ASK_MS = 5 * 60 * 1000; // a challenge of this Mac's is answered within this, once
93
+ /**
94
+ * Full access is for a device whose passkey its owner made: given at the Mac once the device has its passkey, or
95
+ * no more than this long before it makes one (paired with it, the passkey is made as the page first opens). A
96
+ * passkey made later than that, on a device given full access and left without one, opens nothing more than any
97
+ * other device's until full access is given again: whoever picks such a device up cannot make themselves its owner.
98
+ */
99
+ export const GRANT_MS = 10 * 60 * 1000;
100
+ /** Full access as it stands for a device: given, and its passkey not made too long after. */
101
+ const fullOf = (d) => {
102
+ const passkey = passkeyOf(d);
103
+ return d?.admin === true && !!passkey && (passkey.created || 0) - (Number(d.adminAt) || 0) <= GRANT_MS;
104
+ };
105
+ /** The passkey as kept with a device, or null (none, or not one: a file written by hand). */
106
+ const passkeyOf = (d) => (d?.passkey && typeof d.passkey.id === 'string' && typeof d.passkey.key === 'string' && passkeys.ALGS.includes(d.passkey.alg) ? d.passkey : null);
107
+
108
+ /** A device's name as it says it, kept and shown without what would draw over a terminal's other lines or turn text around. */
109
+ export const cleanName = (name) => String(name ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 120);
110
+
111
+ /** Where the membership's secrets are kept: the Keychain (a test gives its own). read: null when there are none. */
112
+ export const keychainStore = {
113
+ read: () => keychainReadStrict(KEY_SERVICE, KEY_ACCOUNT),
114
+ write: (secret) => keychainWrite(KEY_SERVICE, KEY_ACCOUNT, secret),
115
+ remove: () => { try { keychainDelete(KEY_SERVICE, KEY_ACCOUNT); } catch { /* none */ } }
116
+ };
117
+
118
+ // --- what is kept ---------------------------------------------------------------------
119
+
120
+ export function readState(file = RELAY_PATH) {
121
+ try {
122
+ const s = JSON.parse(fs.readFileSync(file, 'utf8'));
123
+ const live = (d) => d && typeof d.id === 'string' && typeof d.key === 'string' && Date.now() - (d.seen || d.created || 0) < IDLE_MS;
124
+ return s && typeof s.url === 'string' && typeof s.instance === 'string' ? { url: s.url, instance: s.instance, label: s.label || '', box: s.box || '', devices: Array.isArray(s.devices) ? s.devices.filter(live) : [] } : null;
125
+ } catch { return null; }
126
+ }
127
+ /** Read what is kept, change it, write it back: one at a time across processes (`sideora web`, `relay forget` in a terminal). `change(state)` returns what the caller wants; the state is written when it returns anything but undefined... and was joined. */
128
+ function changeState(file, change) {
129
+ return withFileLock(file, () => {
130
+ const state = readState(file);
131
+ if (!state) return undefined;
132
+ const out = change(state);
133
+ if (out !== undefined) writeState(state, file);
134
+ return out;
135
+ });
136
+ }
137
+ export function writeState(state, file = RELAY_PATH) {
138
+ fs.mkdirSync(path.dirname(file), { recursive: true });
139
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
140
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
141
+ fs.renameSync(tmp, file);
142
+ }
143
+
144
+ /** The relay's address as given: https, a host, nothing else (http only for one on this computer, to try things). */
145
+ export function relayUrl(text) {
146
+ let url;
147
+ try { url = new URL(/^https?:\/\//i.test(String(text)) ? String(text) : `https://${text}`); } catch { throw new Error('that is not the address of a relay'); }
148
+ const local = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(url.hostname);
149
+ if (url.protocol !== 'https:' && !local) throw new Error('a relay is reached over https');
150
+ if (url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) throw new Error('the address of a relay is its address alone (https://relay.example)');
151
+ return url.origin;
152
+ }
153
+
154
+ /** This Mac becomes an instance of a relay: its keys are made here, their public halves and the invitation sent there. */
155
+ export async function relayJoin({ url, code, label = os.hostname().replace(/\.local$/, ''), file = RELAY_PATH, keyStore = keychainStore, fetchFn = fetch } = {}) {
156
+ if (readState(file)) throw new Error('this computer is already joined to a relay (`sideora relay leave` first)');
157
+ const origin = relayUrl(url);
158
+ if (!String(code || '').trim()) throw new Error('relay join needs the invitation the relay\'s owner gave');
159
+ const signing = await seals.newSignPair();
160
+ const box = await seals.newBoxPair();
161
+ const res = await fetchFn(`${origin}/join`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: String(code).trim(), key: signing.publicRaw, box: box.publicRaw, label: String(label).slice(0, 80) }) });
162
+ const said = await res.json().catch(() => null);
163
+ if (!res.ok || !said?.instance || !said?.token) throw new Error(said?.error || `the relay answered ${res.status}`);
164
+ try {
165
+ keyStore.write(JSON.stringify({ token: said.token, sign: signing.pkcs8, box: box.pkcs8 }));
166
+ writeState({ url: origin, instance: said.instance, label: String(label).slice(0, 80), box: box.publicRaw, devices: [] }, file);
167
+ } catch (e) {
168
+ // admitted there, not kept here: the membership would be one nobody holds. It is closed, and said: the
169
+ // invitation is spent (one admits one Mac), another is needed.
170
+ await fetchFn(`${origin}/i/${said.instance}/retire`, { method: 'POST', headers: { authorization: `Bearer ${said.token}` }, signal: AbortSignal.timeout(8000) }).catch(() => {});
171
+ try { keyStore.remove(); } catch { /* nothing kept */ }
172
+ throw new Error(`the relay admitted this computer, but it could not be kept here (${e.message}); that invitation is spent: ask for another`);
173
+ }
174
+ return { url: origin, instance: said.instance };
175
+ }
176
+
177
+ /**
178
+ * The membership is closed at the relay, and everything about it forgotten here. When the relay cannot be told
179
+ * (it does not answer, or refuses), nothing is forgotten and that is the error: left here only, the membership
180
+ * would stay open there with nobody to close it. `force`: forget here all the same.
181
+ */
182
+ export async function relayLeave({ file = RELAY_PATH, keyStore = keychainStore, fetchFn = fetch, force = false } = {}) {
183
+ const state = readState(file);
184
+ if (!state) return false;
185
+ const secrets = secretsOf(keyStore);
186
+ let told = false;
187
+ if (secrets?.token) told = await fetchFn(`${state.url}/i/${state.instance}/retire`, { method: 'POST', headers: { authorization: `Bearer ${secrets.token}` }, signal: AbortSignal.timeout(8000) }).then((r) => r.ok, () => false);
188
+ if (!told && !force) throw new Error('the relay could not be told this computer is leaving (it did not answer, or refused): nothing was changed. Try again, or `sideora relay leave --force` to forget it here all the same');
189
+ keyStore.remove();
190
+ try { fs.unlinkSync(file); } catch { /* gone */ }
191
+ return true;
192
+ }
193
+
194
+ /**
195
+ * The same relay at another address (a new name for it): this computer's membership, keys and paired devices stay.
196
+ * The relay at the address this computer trusts (the one it joined, or moved to before) is asked which addresses are
197
+ * its own: only one it names is moved to, and the new address must know this computer by the key it holds. (What a
198
+ * relay shows anyone, the instance and its key, could be shown by another server too: it proves nothing alone.)
199
+ * Devices paired at the old address keep it as their site, their passkeys (made or to be made) included.
200
+ */
201
+ export async function relayMove({ url, file = RELAY_PATH, fetchFn = fetch } = {}) {
202
+ const state = readState(file);
203
+ if (!state) throw new Error('this computer is not joined to a relay (`sideora relay join <url> <invitation>`)');
204
+ const to = relayUrl(url);
205
+ if (to === state.url) return { from: state.url, to, moved: false };
206
+ const get = (u) => fetchFn(u, { redirect: 'error', signal: AbortSignal.timeout(10_000) }).then((r) => (r.ok ? r.json() : null), () => null).catch(() => null);
207
+ const names = await get(`${state.url}/health`);
208
+ if (!Array.isArray(names?.hosts) || !names.hosts.includes(new URL(to).host)) throw new Error(`the relay at ${state.url} does not name ${to} as one of its addresses (or it does not answer). Nothing was changed`);
209
+ const said = await get(`${to}/i/${state.instance}`);
210
+ if (!said || said.instance !== state.instance || said.box !== state.box) throw new Error(`${to} does not know this computer by its key. Nothing was changed`);
211
+ const was = passkeys.partyOf(state.url);
212
+ // (checked again inside the lock: another terminal may have left, or joined elsewhere, meanwhile)
213
+ const moved = changeState(file, (s) => {
214
+ if (s.url !== state.url || s.instance !== state.instance || s.box !== state.box) return undefined;
215
+ for (const d of s.devices) {
216
+ if (passkeyOf(d) && !d.passkey.rpId) Object.assign(d.passkey, was);
217
+ if (!d.site) d.site = was;
218
+ }
219
+ s.url = to;
220
+ return true;
221
+ });
222
+ if (!moved) throw new Error('this computer\'s membership changed while it was being moved (left, or joined elsewhere): nothing was changed');
223
+ return { from: was.origin, to, moved: true };
224
+ }
225
+
226
+ function secretsOf(keyStore) {
227
+ const raw = keyStore.read();
228
+ if (!raw) return null;
229
+ try { const s = JSON.parse(raw); return s?.token && s?.sign && s?.box ? s : null; } catch { return null; }
230
+ }
231
+
232
+ /** The link that pairs a browser: the relay's page, and after the # (never sent anywhere) the instance, a code good once, and this Mac's key's fingerprint. */
233
+ export async function relayPairLink(options = {}) { return (await relayPairing(options)).link; }
234
+ /** The same, with the code's reference (access.codeRef): what was paired with it, or withdrawing it, is asked by that. */
235
+ export async function relayPairing({ file = RELAY_PATH, admin = false } = {}) {
236
+ const state = readState(file);
237
+ if (!state) throw new Error('this computer is not joined to a relay (`sideora relay join <url> <invitation>`)');
238
+ // (what the device will be allowed is the code's own, kept here: nothing in the link says it, or could change it)
239
+ const { code } = access.newPairingCode(Date.now(), admin ? 'relay-admin' : 'relay');
240
+ return { link: `${state.url}/#pair=${state.instance}.${code}.${await seals.fingerprint(state.box)}`, ref: access.codeRef(code) };
241
+ }
242
+
243
+ export const relayDevices = ({ file = RELAY_PATH } = {}) => {
244
+ const state = readState(file);
245
+ // (`at`: a device paired at another address of the relay, before it moved: it opens from there until paired again)
246
+ const atOf = (d) => { const o = passkeyOf(d)?.origin ?? d.site?.origin; return typeof o === 'string' && o !== state?.url ? o : undefined; };
247
+ return (state?.devices ?? []).map((d) => ({ id: d.id, name: cleanName(d.name), created: d.created, seen: d.seen, admin: d.admin === true, passkey: !!passkeyOf(d), full: fullOf(d), ...(atOf(d) ? { at: atOf(d) } : {}) })).sort((a, b) => (b.seen || 0) - (a.seen || 0));
248
+ };
249
+
250
+ /**
251
+ * Give one paired device full access (FULL_OPS), or take it back (`on` false; `which` 'all': from every one). The
252
+ * number changed, or null when no such device is paired. Its next request is answered accordingly: nothing is
253
+ * restarted, and what it had already asked is still done.
254
+ */
255
+ export function relayAdmin(which, on = true, { file = RELAY_PATH } = {}) {
256
+ if (on && which === 'all') throw new Error('full access is given to one device at a time');
257
+ let known = which === 'all';
258
+ const n = changeState(file, (state) => {
259
+ let changed = 0;
260
+ for (const d of state.devices) {
261
+ if (which !== 'all' && d.id !== which) continue;
262
+ known = true;
263
+ // (given again to a device that waits for it: given as of now, which is what a passkey made earlier needs)
264
+ if (on ? !fullOf(d) || d.admin !== true : d.admin === true) changed++;
265
+ if (on) { d.admin = true; d.adminAt = Date.now(); } else { delete d.admin; delete d.adminAt; }
266
+ }
267
+ return known ? changed : undefined;
268
+ }) ?? 0;
269
+ return known ? n : null;
270
+ }
271
+
272
+ /** Forget one paired browser, or all ('all'). A running connection (sideora web) sees the file change and tells the relay. */
273
+ export function relayForget(which, { file = RELAY_PATH } = {}) {
274
+ return changeState(file, (state) => {
275
+ const keep = which === 'all' ? [] : state.devices.filter((d) => d.id !== which);
276
+ const n = state.devices.length - keep.length;
277
+ if (!n) return undefined;
278
+ state.devices = keep;
279
+ return n;
280
+ }) ?? 0;
281
+ }
282
+
283
+ // --- answering -----------------------------------------------------------------------
284
+
285
+ /** What a path of this Mac looks like to someone who is not at it: the home folder and Sideora's own are not spelled out. */
286
+ export function scrub(text) {
287
+ let s = String(text ?? '');
288
+ for (const [dir, as] of [[HOME_DIR, '~/.sideora'], [os.homedir(), '~']]) if (dir && dir.length > 1) s = s.split(dir).join(as);
289
+ return s;
290
+ }
291
+
292
+ /**
293
+ * What goes to a device, with what says why something failed scrubbed: an op's own error, and the fields of an
294
+ * answer or a push that carry one (`error`, `failed`, `detail`, `reason`, a `message` in words, a few levels down). A mail's own text is another
295
+ * field, and is left as it is.
296
+ */
297
+ export function scrubbed(value, depth = 0) {
298
+ if (!value || typeof value !== 'object' || depth > 4) return value;
299
+ if (Array.isArray(value)) return value.length > 200 ? value : value.map((v) => scrubbed(v, depth + 1));
300
+ let out = value;
301
+ for (const [k, v] of Object.entries(value)) {
302
+ const next = /^(error|failed|detail|why|reason)$/.test(k) || (k === 'message' && typeof v === 'string') ? (typeof v === 'string' ? scrub(v) : scrubbed(v, depth + 1)) : (k === 'push' || k === 'event' || k === 'result' ? scrubbed(v, depth + 1) : v);
303
+ if (next !== v) { if (out === value) out = { ...value }; out[k] = next; }
304
+ }
305
+ return out;
306
+ }
307
+
308
+ /**
309
+ * What answers the relay's frames: `handle(frame, send)` for each frame of the Mac's socket, `hello()` to say who is
310
+ * paired as the connection opens. `ops`/`served`: what may be asked (never an op that changes accounts), and
311
+ * `full`: what a device given full access at the Mac may ask besides; `onPaired({ id, name, admin })`: a device
312
+ * was let in (said at the Mac, so that a link used by someone else does not go unseen); `onPasskey({ id, name })`:
313
+ * one was given its passkey;
314
+ * `followFn`: the pushes. Nothing here touches the network: the socket is its caller's.
315
+ */
316
+ export async function createRunner({ file = RELAY_PATH, keyStore = keychainStore, ops = OPS, served = RELAY_OPS, full = FULL_OPS, followFn = follow, onPaired = () => {}, onPasskey = () => {}, now = Date.now } = {}) {
317
+ const first = readState(file);
318
+ const secrets = secretsOf(keyStore);
319
+ if (!first || !secrets) throw new Error('this computer is not joined to a relay');
320
+ const instance = first.instance;
321
+ const boxKey = await seals.boxPrivate(secrets.box);
322
+ const signKey = await seals.signPrivate(secrets.sign);
323
+ /** This run of the Mac: a request names it, so one made for an earlier run (kept by the relay, sent again after a restart) is not of this one. */
324
+ const epoch = crypto.randomBytes(9).toString('base64url');
325
+ const shared = new Map(); // device id -> { key (base64url, as paired), aes }
326
+ const used = new Map(); // "<device>.<n>" -> when: a request, a ticket, is answered once
327
+ const streams = new Map(); // conn -> { device, stop }
328
+ const working = new Map(); // request id -> AbortController
329
+ const parts = new Map(); // request id -> { got, n, bytes, at }
330
+ const locks = new Map(); // device id -> { key, open, active, touched }: where its passkey's lock stands, in this run
331
+ const asks = new Map(); // challenge -> { device, kind: 'make' | 'open' | 'op', op?, at }
332
+ const party = passkeys.partyOf(first.url);
333
+ // the site a device's passkey is for: the one it was made at, or for a device paired before the relay moved, the
334
+ // address it was paired at (its page is still there); else this relay's address
335
+ const siteOf = (d) => {
336
+ const at = passkeyOf(d) ?? d?.site;
337
+ return typeof at?.rpId === 'string' && typeof at?.origin === 'string' ? { rpId: at.rpId, origin: at.origin } : party;
338
+ };
339
+ let alive = true;
340
+
341
+ const devices = () => readState(file)?.devices ?? [];
342
+ const paired = (device) => devices().some((d) => d.id === device);
343
+ const keyOf = async (device) => {
344
+ const d = devices().find((x) => x.id === device);
345
+ if (!d) { shared.delete(device); return null; }
346
+ // (kept by the key it was made of: an id given again to another browser is another key)
347
+ if (shared.get(device)?.key !== d.key) shared.set(device, { key: d.key, aes: await seals.sharedKey(boxKey, d.key, instance) });
348
+ return shared.get(device).aes;
349
+ };
350
+ const seen = (device) => {
351
+ const d = devices().find((x) => x.id === device);
352
+ if (!d || now() - (d.seen || 0) <= 60_000) return;
353
+ try { changeState(file, (state) => { const mine = state.devices.find((x) => x.id === device); if (!mine) return undefined; mine.seen = now(); return true; }); } catch { /* busy: noted next time */ }
354
+ };
355
+ const fresh = (at) => Number.isFinite(at) && Math.abs(now() - at) <= FRESH_MS;
356
+
357
+ // --- the passkey's lock
358
+ /** Where a device's lock stands (closed, for one this run has not seen opened; and for an id paired again as another browser). */
359
+ const lockOf = (d) => {
360
+ let l = locks.get(d.id);
361
+ if (!l || l.key !== d.key) { l = { key: d.key, openings: new Map(), active: 0, touched: 0, gen: 0, running: new Set(), models: new Set(), runs: new Set() }; locks.set(d.id, l); }
362
+ return l;
363
+ };
364
+ /** Locked: every opening ends, its pushes end (told why: 423), what it was having done is let go of and not told, and a touch made earlier counts for nothing. */
365
+ const lock = (d) => {
366
+ const l = lockOf(d);
367
+ l.openings.clear();
368
+ l.models.clear();
369
+ l.touched = 0;
370
+ l.gen++;
371
+ for (const stop of l.running) stop.abort();
372
+ // the assistant's answers it started go no further: they would go on reading mail for a device now locked
373
+ for (const run of l.runs) runOp('assistantStop', { run }, ops).catch(() => {});
374
+ l.runs.clear();
375
+ for (const [conn, s] of streams) if (s.device === d.id) { s.stop(); streams.delete(conn); s.end(423); }
376
+ };
377
+ /** How long unused before this device locks: its own choice (LOCK_CHOICES), else LOCK_MS. (Chosen in this run: known at once, to what holds the device as it was read before.) */
378
+ const lockChosen = new Map();
379
+ const lockMs = (d) => { const m = lockChosen.get(d.id) ?? d.lockMinutes; return LOCK_CHOICES.includes(m) ? m * 60_000 : LOCK_MS; };
380
+ /** Locked as a whole: never opened in this run, or left unused since. */
381
+ const isLocked = (d) => {
382
+ const l = lockOf(d);
383
+ const had = l.openings.size;
384
+ for (const [name, at] of l.openings) if (now() - at > OPEN_MS) l.openings.delete(name);
385
+ if (had && (!l.openings.size || now() - l.active > lockMs(d))) lock(d);
386
+ // (an opening that ran its time, beside others still good: its own pushes end)
387
+ else if (had !== l.openings.size) for (const [conn, s] of streams) if (s.device === d.id && !l.openings.has(s.opening)) { s.stop(); streams.delete(conn); s.end(423); }
388
+ return !l.openings.size;
389
+ };
390
+ /** Open for whoever asks under this name (the one its opening was given): the device is, and this is one of its openings. */
391
+ const isOpen = (d, name) => !isLocked(d) && typeof name === 'string' && lockOf(d).openings.has(name);
392
+ /** Opened by its passkey, a moment ago: the name of this opening, for the page that did it (a handful at once: its tabs). */
393
+ const opened = (d) => {
394
+ const l = lockOf(d);
395
+ isLocked(d); // (left unused meanwhile: what was open is closed before this opens)
396
+ const name = crypto.randomBytes(18).toString('base64url');
397
+ for (const old of [...l.openings.keys()].slice(0, Math.max(0, l.openings.size - 7))) l.openings.delete(old);
398
+ l.openings.set(name, now());
399
+ l.active = now();
400
+ l.touched = now();
401
+ return name;
402
+ };
403
+ /** What is asked, as one thing: a touch made for an asking is for this op with these very arguments. */
404
+ const digestOf = (op, args) => crypto.createHash('sha256').update(JSON.stringify([op, args ?? null])).digest('base64url');
405
+ /** A challenge of this Mac's, for one device and one thing, good once within ASK_MS (a handful wait at most, per device). */
406
+ const challengeFor = (device, kind, what) => {
407
+ const mine = [];
408
+ for (const [c, a] of asks) { if (now() - a.at > ASK_MS) asks.delete(c); else if (a.device === device) mine.push(c); }
409
+ for (const c of mine.slice(0, Math.max(0, mine.length - 7))) asks.delete(c);
410
+ const challenge = passkeys.newChallenge();
411
+ asks.set(challenge, { device, kind, at: now(), ...(what ? { what } : {}) });
412
+ return challenge;
413
+ };
414
+ /** The challenge an answer names, when it is this device's, of this kind (and for this very asking), and not yet answered: spent either way. */
415
+ const answered = (device, kind, challenge, what) => {
416
+ const a = typeof challenge === 'string' ? asks.get(challenge) : null;
417
+ if (!a || a.device !== device) return false;
418
+ asks.delete(challenge);
419
+ return a.kind === kind && now() - a.at <= ASK_MS && (kind !== 'op' || a.what === what);
420
+ };
421
+ /** A use of the passkey, checked against a challenge of this Mac's. True, or the reason it is not one. */
422
+ const touched = (d, kind, given, what) => {
423
+ const passkey = passkeyOf(d);
424
+ if (!passkey || !answered(d.id, kind, given?.challenge, what)) return 'that was asked too long ago, not by this computer, or for something else';
425
+ try {
426
+ const { count } = passkeys.verifyAssertion(given, { challenge: given.challenge, ...siteOf(d), passkey });
427
+ // (kept when it can be: a file busy for a moment does not undo a passkey that signed)
428
+ if (count !== (passkey.count || 0)) try { changeState(file, (state) => { const mine = state.devices.find((x) => x.id === d.id); if (!passkeyOf(mine) || mine.passkey.id !== passkey.id) return undefined; mine.passkey.count = count; return true; }); } catch { /* next time */ }
429
+ return true;
430
+ } catch (e) { return e.message; }
431
+ };
432
+ const asking = (d, what) => ({ challenge: challengeFor(d.id, 'op', what), credential: passkeyOf(d).id, rpId: siteOf(d).rpId });
433
+ /** What an op takes of the passkey: a touch for this very asking ('each'), one no older than TOUCH_MS ('fresh'), or none. */
434
+ const touchFor = (op, args) => {
435
+ if (EACH_OPS.has(op) || op === 'setLockAfter') return 'each';
436
+ if (op === 'aiMessage') {
437
+ const type = String(typeof args?.type === 'string' ? args.type : '').replace(/^[a-z]+:/, '');
438
+ // (choosing which connection reads the mail: a touch not long ago; a connection made, changed or removed: one for that asking;
439
+ // a sign-in's steps asked again and again while it is under way: one not long ago)
440
+ if (type === 'ai-set-active') return 'fresh';
441
+ return AI_FROM_AFAR.has(type) ? null : /^ai-((save|delete)-connection|anthropic-login-complete|anthropic-paste-token)$/.test(type) ? 'each' : 'fresh';
442
+ }
443
+ return TOUCH_OPS.has(op) || full.has(op) ? 'fresh' : null;
444
+ };
445
+ // a device left as it is locks by the clock, not at its next asking: its pushes stop then
446
+ const sweep = () => { for (const d of devices()) if (locks.get(d.id)?.openings.size) isLocked(d); };
447
+ const sweeping = setInterval(sweep, 15_000);
448
+ sweeping.unref?.();
449
+ /** True the first time this number is seen from this device (and it is kept for as long as it could be fresh). */
450
+ const once = (device, n) => {
451
+ for (const [k, t] of used) if (now() - t > 2 * FRESH_MS) used.delete(k);
452
+ if (typeof n !== 'string' || !n || n.length > 64 || used.has(`${device}.${n}`)) return false;
453
+ used.set(`${device}.${n}`, now());
454
+ return true;
455
+ };
456
+
457
+ const answer = (send, id, status, body) => {
458
+ const text = body == null ? null : JSON.stringify(body);
459
+ if (text === null || text.length <= PART) return send({ t: 'res', id, status, body: body ?? null });
460
+ const n = Math.ceil(text.length / PART);
461
+ for (let i = 0; i < n; i++) send({ t: 'res', id, status, n, i, part: text.slice(i * PART, (i + 1) * PART) });
462
+ };
463
+
464
+ async function pair(body) {
465
+ if (typeof body?.key !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(body.key) || typeof body?.data !== 'string' || body.data.length > 4096) return [400, null];
466
+ let asked;
467
+ let aes;
468
+ try { aes = await seals.sharedKey(boxKey, body.key, instance); asked = JSON.parse(await seals.open(aes, body.data, 'pair')); } catch { return [403, null]; }
469
+ // sealed to this Mac's key by whoever holds the link: the code inside is what lets it in, once
470
+ // (and what the code was made for is what the device is: full access is the Mac's to give, in the code it made)
471
+ const admin = access.takeCode(asked?.code, now(), 'relay') ? false : access.takeCode(asked?.code, now(), 'relay-admin') ? true : null;
472
+ if (admin === null) return [403, null];
473
+ const id = 'd' + crypto.randomBytes(4).toString('hex');
474
+ const label = changeState(file, (state) => {
475
+ // room for one more: the device unused for longest goes
476
+ state.devices = [...state.devices.sort((a, b) => (a.seen || 0) - (b.seen || 0)).slice(-(MAX_DEVICES - 1)), { id, key: body.key, name: cleanName(asked?.name), created: now(), seen: now(), via: access.codeRef(asked?.code), ...(admin ? { admin: true, adminAt: now() } : {}) }];
477
+ return state.label || '';
478
+ });
479
+ if (label === undefined) return [503, null];
480
+ shared.set(id, { key: body.key, aes });
481
+ try { onPaired({ id, name: cleanName(asked?.name), admin }); } catch { /* said or not, it is paired */ }
482
+ const issued = new Date(now()).toISOString();
483
+ const credential = { id, key: body.key, issued, signature: await seals.sign(signKey, `${id}.${body.key}.${issued}`) };
484
+ // (sealed back: only this Mac could have opened the request, and the browser sees that it did)
485
+ return [200, { device: { id }, credential, data: await seals.seal(aes, JSON.stringify({ ok: true, label, epoch, admin }), `paired.${id}`) }];
486
+ }
487
+
488
+ async function envelope(body, stop) {
489
+ const signal = stop.signal;
490
+ const device = typeof body?.device === 'string' ? body.device : '';
491
+ const key = await keyOf(device);
492
+ if (!key) return [403, null]; // forgotten here: its page says so
493
+ let asked;
494
+ try { asked = JSON.parse(await seals.open(key, String(body?.data ?? ''), `req.${device}`)); } catch { return [400, null]; }
495
+ const n = typeof asked?.n === 'string' ? asked.n : '';
496
+ if (!n || n.length > 64 || !fresh(Number(asked.at))) return [400, null];
497
+ const seal = (what) => seals.seal(key, JSON.stringify({ n, epoch, ...what }), `res.${device}.${n}`).then((data) => [200, { data }]);
498
+ // of another run of this Mac (the page's first request, or one kept and sent again after a restart): not done,
499
+ // and told which run this is, so the page asks again, anew
500
+ if (asked.e !== epoch) return seal({ ok: false, stale: true });
501
+ if (!once(device, n)) return [400, null];
502
+ seen(device);
503
+ if (typeof asked.op !== 'string') return seal({ ok: false, error: 'unknown op' }); // (a name, or nothing is asked)
504
+ if (asked.op === 'forgetMe') { relayForget(device, { file }); shared.delete(device); return seal({ ok: true, result: { forgotten: true } }); }
505
+ // what this device is, as the Mac has it now (given or taken back in a terminal: true of the next request)
506
+ const d = devices().find((x) => x.id === device);
507
+ if (!d) return [403, null];
508
+ const passkey = passkeyOf(d);
509
+ const given = d.admin === true;
510
+ // full access is for a device that has its passkey, made by whoever was given it (fullOf): until then it is as any other
511
+ const admin = fullOf(d);
512
+ const l = lockOf(d);
513
+ if (asked.op === 'session') {
514
+ // (what a locked device is told: that it is, this Mac's name, what it was given, and what its passkey is to sign)
515
+ const locked = !!passkey && !isOpen(d, asked.k);
516
+ return seal({ ok: true, result: { admin: given, full: admin, label: readState(file)?.label || '', passkey: !!passkey, locked, lockAfter: lockMs(d), ...(locked ? { unlock: { challenge: challengeFor(device, 'open'), credential: passkey.id, rpId: siteOf(d).rpId } } : {}) } });
517
+ }
518
+ if (asked.op === 'passkeyBegin') {
519
+ // one passkey per device, made once: to change it, the device is forgotten at the Mac and paired again
520
+ if (passkey) return seal({ ok: false, error: 'This device has its passkey already.' });
521
+ const label = readState(file)?.label || 'Sideora';
522
+ return seal({ ok: true, result: { challenge: challengeFor(device, 'make'), rp: { id: siteOf(d).rpId, name: 'Sideora' }, user: { id: crypto.randomBytes(16).toString('base64url'), name: label, displayName: label }, algs: passkeys.ALGS } });
523
+ }
524
+ if (asked.op === 'passkeyFinish') {
525
+ if (passkey || !answered(device, 'make', asked.args?.challenge)) return seal({ ok: false, error: 'That was asked too long ago, or this device has its passkey already. Try again.' });
526
+ let made;
527
+ try { made = passkeys.verifyRegistration(asked.args, { challenge: asked.args.challenge, ...siteOf(d) }); } catch (e) { return seal({ ok: false, error: `That passkey could not be kept: ${e.message}.` }); }
528
+ let kept = false;
529
+ try { kept = changeState(file, (state) => { const mine = state.devices.find((x) => x.id === device && x.key === d.key); if (!mine || passkeyOf(mine)) return undefined; mine.passkey = { ...made, created: now(), ...siteOf(d) }; return true; }); } catch { kept = false; }
530
+ if (!kept) return seal({ ok: false, error: 'That passkey could not be kept. Try again.' });
531
+ const name = opened(d); // (made with the person verified, a moment ago)
532
+ try { onPasskey({ id: device, name: cleanName(d.name) }); } catch { /* said or not, it is kept */ }
533
+ return seal({ ok: true, result: { passkey: true, open: name } });
534
+ }
535
+ if (asked.op === 'passkeyOpen') {
536
+ const good = touched(d, 'open', asked.args);
537
+ if (good !== true) return seal({ ok: false, error: `The passkey did not open it: ${good}.` });
538
+ return seal({ ok: true, result: { locked: false, open: opened(d) } });
539
+ }
540
+ if (asked.op === 'lock') { if (passkey) lock(d); return seal({ ok: true, result: { locked: !!passkey } }); }
541
+ if (passkey) {
542
+ if (!isOpen(d, asked.k)) return seal({ ok: false, locked: true });
543
+ // done on the device, or only asked by its page: the page says how long ago it was last touched
544
+ const idle = typeof asked.idle === 'number' ? asked.idle : NaN;
545
+ if (Number.isFinite(idle) && idle >= 0) l.active = Math.max(l.active, Math.min(now(), now() - idle));
546
+ }
547
+ if (asked.op === 'alive') return seal({ ok: true, result: {} }); // (the page saying it is being used, when it asks nothing else)
548
+ if (asked.op === 'keptKey') {
549
+ // The key this device's page keeps what it showed under (encrypted in the browser, to show at once on its next
550
+ // load): made here, kept here with the device, given only while the device is open (past its passkey). Locked,
551
+ // or forgotten here, what the browser holds of it cannot be read.
552
+ const have = (x) => typeof x?.keptKey === 'string' && /^[\w-]{43}$/.test(x.keptKey);
553
+ let key = have(d) ? d.keptKey : null;
554
+ if (!key) {
555
+ const made = crypto.randomBytes(32).toString('base64url');
556
+ try { key = changeState(file, (state) => { const mine = state.devices.find((x) => x.id === device && x.key === d.key); if (!mine) return undefined; if (!have(mine)) mine.keptKey = made; return mine.keptKey; }); } catch { key = null; }
557
+ }
558
+ return key ? seal({ ok: true, result: { key } }) : seal({ ok: false, error: 'Sideora could not keep a key for this device just now.' });
559
+ }
560
+ if (asked.op === 'setLockAfter' && !passkey) return seal({ ok: false, error: 'This device has no passkey: it does not lock.' });
561
+ // (checked before the passkey is asked for: a touch is not spent on what would be refused)
562
+ if (asked.op === 'setLockAfter' && !LOCK_CHOICES.includes(Number(asked.args?.minutes))) return seal({ ok: false, error: `It locks after ${LOCK_CHOICES.join(', ')} minutes unused: one of these.` });
563
+ if (asked.op !== 'setLockAfter' && !served.has(asked.op) && !(admin && full.has(asked.op))) {
564
+ if (AT_THE_MAC.has(asked.op)) return seal({ ok: false, error: /^relay/.test(asked.op)
565
+ ? 'The relay is set up on the computer Sideora runs on: its Settings there, Other devices (or `sideora relay`).'
566
+ : /^microsoft/.test(asked.op)
567
+ ? 'A Microsoft mailbox is added on the computer Sideora runs on: Microsoft answers its own browser. There: Settings, Accounts.'
568
+ : 'Signing in to Google is done on the computer Sideora runs on: Google answers its own browser. There: the extension, or `sideora google-login`.' });
569
+ if (full.has(asked.op) && given) return seal({ ok: false, error: passkey ? `Full access was given too long before this device made its passkey: give it again where Sideora runs (\`sideora relay admin ${device}\`).` : 'Full access waits for this device to have its passkey: Settings, This device.' });
570
+ if (full.has(asked.op)) return seal({ ok: false, error: 'This device was not given full access: rules, accounts and AI connections are changed on the computer Sideora runs on, or from a device it was told to trust with them (`sideora relay admin`).' });
571
+ return seal({ ok: false, error: `unknown op "${asked.op}"` });
572
+ }
573
+ let args = asked.args;
574
+ let elsewhere = false; // models asked for at a server of the asker's own naming (a device with full access only)
575
+ if (asked.op === 'aiMessage') {
576
+ const refused = () => seal({ ok: false, error: 'AI connections are added and changed on the computer Sideora runs on (the web app there, or the extension), or from a device given full access there (`sideora relay admin`).' });
577
+ const said = typeof args?.type === 'string' ? args.type : '';
578
+ const type = said.replace(/^[a-z]+:/, '');
579
+ if (!admin && !AI_FROM_AFAR.has(type)) return refused();
580
+ if (type === 'ai-list-models') {
581
+ // the models of a connection this Mac has, asked where the Mac has it: of the asker's own, only which one
582
+ // (a server and a kind of its choosing would be this Mac reaching an address a device far away names: for
583
+ // a device with full access, the form of a connection being added or changed, with a touch of its passkey)
584
+ const id = typeof args.id === 'string' ? args.id : '';
585
+ const view = id && !args.apiKey ? await runOp('aiMessage', { type: said.replace(/ai-list-models$/, 'ai-get') }, ops, { signal }) : null;
586
+ const kept = view?.ok && Array.isArray(view.result?.connections) ? view.result.connections.find((c) => c && c.id === id) : null;
587
+ const same = kept && (args.kind === undefined || args.kind === kept.kind) && (args.baseUrl === undefined || String(args.baseUrl ?? '') === String(kept.baseUrl ?? ''));
588
+ if (kept && (same || !admin)) args = { type: said, ...(typeof args.v === 'number' ? { v: args.v } : {}), id, kind: kept.kind, baseUrl: typeof kept.baseUrl === 'string' ? kept.baseUrl : '' };
589
+ else if (!admin) return refused();
590
+ else elsewhere = true;
591
+ }
592
+ }
593
+ // A chat asked with another connection than the one chosen in the settings: which provider reads the mail is
594
+ // the owner's to say. With a passkey, that connection is confirmed with a touch made for it, once for as long
595
+ // as the device stays open (not for each message of the chat).
596
+ let other = null;
597
+ // (either way a turn is asked: the assistant's, or the settings' "try this connection", a message of aiMessage)
598
+ const aiType = asked.op === 'aiMessage' ? String(typeof args?.type === 'string' ? args.type : '').replace(/^[a-z]+:/, '') : '';
599
+ // (the assistant's answer, run on the Mac, is asked of the connection it names too)
600
+ const turnAsked = asked.op === 'aiChat' || aiType === 'ai-chat' || asked.op === 'assistantStart';
601
+ // (choosing the connection every turn is then asked of, on every device, is naming another connection too: the
602
+ // same touch, for that connection: a touch made for something else a moment ago does not choose it)
603
+ const wanted = asked.op === 'assistantStart' ? args?.asked?.connectionId : turnAsked ? args?.connectionId : aiType === 'ai-set-active' ? args?.id : null;
604
+ if (typeof wanted === 'string' && wanted) {
605
+ const view = await runOp('aiMessage', { type: 'mw:ai-get' }, ops, { signal });
606
+ const config = view?.ok ? view.result : null;
607
+ if (!Array.isArray(config?.connections) || !config.connections.some((c) => c && c.id === wanted)) return seal({ ok: true, result: { ok: false, error: 'That model\'s connection is not in your Sideora any more: choose another.' } });
608
+ // (a connection confirmed for a chat is not thereby the default of every device: that is a touch of its own)
609
+ if (passkey && wanted !== config.activeId && (aiType === 'ai-set-active' || !l.models.has(wanted))) other = wanted;
610
+ }
611
+ if (passkey) {
612
+ const need = elsewhere ? 'fresh' : other ? 'each' : touchFor(asked.op, asked.args);
613
+ // (for another connection: the touch says "this connection", not this very message of the chat)
614
+ const what = other ? (aiType === 'ai-set-active' ? digestOf('aiSetActive', { id: other }) : digestOf('aiChat', { connectionId: other })) : digestOf(asked.op, asked.args);
615
+ let now_ = false;
616
+ if (asked.touch !== undefined) {
617
+ const good = touched(d, 'op', asked.touch, what);
618
+ if (good !== true) return seal({ ok: false, error: `The passkey did not confirm that: ${good}.` });
619
+ l.touched = now();
620
+ now_ = true;
621
+ if (other && aiType !== 'ai-set-active') l.models.add(other);
622
+ }
623
+ // not confirmed (yet): the page is handed what to sign, and asks again with it
624
+ if ((need === 'each' && !now_) || (need === 'fresh' && now() - l.touched > TOUCH_MS)) return seal({ ok: false, touch: asking(d, what) });
625
+ }
626
+ if (asked.op === 'setLockAfter') {
627
+ // How long unused before this device locks: its own to choose, with a touch of its passkey for this very asking
628
+ // (whoever holds it open does not make it stay open). Kept with the device.
629
+ const minutes = Number(args?.minutes);
630
+ let kept = false;
631
+ try { kept = changeState(file, (state) => { const mine = state.devices.find((x) => x.id === device && x.key === d.key); if (!mine) return undefined; mine.lockMinutes = minutes; return true; }) === true; } catch { kept = false; }
632
+ if (!kept) return seal({ ok: false, error: 'Sideora could not keep that just now.' });
633
+ lockChosen.set(device, minutes);
634
+ return seal({ ok: true, result: { lockAfter: minutes * 60_000 } });
635
+ }
636
+ const gen = l.gen;
637
+ l.running.add(stop);
638
+ let r;
639
+ // a Microsoft sign-in asked from afar comes back through the relay: the browser is not on this computer
640
+ const opArgs = asked.op === 'microsoftSignInStart' ? { ...(args && typeof args === 'object' ? args : {}), via: 'relay', port: undefined } : args;
641
+ try { r = await runOp(asked.op, opArgs, ops, { signal }); } finally { l.running.delete(stop); }
642
+ if (asked.op === 'assistantStart' && r.ok && typeof r.result?.run === 'string') {
643
+ // (started as it locked: stopped at once; else kept with the device, so that locking it stops it)
644
+ if (l.gen !== gen) runOp('assistantStop', { run: r.result.run }, ops).catch(() => {});
645
+ else { l.runs.add(r.result.run); if (l.runs.size > 20) l.runs.delete(l.runs.values().next().value); }
646
+ }
647
+ // forgotten while it was being done: what it found is not told
648
+ if (!paired(device)) { shared.delete(device); return [403, null]; }
649
+ // locked while it was being done (left unused, or locked from another of its pages): not told either
650
+ if (passkey && (l.gen !== gen || !isOpen(d, asked.k))) return seal({ ok: false, locked: true });
651
+ const sealed = await seal(r.ok ? { ok: true, result: scrubbed(r.result) } : { ok: false, error: scrub(r.error) });
652
+ // more than the relay holds of one answer (a large attachment): said, in place of an answer that would not arrive
653
+ if (JSON.stringify(sealed[1]).length > MAX_ANSWER) return seal({ ok: false, error: 'That is too large to come through the relay (a file of more than about 8 MB). It is there, where Sideora runs.' });
654
+ return sealed;
655
+ }
656
+
657
+ async function subscribe(f, send) {
658
+ const end = (status) => send({ t: 'end', conn: f.conn, status });
659
+ const key = await keyOf(f.device);
660
+ if (!key) return end(403); // not paired (any more)
661
+ let ticket;
662
+ try { ticket = JSON.parse(await seals.open(key, String(f.ticket ?? ''), `sub.${f.device}`)); } catch { ticket = null; }
663
+ // a ticket that does not open, is old, or was used: this asking is refused, the pairing is not in question (400)
664
+ if (!ticket || !fresh(Number(ticket.at)) || typeof ticket.s !== 'string' || !/^[A-Za-z0-9_-]{8,32}$/.test(ticket.s) || !once(f.device, `sub.${ticket.s}`)) return end(400);
665
+ // locked: nothing is pushed to it until its passkey opens it (423: the page shows its lock, the pairing stands)
666
+ const d = devices().find((x) => x.id === f.device);
667
+ if (!d || (passkeyOf(d) && !isOpen(d, ticket.k))) return end(d ? 423 : 403);
668
+ const guarded = !!passkeyOf(d);
669
+ if ([...streams.values()].filter((x) => x.device === f.device).length >= MAX_STREAMS) return end(429);
670
+ streams.get(f.conn)?.stop(); // (the same name asked again: the earlier one ends)
671
+ const entry = { device: f.device, stop: () => {}, end, opening: ticket.k };
672
+ streams.set(f.conn, entry);
673
+ let i = 0;
674
+ let line = Promise.resolve(); // one at a time, in order: each numbered as it is sealed
675
+ const push = (what) => {
676
+ line = line.then(async () => {
677
+ if (!alive || streams.get(f.conn) !== entry) return;
678
+ // left unused since the clock last looked: locked now (its pushes end there), and this one is not told
679
+ if (guarded && !isOpen(d, ticket.k)) return;
680
+ const data = await seals.seal(key, JSON.stringify({ i: i++, ...scrubbed(what) }), `ev.${f.device}.${ticket.s}`);
681
+ // forgotten meanwhile: nothing more is told
682
+ if (!paired(f.device)) { entry.stop(); streams.delete(f.conn); shared.delete(f.device); return end(403); }
683
+ if (alive && streams.get(f.conn) === entry) send({ t: 'ev', conn: f.conn, id: i, data });
684
+ }).catch(() => {});
685
+ };
686
+ push({ epoch }); // the first thing told: which run of the Mac this is
687
+ entry.stop = followFn((p, cursor) => push({ push: p, ...(Number.isFinite(cursor) ? { cursor } : {}) }), ticket.after ?? undefined, { checkpoint: (cursor) => push({ cursor }) });
688
+ }
689
+
690
+ /** Parts of a long request, kept until the last: bounded in number, in size and in time. */
691
+ function part(f) {
692
+ const t = now();
693
+ for (const [id, p] of parts) if (t - p.at > PARTS_MS) parts.delete(id);
694
+ if (!Number.isInteger(f.n) || !Number.isInteger(f.i) || f.n < 2 || f.n > 512 || f.i < 0 || f.i >= f.n || typeof f.part !== 'string' || f.part.length > PART) { parts.delete(f.id); return 'bad'; }
695
+ const p = parts.get(f.id) ?? { got: new Array(f.n), n: 0, bytes: 0, at: t };
696
+ if (p.got.length !== f.n) { parts.delete(f.id); return 'bad'; }
697
+ if (p.got[f.i] === undefined) { p.got[f.i] = f.part; p.n++; p.bytes += f.part.length; }
698
+ parts.set(f.id, p);
699
+ let held = 0;
700
+ for (const x of parts.values()) held += x.bytes;
701
+ if (held > MAX_PARTS_BYTES) { parts.delete(f.id); return 'bad'; }
702
+ if (p.n < f.n) return null;
703
+ parts.delete(f.id);
704
+ return p.got.join('');
705
+ }
706
+
707
+ /**
708
+ * What a sign-in's provider sent to the relay's /oauth/<provider> for a sign-in started here (the relay read which
709
+ * computer from its state): plain, as the relay saw it; worth nothing without what this computer kept of the sign-in.
710
+ */
711
+ async function signInReturn(body) {
712
+ if (body?.provider !== 'microsoft') return [404, null];
713
+ try { return [200, await (await import('./microsoft-signin.js')).relayReturn(body)]; } catch { return [200, { ok: false, status: 500, text: 'Sideora could not finish the sign-in.' }]; }
714
+ }
715
+
716
+ return {
717
+ instance,
718
+ url: first.url,
719
+ token: secrets.token,
720
+ epoch,
721
+ sweep,
722
+ /** Every device locked (another process of this Mac took the connection meanwhile: what it locked, this one would not know). */
723
+ lockAll() { for (const d of devices()) if (passkeyOf(d)) lock(d); },
724
+ hello: () => ({ t: 'hello', version: 'sideora', devices: devices().map((d) => d.id) }),
725
+ devicesFrame: () => ({ t: 'devices', ids: devices().map((d) => d.id) }),
726
+ /** One frame from the relay. Never throws: what cannot be answered is answered so. */
727
+ async handle(f, send) {
728
+ if (!alive) return;
729
+ const out = (frame) => { if (alive) send(frame); };
730
+ try {
731
+ if (f?.t === 'req' && typeof f.id === 'string' && f.id.length <= 64) {
732
+ let body = f.body;
733
+ if (f.n !== undefined) {
734
+ const whole = part(f);
735
+ if (whole === null) return;
736
+ if (whole === 'bad') return answer(out, f.id, 400, null);
737
+ try { body = JSON.parse(whole); } catch { return answer(out, f.id, 400, null); }
738
+ }
739
+ const stop = new AbortController();
740
+ working.set(f.id, stop);
741
+ try {
742
+ const [status, made] = f.op === 'pair' ? await pair(body) : f.op === 'envelope' ? await envelope(body, stop) : f.op === 'oauth' ? await signInReturn(body) : [404, null];
743
+ answer(out, f.id, status, made);
744
+ if (f.op === 'pair' && status === 200) out({ t: 'devices', ids: devices().map((d) => d.id) });
745
+ } finally {
746
+ working.delete(f.id);
747
+ }
748
+ } else if (f?.t === 'cancel' && typeof f.id === 'string') {
749
+ // whoever asked let go (Stop on a model's turn), or the relay stopped waiting: the op is told
750
+ working.get(f.id)?.abort();
751
+ parts.delete(f.id);
752
+ } else if (f?.t === 'sub' && typeof f.conn === 'string' && typeof f.device === 'string') {
753
+ await subscribe(f, out);
754
+ } else if (f?.t === 'unsub' && typeof f.conn === 'string') {
755
+ streams.get(f.conn)?.stop();
756
+ streams.delete(f.conn);
757
+ }
758
+ } catch {
759
+ if (f?.t === 'req' && typeof f.id === 'string') answer(out, f.id, 500, null);
760
+ }
761
+ },
762
+ /** The connection is gone: every stream stops, every op still working is let go of. `again()`: a new connection, the same run. */
763
+ stop() {
764
+ alive = false;
765
+ for (const s of streams.values()) s.stop();
766
+ streams.clear();
767
+ for (const w of working.values()) w.abort();
768
+ working.clear();
769
+ parts.clear();
770
+ },
771
+ again() { alive = true; }
772
+ };
773
+ }
774
+
775
+ // The relay connection this process keeps, if any (the web app's): a sign-in coming back through the relay arrives
776
+ // here, so it can only be started here. `expected`: the sign-ins waited for, said to the relay at each connection.
777
+ let held = null;
778
+ const expected = new Map(); // hash -> until
779
+ /** Whether this process holds the relay's connection (a sign-in through the relay can be started here). */
780
+ export const relayHere = () => !!held;
781
+ /**
782
+ * A sign-in started here will come back through the relay with this state: the relay is told its hash, and forwards
783
+ * that one only, once. false: this process does not hold the connection.
784
+ */
785
+ export function relayExpect(state, until) {
786
+ if (!held) return false;
787
+ const hash = crypto.createHash('sha256').update(String(state)).digest('base64url');
788
+ const now = Date.now();
789
+ for (const [h, u] of expected) if (u <= now) expected.delete(h);
790
+ expected.set(hash, until);
791
+ held.send({ t: 'expect', hash, until });
792
+ return true;
793
+ }
794
+
795
+ /**
796
+ * Keep the connection to the relay: dial, answer, dial again when it drops (a little later each time, up to a
797
+ * minute). `served`: the ops a browser may ask through it. Returns { stop, status() }.
798
+ */
799
+ export async function connectRelay({ onStatus = () => {}, WebSocketCtor = globalThis.WebSocket, ...options } = {}) {
800
+ const runner = await createRunner(options);
801
+ const file = options.file ?? RELAY_PATH;
802
+ let ws = null;
803
+ let open = true;
804
+ let delay = 1000;
805
+ let timer;
806
+ let state = 'connecting';
807
+ const set = (next, why) => { if (state !== next) { state = next; onStatus(next, why); } };
808
+ const send = (frame) => { try { if (ws?.readyState === 1) ws.send(JSON.stringify(frame)); } catch { /* gone: it will be dialled again */ } };
809
+
810
+ // forgotten or paired from another terminal: the relay is told who is still paired
811
+ let watching;
812
+ try { watching = fs.watch(path.dirname(file), (_k, name) => { if (String(name) === path.basename(file)) send(runner.devicesFrame()); }); watching.on('error', () => {}); } catch { /* not told at once: said at the next connection */ }
813
+
814
+ const dial = () => {
815
+ if (!open) return;
816
+ const at = `${runner.url.replace(/^http/, 'ws')}/i/${runner.instance}/runner?token=${encodeURIComponent(runner.token)}`;
817
+ const sock = new WebSocketCtor(at);
818
+ ws = sock;
819
+ // A connection that says nothing is dropped somewhere on the way, sooner or later, and neither end is told. The
820
+ // relay is asked "ping" now and then; no "pong" in a while, and the connection is taken for dead and dialled again.
821
+ let heard = Date.now();
822
+ let why = ''; // what ended it, when this end knows
823
+ const beat = setInterval(() => {
824
+ if (ws !== sock) return clearInterval(beat);
825
+ if (Date.now() - heard > 75_000) { why = 'no answer from the relay for 75 s'; try { sock.close(); } catch { /* closing */ } return; }
826
+ try { if (sock.readyState === 1) sock.send('ping'); } catch { /* gone */ }
827
+ }, 25_000);
828
+ beat.unref?.();
829
+ sock.addEventListener('open', () => {
830
+ if (ws !== sock) return;
831
+ heard = Date.now(); runner.again(); delay = 1000; send(runner.hello());
832
+ for (const [hash, until] of expected) if (until > Date.now()) send({ t: 'expect', hash, until });
833
+ set('connected');
834
+ });
835
+ sock.addEventListener('message', (e) => {
836
+ if (ws !== sock) return;
837
+ heard = Date.now();
838
+ if (e.data === 'pong') return;
839
+ let f; try { f = JSON.parse(String(e.data)); } catch { return; }
840
+ void runner.handle(f, (frame) => { if (ws === sock) send(frame); });
841
+ });
842
+ const gone = (e) => {
843
+ clearInterval(beat);
844
+ if (ws !== sock) return;
845
+ ws = null;
846
+ runner.stop();
847
+ if (!open) return;
848
+ // 4001: the membership was closed at the relay; 4000: another process of this Mac took the connection
849
+ if (e?.code === 4001) { set('refused', 'the relay closed this computer\'s membership'); open = false; return; }
850
+ // (taken over by another process of this Mac: not fought for; looked at again in a while, should that one stop)
851
+ const taken = e?.code === 4000;
852
+ if (taken) runner.lockAll();
853
+ const closed = e?.code ? `closed ${e.code}${e.reason ? `: ${String(e.reason).slice(0, 120)}` : ''}` : '';
854
+ set('waiting', taken ? 'another Sideora on this computer holds the connection' : [why, closed].filter(Boolean).join('; ') || undefined);
855
+ timer = setTimeout(dial, taken ? 5 * 60_000 : delay);
856
+ delay = Math.min(delay * 2, 60_000);
857
+ };
858
+ sock.addEventListener('close', gone);
859
+ sock.addEventListener('error', (e) => {
860
+ // (what the socket says of it: undici keeps the reason in the event's error, and that one's cause)
861
+ const err = e?.error;
862
+ const said = [e?.message, err?.message, err?.code, err?.cause?.message, err?.cause?.code].filter((x) => typeof x === 'string' && x);
863
+ why ||= `error${said.length ? `: ${[...new Set(said)].join(', ').slice(0, 160)}` : ''}`;
864
+ try { sock.close(); } catch { /* closing */ }
865
+ });
866
+ };
867
+ dial();
868
+ const mine = { send };
869
+ held = mine;
870
+ return {
871
+ url: runner.url,
872
+ instance: runner.instance,
873
+ status: () => state,
874
+ stop() { open = false; if (held === mine) held = null; clearTimeout(timer); watching?.close(); runner.stop(); try { ws?.close(); } catch { /* closed */ } }
875
+ };
876
+ }