@openchamber/web 1.14.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
  8. package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
  9. package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
  10. package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
  12. package/dist/assets/es-r0_jT91q.js +15 -0
  13. package/dist/assets/fr-Bo8rtAJ1.js +13 -0
  14. package/dist/assets/index-8J6waVO6.js +2 -0
  15. package/dist/assets/index-DEMqM4Lz.css +1 -0
  16. package/dist/assets/ja-BPWtkG-c.js +15 -0
  17. package/dist/assets/ko-Bv0k-0E3.js +15 -0
  18. package/dist/assets/main-B-GA5Tg5.js +237 -0
  19. package/dist/assets/main-Dfm-VKZ9.js +2 -0
  20. package/dist/assets/miniChat-CfmCFFfu.js +2 -0
  21. package/dist/assets/mobile-CXJqeDlm.js +2 -0
  22. package/dist/assets/pl-CiTP50bz.js +15 -0
  23. package/dist/assets/pt-BR-DadIjX5L.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
  25. package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
  27. package/dist/assets/uk-2RpsWGoZ.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
  31. package/dist/assets/zh-TW--f_BqBpD.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +236 -2
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  41. package/server/lib/notifications/apns-runtime.js +11 -16
  42. package/server/lib/notifications/runtime.js +135 -33
  43. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  44. package/server/lib/opencode/agents.js +3 -0
  45. package/server/lib/opencode/bootstrap-runtime.js +15 -0
  46. package/server/lib/opencode/core-routes.js +321 -8
  47. package/server/lib/opencode/core-routes.test.js +329 -9
  48. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  49. package/server/lib/opencode/network-runtime.js +14 -1
  50. package/server/lib/opencode/network-runtime.test.js +29 -9
  51. package/server/lib/opencode/proxy.js +47 -6
  52. package/server/lib/opencode/settings-helpers.js +24 -0
  53. package/server/lib/opencode/settings-helpers.test.js +25 -0
  54. package/server/lib/opencode/settings-normalization-runtime.js +21 -4
  55. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  56. package/server/lib/opencode/settings-runtime.js +25 -0
  57. package/server/lib/opencode/shutdown-runtime.js +2 -0
  58. package/server/lib/opencode/tunnel-auth.js +4 -9
  59. package/server/lib/package-manager.js +18 -5
  60. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  61. package/server/lib/permission-auto-accept/runtime.js +263 -0
  62. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  63. package/server/lib/projects/project-config.js +8 -0
  64. package/server/lib/quota/DOCUMENTATION.md +5 -2
  65. package/server/lib/quota/credentials/providers.js +43 -0
  66. package/server/lib/quota/credentials/store.js +48 -0
  67. package/server/lib/quota/credentials/store.test.js +26 -0
  68. package/server/lib/quota/opencode-go-credentials.js +11 -0
  69. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  70. package/server/lib/quota/providers/codex.js +7 -4
  71. package/server/lib/quota/providers/codex.test.js +48 -0
  72. package/server/lib/quota/providers/cursor.js +28 -39
  73. package/server/lib/quota/providers/index.js +7 -0
  74. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  75. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  76. package/server/lib/quota/providers/opencode-go.js +70 -0
  77. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  78. package/server/lib/quota/routes.js +78 -7
  79. package/server/lib/quota/routes.test.js +40 -0
  80. package/server/lib/relay/DOCUMENTATION.md +98 -0
  81. package/server/lib/relay/cross-compat.test.js +135 -0
  82. package/server/lib/relay/e2ee.js +341 -0
  83. package/server/lib/relay/e2ee.test.js +124 -0
  84. package/server/lib/relay/host-client.js +389 -0
  85. package/server/lib/relay/host-client.test.js +280 -0
  86. package/server/lib/relay/host-lock.js +101 -0
  87. package/server/lib/relay/host-lock.test.js +129 -0
  88. package/server/lib/relay/identity.js +93 -0
  89. package/server/lib/relay/identity.test.js +78 -0
  90. package/server/lib/relay/service.js +334 -0
  91. package/server/lib/relay/signing-key.js +73 -0
  92. package/server/lib/relay/tunnel-codec.js +373 -0
  93. package/server/lib/relay/tunnel-codec.test.js +58 -0
  94. package/server/lib/relay/tunnel-host.js +462 -0
  95. package/server/lib/scheduled-tasks/runtime.js +104 -0
  96. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  97. package/server/lib/session-goal/objectives.js +61 -0
  98. package/server/lib/session-goal/routes.js +36 -0
  99. package/server/lib/session-goal/runtime.js +764 -0
  100. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  101. package/server/lib/ui-auth/ui-auth.js +10 -0
  102. package/server/opencode-proxy.test.js +38 -0
  103. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  104. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  105. package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
  106. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  107. package/dist/assets/es-bWcuDy_2.js +0 -15
  108. package/dist/assets/fr-DzRs3OzV.js +0 -13
  109. package/dist/assets/index-KnWk9fmM.css +0 -1
  110. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  111. package/dist/assets/ja-BqUX_UD3.js +0 -15
  112. package/dist/assets/ko-BQo10SNx.js +0 -15
  113. package/dist/assets/main-BDoqLlQB.js +0 -236
  114. package/dist/assets/main-DUGyTrDt.js +0 -2
  115. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  116. package/dist/assets/mobile-DnghtOCb.js +0 -2
  117. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  118. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  119. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  120. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  121. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  122. package/dist/assets/uk-C9k8SP8q.js +0 -15
  123. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  124. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
@@ -0,0 +1,334 @@
1
+ // Private relay service: config persistence, lifecycle of the relay host
2
+ // client, and the /api/openchamber/relay/* management routes.
3
+ //
4
+ // Config lives in the server settings file as `settings.privateRelay =
5
+ // { enabled, relayUrl }` (same storage precedent as tunnels/notifications).
6
+ // Routes are registered with the other OpenChamber feature routes, before the
7
+ // generic OpenCode proxy, and are covered by the same global UI auth gate.
8
+ //
9
+ // Cross-runtime parity note: relay host mode intentionally targets the web
10
+ // server runtime only in v1 (Electron shares this server in-process). The VS
11
+ // Code runtime does not host a relay; shared UI must treat these routes as
12
+ // web-runtime capabilities.
13
+
14
+ import express from 'express';
15
+
16
+ import { createRelayIdentityRuntime } from './identity.js';
17
+ import { startRelayHost } from './host-client.js';
18
+
19
+ export const DEFAULT_RELAY_URL = 'wss://relay.openchamber.dev/ws';
20
+
21
+ const isValidRelayUrl = (value) => {
22
+ if (typeof value !== 'string') return false;
23
+ try {
24
+ const url = new URL(value.trim());
25
+ return url.protocol === 'ws:' || url.protocol === 'wss:';
26
+ } catch {
27
+ return false;
28
+ }
29
+ };
30
+
31
+ const normalizeRelayUrl = (value) => {
32
+ if (typeof value !== 'string') return DEFAULT_RELAY_URL;
33
+ const trimmed = value.trim();
34
+ if (!trimmed || !isValidRelayUrl(trimmed)) return DEFAULT_RELAY_URL;
35
+ return trimmed;
36
+ };
37
+
38
+ // A deployment can pin the relay endpoint via env (e.g. a self-hosted relay on
39
+ // your own Cloudflare account/domain). When set and valid it overrides the
40
+ // stored setting entirely, so the host connection, the pairing offer, and the
41
+ // status all point at it — clients then inherit it from the offer automatically.
42
+ const envRelayUrlOverride = () => {
43
+ const raw = process.env.OPENCHAMBER_RELAY_URL;
44
+ if (typeof raw !== 'string' || !raw.trim() || !isValidRelayUrl(raw)) return null;
45
+ return raw.trim();
46
+ };
47
+
48
+ /**
49
+ * @param {{
50
+ * crypto: typeof import('node:crypto'),
51
+ * readSettingsFromDiskMigrated: () => Promise<object>,
52
+ * writeSettingsToDisk: (settings: object) => Promise<void>,
53
+ * getLocalPort: () => number,
54
+ * logger?: Pick<Console, 'warn'>,
55
+ * }} deps
56
+ */
57
+ export const createRelayService = ({
58
+ crypto,
59
+ readSettingsFromDiskMigrated,
60
+ writeSettingsToDisk,
61
+ // Strict settings reader (throws on corrupt/unreadable) gating identity
62
+ // regeneration — see identity.js/signing-key.js.
63
+ readSettingsStrict,
64
+ getLocalPort,
65
+ // Returns true when any paired device or pending pairing session uses the
66
+ // relay transport. The relay lifecycle is driven purely by this demand.
67
+ hasRelayDemand = async () => false,
68
+ // Per-machine claim (host-lock.js): all local instances share the same
69
+ // serverId, so only ONE process may run the relay host at a time or they
70
+ // evict each other at the relay worker ("Control replaced") and devices land
71
+ // on a random instance. Optional: without it, behavior is pre-lock.
72
+ hostLock = null,
73
+ logger = console,
74
+ }) => {
75
+ const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
76
+
77
+ let hostClient = null;
78
+ let status = { state: 'disabled', lastError: null, connectedClients: 0 };
79
+ // Re-checks the claim while enabled: a standby instance takes over when the
80
+ // claimant dies; a running host stands down when another process claims.
81
+ let claimWatchTimer = null;
82
+ const CLAIM_WATCH_INTERVAL_MS = 30_000;
83
+
84
+ const readConfig = async () => {
85
+ const settings = await readSettingsFromDiskMigrated();
86
+ const stored = settings?.privateRelay;
87
+ const override = envRelayUrlOverride();
88
+ return {
89
+ enabled: stored?.enabled === true,
90
+ relayUrl: override ?? normalizeRelayUrl(stored?.relayUrl),
91
+ // True when the endpoint is pinned by OPENCHAMBER_RELAY_URL (a self-hosted
92
+ // relay); the stored setting is ignored while it is set.
93
+ relayUrlLocked: override !== null,
94
+ };
95
+ };
96
+
97
+ const writeConfig = async (config) => {
98
+ const settings = await readSettingsFromDiskMigrated();
99
+ await writeSettingsToDisk({
100
+ ...settings,
101
+ privateRelay: { enabled: config.enabled === true, relayUrl: normalizeRelayUrl(config.relayUrl) },
102
+ });
103
+ };
104
+
105
+ const stopHostClient = () => {
106
+ if (!hostClient) return;
107
+ hostClient.stop();
108
+ hostClient = null;
109
+ };
110
+
111
+ const standbyStatus = (holderPid) => ({
112
+ state: 'standby',
113
+ lastError: `relay host is owned by another local OpenChamber process (pid ${holderPid})`,
114
+ connectedClients: 0,
115
+ });
116
+
117
+ // Claim watcher, active while the relay is enabled:
118
+ // - standby → claimant died → take over (start our host);
119
+ // - running → another live process claimed → stand down (stop, standby).
120
+ // This back-off is what actually ends the mutual-eviction fight: the loser
121
+ // must STOP reconnecting, otherwise both keep replacing each other forever.
122
+ const ensureClaimWatch = (relayUrl) => {
123
+ if (!hostLock || claimWatchTimer) return;
124
+ claimWatchTimer = setInterval(() => {
125
+ void (async () => {
126
+ try {
127
+ if (hostClient) {
128
+ if (!hostLock.holdsClaim() && hostLock.liveClaimantPid() !== null) {
129
+ logger.warn('[Relay] host claim taken by another local instance — standing down');
130
+ const holder = hostLock.liveClaimantPid();
131
+ stopHostClient();
132
+ status = standbyStatus(holder);
133
+ }
134
+ return;
135
+ }
136
+ if (status.state === 'standby' && hostLock.tryClaim()) {
137
+ logger.warn('[Relay] host claim is free — taking over the relay host');
138
+ await start(relayUrl);
139
+ }
140
+ } catch (error) {
141
+ logger.warn(`[Relay] claim watch failed: ${error?.message ?? error}`);
142
+ }
143
+ })();
144
+ }, CLAIM_WATCH_INTERVAL_MS);
145
+ if (typeof claimWatchTimer.unref === 'function') claimWatchTimer.unref();
146
+ };
147
+
148
+ const stopClaimWatch = () => {
149
+ if (!claimWatchTimer) return;
150
+ clearInterval(claimWatchTimer);
151
+ claimWatchTimer = null;
152
+ };
153
+
154
+ const start = async (relayUrl, { claim = 'try' } = {}) => {
155
+ if (hostClient) return;
156
+ if (hostLock) {
157
+ const claimed = claim === 'force' ? hostLock.forceClaim() : hostLock.tryClaim();
158
+ if (!claimed) {
159
+ status = standbyStatus(hostLock.liveClaimantPid());
160
+ ensureClaimWatch(relayUrl);
161
+ return;
162
+ }
163
+ }
164
+ const identity = await identityRuntime.getRelayIdentity();
165
+ hostClient = startRelayHost({
166
+ relayUrl,
167
+ identity,
168
+ getLocalPort,
169
+ logger,
170
+ onStatus: (next) => {
171
+ status = next;
172
+ },
173
+ });
174
+ status = hostClient.getStatus();
175
+ ensureClaimWatch(relayUrl);
176
+ };
177
+
178
+ const stop = () => {
179
+ stopClaimWatch();
180
+ stopHostClient();
181
+ if (hostLock) hostLock.release();
182
+ status = { state: 'disabled', lastError: null, connectedClients: 0 };
183
+ };
184
+
185
+ const startIfEnabled = async () => {
186
+ try {
187
+ const config = await readConfig();
188
+ if (config.enabled) {
189
+ await start(config.relayUrl);
190
+ }
191
+ } catch (error) {
192
+ logger.warn(`[Relay] startup failed: ${error?.message ?? error}`);
193
+ }
194
+ };
195
+
196
+ // Drive the relay lifecycle from demand: run it when a device or pending
197
+ // session uses the relay, stop it when none remain. Called on startup and after
198
+ // pairing/device changes, so the operator never toggles it manually.
199
+ const reconcile = async () => {
200
+ try {
201
+ const demand = await hasRelayDemand();
202
+ const config = await readConfig();
203
+ if (demand) {
204
+ if (!config.enabled) await writeConfig({ enabled: true, relayUrl: config.relayUrl });
205
+ if (!hostClient) {
206
+ const next = await readConfig();
207
+ await start(next.relayUrl);
208
+ }
209
+ } else {
210
+ if (config.enabled) await writeConfig({ enabled: false, relayUrl: config.relayUrl });
211
+ stop();
212
+ }
213
+ } catch (error) {
214
+ logger.warn(`[Relay] reconcile failed: ${error?.message ?? error}`);
215
+ }
216
+ };
217
+
218
+ // Stable server identity (base64url SHA-256 of the canonical public signing
219
+ // JWK). Derived from a public key, so it is not a secret; clients use it to
220
+ // verify that a learned/probed address belongs to this server before trusting
221
+ // it. Independent of whether the relay host is currently enabled.
222
+ const getServerId = async () => {
223
+ const identity = await identityRuntime.getRelayIdentity();
224
+ return identity.serverId;
225
+ };
226
+
227
+ const getStatus = async () => {
228
+ const config = await readConfig();
229
+ const identity = await identityRuntime.getRelayIdentity();
230
+ const live = hostClient ? hostClient.getStatus() : status;
231
+ return {
232
+ enabled: config.enabled,
233
+ // Without a host client the service is either off or standing by while
234
+ // another local process owns the machine's relay host claim.
235
+ state: hostClient ? live.state : (status.state === 'standby' ? 'standby' : 'disabled'),
236
+ serverId: identity.serverId,
237
+ connectedClients: live.connectedClients,
238
+ relayUrl: config.relayUrl,
239
+ relayUrlLocked: config.relayUrlLocked,
240
+ ...(live.lastError ? { lastError: live.lastError } : {}),
241
+ };
242
+ };
243
+
244
+ // Pairing candidate for the unified connection payload (pairing v2). Relay is
245
+ // just another transport: it carries the relay route + E2EE trust anchor, no
246
+ // embedded token — the client redeems the one-time pairing secret over the
247
+ // tunnel like any other candidate. Returns null when the host relay is off, so
248
+ // callers only advertise relay when it is actually reachable. Priority is high
249
+ // (tried after LAN/tunnel) since the relay path is the last-resort transport.
250
+ const buildPairingCandidate = async () => {
251
+ const config = await readConfig();
252
+ const identity = await identityRuntime.getRelayIdentity();
253
+ return {
254
+ type: 'relay',
255
+ relayUrl: config.relayUrl,
256
+ serverId: identity.serverId,
257
+ hostEncPubJwk: identity.hostEncPubJwk,
258
+ priority: 30,
259
+ };
260
+ };
261
+
262
+ const getPairingCandidate = async () => {
263
+ const config = await readConfig();
264
+ if (!config.enabled) return null;
265
+ return buildPairingCandidate();
266
+ };
267
+
268
+ // Enable the relay host on demand and return its pairing candidate. Creating a
269
+ // relay pairing link IS the demand signal, so the relay turns itself on here
270
+ // rather than requiring a separate manual toggle. Idempotent: a no-op when the
271
+ // relay is already enabled and running.
272
+ const ensureEnabledForPairing = async () => {
273
+ const config = await readConfig();
274
+ if (!config.enabled) {
275
+ await writeConfig({ enabled: true, relayUrl: config.relayUrl });
276
+ }
277
+ if (!hostClient) {
278
+ const next = await readConfig();
279
+ // Force-claim: creating a pairing link is explicit user intent — the
280
+ // instance the user is pairing against MUST be the one devices reach,
281
+ // even if another local process currently holds the machine's claim
282
+ // (its claim watcher sees the takeover and stands down).
283
+ await start(next.relayUrl, { claim: 'force' });
284
+ }
285
+ return buildPairingCandidate();
286
+ };
287
+
288
+ const registerRoutes = (app) => {
289
+ app.get('/api/openchamber/relay/status', async (_req, res) => {
290
+ try {
291
+ res.json(await getStatus());
292
+ } catch (error) {
293
+ res.status(500).json({ error: error?.message ?? 'Failed to read relay status' });
294
+ }
295
+ });
296
+
297
+ app.post('/api/openchamber/relay/enable', express.json({ limit: '16kb' }), async (req, res) => {
298
+ try {
299
+ const current = await readConfig();
300
+ const relayUrl = typeof req.body?.relayUrl === 'string' ? normalizeRelayUrl(req.body.relayUrl) : current.relayUrl;
301
+ await writeConfig({ enabled: true, relayUrl });
302
+ if (hostClient) stop();
303
+ // Explicit user action: take the machine's host claim like pairing does.
304
+ await start(relayUrl, { claim: 'force' });
305
+ res.json(await getStatus());
306
+ } catch (error) {
307
+ res.status(500).json({ error: error?.message ?? 'Failed to enable relay' });
308
+ }
309
+ });
310
+
311
+ app.post('/api/openchamber/relay/disable', async (_req, res) => {
312
+ try {
313
+ const current = await readConfig();
314
+ await writeConfig({ enabled: false, relayUrl: current.relayUrl });
315
+ stop();
316
+ res.json(await getStatus());
317
+ } catch (error) {
318
+ res.status(500).json({ error: error?.message ?? 'Failed to disable relay' });
319
+ }
320
+ });
321
+
322
+ };
323
+
324
+ return {
325
+ registerRoutes,
326
+ startIfEnabled,
327
+ reconcile,
328
+ stop,
329
+ getStatus,
330
+ getServerId,
331
+ getPairingCandidate,
332
+ ensureEnabledForPairing,
333
+ };
334
+ };
@@ -0,0 +1,73 @@
1
+ // Per-server relay signing identity (ECDSA P-256), extracted from
2
+ // lib/notifications/apns-runtime.js so both the push relay and the private
3
+ // relay share the SAME keypair and thus the SAME serverId
4
+ // (base64url(SHA-256(canonical public JWK))). Storage format is unchanged:
5
+ // `settings.relaySigningKey = { privateJwk, publicJwk }` — existing installs'
6
+ // serverId must stay stable because push token binding depends on it.
7
+
8
+ /**
9
+ * @param {{
10
+ * crypto: typeof import('node:crypto'),
11
+ * readSettingsFromDiskMigrated: () => Promise<object>,
12
+ * writeSettingsToDisk: (settings: object) => Promise<void>,
13
+ * readSettingsStrict?: () => Promise<object>,
14
+ * }} deps
15
+ * @returns {Promise<{ privateKey: import('node:crypto').KeyObject, publicJwk: JsonWebKey }>}
16
+ */
17
+ export const getOrCreateRelaySigningKeypair = async ({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict }) => {
18
+ const toKeypair = (stored) => ({
19
+ privateKey: crypto.createPrivateKey({ key: stored.privateJwk, format: 'jwk' }),
20
+ publicJwk: stored.publicJwk,
21
+ });
22
+ const settings = await readSettingsFromDiskMigrated();
23
+ const existing = settings?.relaySigningKey;
24
+ if (existing && existing.privateJwk && existing.publicJwk) {
25
+ return toKeypair(existing);
26
+ }
27
+ // Regeneration gate: the lenient settings reader maps read failures to `{}`,
28
+ // indistinguishable from "first run". Minting a new keypair changes serverId,
29
+ // which orphans every paired device and push binding AND the write below would
30
+ // clobber the settings file with the empty spread. Re-verify with the strict
31
+ // reader (throws on corrupt/unreadable) before generating; if it finds the
32
+ // key the lenient read lost, use it and generate nothing.
33
+ let verifiedSettings = settings;
34
+ if (readSettingsStrict) {
35
+ verifiedSettings = await readSettingsStrict();
36
+ const verified = verifiedSettings?.relaySigningKey;
37
+ if (verified && verified.privateJwk && verified.publicJwk) {
38
+ return toKeypair(verified);
39
+ }
40
+ }
41
+ // Loud on purpose: a new signing key means a new serverId — every previously
42
+ // paired device and push binding is orphaned. Expected exactly once, on first run.
43
+ console.warn('[relay-identity] Generating NEW relay signing keypair (serverId changes; previously paired devices must re-pair)');
44
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
45
+ const privateJwk = privateKey.export({ format: 'jwk' });
46
+ const publicJwk = publicKey.export({ format: 'jwk' });
47
+ await writeSettingsToDisk({ ...settings, ...(verifiedSettings || {}), relaySigningKey: { privateJwk, publicJwk } });
48
+ return { privateKey, publicJwk };
49
+ };
50
+
51
+ // Fixed key order so the hash is stable regardless of stored JSON field order.
52
+ // Byte-for-byte mirror of canonicalJwk in openchamber-website apps/api relay-auth.ts.
53
+ /** @param {JsonWebKey} jwk */
54
+ export const canonicalPublicJwkString = (jwk) =>
55
+ JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
56
+
57
+ /**
58
+ * serverId = base64url(SHA-256(canonical public JWK)). Must match the push
59
+ * relay's deriveServerId — this id is the routing key for both relays.
60
+ * @param {{ crypto: typeof import('node:crypto') }} deps
61
+ * @param {JsonWebKey} publicJwk
62
+ */
63
+ export const deriveServerId = ({ crypto }, publicJwk) =>
64
+ crypto.createHash('sha256').update(canonicalPublicJwkString(publicJwk)).digest('base64url');
65
+
66
+ /**
67
+ * ECDSA-SHA256, IEEE P1363 (raw r||s) signature — the form WebCrypto verifies.
68
+ * @param {{ crypto: typeof import('node:crypto') }} deps
69
+ * @param {import('node:crypto').KeyObject} privateKey
70
+ * @param {string} message
71
+ */
72
+ export const signRelayMessage = ({ crypto }, privateKey, message) =>
73
+ crypto.sign('SHA256', Buffer.from(message), { key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');