dsh-zen-remote 1.1.16 → 2.0.1

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 (261) hide show
  1. package/AGENTS.md +54 -9
  2. package/README.md +249 -190
  3. package/README.zh-CN.md +247 -201
  4. package/assets/home.png +0 -0
  5. package/assets/info.png +0 -0
  6. package/assets/pairing.png +0 -0
  7. package/assets/session.png +0 -0
  8. package/assets/sheet.png +0 -0
  9. package/cordis.patch.yml +12 -11
  10. package/cordis.patch.yml.example +24 -9
  11. package/docs/interface.md +57 -2
  12. package/docs/remote-access.en.md +99 -58
  13. package/docs/remote-access.md +99 -42
  14. package/dsh-push.mjs +67 -54
  15. package/lan-gate.mjs +88 -20
  16. package/lib/activity.js +168 -0
  17. package/lib/activity.js.map +1 -0
  18. package/lib/admin-routes.js +526 -0
  19. package/lib/admin-routes.js.map +1 -0
  20. package/lib/client-pairing.js +224 -0
  21. package/lib/client-pairing.js.map +1 -0
  22. package/lib/client-routes.js +674 -0
  23. package/lib/client-routes.js.map +1 -0
  24. package/lib/client.js +11498 -5990
  25. package/lib/config.js +346 -0
  26. package/lib/config.js.map +1 -0
  27. package/lib/fetch-route-intercept.js +418 -0
  28. package/lib/fetch-route-intercept.js.map +1 -0
  29. package/lib/fingerprint.js +365 -0
  30. package/lib/fingerprint.js.map +1 -0
  31. package/lib/http.js +69 -0
  32. package/lib/http.js.map +1 -0
  33. package/lib/index.js +675 -54
  34. package/lib/index.js.map +1 -1
  35. package/lib/intercept-shape.js +81 -0
  36. package/lib/intercept-shape.js.map +1 -0
  37. package/lib/intercept.js +3181 -0
  38. package/lib/intercept.js.map +1 -0
  39. package/lib/lan-gate-server.cjs +532 -121
  40. package/lib/merge-streams.js +1172 -0
  41. package/lib/merge-streams.js.map +1 -0
  42. package/lib/relay-access.js +496 -0
  43. package/lib/relay-access.js.map +1 -0
  44. package/lib/relay-client.js +1303 -0
  45. package/lib/relay-client.js.map +1 -0
  46. package/lib/relay-filter.js +282 -0
  47. package/lib/relay-filter.js.map +1 -0
  48. package/lib/relay-server.js +1813 -0
  49. package/lib/relay-server.js.map +1 -0
  50. package/lib/restart-fields.js +34 -0
  51. package/lib/restart-fields.js.map +1 -0
  52. package/lib/restart-watcher.js +106 -0
  53. package/lib/restart-watcher.js.map +1 -0
  54. package/lib/session-reference.js +157 -0
  55. package/lib/session-reference.js.map +1 -0
  56. package/lib/share-export.js +16 -1
  57. package/lib/share-export.js.map +1 -1
  58. package/lib/share-ops.js +86 -0
  59. package/lib/share-ops.js.map +1 -0
  60. package/lib/share-store.js +294 -0
  61. package/lib/share-store.js.map +1 -0
  62. package/lib/types/activity.d.ts +99 -0
  63. package/lib/types/activity.d.ts.map +1 -0
  64. package/lib/types/admin-routes.d.ts +129 -0
  65. package/lib/types/admin-routes.d.ts.map +1 -0
  66. package/lib/types/client/MobileDrawerFooter.d.ts.map +1 -1
  67. package/lib/types/client/MobileHome.d.ts +1 -1
  68. package/lib/types/client/MobileHome.d.ts.map +1 -1
  69. package/lib/types/client/MobileHomeChips.d.ts +1 -1
  70. package/lib/types/client/MobileHomeChips.d.ts.map +1 -1
  71. package/lib/types/client/MobileSessionHeader.d.ts +13 -2
  72. package/lib/types/client/MobileSessionHeader.d.ts.map +1 -1
  73. package/lib/types/client/MobileSessionInfo.d.ts +20 -3
  74. package/lib/types/client/MobileSessionInfo.d.ts.map +1 -1
  75. package/lib/types/client/RemoteComposerBanner.d.ts +42 -0
  76. package/lib/types/client/RemoteComposerBanner.d.ts.map +1 -0
  77. package/lib/types/client/RemoteHeaderIcon.d.ts +37 -0
  78. package/lib/types/client/RemoteHeaderIcon.d.ts.map +1 -0
  79. package/lib/types/client/RemoteShareMenu.d.ts +28 -0
  80. package/lib/types/client/RemoteShareMenu.d.ts.map +1 -0
  81. package/lib/types/client/RemoteStatusIcon.d.ts +36 -0
  82. package/lib/types/client/RemoteStatusIcon.d.ts.map +1 -0
  83. package/lib/types/client/compat/desktop.d.ts +21 -0
  84. package/lib/types/client/compat/desktop.d.ts.map +1 -0
  85. package/lib/types/client/compat/types.d.ts +57 -0
  86. package/lib/types/client/compat/types.d.ts.map +1 -1
  87. package/lib/types/client/current-session-report.d.ts +37 -0
  88. package/lib/types/client/current-session-report.d.ts.map +1 -0
  89. package/lib/types/client/effects/header-status.d.ts.map +1 -1
  90. package/lib/types/client/effects/keyboard-guard.d.ts.map +1 -1
  91. package/lib/types/client/effects/model-group-side.d.ts +13 -0
  92. package/lib/types/client/effects/model-group-side.d.ts.map +1 -0
  93. package/lib/types/client/effects/permission-sheet.d.ts +39 -0
  94. package/lib/types/client/effects/permission-sheet.d.ts.map +1 -0
  95. package/lib/types/client/effects/remote-session.d.ts +25 -0
  96. package/lib/types/client/effects/remote-session.d.ts.map +1 -0
  97. package/lib/types/client/effects/turn-fold.d.ts +9 -0
  98. package/lib/types/client/effects/turn-fold.d.ts.map +1 -1
  99. package/lib/types/client/index.d.ts.map +1 -1
  100. package/lib/types/client/locales.d.ts +187 -2
  101. package/lib/types/client/locales.d.ts.map +1 -1
  102. package/lib/types/client/remote-fetch.d.ts +51 -0
  103. package/lib/types/client/remote-fetch.d.ts.map +1 -0
  104. package/lib/types/client/remote-group-expansion.d.ts +41 -0
  105. package/lib/types/client/remote-group-expansion.d.ts.map +1 -0
  106. package/lib/types/client/remote-share-css.d.ts +19 -0
  107. package/lib/types/client/remote-share-css.d.ts.map +1 -0
  108. package/lib/types/client/remote-share-register.d.ts +113 -0
  109. package/lib/types/client/remote-share-register.d.ts.map +1 -0
  110. package/lib/types/client/remote-status-css.d.ts +15 -0
  111. package/lib/types/client/remote-status-css.d.ts.map +1 -0
  112. package/lib/types/client/remote-status-register.d.ts +46 -0
  113. package/lib/types/client/remote-status-register.d.ts.map +1 -0
  114. package/lib/types/client/settings/SettingsSection.d.ts +46 -0
  115. package/lib/types/client/settings/SettingsSection.d.ts.map +1 -0
  116. package/lib/types/client/settings/register-settings.d.ts +58 -0
  117. package/lib/types/client/settings/register-settings.d.ts.map +1 -0
  118. package/lib/types/client/settings/settings-css.d.ts +10 -0
  119. package/lib/types/client/settings/settings-css.d.ts.map +1 -0
  120. package/lib/types/client/share/share-preview.d.ts.map +1 -1
  121. package/lib/types/client/styles/composer.css.d.ts +1 -1
  122. package/lib/types/client/styles/composer.css.d.ts.map +1 -1
  123. package/lib/types/client/styles/header.css.d.ts +1 -1
  124. package/lib/types/client/styles/header.css.d.ts.map +1 -1
  125. package/lib/types/client/styles/info.css.d.ts +1 -1
  126. package/lib/types/client/styles/info.css.d.ts.map +1 -1
  127. package/lib/types/client/styles/remote-session.css.d.ts +2 -0
  128. package/lib/types/client/styles/remote-session.css.d.ts.map +1 -0
  129. package/lib/types/client-data/current-session.d.ts +41 -0
  130. package/lib/types/client-data/current-session.d.ts.map +1 -0
  131. package/lib/types/client-data/model-group-side.d.ts +44 -0
  132. package/lib/types/client-data/model-group-side.d.ts.map +1 -0
  133. package/lib/types/client-data/remote-group-expansion.d.ts +76 -0
  134. package/lib/types/client-data/remote-group-expansion.d.ts.map +1 -0
  135. package/lib/types/client-data/remote-status.d.ts +148 -0
  136. package/lib/types/client-data/remote-status.d.ts.map +1 -0
  137. package/lib/types/client-data/settings-form.d.ts +774 -0
  138. package/lib/types/client-data/settings-form.d.ts.map +1 -0
  139. package/lib/types/client-data/shares.d.ts +211 -0
  140. package/lib/types/client-data/shares.d.ts.map +1 -0
  141. package/lib/types/client-pairing.d.ts +114 -0
  142. package/lib/types/client-pairing.d.ts.map +1 -0
  143. package/lib/types/client-routes.d.ts +112 -0
  144. package/lib/types/client-routes.d.ts.map +1 -0
  145. package/lib/types/config.d.ts +200 -0
  146. package/lib/types/config.d.ts.map +1 -0
  147. package/lib/types/fetch-route-intercept.d.ts +156 -0
  148. package/lib/types/fetch-route-intercept.d.ts.map +1 -0
  149. package/lib/types/fingerprint.d.ts +166 -0
  150. package/lib/types/fingerprint.d.ts.map +1 -0
  151. package/lib/types/http.d.ts +41 -0
  152. package/lib/types/http.d.ts.map +1 -0
  153. package/lib/types/index.d.ts +56 -24
  154. package/lib/types/index.d.ts.map +1 -1
  155. package/lib/types/intercept-shape.d.ts +32 -0
  156. package/lib/types/intercept-shape.d.ts.map +1 -0
  157. package/lib/types/intercept.d.ts +442 -0
  158. package/lib/types/intercept.d.ts.map +1 -0
  159. package/lib/types/merge-streams.d.ts +398 -0
  160. package/lib/types/merge-streams.d.ts.map +1 -0
  161. package/lib/types/relay-access.d.ts +310 -0
  162. package/lib/types/relay-access.d.ts.map +1 -0
  163. package/lib/types/relay-client.d.ts +274 -0
  164. package/lib/types/relay-client.d.ts.map +1 -0
  165. package/lib/types/relay-filter.d.ts +103 -0
  166. package/lib/types/relay-filter.d.ts.map +1 -0
  167. package/lib/types/relay-server.d.ts +208 -0
  168. package/lib/types/relay-server.d.ts.map +1 -0
  169. package/lib/types/restart-fields.d.ts +22 -0
  170. package/lib/types/restart-fields.d.ts.map +1 -0
  171. package/lib/types/restart-watcher.d.ts +83 -0
  172. package/lib/types/restart-watcher.d.ts.map +1 -0
  173. package/lib/types/session-reference.d.ts +66 -0
  174. package/lib/types/session-reference.d.ts.map +1 -0
  175. package/lib/types/share-export.d.ts +14 -1
  176. package/lib/types/share-export.d.ts.map +1 -1
  177. package/lib/types/share-ops.d.ts +79 -0
  178. package/lib/types/share-ops.d.ts.map +1 -0
  179. package/lib/types/share-store.d.ts +87 -0
  180. package/lib/types/share-store.d.ts.map +1 -0
  181. package/lib/types/virtual-id.d.ts +52 -0
  182. package/lib/types/virtual-id.d.ts.map +1 -0
  183. package/lib/virtual-id.js +66 -0
  184. package/lib/virtual-id.js.map +1 -0
  185. package/llms.txt +17 -14
  186. package/package.json +60 -50
  187. package/scripts/build-client.mjs +5 -3
  188. package/scripts/check-host-shadow.mjs +19 -2
  189. package/scripts/check-settings-form.mjs +933 -0
  190. package/scripts/check-shares.mjs +397 -0
  191. package/scripts/check-upload-endpoint.mjs +59 -3
  192. package/scripts/sync-doc-version.mjs +8 -15
  193. package/scripts/verify-fingerprint-live.mjs +111 -0
  194. package/src/activity.ts +218 -0
  195. package/src/admin-routes.ts +627 -0
  196. package/src/client/MobileAttachButton.tsx +2 -2
  197. package/src/client/MobileAttachChips.tsx +3 -3
  198. package/src/client/MobileDrawerFooter.tsx +7 -4
  199. package/src/client/MobileHome.tsx +20 -16
  200. package/src/client/MobileHomeChips.tsx +16 -16
  201. package/src/client/MobileNavOverlay.tsx +2 -2
  202. package/src/client/MobileNavToggle.tsx +3 -3
  203. package/src/client/MobileSessionHeader.tsx +63 -42
  204. package/src/client/MobileSessionInfo.tsx +118 -17
  205. package/src/client/RemoteComposerBanner.tsx +76 -0
  206. package/src/client/RemoteHeaderIcon.tsx +103 -0
  207. package/src/client/RemoteShareMenu.tsx +57 -0
  208. package/src/client/RemoteStatusIcon.tsx +91 -0
  209. package/src/client/compat/desktop.ts +22 -0
  210. package/src/client/compat/types.ts +62 -0
  211. package/src/client/current-session-report.ts +164 -0
  212. package/src/client/effects/header-status.ts +21 -17
  213. package/src/client/effects/keyboard-guard.ts +65 -1
  214. package/src/client/effects/model-group-side.ts +132 -0
  215. package/src/client/effects/permission-sheet.ts +149 -0
  216. package/src/client/effects/remote-session.ts +68 -0
  217. package/src/client/effects/turn-fold.ts +52 -0
  218. package/src/client/index.tsx +158 -36
  219. package/src/client/locales.ts +396 -2
  220. package/src/client/remote-fetch.ts +125 -0
  221. package/src/client/remote-group-expansion.ts +190 -0
  222. package/src/client/remote-share-css.ts +54 -0
  223. package/src/client/remote-share-register.ts +244 -0
  224. package/src/client/remote-status-css.ts +64 -0
  225. package/src/client/remote-status-register.ts +107 -0
  226. package/src/client/settings/SettingsSection.tsx +1229 -0
  227. package/src/client/settings/register-settings.ts +116 -0
  228. package/src/client/settings/settings-css.ts +236 -0
  229. package/src/client/share/share-preview.tsx +6 -3
  230. package/src/client/share/share-sheet.tsx +3 -3
  231. package/src/client/styles/composer.css.ts +119 -26
  232. package/src/client/styles/header.css.ts +7 -7
  233. package/src/client/styles/info.css.ts +74 -0
  234. package/src/client/styles/remote-session.css.ts +274 -0
  235. package/src/client-data/current-session.ts +57 -0
  236. package/src/client-data/model-group-side.ts +65 -0
  237. package/src/client-data/remote-group-expansion.ts +145 -0
  238. package/src/client-data/remote-status.ts +374 -0
  239. package/src/client-data/settings-form.ts +1371 -0
  240. package/src/client-data/shares.ts +467 -0
  241. package/src/client-pairing.ts +244 -0
  242. package/src/client-routes.ts +732 -0
  243. package/src/config.ts +447 -0
  244. package/src/fetch-route-intercept.ts +510 -0
  245. package/src/fingerprint.ts +410 -0
  246. package/src/http.ts +68 -0
  247. package/src/index.ts +719 -62
  248. package/src/intercept-shape.ts +87 -0
  249. package/src/intercept.ts +3510 -0
  250. package/src/merge-streams.ts +1279 -0
  251. package/src/relay-access.ts +672 -0
  252. package/src/relay-client.ts +1514 -0
  253. package/src/relay-filter.ts +291 -0
  254. package/src/relay-server.ts +2063 -0
  255. package/src/restart-fields.ts +36 -0
  256. package/src/restart-watcher.ts +140 -0
  257. package/src/session-reference.ts +156 -0
  258. package/src/share-export.ts +26 -1
  259. package/src/share-ops.ts +114 -0
  260. package/src/share-store.ts +373 -0
  261. package/src/virtual-id.ts +74 -0
@@ -0,0 +1,1514 @@
1
+ /**
2
+ * Relay client for the sub-client half (T23a): the `client`-role side of the
3
+ * 2.0.0 relay protocol. A DSH process on another machine pairs with a relay
4
+ * server's gateway (Bearer device token, T16) and reaches the server's
5
+ * shared sessions through `POST relay/v1/handshake|invoke|stream` — this
6
+ * module speaks that wire from the far end, with no dependencies beyond the
7
+ * Node 18+ standard library and the global `fetch`.
8
+ *
9
+ * Every call re-reads the credentials through the injected getters, so a
10
+ * re-pair in the settings page applies to the NEXT request without touching
11
+ * this module (the same volatile-row discipline src/client-routes.ts keeps).
12
+ * Missing credentials never touch the network: the client reports
13
+ * `unpaired` and every entry point throws immediately.
14
+ *
15
+ * Two wire details are load-bearing. `accept: application/json` — the
16
+ * gateway answers its pairing wall as a JSON 401 `{reason:'unpaired'}` only
17
+ * to requests that accept JSON; without the header a revoked token would
18
+ * draw the HTML pairing page and be unclassifiable. `redirect: 'manual'` —
19
+ * a wrong or hijacked server must not walk the pairing token through a
20
+ * redirect chain (the same rule src/client-routes.ts probes with).
21
+ *
22
+ * State moves only where the contract says so: `offline` on transport
23
+ * failure, `revoked` on the gateway's unpaired wall, `incompatible` on the
24
+ * relay-only wall or a handshake protocol mismatch, and back to `online` on
25
+ * any success envelope. Everything else — the per-call refusals
26
+ * (`not-shared` / `no-session` / `forbidden-method`), a 200 `{ok:false}`
27
+ * envelope, the gateway's own `relay-unauthorized` — is an ANSWER about the
28
+ * call, not about the link, and leaves the state alone.
29
+ *
30
+ * Since T43 the client also reconnects on its own: an `offline` client walks
31
+ * a 1s → 2s → 5s → 10s → 30s ladder (0–20% jitter per wait) until a success
32
+ * lifts it back to `online`; `unpaired`, `revoked` and `incompatible` never
33
+ * reconnect on their own — they need a user action, which arrives as
34
+ * `credentialsChanged()` (or a fresh `connect()`). The wait is observable as
35
+ * `nextRetryAt`, the last failure code as `lastError`; both carry no
36
+ * credential material.
37
+ *
38
+ * Since T42 the client also judges INTERFACE compatibility: when the wiring
39
+ * injects `computeOwnFingerprints`, every completed handshake is followed by
40
+ * a group-by-group comparison of the server's `fingerprints` map against the
41
+ * locally computed one, stored as `compat` ({@link RelayCompatVerdict}).
42
+ * Groups either side could not compute land in `unavailable` — never in
43
+ * `different` — so a partial view stays silent. The verdict is read live by
44
+ * the status route; listeners additionally hear about it through the same
45
+ * notification channel the state changes use.
46
+ */
47
+
48
+ import { createHash } from 'node:crypto'
49
+
50
+ import { compareFingerprints } from './fingerprint.js'
51
+ import type { RelayCompatVerdict } from './fingerprint.js'
52
+
53
+ /** The one protocol version this client speaks; the handshake verifies it. */
54
+ const RELAY_PROTOCOL = 1
55
+
56
+ const HANDSHAKE_PATH = '/_dsh/zen-remote/relay/v1/handshake'
57
+ const INVOKE_PATH = '/_dsh/zen-remote/relay/v1/invoke'
58
+ const STREAM_PATH = '/_dsh/zen-remote/relay/v1/stream'
59
+ const UNSHARE_PATH = '/_dsh/zen-remote/relay/v1/unshare'
60
+ const EVENT_RESULT_PATH = '/_dsh/zen-remote/relay/v1/event-result'
61
+ const HTTP_PATH = '/_dsh/zen-remote/relay/v1/http'
62
+ const UPLOAD_PATH = '/_dsh/zen-remote/relay/v1/upload'
63
+ /** T59: a desktop-client device renaming ITSELF in the gateway's table. */
64
+ const DEVICE_NAME_PATH = '/_dsh/zen-remote/relay/v1/device/name'
65
+
66
+ /** How long a stream may stay line-silent before it is judged dead. */
67
+ const DEFAULT_IDLE_TIMEOUT_MS = 45_000
68
+
69
+ /** How long one request/response round-trip may take in full. */
70
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
71
+
72
+ /**
73
+ * The invoke round-trip budget (T31-fix): the configured request timeout
74
+ * plus 2 s per MiB of request body, capped at five minutes. The large
75
+ * bodies are the prompt routes' INLINE images — `session/prompt` /
76
+ * `subagents/prompt` content blocks carry base64 `image` data, one image up
77
+ * to 20 MiB by default (`maxImageBytes`, dsh-attachment-local) or ~27 MiB
78
+ * encoded — so a full-size picture over a slow link gets minutes, not the
79
+ * base seconds. The cap never lands below the configured base timeout.
80
+ */
81
+ const INVOKE_TIMEOUT_PER_MIB_MS = 2_000
82
+ const INVOKE_TIMEOUT_CAP_MS = 300_000
83
+
84
+ /**
85
+ * How often an ONLINE client re-runs the handshake purely to refresh the two
86
+ * names (T59): the server's display name and this device's name in its
87
+ * table. The stream heartbeat covers the server name mid-stream, but a
88
+ * device-side rename (an admin edit in the gateway's list) only reaches the
89
+ * server→client direction when THIS side sends a request — the handshake's
90
+ * marking header is always the gateway's freshest record. Deliberately quiet:
91
+ * a failed refresh changes nothing (the heartbeat/idle clocks judge the
92
+ * link), and the state never leaves `online`.
93
+ */
94
+ const INFO_REFRESH_MS = 30_000
95
+
96
+ /**
97
+ * The budget one size-backed exchange gets (invoke since T31-fix, upload
98
+ * since T51): whole MiB only (floored), so a small call keeps the plain
99
+ * base budget. The upload's size is the DECLARED `Content-Length` of the
100
+ * local request when it carried one; an unknown size (a chunked body has no
101
+ * length header, and this process's undici forbids hand-set length headers)
102
+ * gets the full cap — the honest budget for an upload whose end is not in
103
+ * sight.
104
+ */
105
+ function sizeBackedTimeoutMs(requestTimeoutMs: number, bytes: number | undefined): number {
106
+ const mib = bytes === undefined ? Number.POSITIVE_INFINITY : Math.floor(bytes / (1024 * 1024))
107
+ return Math.min(requestTimeoutMs + INVOKE_TIMEOUT_PER_MIB_MS * mib, Math.max(requestTimeoutMs, INVOKE_TIMEOUT_CAP_MS))
108
+ }
109
+
110
+ /** The budget one invoke exchange gets, from its serialized body size. */
111
+ function invokeTimeoutMs(requestTimeoutMs: number, bodyJson: string): number {
112
+ return sizeBackedTimeoutMs(requestTimeoutMs, Buffer.byteLength(bodyJson, 'utf8'))
113
+ }
114
+
115
+ /** 0 or less disables the periodic refresh entirely (tests that count
116
+ * handshakes inject 0; the T59 refresh test injects the real cadence). */
117
+ function infoRefreshDelay(options: CreateRelayClientOptions): number {
118
+ return options.infoRefreshMs ?? INFO_REFRESH_MS
119
+ }
120
+
121
+ /**
122
+ * The automatic reconnect ladder (T43): after the client lands `offline` it
123
+ * retries after 1s, 2s, 5s, 10s, 30s — and then every 30s until the link
124
+ * comes back. Each wait gains 0–20% of random jitter so a fleet of clients
125
+ * that lost the same server does not retry in lockstep. A success back to
126
+ * `online` resets the ladder to the first step.
127
+ */
128
+ const RETRY_STEPS_MS = [1_000, 2_000, 5_000, 10_000, 30_000] as const
129
+
130
+ /** Upper bound of the jitter fraction added to one retry delay (0–20%). */
131
+ const RETRY_JITTER = 0.2
132
+
133
+ /**
134
+ * The clock face the reconnect machinery runs on: wall time, timers and the
135
+ * jitter source. Injectable so tests drive the whole backoff sequence
136
+ * deterministically. The default timers are `unref()`ed — a pending retry
137
+ * must never keep the host process alive on its own.
138
+ */
139
+ export interface RelayClock {
140
+ /** Epoch milliseconds. */
141
+ now(): number
142
+ setTimeout(fn: () => void, ms: number): unknown
143
+ clearTimeout(handle: unknown): void
144
+ /** One random sample in [0, 1] — the jitter source. */
145
+ random(): number
146
+ }
147
+
148
+ /**
149
+ * The default clock: real time, `unref()`ed timers, `Math.random`. Exported
150
+ * so the interceptor's own waits (the merged-stream reopen delays) run on
151
+ * the SAME clock face — one injectable seam for tests instead of two.
152
+ */
153
+ export const defaultClock: RelayClock = {
154
+ now: () => Date.now(),
155
+ setTimeout: (fn, ms) => {
156
+ const handle = setTimeout(fn, ms)
157
+ if (typeof handle.unref === 'function') handle.unref()
158
+ return handle
159
+ },
160
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
161
+ random: () => Math.random(),
162
+ }
163
+
164
+ /** The connection states the settings surface renders (and `subscribe`
165
+ * listeners react to). */
166
+ export type RelayState = 'unpaired' | 'connecting' | 'online' | 'offline' | 'revoked' | 'incompatible'
167
+
168
+ /** The handshake reply, verbatim from `POST relay/v1/handshake`. */
169
+ export interface RelayHandshake {
170
+ relayProtocol: number
171
+ serverId: string
172
+ serverName: string
173
+ dshVersion: string
174
+ fingerprints: Record<string, string>
175
+ /**
176
+ * The SERVER's record of THIS device's name (T59) — what the pairing
177
+ * registered and renames have since made of it. `undefined` from an older
178
+ * server that does not send the field; the client then keeps whatever it
179
+ * has and pushes nothing.
180
+ */
181
+ deviceName?: string
182
+ }
183
+
184
+ /**
185
+ * One relay failure. `code` is the mapped reason (the contract's state
186
+ * vocabulary, a server refusal like `not-shared`, or a DSH error code from
187
+ * a 200 `{ok:false}` envelope); `status` carries the HTTP status when a
188
+ * response existed. `reason` is the OPTIONAL structured detail some error
189
+ * frames carry beside the message — today only the server's `unshared`
190
+ * stream-closure frame, whose `reason` ('manual' | 'client' | 'idle', T34)
191
+ * the interceptor's closed-session display keys on. Fields are assigned in
192
+ * the constructor body rather than declared as parameter properties: Node's
193
+ * strip-only type mode rejects that syntax (the same rule as UploadError in
194
+ * index.ts).
195
+ */
196
+ export class RelayError extends Error {
197
+ code: string
198
+ status?: number
199
+ reason?: string
200
+
201
+ constructor(code: string, message?: string, httpStatus?: number, reason?: string) {
202
+ super(message === undefined ? code : message)
203
+ this.name = 'RelayError'
204
+ this.code = code
205
+ if (httpStatus !== undefined) this.status = httpStatus
206
+ if (reason !== undefined) this.reason = reason
207
+ }
208
+ }
209
+
210
+ export interface CreateRelayClientOptions {
211
+ /** The normalized server address (no trailing slash), read live per
212
+ * request; `undefined` counts as unpaired. */
213
+ getServerUrl: () => string | undefined
214
+ /** The pairing token, read live per request; `undefined` counts as
215
+ * unpaired. */
216
+ getToken: () => string | undefined
217
+ /** Outbound fetch, defaulting to the global one. */
218
+ fetchImpl?: typeof fetch
219
+ /** How long a stream may go without receiving ANY line (frames and
220
+ * `ping`s alike) before it is judged dead and aborted; default 45000. */
221
+ idleTimeoutMs?: number
222
+ /** How long one request/response round-trip (handshake, invoke — and the
223
+ * headers of a stream open) may take; default 15000. */
224
+ requestTimeoutMs?: number
225
+ /** Clock/timers/jitter for the reconnect backoff; defaults to the real
226
+ * ones (timers `unref()`ed). Tests inject a manual clock. */
227
+ clock?: RelayClock
228
+ /**
229
+ * How often an ONLINE client re-runs the handshake to refresh the two
230
+ * names (T59, {@link INFO_REFRESH_MS}); `0` disables the periodic refresh
231
+ * — handshake-counting tests inject 0, the refresh test injects a cadence
232
+ * its fake clock can drive.
233
+ */
234
+ infoRefreshMs?: number
235
+ /** This side's own interface fingerprints (T42), computed after each
236
+ * completed handshake and compared group by group against the handshake's
237
+ * map. May be sync or async; a throw counts as "nothing computed" (an
238
+ * empty map — every group lands `unavailable`). Absent: `compat` stays
239
+ * undefined and no comparison ever runs (the host role's client, tests). */
240
+ computeOwnFingerprints?: () => Promise<Record<string, string>> | Record<string, string>
241
+ }
242
+
243
+ export interface RelayClient {
244
+ readonly state: RelayState
245
+ /** The last completed handshake, undefined until one succeeds. */
246
+ readonly handshakeInfo: RelayHandshake | undefined
247
+ /** Digest ({@link relayCredentialsDigest}) of the address+token the last
248
+ * completed handshake actually used, undefined until one succeeds. The
249
+ * status route compares it against the CURRENT row credentials to keep a
250
+ * cached "online" verdict from outliving the credentials it was earned
251
+ * with. */
252
+ readonly lastHandshakeDigest: string | undefined
253
+ /** Epoch ms of the next automatic reconnect, or null while none is
254
+ * scheduled (connected, attempting, or in a state that never reconnects).
255
+ * Rendered by the settings page as "离线,将于 N 秒后重试". */
256
+ readonly nextRetryAt: number | null
257
+ /** The error CODE of the most recent failure ('offline',
258
+ * 'relay-unauthorized', a DSH code, …) — never a message, never a token or
259
+ * URL. Cleared when a request succeeds again. */
260
+ readonly lastError: string | undefined
261
+ /** The interface-compatibility verdict of the most recent handshake (T42):
262
+ * group names that matched, differed, or could not be compared. Undefined
263
+ * until a first handshake ran WITH `computeOwnFingerprints` wired, and
264
+ * cleared again whenever the link or the credentials move (unpaired,
265
+ * revoked, credentialsChanged) — it describes the credentials it was
266
+ * earned with, never the current ones. */
267
+ readonly compat: RelayCompatVerdict | undefined
268
+ /** Observe state changes; a throwing listener never blocks the others.
269
+ * The CURRENT state is also broadcast when only the handshake identity
270
+ * moved (the T59 heartbeat names) — listeners re-read the getters. */
271
+ subscribe(listener: (state: RelayState) => void): () => void
272
+ /** The row's `serverName` was just committed (T59): forward it to the
273
+ * gateway's device table when it differs from the server's record —
274
+ * immediately while online, queued for the next `online` otherwise. A
275
+ * name equal to the server's record is a no-op BY CONTRACT: that is the
276
+ * settings page's server-driven write echoing back, and pushing it would
277
+ * set the two ends overwriting each other. */
278
+ queueDeviceName(name: string): void
279
+ /** Whether a locally-pushed rename is queued or in flight (T59-fix). The
280
+ * status route answers an EMPTY `deviceName` while this is true — an
281
+ * in-flight answer could still carry the pre-push record, and the page
282
+ * following it would bounce the fresh save back to the old name. */
283
+ readonly deviceNameSyncing: boolean
284
+ /** Run the handshake; success resolves with it and leaves `online`. */
285
+ connect(): Promise<RelayHandshake>
286
+ /** One immediate connection attempt from `offline`, resetting the backoff
287
+ * ladder (the settings page's 立即重连). Answers whether an attempt was
288
+ * started — the reconnect route turns a false into a 409. */
289
+ reconnect(): boolean
290
+ /** Notify that the credentials source may have changed (the loader's
291
+ * volatile-update for the row): a pending reconnect wait is cancelled and,
292
+ * with credentials present, one immediate attempt runs with the new
293
+ * values; without them the client lands `unpaired`. */
294
+ credentialsChanged(): void
295
+ /** Stop the automatic reconnect machinery (plugin row teardown). Explicit
296
+ * connect() calls still work, but no timer is armed again. */
297
+ stop(): void
298
+ /** One invoke round-trip; resolves with the unwrapped `value`, throws
299
+ * RelayError otherwise. A caller abort surfaces as `RelayError('aborted')`. */
300
+ invoke(namespace: string, method: string, args: unknown, signal?: AbortSignal): Promise<unknown>
301
+ /** Close one session's remote access on the SERVER (T34): the original
302
+ * (non-virtual) session id rides `POST relay/v1/unshare`, the server
303
+ * unshares it with reason `'client'`. Resolves on the success envelope;
304
+ * every refusal (`not-shared`, a wall, transport death) throws RelayError.
305
+ * A success proves the link and lifts a stale `offline` back to `online`,
306
+ * exactly like invoke. */
307
+ unshare(sessionId: string, signal?: AbortSignal): Promise<void>
308
+ /** Answer one forwarded Remote event (T32): `eventId` is the ORIGINAL id
309
+ * (the interceptor swapped the virtual one back), `result` the Remote
310
+ * event OUTCOME, forwarded verbatim — the gateway validates it. The error
311
+ * mapping is invoke's: a success envelope resolves (with the value, in
312
+ * practice undefined), everything else throws RelayError. */
313
+ postEventResult(eventId: string, result: unknown, signal?: AbortSignal): Promise<unknown>
314
+ /** Open the NDJSON stream route. `frame` lines are yielded, `ping` lines
315
+ * only refresh the idle clock, `end` finishes the iteration, an `error`
316
+ * line throws its RelayError. A caller abort ENDS the iteration normally;
317
+ * `break` aborts the underlying request. */
318
+ openStream(namespace: string, method: string, args: unknown, signal?: AbortSignal): AsyncIterable<unknown>
319
+ /** One plain-HTTP round-trip (T41b): `route` / `query` name a registered
320
+ * `/api` GET (relay-access's RELAY_HTTP_ROUTES; `query` is the URL-encoded
321
+ * query string with the session id already restored). Resolves with the
322
+ * UPSTREAM answer — its status, content type and body text ride inside the
323
+ * success envelope, so a 404 from the underlying route is a RESOLVED
324
+ * result here, never a RelayError. */
325
+ http(route: string, query: string, signal?: AbortSignal): Promise<RelayHttpResult>
326
+ /** One binary upload round-trip (T51): `sessionId` is the ORIGINAL
327
+ * session id, `name` the optional display filename, `body` the raw byte
328
+ * stream forwarded verbatim. The upstream answer (its status, content
329
+ * type and body text — the host route answers its business failures as
330
+ * 200-with-envelope, so those ride RESOLVED like `http`'s) comes back in
331
+ * the success envelope; every refusal or link death throws RelayError.
332
+ * The round-trip budget scales with `bytes` (the local request's declared
333
+ * `Content-Length`, when it had one) and a timeout there never moves the
334
+ * connection state — the invoke route's rules (T31-fix). */
335
+ upload(options: RelayUploadOptions, signal?: AbortSignal): Promise<RelayHttpResult>
336
+ }
337
+
338
+ /** The inputs of one {@link RelayClient.upload} round-trip. */
339
+ export interface RelayUploadOptions {
340
+ /** The ORIGINAL (non-virtual) session id, already restored by the caller. */
341
+ sessionId: string
342
+ /** The file's display name, when the local request carried one. */
343
+ name?: string
344
+ /** The raw request body. `null` (a bodyless upload — the host route would
345
+ * answer its own empty-stream business failure) forwards as an empty
346
+ * stream. */
347
+ body: ReadableStream<Uint8Array> | null
348
+ /** The local request's declared byte count, when its `Content-Length` was
349
+ * readable — sizes the round-trip budget and nothing else. */
350
+ bytes?: number
351
+ }
352
+
353
+ /** The upstream answer one {@link RelayClient.http} round-trip carries. */
354
+ export interface RelayHttpResult {
355
+ /** The underlying `/api` route's HTTP status. */
356
+ status: number
357
+ /** The underlying response's content type, when it sent one. */
358
+ contentType: string | undefined
359
+ /** The underlying response body, decoded as text (both registered routes
360
+ * answer buffered JSON). */
361
+ body: string
362
+ }
363
+
364
+ /**
365
+ * The credential digest recorded beside a completed handshake (T23a-fix):
366
+ * sha256 over `url + "\n" + token`, first 16 hex chars. Enough to detect a
367
+ * changed address or a re-pair, without keeping — or ever exposing — a
368
+ * plaintext copy of either value.
369
+ */
370
+ export function relayCredentialsDigest(serverUrl: string, token: string): string {
371
+ return createHash('sha256').update(`${serverUrl}\n${token}`).digest('hex').slice(0, 16)
372
+ }
373
+
374
+ function isRecord(value: unknown): value is Record<string, unknown> {
375
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
376
+ }
377
+
378
+ /**
379
+ * Whether the loader's `loader/volatile-update` announcement names the
380
+ * device's own field (T59-fix): the announcement rides EVERY volatile
381
+ * commit — an unrelated knob, or the settings page's own follow write — and
382
+ * only a commit that actually moved `serverName` may queue a push. The
383
+ * paths are the loader's changed-field lists (`[['serverName'], …]`).
384
+ */
385
+ export function volatileUpdateTouchesServerName(paths: unknown): boolean {
386
+ return Array.isArray(paths) && paths.some((entry) => Array.isArray(entry) && entry[0] === 'serverName')
387
+ }
388
+
389
+ function messageOf(error: unknown): string {
390
+ return error instanceof Error ? error.message : String(error)
391
+ }
392
+
393
+ /**
394
+ * One response body, parsed leniently. Reading the text is allowed to
395
+ * REJECT (a connection cut mid-body is a transport failure the caller maps
396
+ * to `offline`); only the JSON step is lenient — an HTML wall or any other
397
+ * non-JSON body becomes `undefined`, which the classifier then treats as
398
+ * "no usable body".
399
+ */
400
+ async function readPayload(response: Response): Promise<unknown> {
401
+ const text = await response.text()
402
+ if (text === '') return undefined
403
+ try {
404
+ return JSON.parse(text)
405
+ } catch {
406
+ return undefined
407
+ }
408
+ }
409
+
410
+ /** One parsed NDJSON line's verdict. */
411
+ type LineVerdict =
412
+ | { kind: 'none' }
413
+ | { kind: 'frame'; frame: unknown }
414
+ | { kind: 'end' }
415
+ | { kind: 'error'; error: RelayError }
416
+ | { kind: 'info'; serverName?: string; deviceName?: string }
417
+
418
+ /** A string field of an info line, or undefined — absent, blank or not a string. */
419
+ function infoString(value: unknown): string | undefined {
420
+ return typeof value === 'string' && value !== '' ? value : undefined
421
+ }
422
+
423
+ function classifyLine(line: string): LineVerdict {
424
+ let parsed: unknown
425
+ try {
426
+ parsed = JSON.parse(line)
427
+ } catch {
428
+ return { kind: 'none' } // a damaged line is skipped, never fatal
429
+ }
430
+ if (!isRecord(parsed)) return { kind: 'none' }
431
+ if (parsed.type === 'frame' && 'frame' in parsed) return { kind: 'frame', frame: parsed.frame }
432
+ if (parsed.type === 'end') return { kind: 'end' }
433
+ if (parsed.type === 'error') {
434
+ const detail = isRecord(parsed.error) ? parsed.error : {}
435
+ const code = typeof detail.code === 'string' && detail.code !== '' ? detail.code : 'internal'
436
+ const message = typeof detail.message === 'string' ? detail.message : undefined
437
+ // The structured detail beside the message (T34): today only the
438
+ // `unshared` frame carries one. An absent or non-string reason stays
439
+ // undefined — the consumer degrades to its own default.
440
+ const reason = typeof detail.reason === 'string' ? detail.reason : undefined
441
+ return { kind: 'error', error: new RelayError(code, message, undefined, reason) }
442
+ }
443
+ // T59: a ping may carry the names as of NOW (`serverName` — the server's
444
+ // display name; `deviceName` — this device's name in its table). An old
445
+ // server's bare `{"type":"ping"}` carries neither and stays `none`.
446
+ if (parsed.type === 'ping') {
447
+ const serverName = infoString(parsed.serverName)
448
+ const deviceName = infoString(parsed.deviceName)
449
+ if (serverName !== undefined || deviceName !== undefined) return { kind: 'info', serverName, deviceName }
450
+ }
451
+ // Any shape the protocol does not define — ignored.
452
+ return { kind: 'none' }
453
+ }
454
+
455
+ /**
456
+ * Build one relay client. Pure state machine + fetch plumbing; the row is
457
+ * only ever seen through the two getters.
458
+ */
459
+ export function createRelayClient(options: CreateRelayClientOptions): RelayClient {
460
+ const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS
461
+ const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
462
+ const fetchImpl: typeof fetch = options.fetchImpl ?? ((url, init) => fetch(url, init))
463
+ const clock: RelayClock = options.clock ?? defaultClock
464
+
465
+ let state: RelayState = 'unpaired'
466
+ let handshakeInfo: RelayHandshake | undefined
467
+ let compat: RelayCompatVerdict | undefined
468
+ let lastHandshakeDigest: string | undefined
469
+ let connectInFlight: Promise<RelayHandshake> | undefined
470
+ // T43 reconnect machinery: the armed timer handle, how many consecutive
471
+ // attempts have failed (the ladder index), when the armed timer fires, the
472
+ // code of the most recent failure, and whether the row teardown stopped
473
+ // the machinery.
474
+ let retryTimer: unknown | undefined
475
+ let retryAttempt = 0
476
+ let nextRetryAt: number | null = null
477
+ let lastError: string | undefined
478
+ let stopped = false
479
+ // Digest of the credentials the machinery last SAW — the change detector
480
+ // behind credentialsChanged().
481
+ const initialCredentials = currentCredentials()
482
+ let credentialsDigest =
483
+ initialCredentials === undefined ? undefined : relayCredentialsDigest(initialCredentials.url, initialCredentials.token)
484
+ const listeners = new Set<(state: RelayState) => void>()
485
+
486
+ /** One broadcast of the CURRENT state to every subscriber; a throwing
487
+ * listener never blocks the rest. State transitions are the only trigger —
488
+ * including the handshake's connecting→online pair, which is how the T42
489
+ * compat verdict (stored just before `online`) reaches the settings
490
+ * surface: woken listeners read the getter fresh. */
491
+ function notify(): void {
492
+ for (const listener of [...listeners]) {
493
+ try {
494
+ listener(state)
495
+ } catch {
496
+ // One broken listener never blocks the rest.
497
+ }
498
+ }
499
+ }
500
+
501
+ function setState(next: RelayState): void {
502
+ if (state === next) return
503
+ state = next
504
+ // The reconnect hooks ride the transitions (T43): landing offline arms
505
+ // the next wait; online resets the ladder; the three user-action states
506
+ // never reconnect and drop any pending wait; an attempt start leaves the
507
+ // ladder alone but the wait display is fireRetry's business.
508
+ if (next === 'offline') scheduleRetry()
509
+ else if (next === 'online') {
510
+ resetRetry()
511
+ // T59: a server confirmation retires the local push authority (the
512
+ // handshake/stream/invoke that just landed saw the table as it is),
513
+ // the periodic name refresh arms, and a rename queued while offline
514
+ // goes out now.
515
+ deviceNameAuthoritative = false
516
+ armInfoRefresh()
517
+ flushPendingDeviceName()
518
+ }
519
+ else if (next === 'unpaired' || next === 'revoked' || next === 'incompatible') cancelRetry()
520
+ // A compat verdict describes the server the CURRENT credentials pointed
521
+ // at. Unpairing (or a revocation — the same "this server is gone" wall)
522
+ // invalidates that answer, so the verdict goes with the link (T42-fix).
523
+ if (next === 'unpaired' || next === 'revoked') compat = undefined
524
+ notify()
525
+ }
526
+
527
+ /**
528
+ * The live credentials, or undefined — the requireCredentials logic
529
+ * without the announcement, shared with credentialsChanged's change
530
+ * detection.
531
+ */
532
+ function currentCredentials(): { url: string; token: string } | undefined {
533
+ const url = options.getServerUrl()
534
+ const token = options.getToken()
535
+ if (url === undefined || url.trim() === '' || token === undefined || token === '') return undefined
536
+ // The getter contract delivers a normalized address; stripping stray
537
+ // trailing slashes anyway keeps a hand-edited row from silently producing
538
+ // `…/relay//v1/…`, which no route would ever match.
539
+ return { url: url.trim().replace(/\/+$/u, ''), token }
540
+ }
541
+
542
+ /**
543
+ * The live credentials, or the unpaired failure. Never a request without
544
+ * both halves — and the unpaired state is (re)announced, so a row whose
545
+ * address or token was cleared later shows up as unpaired too.
546
+ */
547
+ function requireCredentials(): { url: string; token: string } {
548
+ const creds = currentCredentials()
549
+ if (creds === undefined) {
550
+ setState('unpaired')
551
+ throw new RelayError('unpaired', 'no server address or pairing token is configured')
552
+ }
553
+ credentialsDigest = relayCredentialsDigest(creds.url, creds.token)
554
+ return creds
555
+ }
556
+
557
+ // ---- the reconnect ladder (T43) ------------------------------------------
558
+
559
+ function cancelRetry(): void {
560
+ if (retryTimer !== undefined) {
561
+ clock.clearTimeout(retryTimer)
562
+ retryTimer = undefined
563
+ }
564
+ retryAttempt = 0
565
+ nextRetryAt = null
566
+ }
567
+
568
+ function resetRetry(): void {
569
+ cancelRetry()
570
+ lastError = undefined
571
+ }
572
+
573
+ function scheduleRetry(): void {
574
+ // One wait at a time — a second offline entry while a timer is armed
575
+ // (e.g. a status-route connect failing between two ticks) leaves the
576
+ // armed timer in charge.
577
+ if (stopped || retryTimer !== undefined) return
578
+ const base = RETRY_STEPS_MS[Math.min(retryAttempt, RETRY_STEPS_MS.length - 1)]
579
+ const delay = Math.round(base * (1 + clock.random() * RETRY_JITTER))
580
+ retryAttempt += 1
581
+ nextRetryAt = clock.now() + delay
582
+ retryTimer = clock.setTimeout(fireRetry, delay)
583
+ }
584
+
585
+ function fireRetry(): void {
586
+ retryTimer = undefined
587
+ nextRetryAt = null
588
+ if (stopped || state !== 'offline') return
589
+ // The attempt's own outcome drives the machine: success → online (ladder
590
+ // reset), a still-offline failure → scheduleRetry armed the next step,
591
+ // a wall (revoked/incompatible/unpaired) → cancelRetry ran.
592
+ void connect().catch(() => {})
593
+ }
594
+
595
+ /**
596
+ * The error-code vocabulary the diagnostics readout accepts (T43-fix):
597
+ * short, alphanumeric with / _ - separators. A server that answers a
598
+ * "code" quoting URLs or anything stranger does not get to write it into
599
+ * the client's state — it degrades to `unexpected`.
600
+ */
601
+ function sanitizeCode(code: string): string {
602
+ return /^[a-z0-9/_-]{1,64}$/i.test(code) ? code : 'unexpected'
603
+ }
604
+
605
+ /** Record the failing call's code for the diagnostics surface (the CODE
606
+ * only — messages quote URLs, and codes never carry credentials). */
607
+ function noteFailure(code: string): void {
608
+ lastError = sanitizeCode(code)
609
+ }
610
+
611
+ function subscribe(listener: (state: RelayState) => void): () => void {
612
+ listeners.add(listener)
613
+ return () => {
614
+ listeners.delete(listener)
615
+ }
616
+ }
617
+
618
+ // ---- the T59 device-name sync ----------------------------------------------
619
+
620
+ /**
621
+ * True while THIS side's `deviceName` is the authority: a rename this
622
+ * client pushed that the gateway just answered OK to. In-flight stream
623
+ * heartbeats still carry the OLD name (their marking header was written
624
+ * when the stream opened), and without this flag those pings would pull
625
+ * `handshakeInfo` back to the stale name — and the settings page would
626
+ * then "follow" it straight over the user's fresh save. The next server
627
+ * confirmation (handshake or refresh) retires the flag: the answer there
628
+ * IS the table's current record.
629
+ */
630
+ let deviceNameAuthoritative = false
631
+
632
+ /** A rename waiting for the link: queued while offline (or before the
633
+ * first handshake), flushed once `online` lands. */
634
+ let pendingDeviceName: string | undefined
635
+
636
+ // T59-fix: a push that is IN FLIGHT right now, plus a sequence counter
637
+ // bumped at every push start AND settle. An info-refresh answer that
638
+ // overlapped a push (seq moved, or a push is still queued) carries the
639
+ // PRE-push record and must not win — see {@link refreshInfo}.
640
+ let deviceNamePushBusy = false
641
+ let deviceNamePushSeq = 0
642
+
643
+ /**
644
+ * Whether a locally-pushed rename is queued or in flight (T59-fix). The
645
+ * status route answers an EMPTY `deviceName` while this is true: an
646
+ * in-flight status answer could still carry the pre-push record, and a
647
+ * page that followed it would bounce the user's fresh save straight back
648
+ * to the old name.
649
+ */
650
+ function deviceNameSyncing(): boolean {
651
+ return deviceNamePushBusy || pendingDeviceName !== undefined
652
+ }
653
+
654
+ /** The periodic info-refresh's armed timer (see {@link INFO_REFRESH_MS}). */
655
+ let infoTimer: unknown | undefined
656
+
657
+ /** Fold one heartbeat's names into the stored handshake (T59). */
658
+ function applyInfoDelta(serverName: string | undefined, deviceName: string | undefined): void {
659
+ if (handshakeInfo === undefined) return
660
+ const next = { ...handshakeInfo }
661
+ let changed = false
662
+ if (serverName !== undefined && serverName !== next.serverName) {
663
+ next.serverName = serverName
664
+ changed = true
665
+ }
666
+ // A locally-pushed rename outranks the stream heartbeat until the server
667
+ // confirms it — see {@link deviceNameAuthoritative}; a push IN FLIGHT is
668
+ // equally authoritative for the same reason (T59-fix): the heartbeat's
669
+ // name was stamped before our rename reached the table.
670
+ if (deviceName !== undefined && deviceName !== next.deviceName && !deviceNameAuthoritative && !deviceNamePushBusy) {
671
+ next.deviceName = deviceName
672
+ changed = true
673
+ }
674
+ if (!changed) return
675
+ handshakeInfo = next
676
+ // The state itself did not move, but the identity did: subscribers (the
677
+ // interceptor's rename path above all) must see the new names. The
678
+ // current-state broadcast is exactly that — no reconnect can come from
679
+ // it, because only setState moves the machine.
680
+ notify()
681
+ }
682
+
683
+ /**
684
+ * Push one name to the gateway's `device/name` endpoint (T59): the gateway
685
+ * renames the CALLING device's own record. Resolves `true` when the table
686
+ * now carries `name` (the push answered OK) or when no push was needed;
687
+ * a failed push queues the name for the next `online` and resolves false.
688
+ * Never touches the connection state — a refused rename is not a dead
689
+ * link.
690
+ */
691
+ async function pushDeviceName(name: string): Promise<boolean> {
692
+ const creds = currentCredentials()
693
+ if (creds === undefined) {
694
+ pendingDeviceName = name
695
+ return false
696
+ }
697
+ // T59-fix: the busy window covers the whole round-trip (the status route
698
+ // answers an empty deviceName while it lasts), and the sequence counter
699
+ // lets an overlapping info refresh know its answer is stale.
700
+ const digestAtStart = credentialsDigest
701
+ deviceNamePushBusy = true
702
+ deviceNamePushSeq += 1
703
+ let payload: unknown
704
+ try {
705
+ const controller = new AbortController()
706
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs)
707
+ if (typeof timer.unref === 'function') timer.unref()
708
+ try {
709
+ const response = await fetchImpl(`${creds.url}${DEVICE_NAME_PATH}`, {
710
+ ...requestInit(creds.token, JSON.stringify({ name })),
711
+ signal: controller.signal,
712
+ })
713
+ if (response.ok) payload = await readPayload(response)
714
+ } finally {
715
+ clearTimeout(timer)
716
+ }
717
+ } catch {
718
+ payload = undefined
719
+ }
720
+ deviceNamePushBusy = false
721
+ deviceNamePushSeq += 1
722
+ // T59-fix2: TWO different endings hide behind the old combined guard.
723
+ // A stopped client has nothing to come back for, and an answer about
724
+ // DIFFERENT credentials describes a table we no longer talk to — those
725
+ // give up outright (a later row commit re-queues a fresh name). A
726
+ // merely dropped link is NOT the end: the name re-queues and the next
727
+ // `online` transition flushes it, exactly like a push that was refused
728
+ // before it ever left.
729
+ if (stopped || credentialsDigest !== digestAtStart) return false
730
+ if (state !== 'online') {
731
+ pendingDeviceName = name
732
+ return false
733
+ }
734
+ const confirmed = isRecord(payload) && payload.ok === true && infoString(payload.name) === name
735
+ if (!confirmed) {
736
+ pendingDeviceName = name
737
+ return false
738
+ }
739
+ // The table took the new name: remember it locally (without a state
740
+ // announcement — nothing but the name moved) and mark it authoritative
741
+ // until the server's own answer says the same.
742
+ if (handshakeInfo !== undefined && handshakeInfo.deviceName !== name) {
743
+ handshakeInfo = { ...handshakeInfo, deviceName: name }
744
+ }
745
+ deviceNameAuthoritative = true
746
+ pendingDeviceName = undefined
747
+ return true
748
+ }
749
+
750
+ /** Flush a queued rename against the fresh online state (T59). */
751
+ function flushPendingDeviceName(): void {
752
+ if (pendingDeviceName === undefined) return
753
+ const name = pendingDeviceName
754
+ pendingDeviceName = undefined
755
+ if (handshakeInfo === undefined) {
756
+ pendingDeviceName = name
757
+ return
758
+ }
759
+ if (name === (handshakeInfo.deviceName ?? '')) return
760
+ void pushDeviceName(name)
761
+ }
762
+
763
+ /**
764
+ * The backend's one entry point (T59): the row's `serverName` was just
765
+ * committed. Online with a handshake, the name travels to the gateway only
766
+ * when it DIFFERS from the server's record — the settings page's
767
+ * server-driven write lands here with both sides equal, which is exactly
768
+ * what keeps the two ends from overwriting each other. Offline (or not yet
769
+ * handshaken), the name queues for the next `online`.
770
+ */
771
+ function queueDeviceName(name: string): void {
772
+ const trimmed = name.trim()
773
+ if (trimmed === '') return
774
+ if (state !== 'online' || handshakeInfo === undefined) {
775
+ pendingDeviceName = trimmed
776
+ return
777
+ }
778
+ if (trimmed === (handshakeInfo.deviceName ?? '')) {
779
+ pendingDeviceName = undefined
780
+ return
781
+ }
782
+ void pushDeviceName(trimmed)
783
+ }
784
+
785
+ /**
786
+ * One QUIET handshake re-run (T59): refreshes the two names while online —
787
+ * no state announcement, no ladder movement, failures silent (the next
788
+ * tick retries; the idle and heartbeat clocks own the link's verdict).
789
+ * The reply carries the gateway's freshest record of BOTH names (its
790
+ * marking headers are written per forward), so this is also how a rename
791
+ * an admin made on the server reaches an otherwise-idle client.
792
+ */
793
+ async function refreshInfo(): Promise<void> {
794
+ if (stopped || state !== 'online' || connectInFlight !== undefined) return
795
+ const creds = currentCredentials()
796
+ if (creds === undefined) return
797
+ // T59-fix: remember the world at request time — the answer only counts
798
+ // if we are still the same online client (the credential digest catches
799
+ // a re-pair to another server), and a name push that overlapped the
800
+ // round-trip makes the answer's deviceName a PRE-push record.
801
+ const digestAtStart = credentialsDigest
802
+ const pushSeqAtStart = deviceNamePushSeq
803
+ let payload: unknown
804
+ try {
805
+ const controller = new AbortController()
806
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs)
807
+ if (typeof timer.unref === 'function') timer.unref()
808
+ try {
809
+ const response = await fetchImpl(`${creds.url}${HANDSHAKE_PATH}`, {
810
+ ...requestInit(creds.token, '{}'),
811
+ signal: controller.signal,
812
+ })
813
+ if (!response.ok) return
814
+ payload = await readPayload(response)
815
+ } finally {
816
+ clearTimeout(timer)
817
+ }
818
+ } catch {
819
+ return
820
+ }
821
+ if (stopped || state !== 'online' || credentialsDigest !== digestAtStart) return
822
+ if (!isRecord(payload) || payload.ok !== true || payload.relayProtocol !== RELAY_PROTOCOL) return
823
+ // T59-fix: NAMES ONLY. serverId / dshVersion / fingerprints belong to the
824
+ // real handshake (the compat verdict is computed there, on both maps
825
+ // fresh); a quiet refresh never disturbs them.
826
+ const previous = handshakeInfo
827
+ if (previous === undefined) return
828
+ const serverName = typeof payload.serverName === 'string' ? payload.serverName : previous.serverName
829
+ const serverDeviceName = infoString(payload.deviceName)
830
+ // A push that overlapped this round-trip — STARTED before it (the seq
831
+ // moved by the settle), still IN FLIGHT, or still QUEUED — makes the
832
+ // answer's deviceName a pre-push record: dropped, and the local
833
+ // authority stays; the next clean refresh confirms instead.
834
+ const pushedDuringRefresh = deviceNamePushSeq !== pushSeqAtStart || deviceNamePushBusy || pendingDeviceName !== undefined
835
+ const deviceName = pushedDuringRefresh ? undefined : serverDeviceName
836
+ if (deviceName !== undefined) deviceNameAuthoritative = false
837
+ let changed = previous.serverName !== serverName
838
+ if (deviceName !== undefined && deviceName !== previous.deviceName) changed = true
839
+ if (!changed) return
840
+ handshakeInfo = { ...previous, serverName, ...(deviceName !== undefined ? { deviceName } : {}) }
841
+ notify()
842
+ }
843
+
844
+ /** Arm one refresh tick; re-arms itself while the client stays online. */
845
+ function armInfoRefresh(): void {
846
+ const delay = infoRefreshDelay(options)
847
+ if (delay <= 0 || infoTimer !== undefined || stopped) return
848
+ infoTimer = clock.setTimeout(() => {
849
+ infoTimer = undefined
850
+ if (stopped || state !== 'online') return
851
+ // T59-fix2: a rename whose push FAILED while the link stayed up waits
852
+ // in the queue with no state transition coming to flush it — it
853
+ // retries on this cadence, or it would hang forever: syncing (and
854
+ // the empty `deviceName` the status route answers) would never clear,
855
+ // and the next reconnect would push the stale queued name over
856
+ // whatever an administrator renamed the device to meanwhile.
857
+ flushPendingDeviceName()
858
+ void refreshInfo().then(() => {
859
+ if (state === 'online' && !stopped) armInfoRefresh()
860
+ })
861
+ }, delay)
862
+ }
863
+
864
+ /** The shared request face of every route. ONLY endpoint headers live
865
+ * here — content-length, host, connection and transfer-encoding are the
866
+ * dispatcher's business and must never be set by hand: DSH's process
867
+ * swaps the global fetch dispatcher for its own undici, which rejects a
868
+ * manual content-length outright (fetch failed / UND_ERR_INVALID_ARG).
869
+ * The JSON body arrives PRE-SERIALIZED: the invoke caller needs the JSON
870
+ * once for its size-based timeout, so every route stringifies exactly
871
+ * one. */
872
+ function requestInit(token: string, bodyJson: string): RequestInit {
873
+ return {
874
+ method: 'POST',
875
+ headers: {
876
+ authorization: `Bearer ${token}`,
877
+ 'content-type': 'application/json',
878
+ // Load-bearing (module comment): without it the gateway's pairing
879
+ // wall arrives as HTML and a revocation cannot be classified.
880
+ accept: 'application/json',
881
+ },
882
+ body: bodyJson,
883
+ // A wrong server must not walk the pairing token through a redirect.
884
+ redirect: 'manual',
885
+ }
886
+ }
887
+
888
+ /**
889
+ * The binary upload's init (T51): the same endpoint-headers-only
890
+ * discipline as {@link requestInit} — the body rides as the raw byte
891
+ * stream with `content-type: application/octet-stream` (the ONE header
892
+ * the host's upload route mandates, RT dsh-client-file-upload
893
+ * lib/index.js:18) and no content-length: DSH's undici refuses a hand-set
894
+ * length outright, so a stream body goes chunked and the server's
895
+ * streaming byte count is the size gate. `duplex: 'half'` is what a
896
+ * streaming request body requires.
897
+ */
898
+ function uploadInit(token: string, body: ReadableStream<Uint8Array>): RequestInit {
899
+ const init: RequestInit = {
900
+ method: 'POST',
901
+ headers: {
902
+ authorization: `Bearer ${token}`,
903
+ 'content-type': 'application/octet-stream',
904
+ accept: 'application/json',
905
+ },
906
+ body,
907
+ redirect: 'manual',
908
+ }
909
+ // `duplex` is what a streaming request body requires — the resolved
910
+ // RequestInit type here hides it (the DOM-vs-undici conditional in
911
+ // @types/node collapses to the DOM face, which has no such field), so
912
+ // the assignment carries its own cast.
913
+ ;(init as { duplex?: string }).duplex = 'half'
914
+ return init
915
+ }
916
+
917
+ /**
918
+ * Map one non-success response onto the RelayError (and state) contract.
919
+ * Only the two walls move the state — the gateway's unpaired 401 means
920
+ * the token died (`revoked`), the relay-only 403 means the far end is not
921
+ * a 2.0.0 relay server (`incompatible`). The 401 `relay-unauthorized`
922
+ * deliberately does NOT become `revoked`: the gateway ACCEPTED the token
923
+ * and the server's internal secret disagrees — a server-side fault, and
924
+ * unpairing a valid device would be the wrong lesson.
925
+ */
926
+ function failureOf(status: number, payload: unknown): RelayError {
927
+ const body = isRecord(payload) ? payload : {}
928
+ const error = isRecord(body.error) ? body.error : {}
929
+ const code = typeof error.code === 'string' && error.code !== '' ? error.code : undefined
930
+ const message = typeof error.message === 'string' ? error.message : undefined
931
+ const reason = typeof body.reason === 'string' ? body.reason : undefined
932
+ if (status === 401) {
933
+ if (reason === 'unpaired') {
934
+ setState('revoked')
935
+ return new RelayError('revoked', 'the pairing token was rejected by the server gateway', 401)
936
+ }
937
+ if (code === 'relay-unauthorized') return new RelayError('relay-unauthorized', message, 401)
938
+ }
939
+ if (status === 403) {
940
+ if (reason === 'relay-only') {
941
+ setState('incompatible')
942
+ return new RelayError('incompatible', 'the server refused the relay prefix — it is not running the 2.0.0 relay', 403)
943
+ }
944
+ if (code === 'not-shared' || code === 'no-session' || code === 'forbidden-method') {
945
+ return new RelayError(code, message, 403)
946
+ }
947
+ }
948
+ // 200 {ok:false} envelopes, 400/404/429 answers and anything else
949
+ // unheard-of: the body's error code is the answer, the state is not
950
+ // touched.
951
+ if (code !== undefined) return new RelayError(code, message, status)
952
+ // The bad-gateway band carries no relay body of its own — it is what a
953
+ // reverse proxy answers when the gateway behind it is down (nginx: an
954
+ // HTML 502). That IS the offline case, and the e2e contract expects it.
955
+ if (status === 502 || status === 503 || status === 504) {
956
+ noteFailure('offline')
957
+ setState('offline')
958
+ return new RelayError('offline', `the relay chain answered ${status} — the gateway is unreachable`, status)
959
+ }
960
+ return new RelayError(`http-${status}`, `unexpected relay response with status ${status}`, status)
961
+ }
962
+
963
+ /**
964
+ * The server-restart stream line (the server App exits cleanly or reloads
965
+ * its plugin row: relay-server.ts's closeAll ends every NDJSON stream with
966
+ * `error{code:'server-restart'}`) is a LINK fact, not an answer about one
967
+ * call — the whole server is going down. Mark the client offline exactly
968
+ * like a transport death would: the reconnect ladder arms, the merged
969
+ * streams' offline annotations apply, and the eventual reconnect runs a
970
+ * fresh handshake that picks up the (possibly changed) server name. The
971
+ * thrown RelayError keeps the specific code for the diagnostics ring.
972
+ */
973
+ function noteServerRestart(error: RelayError): void {
974
+ if (error.code !== 'server-restart') return
975
+ noteFailure('offline')
976
+ setState('offline')
977
+ }
978
+
979
+ /** `aborted` — a caller's signal, not a transport fault. */
980
+ function abortedError(): RelayError {
981
+ return new RelayError('aborted', 'the caller aborted the request')
982
+ }
983
+
984
+ /**
985
+ * One request/response exchange (handshake, invoke, upload) with the
986
+ * shared timeout wiring. The URL and the RequestInit arrive PREBUILT —
987
+ * the JSON routes compose theirs from {@link requestInit}, the upload
988
+ * from {@link uploadInit} — so the body shape (serialized string or byte
989
+ * stream) stays the caller's business. Resolves only on a success
990
+ * envelope — 2xx plus `ok:true` — and then lifts a stale `offline` back
991
+ * to `online`, because a success proves the link. EVERY other outcome
992
+ * throws the mapped RelayError; transport failures (fetch rejection,
993
+ * mid-body cut, timeout) set `offline` first — EXCEPT on a route that
994
+ * opted out (`timeoutSetsOffline: false`, the invoke and upload routes):
995
+ * a slow call — a 28 MiB inline-image prompt or a 100 MiB attachment
996
+ * crawling up a slow link — and, since T51-fix, an upload CUT MID-STREAM
997
+ * (a reset under a huge body is the size gate and the drain doing their
998
+ * job, not a dead link) both fail THIS call and leave the connection
999
+ * state exactly where it was; the diagnostics still record the failure
1000
+ * code. Only the handshake / stream-header legs and real network-layer
1001
+ * failures on the opted-in routes judge the link.
1002
+ */
1003
+ async function exchangeRequest(
1004
+ url: string,
1005
+ init: RequestInit,
1006
+ signal: AbortSignal | undefined,
1007
+ applySuccessState: boolean,
1008
+ opts: { timeoutMs?: number; timeoutSetsOffline?: boolean; transportSetsOffline?: boolean } = {},
1009
+ ): Promise<Record<string, unknown>> {
1010
+ const timeoutMs = opts.timeoutMs ?? requestTimeoutMs
1011
+ const timeoutSetsOffline = opts.timeoutSetsOffline ?? true
1012
+ // The transport-failure opt-out (T51-fix) is SEPARATE from the timeout
1013
+ // one: the invoke route opts out of the timeout judging the link but
1014
+ // keeps real transport deaths offline (the T43 reconnect ladder hangs
1015
+ // off them); the upload route opts out of BOTH — a reset under a huge
1016
+ // body is the size gate doing its job, not a dead link.
1017
+ const transportSetsOffline = opts.transportSetsOffline ?? true
1018
+ const controller = new AbortController()
1019
+ const onExternalAbort = (): void => {
1020
+ controller.abort()
1021
+ }
1022
+ let timedOut = false
1023
+ if (signal !== undefined) {
1024
+ if (signal.aborted) controller.abort()
1025
+ else signal.addEventListener('abort', onExternalAbort)
1026
+ }
1027
+ const timer = setTimeout(() => {
1028
+ timedOut = true
1029
+ controller.abort()
1030
+ }, timeoutMs)
1031
+ if (typeof timer.unref === 'function') timer.unref()
1032
+ try {
1033
+ let response: Response
1034
+ try {
1035
+ response = await fetchImpl(url, { ...init, signal: controller.signal })
1036
+ } catch (error) {
1037
+ if (signal?.aborted) throw abortedError()
1038
+ if (timedOut && !timeoutSetsOffline) {
1039
+ noteFailure('request-timeout')
1040
+ throw new RelayError('request-timeout', `no response within ${timeoutMs} ms`)
1041
+ }
1042
+ noteFailure('offline')
1043
+ if (transportSetsOffline) setState('offline')
1044
+ throw new RelayError('offline', timedOut ? `no response within ${timeoutMs} ms` : messageOf(error))
1045
+ }
1046
+ let payload: unknown
1047
+ try {
1048
+ payload = await readPayload(response)
1049
+ } catch (error) {
1050
+ if (signal?.aborted) throw abortedError()
1051
+ noteFailure('offline')
1052
+ if (transportSetsOffline) setState('offline')
1053
+ throw new RelayError('offline', messageOf(error))
1054
+ }
1055
+ if (response.status >= 200 && response.status < 300 && isRecord(payload) && payload.ok === true) {
1056
+ // A success answers the link question: the last failure is superseded.
1057
+ lastError = undefined
1058
+ if (applySuccessState) setState('online')
1059
+ return payload
1060
+ }
1061
+ throw failureOf(response.status, payload)
1062
+ } finally {
1063
+ clearTimeout(timer)
1064
+ if (signal !== undefined) signal.removeEventListener('abort', onExternalAbort)
1065
+ }
1066
+ }
1067
+
1068
+ /** The JSON routes' one exchange: path + pre-serialized body over
1069
+ * {@link exchangeRequest}. */
1070
+ async function exchange(
1071
+ pathName: string,
1072
+ bodyJson: string,
1073
+ signal: AbortSignal | undefined,
1074
+ applySuccessState: boolean,
1075
+ creds: { url: string; token: string },
1076
+ opts: { timeoutMs?: number; timeoutSetsOffline?: boolean } = {},
1077
+ ): Promise<Record<string, unknown>> {
1078
+ return exchangeRequest(`${creds.url}${pathName}`, requestInit(creds.token, bodyJson), signal, applySuccessState, opts)
1079
+ }
1080
+
1081
+ function connect(): Promise<RelayHandshake> {
1082
+ // A connect already running IS the answer (T23a-fix2): a caller that
1083
+ // raced one — the status route abandons its wait after 5s while the
1084
+ // attempt keeps going — joins the SAME promise instead of stacking a
1085
+ // second handshake on the wire. The slot clears the moment the attempt
1086
+ // settles, so a later connect is a genuinely fresh one.
1087
+ if (connectInFlight !== undefined) return connectInFlight
1088
+ const attempt = (async (): Promise<RelayHandshake> => {
1089
+ // Fail before 'connecting' is announced when nothing is configured —
1090
+ // an unpaired client must never look like it is trying.
1091
+ const creds = requireCredentials()
1092
+ const previous = state
1093
+ setState('connecting')
1094
+ let payload: Record<string, unknown>
1095
+ try {
1096
+ payload = await exchange(HANDSHAKE_PATH, '{}', undefined, false, creds)
1097
+ } catch (error) {
1098
+ // The two walls keep the state the mapping gave them (revoked /
1099
+ // incompatible). Every OTHER failure is an answer the contract says
1100
+ // must not move the state — but the entry into this attempt already
1101
+ // announced 'connecting', and a refusal would leave it stuck there
1102
+ // forever, so the entry state is restored instead (T23a-fix). One
1103
+ // correction (T23a-fix2): `unpaired` is reserved for "no credentials
1104
+ // configured" — this attempt HAD them, so a restored first attempt
1105
+ // lands on `offline`, the honest "configured but not reached".
1106
+ if (state === 'connecting') setState(previous === 'unpaired' ? 'offline' : previous)
1107
+ // Whatever the failure was, its code is the diagnostics answer — even
1108
+ // when the restore left the state untouched (e.g. an online verdict
1109
+ // surviving an unmapped handshake failure). Server-supplied codes go
1110
+ // through the sanitizer first (T43-fix).
1111
+ if (error instanceof RelayError) lastError = sanitizeCode(error.code)
1112
+ throw error
1113
+ }
1114
+ // The protocol gate runs BEFORE the online transition: an incompatible
1115
+ // server must end `incompatible`, never flicker through online.
1116
+ if (payload.relayProtocol !== RELAY_PROTOCOL) {
1117
+ setState('incompatible')
1118
+ lastError = 'incompatible'
1119
+ throw new RelayError(
1120
+ 'incompatible',
1121
+ `the server speaks relay protocol ${String(payload.relayProtocol)}, this client speaks ${RELAY_PROTOCOL}`,
1122
+ )
1123
+ }
1124
+ handshakeInfo = {
1125
+ relayProtocol: RELAY_PROTOCOL,
1126
+ serverId: typeof payload.serverId === 'string' ? payload.serverId : '',
1127
+ serverName: typeof payload.serverName === 'string' ? payload.serverName : '',
1128
+ dshVersion: typeof payload.dshVersion === 'string' ? payload.dshVersion : '',
1129
+ fingerprints: isRecord(payload.fingerprints) ? (payload.fingerprints as Record<string, string>) : {},
1130
+ // T59: the gateway's record of THIS device's name, when the server
1131
+ // speaks the field at all (an older server omits it and the client
1132
+ // keeps whatever it had).
1133
+ ...(infoString(payload.deviceName) !== undefined ? { deviceName: infoString(payload.deviceName) } : {}),
1134
+ }
1135
+ // Interface compatibility (T42): compare the handshake's group map
1136
+ // against this side's own, right here where both are fresh. A compute
1137
+ // failure degrades to "nothing computed" — every group lands in
1138
+ // `unavailable`, which the comparison contract keeps away from
1139
+ // `different`. The verdict is stored BEFORE the online transition, so
1140
+ // every subscriber woken by it reads the getter fresh.
1141
+ if (options.computeOwnFingerprints !== undefined) {
1142
+ let own: Record<string, string> = {}
1143
+ try {
1144
+ own = (await options.computeOwnFingerprints()) ?? {}
1145
+ } catch {
1146
+ // Own fingerprints unavailable — the verdict says so, honestly.
1147
+ }
1148
+ compat = compareFingerprints(handshakeInfo.fingerprints, own)
1149
+ }
1150
+ // Digest of exactly the credentials this handshake used — never the
1151
+ // plaintext values (T23a-fix).
1152
+ lastHandshakeDigest = relayCredentialsDigest(creds.url, creds.token)
1153
+ setState('online')
1154
+ return handshakeInfo
1155
+ })()
1156
+ connectInFlight = attempt
1157
+ const clear = (): void => {
1158
+ if (connectInFlight === attempt) connectInFlight = undefined
1159
+ }
1160
+ attempt.then(clear, clear)
1161
+ return attempt
1162
+ }
1163
+
1164
+ /** One immediate attempt, ladder reset to the first step (T43). Only an
1165
+ * `offline` client has anything to reconnect. */
1166
+ function reconnect(): boolean {
1167
+ if (stopped || state !== 'offline') return false
1168
+ cancelRetry()
1169
+ void connect().catch(() => {})
1170
+ return true
1171
+ }
1172
+
1173
+ /**
1174
+ * The credentials source moved (a pairing write, an unpair, a hand edit
1175
+ * committed by the loader): drop any pending wait — the ladder belongs to
1176
+ * the OLD credentials — clear the stored compat verdict (it describes the
1177
+ * server the OLD credentials pointed at, T23b2-fix3) and dial the new
1178
+ * values at once. Nothing configured lands `unpaired`, exactly like a
1179
+ * request would. A connect already running joined in with the old values
1180
+ * (its getters were read at its start); when it settles, ONE follow-up
1181
+ * goes out with the new values — skipped if a still-newer change
1182
+ * superseded this one.
1183
+ */
1184
+ function credentialsChanged(): void {
1185
+ const creds = currentCredentials()
1186
+ const digest = creds === undefined ? undefined : relayCredentialsDigest(creds.url, creds.token)
1187
+ if (digest === credentialsDigest) return
1188
+ credentialsDigest = digest
1189
+ // Same invalidation rule as setState's unpaired/revoked branch: a
1190
+ // verdict the current credentials never earned must not stay visible —
1191
+ // even when the very next handshake lands online, there is a window
1192
+ // between the change and that handshake.
1193
+ compat = undefined
1194
+ cancelRetry()
1195
+ if (stopped) return
1196
+ if (creds === undefined) {
1197
+ setState('unpaired')
1198
+ return
1199
+ }
1200
+ const inFlight = connectInFlight
1201
+ if (inFlight === undefined) {
1202
+ void connect().catch(() => {})
1203
+ return
1204
+ }
1205
+ // The running attempt is the old credentials' dial. Joining it would be
1206
+ // a no-op (T23a-fix2 dedupe) AND answer nothing about the new values —
1207
+ // the follow-up below is the new dial (T43-fix).
1208
+ void inFlight.catch(() => {}).then(() => {
1209
+ if (stopped) return
1210
+ const latest = currentCredentials()
1211
+ if (latest === undefined || relayCredentialsDigest(latest.url, latest.token) !== digest) return
1212
+ void connect().catch(() => {})
1213
+ })
1214
+ }
1215
+
1216
+ function stop(): void {
1217
+ stopped = true
1218
+ cancelRetry()
1219
+ if (infoTimer !== undefined) {
1220
+ clock.clearTimeout(infoTimer)
1221
+ infoTimer = undefined
1222
+ }
1223
+ }
1224
+
1225
+ async function invoke(namespace: string, method: string, args: unknown, signal?: AbortSignal): Promise<unknown> {
1226
+ const creds = requireCredentials()
1227
+ // One serialization, two uses: the body on the wire and the size the
1228
+ // round-trip budget scales with. The timeout deliberately does NOT move
1229
+ // the connection state — a slow prompt is a slow call, not a dead link.
1230
+ const bodyJson = JSON.stringify({ namespace, method, args })
1231
+ const payload = await exchange(INVOKE_PATH, bodyJson, signal, true, creds, {
1232
+ timeoutMs: invokeTimeoutMs(requestTimeoutMs, bodyJson),
1233
+ timeoutSetsOffline: false,
1234
+ })
1235
+ return payload.value
1236
+ }
1237
+
1238
+ async function postEventResult(eventId: string, result: unknown, signal?: AbortSignal): Promise<unknown> {
1239
+ const creds = requireCredentials()
1240
+ const payload = await exchange(EVENT_RESULT_PATH, JSON.stringify({ eventId, result }), signal, true, creds)
1241
+ return payload.value
1242
+ }
1243
+
1244
+ async function unshare(sessionId: string, signal?: AbortSignal): Promise<void> {
1245
+ const creds = requireCredentials()
1246
+ await exchange(UNSHARE_PATH, JSON.stringify({ sessionId }), signal, true, creds)
1247
+ }
1248
+
1249
+ async function http(route: string, query: string, signal?: AbortSignal): Promise<RelayHttpResult> {
1250
+ const creds = requireCredentials()
1251
+ const payload = await exchange(HTTP_PATH, JSON.stringify({ route, query }), signal, true, creds)
1252
+ const value = payload.value
1253
+ if (
1254
+ !isRecord(value) ||
1255
+ typeof value.status !== 'number' ||
1256
+ !Number.isSafeInteger(value.status) ||
1257
+ typeof value.body !== 'string'
1258
+ ) {
1259
+ throw new RelayError('internal', 'the relay http answer carries no upstream response')
1260
+ }
1261
+ return {
1262
+ status: value.status,
1263
+ contentType: typeof value.contentType === 'string' ? value.contentType : undefined,
1264
+ body: value.body,
1265
+ }
1266
+ }
1267
+
1268
+ async function upload(options: RelayUploadOptions, signal?: AbortSignal): Promise<RelayHttpResult> {
1269
+ const creds = requireCredentials()
1270
+ const params = new URLSearchParams()
1271
+ params.set('sessionId', options.sessionId)
1272
+ if (options.name !== undefined) params.set('name', options.name)
1273
+ // The empty-body upload still rides a (closed) stream: the wire route
1274
+ // always speaks a request body, and a missing one would be a transport
1275
+ // error, not the host's own empty-upload business failure.
1276
+ const body =
1277
+ options.body ??
1278
+ new ReadableStream<Uint8Array>({
1279
+ start: (controller) => {
1280
+ controller.close()
1281
+ },
1282
+ })
1283
+ // The budget scales with the DECLARED size (T31-fix's rule); a timeout
1284
+ // deliberately does not move the connection state — a slow upload is a
1285
+ // slow call, not a dead link.
1286
+ const payload = await exchangeRequest(
1287
+ `${creds.url}${UPLOAD_PATH}?${params.toString()}`,
1288
+ uploadInit(creds.token, body),
1289
+ signal,
1290
+ true,
1291
+ { timeoutMs: sizeBackedTimeoutMs(requestTimeoutMs, options.bytes), timeoutSetsOffline: false, transportSetsOffline: false },
1292
+ )
1293
+ const value = payload.value
1294
+ if (
1295
+ !isRecord(value) ||
1296
+ typeof value.status !== 'number' ||
1297
+ !Number.isSafeInteger(value.status) ||
1298
+ typeof value.body !== 'string'
1299
+ ) {
1300
+ throw new RelayError('internal', 'the relay upload answer carries no upstream response')
1301
+ }
1302
+ return {
1303
+ status: value.status,
1304
+ contentType: typeof value.contentType === 'string' ? value.contentType : undefined,
1305
+ body: value.body,
1306
+ }
1307
+ }
1308
+
1309
+ function openStream(namespace: string, method: string, args: unknown, signal?: AbortSignal): AsyncIterable<unknown> {
1310
+ // Eager, not generator-lazy: an unconfigured client fails at CALL time,
1311
+ // exactly like connect/invoke, instead of hiding the error inside the
1312
+ // first next().
1313
+ requireCredentials()
1314
+ return streamLines(namespace, method, args, signal)
1315
+ }
1316
+
1317
+ /**
1318
+ * The NDJSON body pump. The request is owned by `controller`, which three
1319
+ * things may abort: the caller's signal (→ the iteration ends normally),
1320
+ * the idle clock (no line of any kind within `idleTimeoutMs` → offline),
1321
+ * and the generator's own exit — `break`, a thrown error line, normal
1322
+ * end — which tears the request down so the server's upstream does not
1323
+ * keep pumping behind a consumer that left.
1324
+ */
1325
+ async function* streamLines(
1326
+ namespace: string,
1327
+ method: string,
1328
+ args: unknown,
1329
+ signal: AbortSignal | undefined,
1330
+ ): AsyncGenerator<unknown> {
1331
+ if (signal?.aborted) return
1332
+ // Re-checked: the generator body runs at the first next(), so the
1333
+ // credentials may have vanished since openStream validated them.
1334
+ const { url, token } = requireCredentials()
1335
+ const controller = new AbortController()
1336
+ const onExternalAbort = (): void => {
1337
+ controller.abort()
1338
+ }
1339
+ if (signal !== undefined) signal.addEventListener('abort', onExternalAbort)
1340
+
1341
+ let idleFired = false
1342
+ let headersTimedOut = false
1343
+ let idleTimer: ReturnType<typeof setTimeout> | undefined
1344
+ const armIdle = (): void => {
1345
+ if (idleTimer !== undefined) clearTimeout(idleTimer)
1346
+ idleTimer = setTimeout(() => {
1347
+ idleFired = true
1348
+ controller.abort()
1349
+ }, idleTimeoutMs)
1350
+ if (typeof idleTimer.unref === 'function') idleTimer.unref()
1351
+ }
1352
+ const disarmIdle = (): void => {
1353
+ if (idleTimer !== undefined) {
1354
+ clearTimeout(idleTimer)
1355
+ idleTimer = undefined
1356
+ }
1357
+ }
1358
+ // Headers get the request timeout; the BODY is governed by the idle
1359
+ // clock alone — a healthy stream stays silent for hours. The timer is
1360
+ // disarmed the moment the response HEADERS arrive (it is cleared again
1361
+ // in the finally for the pre-header failure paths), or it would abort
1362
+ // every stream still alive past requestTimeoutMs (T23a-fix).
1363
+ const headerTimer = setTimeout(() => {
1364
+ headersTimedOut = true
1365
+ controller.abort()
1366
+ }, requestTimeoutMs)
1367
+ if (typeof headerTimer.unref === 'function') headerTimer.unref()
1368
+ // Hoisted for the teardown below: even a fetchImpl that ignores the
1369
+ // signal must have its response body released (T23a-fix).
1370
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
1371
+
1372
+ try {
1373
+ let response: Response
1374
+ try {
1375
+ response = await fetchImpl(`${url}${STREAM_PATH}`, {
1376
+ ...requestInit(token, JSON.stringify({ namespace, method, args })),
1377
+ signal: controller.signal,
1378
+ })
1379
+ } catch (error) {
1380
+ if (signal?.aborted) return
1381
+ noteFailure('offline')
1382
+ setState('offline')
1383
+ throw new RelayError('offline', headersTimedOut ? `no response within ${requestTimeoutMs} ms` : messageOf(error))
1384
+ }
1385
+ if (!response.ok) {
1386
+ // The NDJSON protocol only starts once the stream is allowed — a
1387
+ // refusal is the same JSON the invoke route answers, mapped the
1388
+ // same way. The header clock keeps guarding this leg: a server that
1389
+ // answers 4xx headers but never sends the body must not hang the
1390
+ // stream forever (T23a-fix2) — the abort lands here as offline.
1391
+ let payload: unknown
1392
+ try {
1393
+ payload = await readPayload(response)
1394
+ } catch (error) {
1395
+ if (signal?.aborted) return
1396
+ noteFailure('offline')
1397
+ setState('offline')
1398
+ throw new RelayError('offline', messageOf(error))
1399
+ }
1400
+ throw failureOf(response.status, payload)
1401
+ }
1402
+ // The 200 itself is a successful response: the link works. Only NOW
1403
+ // is the header phase truly over and its clock disarmed.
1404
+ clearTimeout(headerTimer)
1405
+ setState('online')
1406
+ if (response.body === null) return
1407
+ armIdle()
1408
+ const decoder = new TextDecoder()
1409
+ let buffer = ''
1410
+ reader = response.body.getReader()
1411
+ while (true) {
1412
+ const { done, value } = await reader.read()
1413
+ armIdle() // bytes arrived — any line content refreshes the clock
1414
+ if (done) break
1415
+ buffer += decoder.decode(value, { stream: true })
1416
+ let idx: number
1417
+ while ((idx = buffer.indexOf('\n')) >= 0) {
1418
+ const line = buffer.slice(0, idx)
1419
+ buffer = buffer.slice(idx + 1)
1420
+ const verdict = classifyLine(line)
1421
+ if (verdict.kind === 'frame') {
1422
+ // The idle clock measures TRANSPORT silence, not the consumer's
1423
+ // processing time: it is paused across the yield and re-armed
1424
+ // when the value is pulled.
1425
+ disarmIdle()
1426
+ yield verdict.frame
1427
+ armIdle()
1428
+ } else if (verdict.kind === 'end') {
1429
+ return
1430
+ } else if (verdict.kind === 'error') {
1431
+ noteServerRestart(verdict.error)
1432
+ throw verdict.error
1433
+ } else if (verdict.kind === 'info') {
1434
+ // T59: the heartbeat's names, folded in quietly — a state-sparing
1435
+ // notify wakes the interceptor's rename path without any reconnect.
1436
+ applyInfoDelta(verdict.serverName, verdict.deviceName)
1437
+ }
1438
+ }
1439
+ }
1440
+ // Tolerant tail: a final line without its newline still counts.
1441
+ buffer += decoder.decode()
1442
+ if (buffer.trim() !== '') {
1443
+ const verdict = classifyLine(buffer)
1444
+ if (verdict.kind === 'frame') {
1445
+ disarmIdle()
1446
+ yield verdict.frame
1447
+ } else if (verdict.kind === 'end') {
1448
+ return
1449
+ } else if (verdict.kind === 'error') {
1450
+ noteServerRestart(verdict.error)
1451
+ throw verdict.error
1452
+ } else if (verdict.kind === 'info') {
1453
+ applyInfoDelta(verdict.serverName, verdict.deviceName)
1454
+ }
1455
+ }
1456
+ } catch (error) {
1457
+ if (signal?.aborted) return
1458
+ if (error instanceof RelayError) throw error
1459
+ // Anything else escaping the body read is the transport dying.
1460
+ noteFailure('offline')
1461
+ setState('offline')
1462
+ throw new RelayError('offline', idleFired ? `no line received for ${idleTimeoutMs} ms` : messageOf(error))
1463
+ } finally {
1464
+ disarmIdle()
1465
+ clearTimeout(headerTimer)
1466
+ if (signal !== undefined) signal.removeEventListener('abort', onExternalAbort)
1467
+ // Release the body even if a custom fetchImpl ignored the signal —
1468
+ // an in-flight reader keeps the connection's buffers alive. Cancel
1469
+ // may reject on an already-dead stream; that is fine.
1470
+ if (reader !== undefined) reader.cancel().catch(() => {})
1471
+ // However we left the body — break, error line, normal end, caller
1472
+ // abort — the request itself must not linger: the server aborts its
1473
+ // upstream when the socket closes. Aborting a finished request is a
1474
+ // no-op.
1475
+ controller.abort()
1476
+ }
1477
+ }
1478
+
1479
+ return {
1480
+ get state(): RelayState {
1481
+ return state
1482
+ },
1483
+ get handshakeInfo(): RelayHandshake | undefined {
1484
+ return handshakeInfo
1485
+ },
1486
+ get lastHandshakeDigest(): string | undefined {
1487
+ return lastHandshakeDigest
1488
+ },
1489
+ get nextRetryAt(): number | null {
1490
+ return nextRetryAt
1491
+ },
1492
+ get lastError(): string | undefined {
1493
+ return lastError
1494
+ },
1495
+ get compat(): RelayCompatVerdict | undefined {
1496
+ return compat
1497
+ },
1498
+ get deviceNameSyncing(): boolean {
1499
+ return deviceNameSyncing()
1500
+ },
1501
+ subscribe,
1502
+ queueDeviceName,
1503
+ connect,
1504
+ reconnect,
1505
+ credentialsChanged,
1506
+ stop,
1507
+ invoke,
1508
+ unshare,
1509
+ postEventResult,
1510
+ openStream,
1511
+ http,
1512
+ upload,
1513
+ }
1514
+ }