@openchamber/web 1.14.0 → 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 (100) 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-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-DF7-jlam.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-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
  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 +157 -6
  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 +247 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  45. package/server/lib/opencode/models-metadata.js +61 -0
  46. package/server/lib/opencode/network-runtime.js +14 -1
  47. package/server/lib/opencode/network-runtime.test.js +29 -9
  48. package/server/lib/opencode/openchamber-routes.js +7 -40
  49. package/server/lib/opencode/proxy.js +47 -6
  50. package/server/lib/opencode/settings-helpers.js +16 -0
  51. package/server/lib/opencode/settings-helpers.test.js +11 -0
  52. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  53. package/server/lib/opencode/shutdown-runtime.js +2 -0
  54. package/server/lib/package-manager.js +18 -5
  55. package/server/lib/relay/DOCUMENTATION.md +78 -0
  56. package/server/lib/relay/cross-compat.test.js +135 -0
  57. package/server/lib/relay/e2ee.js +341 -0
  58. package/server/lib/relay/e2ee.test.js +124 -0
  59. package/server/lib/relay/host-client.js +389 -0
  60. package/server/lib/relay/host-client.test.js +280 -0
  61. package/server/lib/relay/identity.js +73 -0
  62. package/server/lib/relay/identity.test.js +78 -0
  63. package/server/lib/relay/service.js +247 -0
  64. package/server/lib/relay/signing-key.js +50 -0
  65. package/server/lib/relay/tunnel-codec.js +373 -0
  66. package/server/lib/relay/tunnel-codec.test.js +58 -0
  67. package/server/lib/relay/tunnel-host.js +462 -0
  68. package/server/lib/session-assist/DOCUMENTATION.md +66 -0
  69. package/server/lib/session-assist/runtime.js +394 -0
  70. package/server/lib/small-model/DOCUMENTATION.md +78 -0
  71. package/server/lib/small-model/call.js +380 -0
  72. package/server/lib/small-model/catalog.js +13 -0
  73. package/server/lib/small-model/index.js +167 -0
  74. package/server/lib/small-model/resolve.js +131 -0
  75. package/server/lib/small-model/resolve.test.js +197 -0
  76. package/server/lib/small-model/routes.js +44 -0
  77. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  78. package/server/lib/ui-auth/ui-auth.js +10 -0
  79. package/server/opencode-proxy.test.js +38 -0
  80. package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
  81. package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
  82. package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
  83. package/dist/assets/es-DQIFCjC2.js +0 -15
  84. package/dist/assets/fr-CJRav0LS.js +0 -13
  85. package/dist/assets/index-5eUDDB6w.js +0 -2
  86. package/dist/assets/index-CgpE7F8T.css +0 -1
  87. package/dist/assets/ja-CjAaqvHO.js +0 -15
  88. package/dist/assets/ko-BEbFxvrd.js +0 -15
  89. package/dist/assets/main-C2put7uQ.js +0 -2
  90. package/dist/assets/main-DuQEoz31.js +0 -214
  91. package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
  92. package/dist/assets/mobile-X0421aWz.js +0 -2
  93. package/dist/assets/pl-D4kzai5T.js +0 -15
  94. package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
  95. package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
  96. package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
  97. package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
  98. package/dist/assets/uk-DW_dTfoO.js +0 -15
  99. package/dist/assets/zh-CN-r2_euV7U.js +0 -15
  100. package/dist/assets/zh-TW-BdPx3NWh.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-C2put7uQ.js"></script>
519
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
520
- <link rel="modulepreload" crossorigin href="/assets/index-5eUDDB6w.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-CgpE7F8T.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-o3AAQ-8r.js"></script>
78
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
79
- <link rel="modulepreload" crossorigin href="/assets/index-5eUDDB6w.js">
80
- <link rel="stylesheet" crossorigin href="/assets/index-CgpE7F8T.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-X0421aWz.js"></script>
67
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
68
- <link rel="modulepreload" crossorigin href="/assets/index-5eUDDB6w.js">
69
- <link rel="stylesheet" crossorigin href="/assets/index-CgpE7F8T.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.0",
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
@@ -72,6 +72,7 @@ import { createOpenCodeResolutionRuntime } from './lib/opencode/opencode-resolut
72
72
  import { createBootstrapRuntime } from './lib/opencode/bootstrap-runtime.js';
73
73
  import { createSessionRuntime } from './lib/opencode/session-runtime.js';
74
74
  import { createOpenCodeWatcherRuntime } from './lib/opencode/watcher.js';
75
+ import { createSessionAssistRuntime } from './lib/session-assist/runtime.js';
75
76
  import { createScheduledTasksRuntime } from './lib/scheduled-tasks/runtime.js';
76
77
  import { createServerStartupRuntime } from './lib/opencode/server-startup-runtime.js';
77
78
  import { createTunnelWiringRuntime } from './lib/opencode/tunnel-wiring-runtime.js';
@@ -86,8 +87,10 @@ import { createNotificationTemplateRuntime } from './lib/notifications/template-
86
87
  import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
87
88
  import { createProjectConfigRuntime } from './lib/projects/project-config.js';
88
89
  import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
90
+ import { createClientPairingRuntime } from './lib/client-auth/pairing.js';
89
91
  import { createPreviewProxyRuntime } from './lib/preview/proxy-runtime.js';
90
92
  import { attachRealtimeProxy } from './lib/realtime-proxy.js';
93
+ import { createRelayService } from './lib/relay/service.js';
91
94
  import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
92
95
  import webPush from 'web-push';
93
96
 
@@ -280,6 +283,7 @@ const SETTINGS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'settings.json');
280
283
  const PUSH_SUBSCRIPTIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'push-subscriptions.json');
281
284
  const APNS_TOKENS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'apns-tokens.json');
282
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');
283
287
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-managed-remote-tunnels.json');
284
288
  const CLOUDFLARE_LEGACY_NAMED_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-named-tunnels.json');
285
289
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_VERSION = 1;
@@ -601,6 +605,7 @@ Object.defineProperties(openCodeNetworkState, {
601
605
  const openCodeNetworkRuntime = createOpenCodeNetworkRuntime({
602
606
  state: openCodeNetworkState,
603
607
  getOpenCodeAuthHeaders,
608
+ configuredOpenCodeHostname: ENV_CONFIGURED_OPENCODE_HOSTNAME,
604
609
  });
605
610
 
606
611
  const waitForReady = (...args) => openCodeNetworkRuntime.waitForReady(...args);
@@ -713,6 +718,12 @@ const maybeSendPushForTrigger = (...args) => notificationTriggerRuntime.maybeSen
713
718
  const setAutoAcceptSession = (...args) => notificationTriggerRuntime.setAutoAcceptSession(...args);
714
719
  clearPendingPushBadge = () => notificationTriggerRuntime.clearPendingPushBadge();
715
720
 
721
+ const sessionAssistRuntime = createSessionAssistRuntime({
722
+ buildOpenCodeUrl,
723
+ getOpenCodeAuthHeaders,
724
+ getSmallModelService: async () => import('./lib/small-model/index.js'),
725
+ });
726
+
716
727
  const globalMessageStreamHub = createGlobalMessageStreamHub({
717
728
  buildOpenCodeUrl,
718
729
  getOpenCodeAuthHeaders,
@@ -732,6 +743,19 @@ const openCodeWatcherRuntime = createOpenCodeWatcherRuntime({
732
743
  },
733
744
  });
734
745
 
746
+ // Session-assist subscribes to the hub directly: it needs the envelope's
747
+ // directory to route its own OpenCode calls to the right instance.
748
+ console.log('[session-assist] listening for session events');
749
+ globalMessageStreamHub.subscribeEvent((event) => {
750
+ const raw = event?.payload;
751
+ const payload = raw?.payload && typeof raw.payload === 'object' ? raw.payload : raw;
752
+ if (!payload || typeof payload !== 'object') return;
753
+ const directory = typeof event?.directory === 'string' && event.directory && event.directory !== 'global'
754
+ ? event.directory
755
+ : '';
756
+ sessionAssistRuntime.processPayload(payload, directory);
757
+ });
758
+
735
759
  const processForwardedEventPayload = (payload, emitSyntheticEvent) => {
736
760
  if (!payload || typeof payload !== 'object' || typeof emitSyntheticEvent !== 'function') {
737
761
  return;
@@ -851,6 +875,13 @@ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({
851
875
  crypto,
852
876
  storePath: REMOTE_CLIENTS_FILE_PATH,
853
877
  });
878
+ const clientPairingRuntime = createClientPairingRuntime({
879
+ fsPromises,
880
+ path,
881
+ crypto,
882
+ storePath: CLIENT_PAIRING_SESSIONS_FILE_PATH,
883
+ remoteClientAuthRuntime,
884
+ });
854
885
  const featureRoutesRuntime = createFeatureRoutesRuntime({
855
886
  clientReloadDelayMs: CLIENT_RELOAD_DELAY_MS,
856
887
  });
@@ -1014,11 +1045,12 @@ const bootstrapOpenCodeAtStartup = async (...args) => {
1014
1045
  if (openCodeLifecycleState.openCodeProcess && !openCodeLifecycleState.isExternalOpenCode) {
1015
1046
  startHealthMonitoring();
1016
1047
  }
1017
- if (ENV_DESKTOP_NOTIFY) {
1018
- void ensureGlobalWatcherStarted().catch((error) => {
1019
- console.warn(`Global event watcher startup failed: ${error?.message || error}`);
1020
- });
1021
- }
1048
+ // The global watcher used to start only for desktop notifications; the
1049
+ // session-assist runtime also rides its event hub, so it now starts
1050
+ // unconditionally once OpenCode is up.
1051
+ void ensureGlobalWatcherStarted().catch((error) => {
1052
+ console.warn(`Global event watcher startup failed: ${error?.message || error}`);
1053
+ });
1022
1054
  };
1023
1055
  const killProcessOnPort = (...args) => openCodeLifecycleRuntime.killProcessOnPort(...args);
1024
1056
  const waitForPortRelease = (...args) => openCodeLifecycleRuntime.waitForPortRelease(...args);
@@ -1037,6 +1069,7 @@ const gracefulShutdownRuntime = createGracefulShutdownRuntime({
1037
1069
  },
1038
1070
  syncToHmrState,
1039
1071
  openCodeWatcherRuntime,
1072
+ sessionAssistRuntime,
1040
1073
  sessionRuntime,
1041
1074
  getHealthCheckInterval: () => healthCheckInterval,
1042
1075
  clearHealthCheckInterval: (value) => clearInterval(value),
@@ -1078,6 +1111,52 @@ async function main(options = {}) {
1078
1111
  || (typeof process.env.OPENCHAMBER_HOST === 'string' && process.env.OPENCHAMBER_HOST.trim().length > 0
1079
1112
  ? process.env.OPENCHAMBER_HOST.trim()
1080
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
+ };
1081
1160
  const uiPassword = typeof options.uiPassword === 'string'
1082
1161
  ? options.uiPassword
1083
1162
  : (typeof process.env.OPENCHAMBER_UI_PASSWORD === 'string' ? process.env.OPENCHAMBER_UI_PASSWORD : null);
@@ -1159,7 +1238,7 @@ async function main(options = {}) {
1159
1238
  res.setHeader('Access-Control-Allow-Origin', origin);
1160
1239
  res.setHeader('Access-Control-Allow-Credentials', 'true');
1161
1240
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
1162
- 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');
1163
1242
  res.setHeader('Access-Control-Expose-Headers', 'x-next-cursor');
1164
1243
  res.setHeader('Vary', 'Origin');
1165
1244
  if (req.method === 'OPTIONS') {
@@ -1180,6 +1259,11 @@ async function main(options = {}) {
1180
1259
  server = http.createServer(app);
1181
1260
  let realtimeProxyRuntime = { stop: () => {} };
1182
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
+
1183
1267
  const bootstrapResult = bootstrapRuntime.setupBaseRoutes(app, {
1184
1268
  process,
1185
1269
  openchamberVersion: OPENCHAMBER_VERSION,
@@ -1220,6 +1304,30 @@ async function main(options = {}) {
1220
1304
  uiPassword,
1221
1305
  tunnelAuthController,
1222
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
+ },
1223
1331
  readSettingsFromDiskMigrated,
1224
1332
  normalizeTunnelSessionTtlMs,
1225
1333
  sayTTSCapability,
@@ -1263,6 +1371,29 @@ async function main(options = {}) {
1263
1371
  const tunnelRuntimeContext = tunnelWiringRuntime.initialize(app, port);
1264
1372
  const { tunnelService, startTunnelWithNormalizedRequest } = tunnelRuntimeContext;
1265
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
+
1266
1397
  await featureRoutesRuntime.registerRoutes(app, {
1267
1398
  crypto,
1268
1399
  fs,
@@ -1372,6 +1503,20 @@ async function main(options = {}) {
1372
1503
  console.warn('[ScheduledTasks] Failed to start runtime:', error?.message || error);
1373
1504
  }
1374
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
+
1375
1520
  return {
1376
1521
  expressApp: app,
1377
1522
  httpServer: server,
@@ -1402,6 +1547,12 @@ async function main(options = {}) {
1402
1547
  },
1403
1548
  stop: (shutdownOptions = {}) => {
1404
1549
  realtimeProxyRuntime.stop();
1550
+ clearInterval(relayReconcileTimer);
1551
+ try {
1552
+ relayService.stop();
1553
+ } catch {
1554
+ // best-effort teardown of the relay host client
1555
+ }
1405
1556
  try {
1406
1557
  dictationRuntime?.stop?.();
1407
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
+ };