@openchamber/web 1.14.1 → 1.15.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 (87) 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-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-4FWg9xMC.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DzBg8hrC.js} +123 -119
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.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 +130 -1
  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/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +246 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/network-runtime.js +14 -1
  45. package/server/lib/opencode/network-runtime.test.js +29 -9
  46. package/server/lib/opencode/proxy.js +47 -6
  47. package/server/lib/opencode/settings-helpers.js +3 -0
  48. package/server/lib/opencode/settings-helpers.test.js +11 -0
  49. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  50. package/server/lib/package-manager.js +18 -5
  51. package/server/lib/relay/DOCUMENTATION.md +78 -0
  52. package/server/lib/relay/cross-compat.test.js +135 -0
  53. package/server/lib/relay/e2ee.js +341 -0
  54. package/server/lib/relay/e2ee.test.js +124 -0
  55. package/server/lib/relay/host-client.js +389 -0
  56. package/server/lib/relay/host-client.test.js +280 -0
  57. package/server/lib/relay/identity.js +73 -0
  58. package/server/lib/relay/identity.test.js +78 -0
  59. package/server/lib/relay/service.js +247 -0
  60. package/server/lib/relay/signing-key.js +50 -0
  61. package/server/lib/relay/tunnel-codec.js +373 -0
  62. package/server/lib/relay/tunnel-codec.test.js +58 -0
  63. package/server/lib/relay/tunnel-host.js +462 -0
  64. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  65. package/server/lib/ui-auth/ui-auth.js +10 -0
  66. package/server/opencode-proxy.test.js +38 -0
  67. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  68. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  69. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  70. package/dist/assets/es-bWcuDy_2.js +0 -15
  71. package/dist/assets/fr-DzRs3OzV.js +0 -13
  72. package/dist/assets/index-KnWk9fmM.css +0 -1
  73. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  74. package/dist/assets/ja-BqUX_UD3.js +0 -15
  75. package/dist/assets/ko-BQo10SNx.js +0 -15
  76. package/dist/assets/main-BDoqLlQB.js +0 -236
  77. package/dist/assets/main-DUGyTrDt.js +0 -2
  78. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  79. package/dist/assets/mobile-DnghtOCb.js +0 -2
  80. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  81. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  82. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  83. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  84. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  85. package/dist/assets/uk-C9k8SP8q.js +0 -15
  86. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  87. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
package/dist/index.html CHANGED
@@ -515,11 +515,11 @@
515
515
  pointer-events: none;
516
516
  }
517
517
  </style>
518
- <script type="module" crossorigin src="/assets/main-DUGyTrDt.js"></script>
519
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
520
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
518
+ <script type="module" crossorigin src="/assets/main-DzNa8r0N.js"></script>
519
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
520
+ <link rel="modulepreload" crossorigin href="/assets/index-ltrmNGAf.js">
521
521
  <link rel="modulepreload" crossorigin href="/assets/mobileLayoutPreference-Dio-WWkI.js">
522
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
522
+ <link rel="stylesheet" crossorigin href="/assets/index-Dg0nmvQU.css">
523
523
  </head>
524
524
  <body class="h-full bg-background text-foreground">
525
525
  <div id="root" class="h-full">
@@ -74,10 +74,10 @@
74
74
  }
75
75
  </style>
76
76
 
77
- <script type="module" crossorigin src="/assets/miniChat-DNDiX8GA.js"></script>
78
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
79
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
80
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
77
+ <script type="module" crossorigin src="/assets/miniChat-BRYDE-Se.js"></script>
78
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
79
+ <link rel="modulepreload" crossorigin href="/assets/index-ltrmNGAf.js">
80
+ <link rel="stylesheet" crossorigin href="/assets/index-Dg0nmvQU.css">
81
81
  </head>
82
82
  <body class="h-full bg-background text-foreground">
83
83
  <div id="root" class="h-full">
package/dist/mobile.html CHANGED
@@ -63,10 +63,10 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-DnghtOCb.js"></script>
67
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
68
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
69
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
66
+ <script type="module" crossorigin src="/assets/mobile-C3QJVA97.js"></script>
67
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
68
+ <link rel="modulepreload" crossorigin href="/assets/index-ltrmNGAf.js">
69
+ <link rel="stylesheet" crossorigin href="/assets/index-Dg0nmvQU.css">
70
70
  </head>
71
71
  <body class="h-full bg-background text-foreground">
72
72
  <div id="root" class="h-full"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openchamber/web",
3
- "version": "1.14.1",
3
+ "version": "1.15.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./server/index.js",
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "@clack/prompts": "^1.1.0",
27
27
  "@octokit/rest": "^22.0.1",
28
- "@opencode-ai/sdk": "1.17.12",
28
+ "@opencode-ai/sdk": "1.17.18",
29
29
  "@simplewebauthn/server": "13.3.1",
30
30
  "adm-zip": "^0.5.16",
31
31
  "better-sqlite3": "^12.10.0",
package/server/index.js CHANGED
@@ -87,8 +87,10 @@ import { createNotificationTemplateRuntime } from './lib/notifications/template-
87
87
  import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
88
88
  import { createProjectConfigRuntime } from './lib/projects/project-config.js';
89
89
  import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
90
+ import { createClientPairingRuntime } from './lib/client-auth/pairing.js';
90
91
  import { createPreviewProxyRuntime } from './lib/preview/proxy-runtime.js';
91
92
  import { attachRealtimeProxy } from './lib/realtime-proxy.js';
93
+ import { createRelayService } from './lib/relay/service.js';
92
94
  import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
93
95
  import webPush from 'web-push';
94
96
 
@@ -281,6 +283,7 @@ const SETTINGS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'settings.json');
281
283
  const PUSH_SUBSCRIPTIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'push-subscriptions.json');
282
284
  const APNS_TOKENS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'apns-tokens.json');
283
285
  const REMOTE_CLIENTS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'remote-clients.json');
286
+ const CLIENT_PAIRING_SESSIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'client-pairing-sessions.json');
284
287
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-managed-remote-tunnels.json');
285
288
  const CLOUDFLARE_LEGACY_NAMED_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-named-tunnels.json');
286
289
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_VERSION = 1;
@@ -602,6 +605,7 @@ Object.defineProperties(openCodeNetworkState, {
602
605
  const openCodeNetworkRuntime = createOpenCodeNetworkRuntime({
603
606
  state: openCodeNetworkState,
604
607
  getOpenCodeAuthHeaders,
608
+ configuredOpenCodeHostname: ENV_CONFIGURED_OPENCODE_HOSTNAME,
605
609
  });
606
610
 
607
611
  const waitForReady = (...args) => openCodeNetworkRuntime.waitForReady(...args);
@@ -871,6 +875,13 @@ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({
871
875
  crypto,
872
876
  storePath: REMOTE_CLIENTS_FILE_PATH,
873
877
  });
878
+ const clientPairingRuntime = createClientPairingRuntime({
879
+ fsPromises,
880
+ path,
881
+ crypto,
882
+ storePath: CLIENT_PAIRING_SESSIONS_FILE_PATH,
883
+ remoteClientAuthRuntime,
884
+ });
874
885
  const featureRoutesRuntime = createFeatureRoutesRuntime({
875
886
  clientReloadDelayMs: CLIENT_RELOAD_DELAY_MS,
876
887
  });
@@ -1100,6 +1111,52 @@ async function main(options = {}) {
1100
1111
  || (typeof process.env.OPENCHAMBER_HOST === 'string' && process.env.OPENCHAMBER_HOST.trim().length > 0
1101
1112
  ? process.env.OPENCHAMBER_HOST.trim()
1102
1113
  : '127.0.0.1');
1114
+
1115
+ // Pairing transports advertised to the create-device dialog. LAN reachability is
1116
+ // derived from the SERVER's actual bind (a wildcard bind → the machine's LAN IP;
1117
+ // a specific non-loopback host → that host), NOT from how the UI was opened — so
1118
+ // "Local network" works even when the UI is opened on localhost, and is absent
1119
+ // when the server is only bound to loopback (a LAN link would not connect).
1120
+ // The IPv4 the requesting client actually reached this server on (if any).
1121
+ // Strips the IPv6-mapped prefix; loopback means "not a LAN path".
1122
+ const requestReachedLanAddress = (req) => {
1123
+ const raw = typeof req?.socket?.localAddress === 'string' ? req.socket.localAddress : '';
1124
+ const address = raw.startsWith('::ffff:') ? raw.slice(7) : raw;
1125
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(address)) return null;
1126
+ if (address.startsWith('127.')) return null;
1127
+ return address;
1128
+ };
1129
+ const resolvePairingTransports = (req) => {
1130
+ const activePort = tunnelRuntimeContext.getActivePort() || port;
1131
+ const local = `http://127.0.0.1:${activePort}`;
1132
+ let lanHost = null;
1133
+ if (isNetworkExposedBindHost(effectiveBindHost)) {
1134
+ // Prefer the address the client is ALREADY talking to us on — it is the
1135
+ // one interface guaranteed to be routable from that client's network.
1136
+ // Interface scanning is only a fallback: on servers with virtual bridges
1137
+ // (docker0 etc.) the first non-internal IPv4 can be an address no other
1138
+ // machine can reach, which produced pairing links whose LAN candidate
1139
+ // silently failed and forced devices onto the relay.
1140
+ lanHost = requestReachedLanAddress(req);
1141
+ try {
1142
+ if (!lanHost) {
1143
+ for (const list of Object.values(os.networkInterfaces())) {
1144
+ for (const entry of (list || [])) {
1145
+ if (entry.family === 'IPv4' && !entry.internal) { lanHost = entry.address; break; }
1146
+ }
1147
+ if (lanHost) break;
1148
+ }
1149
+ }
1150
+ } catch {
1151
+ lanHost = null;
1152
+ }
1153
+ } else {
1154
+ const h = String(effectiveBindHost || '').toLowerCase();
1155
+ if (h && h !== '127.0.0.1' && h !== 'localhost' && h !== '::1') lanHost = effectiveBindHost;
1156
+ }
1157
+ const lan = lanHost ? `http://${lanHost.includes(':') ? `[${lanHost}]` : lanHost}:${activePort}` : null;
1158
+ return { local, lan, relayAvailable: true };
1159
+ };
1103
1160
  const uiPassword = typeof options.uiPassword === 'string'
1104
1161
  ? options.uiPassword
1105
1162
  : (typeof process.env.OPENCHAMBER_UI_PASSWORD === 'string' ? process.env.OPENCHAMBER_UI_PASSWORD : null);
@@ -1181,7 +1238,7 @@ async function main(options = {}) {
1181
1238
  res.setHeader('Access-Control-Allow-Origin', origin);
1182
1239
  res.setHeader('Access-Control-Allow-Credentials', 'true');
1183
1240
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
1184
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory');
1241
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding');
1185
1242
  res.setHeader('Access-Control-Expose-Headers', 'x-next-cursor');
1186
1243
  res.setHeader('Vary', 'Origin');
1187
1244
  if (req.method === 'OPTIONS') {
@@ -1202,6 +1259,11 @@ async function main(options = {}) {
1202
1259
  server = http.createServer(app);
1203
1260
  let realtimeProxyRuntime = { stop: () => {} };
1204
1261
 
1262
+ // The relay service is constructed further below (it depends on the tunnel
1263
+ // runtime's active port). The pairing routes registered here only read the
1264
+ // relay candidate lazily at request time, so a late-bound holder is enough.
1265
+ let relayServiceInstance = null;
1266
+
1205
1267
  const bootstrapResult = bootstrapRuntime.setupBaseRoutes(app, {
1206
1268
  process,
1207
1269
  openchamberVersion: OPENCHAMBER_VERSION,
@@ -1242,6 +1304,30 @@ async function main(options = {}) {
1242
1304
  uiPassword,
1243
1305
  tunnelAuthController,
1244
1306
  remoteClientAuthRuntime,
1307
+ clientPairingRuntime,
1308
+ getRelayPairingCandidate: (options) => {
1309
+ if (!relayServiceInstance) return null;
1310
+ // A relay pairing link enables the relay on demand; a plain link only
1311
+ // advertises relay when it is already on.
1312
+ return options?.ensureEnabled
1313
+ ? relayServiceInstance.ensureEnabledForPairing()
1314
+ : relayServiceInstance.getPairingCandidate();
1315
+ },
1316
+ // Re-evaluate the relay lifecycle after pairing/device changes (a revoked or
1317
+ // redeemed device can flip relay demand on or off).
1318
+ reconcileRelay: () => (relayServiceInstance ? relayServiceInstance.reconcile() : Promise.resolve()),
1319
+ getPairingTransports: resolvePairingTransports,
1320
+ // The display name a paired device shows for THIS server. Devices name the
1321
+ // connection by the issuing machine's hostname, not the per-device pairing
1322
+ // label typed by the operator.
1323
+ getServerLabel: () => {
1324
+ try {
1325
+ const name = os.hostname();
1326
+ return typeof name === 'string' && name.trim().length > 0 ? name.trim() : 'OpenChamber';
1327
+ } catch {
1328
+ return 'OpenChamber';
1329
+ }
1330
+ },
1245
1331
  readSettingsFromDiskMigrated,
1246
1332
  normalizeTunnelSessionTtlMs,
1247
1333
  sayTTSCapability,
@@ -1285,6 +1371,29 @@ async function main(options = {}) {
1285
1371
  const tunnelRuntimeContext = tunnelWiringRuntime.initialize(app, port);
1286
1372
  const { tunnelService, startTunnelWithNormalizedRequest } = tunnelRuntimeContext;
1287
1373
 
1374
+ // Private relay host service: config + management routes + host client
1375
+ // lifecycle. Loopback port comes from the same source the tunnel uses so
1376
+ // relay-tunneled requests hit the local Express app on 127.0.0.1.
1377
+ const relayService = createRelayService({
1378
+ crypto,
1379
+ os,
1380
+ readSettingsFromDiskMigrated,
1381
+ writeSettingsToDisk,
1382
+ remoteClientAuthRuntime,
1383
+ getLocalPort: () => tunnelRuntimeContext.getActivePort(),
1384
+ // Relay demand = any paired device or pending pairing session that uses the
1385
+ // relay transport. Drives the auto on/off lifecycle.
1386
+ hasRelayDemand: async () => {
1387
+ const [pendingRelay, deviceRelay] = await Promise.all([
1388
+ clientPairingRuntime.hasActiveRelaySession().catch(() => false),
1389
+ remoteClientAuthRuntime.hasActiveRelayClients().catch(() => false),
1390
+ ]);
1391
+ return pendingRelay || deviceRelay;
1392
+ },
1393
+ });
1394
+ relayServiceInstance = relayService;
1395
+ relayService.registerRoutes(app);
1396
+
1288
1397
  await featureRoutesRuntime.registerRoutes(app, {
1289
1398
  crypto,
1290
1399
  fs,
@@ -1394,6 +1503,20 @@ async function main(options = {}) {
1394
1503
  console.warn('[ScheduledTasks] Failed to start runtime:', error?.message || error);
1395
1504
  }
1396
1505
 
1506
+ // Only opens a relay control socket when the user opted in (config enabled).
1507
+ // Reconcile the relay lifecycle from demand on startup: run it if any relay
1508
+ // device/session exists, stop it (and clear a stale enabled flag) otherwise.
1509
+ void relayService.reconcile();
1510
+
1511
+ // Relay demand can change outside our routes: `openchamber connect-url
1512
+ // --relay` writes a pending relay session straight to the on-disk store, and
1513
+ // pending sessions expire without any request hitting us. Poll reconcile so a
1514
+ // headless instance picks the relay up (or drops it) within a minute.
1515
+ const relayReconcileTimer = setInterval(() => {
1516
+ void relayService.reconcile();
1517
+ }, 60_000);
1518
+ relayReconcileTimer.unref?.();
1519
+
1397
1520
  return {
1398
1521
  expressApp: app,
1399
1522
  httpServer: server,
@@ -1424,6 +1547,12 @@ async function main(options = {}) {
1424
1547
  },
1425
1548
  stop: (shutdownOptions = {}) => {
1426
1549
  realtimeProxyRuntime.stop();
1550
+ clearInterval(relayReconcileTimer);
1551
+ try {
1552
+ relayService.stop();
1553
+ } catch {
1554
+ // best-effort teardown of the relay host client
1555
+ }
1427
1556
  try {
1428
1557
  dictationRuntime?.stop?.();
1429
1558
  } catch {
@@ -0,0 +1,308 @@
1
+ const STORE_VERSION = 1;
2
+ const PAIRING_ID_PREFIX = 'pair_';
3
+ const SECRET_BYTES = 32;
4
+ const FINGERPRINT_BYTES = 4;
5
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
6
+ const MAX_LABEL_LENGTH = 80;
7
+ const VALID_CLIENT_KINDS = new Set(['mobile', 'desktop']);
8
+ const GENERIC_REDEEM_ERROR = 'Invalid or expired pairing session';
9
+
10
+ const normalizeOptionalString = (value) => {
11
+ if (typeof value !== 'string') return null;
12
+ const trimmed = value.trim();
13
+ return trimmed.length > 0 ? trimmed : null;
14
+ };
15
+
16
+ // Placeholder shown in the pending-devices list when the operator did not type a
17
+ // name. It is a DISPLAY default only — the stored label stays null so redeem can
18
+ // fall back to the device's own reported name instead of this placeholder.
19
+ const PAIRING_LABEL_PLACEHOLDER = 'Pair new device';
20
+
21
+ // The operator's typed device label, capped. Returns null when unset so callers
22
+ // can distinguish "no name given" from a real name.
23
+ const normalizeStoredLabel = (value) => {
24
+ const normalized = normalizeOptionalString(value);
25
+ if (!normalized) return null;
26
+ return normalized.length > MAX_LABEL_LENGTH ? normalized.slice(0, MAX_LABEL_LENGTH) : normalized;
27
+ };
28
+
29
+ const normalizeTimestamp = (value) => {
30
+ const normalized = normalizeOptionalString(value);
31
+ if (!normalized) return null;
32
+ const time = Date.parse(normalized);
33
+ return Number.isFinite(time) ? new Date(time).toISOString() : null;
34
+ };
35
+
36
+ const normalizeClientKind = (value) => {
37
+ const normalized = normalizeOptionalString(value);
38
+ return normalized && VALID_CLIENT_KINDS.has(normalized) ? normalized : null;
39
+ };
40
+
41
+ const normalizeAllowedClientKinds = (value) => {
42
+ if (!Array.isArray(value)) return ['mobile', 'desktop'];
43
+ const kinds = value.map(normalizeClientKind).filter(Boolean);
44
+ return kinds.length > 0 ? Array.from(new Set(kinds)) : ['mobile', 'desktop'];
45
+ };
46
+
47
+ const safeJsonParse = (raw) => {
48
+ try {
49
+ return JSON.parse(raw);
50
+ } catch {
51
+ return null;
52
+ }
53
+ };
54
+
55
+ const constantTimeEqual = (left, right, crypto) => {
56
+ if (typeof left !== 'string' || typeof right !== 'string') return false;
57
+ const leftBuffer = Buffer.from(left, 'hex');
58
+ const rightBuffer = Buffer.from(right, 'hex');
59
+ if (leftBuffer.length !== rightBuffer.length) return false;
60
+ return crypto.timingSafeEqual(leftBuffer, rightBuffer);
61
+ };
62
+
63
+ const publicSession = (session) => ({
64
+ id: session.id,
65
+ createdAt: session.createdAt,
66
+ expiresAt: session.expiresAt,
67
+ usedAt: session.usedAt,
68
+ cancelledAt: session.cancelledAt,
69
+ clientId: session.clientId,
70
+ label: session.label || PAIRING_LABEL_PLACEHOLDER,
71
+ fingerprint: session.fingerprint,
72
+ allowedClientKinds: session.allowedClientKinds,
73
+ createdByClientId: session.createdByClientId,
74
+ usesRelay: session.usesRelay === true,
75
+ });
76
+
77
+ // A pending session is one that can still be redeemed: not used, not cancelled,
78
+ // not expired.
79
+ const isPendingSession = (session) => !session.usedAt
80
+ && !session.cancelledAt
81
+ && Number.isFinite(Date.parse(session.expiresAt))
82
+ && Date.parse(session.expiresAt) > Date.now();
83
+
84
+ const redeemError = () => {
85
+ const error = new Error(GENERIC_REDEEM_ERROR);
86
+ error.statusCode = 400;
87
+ return error;
88
+ };
89
+
90
+ export const createClientPairingRuntime = ({
91
+ fsPromises,
92
+ path,
93
+ crypto,
94
+ storePath,
95
+ remoteClientAuthRuntime,
96
+ ttlMs = DEFAULT_TTL_MS,
97
+ } = {}) => {
98
+ if (!fsPromises || !path || !crypto || !storePath || !remoteClientAuthRuntime) {
99
+ throw new Error('createClientPairingRuntime requires fsPromises, path, crypto, storePath, and remoteClientAuthRuntime');
100
+ }
101
+
102
+ const nowIso = () => new Date().toISOString();
103
+ const hashSecret = (secret) => crypto.createHash('sha256').update(secret).digest('hex');
104
+ const generateId = () => `${PAIRING_ID_PREFIX}${crypto.randomBytes(12).toString('hex')}`;
105
+ const generateSecret = () => crypto.randomBytes(SECRET_BYTES).toString('base64url');
106
+ const generateFingerprint = () => crypto.randomBytes(FINGERPRINT_BYTES).toString('hex').toUpperCase().replace(/^(.{4})(.{4})$/, '$1-$2');
107
+ let storeMutationQueue = Promise.resolve();
108
+
109
+ const withStoreMutation = async (fn) => {
110
+ const previous = storeMutationQueue;
111
+ let release;
112
+ storeMutationQueue = new Promise((resolve) => {
113
+ release = resolve;
114
+ });
115
+ await previous;
116
+ try {
117
+ return await fn();
118
+ } finally {
119
+ release();
120
+ }
121
+ };
122
+
123
+ const normalizeStore = (payload) => ({
124
+ version: STORE_VERSION,
125
+ sessions: Array.isArray(payload?.sessions)
126
+ ? payload.sessions
127
+ .filter((session) => session && typeof session === 'object')
128
+ .map((session) => ({
129
+ id: typeof session.id === 'string' ? session.id : generateId(),
130
+ secretHash: typeof session.secretHash === 'string' ? session.secretHash : '',
131
+ createdAt: typeof session.createdAt === 'string' ? session.createdAt : nowIso(),
132
+ expiresAt: normalizeTimestamp(session.expiresAt) || new Date(Date.now() + ttlMs).toISOString(),
133
+ usedAt: normalizeTimestamp(session.usedAt),
134
+ cancelledAt: normalizeTimestamp(session.cancelledAt),
135
+ clientId: normalizeOptionalString(session.clientId),
136
+ label: normalizeStoredLabel(session.label),
137
+ fingerprint: normalizeOptionalString(session.fingerprint) || generateFingerprint(),
138
+ allowedClientKinds: normalizeAllowedClientKinds(session.allowedClientKinds),
139
+ createdByClientId: normalizeOptionalString(session.createdByClientId),
140
+ usesRelay: session.usesRelay === true,
141
+ }))
142
+ .filter((session) => session.secretHash.length > 0)
143
+ : [],
144
+ });
145
+
146
+ const readStore = async () => {
147
+ try {
148
+ const raw = await fsPromises.readFile(storePath, 'utf8');
149
+ return normalizeStore(safeJsonParse(raw));
150
+ } catch (error) {
151
+ if (error?.code === 'ENOENT') return normalizeStore(null);
152
+ throw error;
153
+ }
154
+ };
155
+
156
+ const writeStore = async (store) => {
157
+ await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
158
+ await fsPromises.writeFile(storePath, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
159
+ if (typeof fsPromises.chmod === 'function') {
160
+ await fsPromises.chmod(storePath, 0o600).catch(() => {});
161
+ }
162
+ };
163
+
164
+ const sweepExpiredSessionsFromStore = (store) => {
165
+ const now = Date.now();
166
+ const cutoff = now - ttlMs;
167
+ store.sessions = store.sessions.filter((session) => {
168
+ const usedAt = Date.parse(session.usedAt || '');
169
+ const cancelledAt = Date.parse(session.cancelledAt || '');
170
+ const inactiveAt = Number.isFinite(usedAt) ? usedAt : cancelledAt;
171
+ if (Number.isFinite(inactiveAt)) return inactiveAt >= cutoff;
172
+ // Never used or cancelled: drop once the session itself has expired —
173
+ // it can no longer be redeemed and would otherwise sit in the store forever.
174
+ const expiresAt = Date.parse(session.expiresAt || '');
175
+ return !Number.isFinite(expiresAt) || expiresAt > now;
176
+ });
177
+ };
178
+
179
+ const createPairingSession = async ({ label, allowedClientKinds, createdByClientId, usesRelay } = {}) => {
180
+ return withStoreMutation(async () => {
181
+ const store = await readStore();
182
+ sweepExpiredSessionsFromStore(store);
183
+ const secret = generateSecret();
184
+ const session = {
185
+ id: generateId(),
186
+ secretHash: hashSecret(secret),
187
+ createdAt: nowIso(),
188
+ expiresAt: new Date(Date.now() + ttlMs).toISOString(),
189
+ usedAt: null,
190
+ cancelledAt: null,
191
+ clientId: null,
192
+ label: normalizeStoredLabel(label),
193
+ fingerprint: generateFingerprint(),
194
+ allowedClientKinds: normalizeAllowedClientKinds(allowedClientKinds),
195
+ createdByClientId: normalizeOptionalString(createdByClientId),
196
+ usesRelay: usesRelay === true,
197
+ };
198
+ store.sessions.push(session);
199
+ await writeStore(store);
200
+ return { pairing: { ...publicSession(session), secret } };
201
+ });
202
+ };
203
+
204
+ // Sessions that can still be redeemed (link created, device not yet connected).
205
+ const listPendingSessions = async () => withStoreMutation(async () => {
206
+ const store = await readStore();
207
+ return store.sessions.filter(isPendingSession).map(publicSession);
208
+ });
209
+
210
+ // Relay-transport demand from pairing: any still-redeemable relay session.
211
+ const hasActiveRelaySession = async () => withStoreMutation(async () => {
212
+ const store = await readStore();
213
+ return store.sessions.some((session) => session.usesRelay === true && isPendingSession(session));
214
+ });
215
+
216
+ const getPairingSession = async (id) => {
217
+ const normalizedId = normalizeOptionalString(id);
218
+ if (!normalizedId) return null;
219
+ return withStoreMutation(async () => {
220
+ const store = await readStore();
221
+ const session = store.sessions.find((entry) => entry.id === normalizedId);
222
+ return session ? publicSession(session) : null;
223
+ });
224
+ };
225
+
226
+ const cancelPairingSession = async (id) => {
227
+ const normalizedId = normalizeOptionalString(id);
228
+ if (!normalizedId) return { cancelled: false };
229
+ return withStoreMutation(async () => {
230
+ const store = await readStore();
231
+ const session = store.sessions.find((entry) => entry.id === normalizedId);
232
+ if (!session) return { cancelled: false };
233
+ if (!session.cancelledAt) session.cancelledAt = nowIso();
234
+ await writeStore(store);
235
+ return { cancelled: true, pairing: publicSession(session) };
236
+ });
237
+ };
238
+
239
+ const redeemPairingSession = async ({
240
+ pairingId,
241
+ secret,
242
+ clientLabel,
243
+ clientKind,
244
+ deviceName,
245
+ devicePlatform,
246
+ deviceModel,
247
+ appVersion,
248
+ dedupeKey,
249
+ } = {}) => {
250
+ const normalizedId = normalizeOptionalString(pairingId);
251
+ const normalizedSecret = normalizeOptionalString(secret);
252
+ const normalizedKind = normalizeClientKind(clientKind) || 'mobile';
253
+ if (!normalizedId || !normalizedSecret) throw redeemError();
254
+
255
+ return withStoreMutation(async () => {
256
+ const store = await readStore();
257
+ const session = store.sessions.find((entry) => entry.id === normalizedId);
258
+ if (!session) throw redeemError();
259
+ if (session.cancelledAt || session.usedAt) throw redeemError();
260
+ if (Date.parse(session.expiresAt) <= Date.now()) throw redeemError();
261
+ if (!session.allowedClientKinds.includes(normalizedKind)) throw redeemError();
262
+ if (!constantTimeEqual(session.secretHash, hashSecret(normalizedSecret), crypto)) throw redeemError();
263
+
264
+ // The operator's typed pairing label is THIS server's name for the device
265
+ // (shown in the device list). It wins over the device's self-reported
266
+ // label; fall back to that only when no pairing label was set.
267
+ const label = normalizeOptionalString(session.label)
268
+ || normalizeOptionalString(clientLabel)
269
+ || normalizeOptionalString(deviceName)
270
+ || 'Remote client';
271
+ const result = await remoteClientAuthRuntime.createClient({
272
+ label,
273
+ clientKind: normalizedKind,
274
+ dedupeKey: normalizeOptionalString(dedupeKey) || `pairing:${session.id}`,
275
+ authMethod: 'pairing',
276
+ pairingId: session.id,
277
+ deviceName,
278
+ devicePlatform,
279
+ deviceModel,
280
+ appVersion,
281
+ usesRelay: session.usesRelay === true,
282
+ });
283
+ session.usedAt = nowIso();
284
+ session.clientId = result.client?.id || null;
285
+ await writeStore(store);
286
+ return { pairing: publicSession(session), client: result.client, token: result.token };
287
+ });
288
+ };
289
+
290
+ const sweepExpiredSessions = async () => withStoreMutation(async () => {
291
+ const store = await readStore();
292
+ const before = store.sessions.length;
293
+ sweepExpiredSessionsFromStore(store);
294
+ const purged = before - store.sessions.length;
295
+ if (purged > 0) await writeStore(store);
296
+ return { purged };
297
+ });
298
+
299
+ return {
300
+ createPairingSession,
301
+ getPairingSession,
302
+ listPendingSessions,
303
+ hasActiveRelaySession,
304
+ cancelPairingSession,
305
+ redeemPairingSession,
306
+ sweepExpiredSessions,
307
+ };
308
+ };