@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
@@ -67,10 +67,29 @@ export const registerServerStatusRoutes = (app, dependencies) => {
67
67
  serverStartedAt,
68
68
  gracefulShutdown,
69
69
  getHealthSnapshot,
70
+ // Stable server identity (hash of the public signing key — not a secret).
71
+ // Exposed on /health and /api/version so a client can verify that a
72
+ // learned/probed address belongs to the expected server BEFORE sending its
73
+ // bearer token there. Optional: older wiring omits it.
74
+ getServerId = async () => null,
70
75
  tunnelAuthController = null,
71
76
  uiAuthController = null,
72
77
  } = dependencies;
73
78
 
79
+ // The identity is immutable for the process lifetime; resolve once, and never
80
+ // let an identity failure break health reporting.
81
+ let cachedServerId = null;
82
+ const resolveServerId = async () => {
83
+ if (cachedServerId) return cachedServerId;
84
+ try {
85
+ const value = await getServerId();
86
+ cachedServerId = typeof value === 'string' && value.trim() ? value.trim() : null;
87
+ } catch {
88
+ cachedServerId = null;
89
+ }
90
+ return cachedServerId;
91
+ };
92
+
74
93
  const allocateLoopbackPort = async () => {
75
94
  const net = await import('node:net');
76
95
  return await new Promise((resolve, reject) => {
@@ -213,24 +232,28 @@ export const registerServerStatusRoutes = (app, dependencies) => {
213
232
  }
214
233
  };
215
234
 
216
- app.get('/health', (_req, res) => {
235
+ app.get('/health', async (_req, res) => {
236
+ const serverId = await resolveServerId();
217
237
  res.json({
218
238
  status: 'ok',
219
239
  timestamp: new Date().toISOString(),
220
240
  openchamberVersion,
221
241
  runtime: runtimeName,
222
242
  compatibility,
243
+ ...(serverId ? { serverId } : {}),
223
244
  ...getHealthSnapshot(),
224
245
  });
225
246
  });
226
247
 
227
- app.get('/api/version', (_req, res) => {
248
+ app.get('/api/version', async (_req, res) => {
249
+ const serverId = await resolveServerId();
228
250
  res.json({
229
251
  status: 'ok',
230
252
  openchamberVersion,
231
253
  runtime: runtimeName,
232
254
  startedAt: serverStartedAt,
233
255
  compatibility,
256
+ ...(serverId ? { serverId } : {}),
234
257
  });
235
258
  });
236
259
 
@@ -358,9 +381,32 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
358
381
  tunnelAuthController,
359
382
  uiAuthController,
360
383
  remoteClientAuthRuntime,
384
+ clientPairingRuntime,
361
385
  readSettingsFromDiskMigrated,
362
386
  normalizeTunnelSessionTtlMs,
387
+ // Returns the relay pairing candidate ({ type:'relay', relayUrl, serverId,
388
+ // hostEncPubJwk, priority }) when the host relay is enabled, else null.
389
+ // Injected lazily because the relay service is constructed after these routes.
390
+ getRelayPairingCandidate = async () => null,
391
+ // Re-evaluate the relay lifecycle after pairing/device changes.
392
+ reconcileRelay = async () => {},
393
+ // Returns { local, lan, relayAvailable } — the direct transport URLs the
394
+ // server can actually be reached on (LAN derived from the server bind, not
395
+ // the UI origin), for the create-device dialog.
396
+ getPairingTransports = () => ({ local: null, lan: null, relayAvailable: true }),
397
+ // Returns ALL direct LAN URLs the server is currently reachable on (client-
398
+ // reached address first, then interface scan) for the candidates-refresh
399
+ // endpoint. Empty when the server is loopback-only.
400
+ getDirectCandidateUrls = () => [],
401
+ // Stable server identity for client-side verification of learned addresses.
402
+ getServerId = async () => null,
403
+ // Display name a paired device shows for THIS server (issuing machine's
404
+ // hostname), distinct from the per-device pairing label typed by the operator.
405
+ getServerLabel = () => 'OpenChamber',
363
406
  } = dependencies;
407
+ const PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS = 5 * 60 * 1000;
408
+ const PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS = 10;
409
+ const pairingRedeemAttempts = new Map();
364
410
 
365
411
  const runWithUiAuth = async (req, res, next, handler, options = {}) => {
366
412
  try {
@@ -440,6 +486,112 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
440
486
  return clients.find((client) => client.id === clientId) || null;
441
487
  };
442
488
 
489
+ const requestOrigin = (req) => {
490
+ const forwardedProto = typeof req.headers?.['x-forwarded-proto'] === 'string'
491
+ ? req.headers['x-forwarded-proto'].split(',')[0].trim()
492
+ : '';
493
+ const protocol = forwardedProto || (req.socket?.encrypted ? 'https' : 'http');
494
+ const host = typeof req.headers?.host === 'string' ? req.headers.host.trim() : '';
495
+ if (!host) return null;
496
+ return `${protocol}://${host}`;
497
+ };
498
+
499
+ const requestIp = (req) => {
500
+ // Do not use req.ip here: Express rewrites it from X-Forwarded-For when
501
+ // trust proxy is enabled, and redeem is unauthenticated before this limit.
502
+ return req.socket?.remoteAddress || req.connection?.remoteAddress || 'unknown';
503
+ };
504
+
505
+ const pairingIdFromRequest = (req) => {
506
+ const raw = typeof req.body?.pairingId === 'string' ? req.body.pairingId.trim() : '';
507
+ return raw || 'missing';
508
+ };
509
+
510
+ const checkPairingRedeemRateLimit = (req) => {
511
+ const now = Date.now();
512
+ const key = `${requestIp(req)}:${pairingIdFromRequest(req)}`;
513
+ for (const [entryKey, entry] of pairingRedeemAttempts.entries()) {
514
+ if (!entry || now - entry.firstAttemptAt >= PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) {
515
+ pairingRedeemAttempts.delete(entryKey);
516
+ }
517
+ }
518
+ const entry = pairingRedeemAttempts.get(key);
519
+ if (!entry) {
520
+ pairingRedeemAttempts.set(key, { count: 1, firstAttemptAt: now });
521
+ return { allowed: true, remaining: PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS - 1, reset: Math.ceil((now + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) / 1000) };
522
+ }
523
+ const reset = Math.ceil((entry.firstAttemptAt + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) / 1000);
524
+ if (entry.count >= PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS) {
525
+ return {
526
+ allowed: false,
527
+ remaining: 0,
528
+ reset,
529
+ retryAfter: Math.max(1, Math.ceil((entry.firstAttemptAt + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS - now) / 1000)),
530
+ };
531
+ }
532
+ entry.count += 1;
533
+ return { allowed: true, remaining: PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS - entry.count, reset };
534
+ };
535
+
536
+ const clearPairingRedeemRateLimit = (req) => {
537
+ pairingRedeemAttempts.delete(`${requestIp(req)}:${pairingIdFromRequest(req)}`);
538
+ };
539
+
540
+ const normalizeCandidateUrl = (value) => {
541
+ if (typeof value !== 'string' || !value.trim()) return null;
542
+ try {
543
+ const parsed = new URL(value.trim());
544
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
545
+ parsed.hash = '';
546
+ parsed.search = '';
547
+ return parsed.toString().replace(/\/+$/, '');
548
+ } catch {
549
+ return null;
550
+ }
551
+ };
552
+
553
+ // `preferredServerUrl` is the caller-supplied externally reachable URL (the
554
+ // desktop UI reaches its own server over loopback, so the request origin is not
555
+ // scannable — it passes the LAN URL instead). Falls back to the request origin
556
+ // for remote callers where the Host header IS the reachable address.
557
+ //
558
+ // `includeRelay` is the per-link transport choice from the create-link dialog:
559
+ // true → add the relay candidate, enabling the relay host on demand;
560
+ // false → direct only, never relay;
561
+ // undefined → legacy: advertise relay only if it is already enabled.
562
+ // `includeDirect === false` produces a relay-only link (no direct candidate).
563
+ const pairingServerCandidates = async (req, { preferredServerUrl, includeRelay, includeDirect = true } = {}) => {
564
+ const candidates = [];
565
+ if (includeDirect) {
566
+ const direct = normalizeCandidateUrl(preferredServerUrl) || requestOrigin(req);
567
+ if (direct) {
568
+ let type = 'lan';
569
+ try {
570
+ const parsed = new URL(direct);
571
+ type = parsed.protocol === 'https:' ? 'tunnel' : 'lan';
572
+ } catch {
573
+ }
574
+ candidates.push({ type, url: direct, priority: 10 });
575
+ }
576
+ }
577
+ // The client races candidates and falls back to relay only if the direct URL
578
+ // is unreachable (relay carries a higher priority number).
579
+ if (includeRelay !== false) {
580
+ try {
581
+ const relayCandidate = await getRelayPairingCandidate({ ensureEnabled: includeRelay === true });
582
+ if (relayCandidate) candidates.push(relayCandidate);
583
+ } catch {
584
+ // A relay enable/status failure must not break direct pairing.
585
+ }
586
+ }
587
+ return candidates;
588
+ };
589
+
590
+ const sendPairingRedeemError = (res, error) => {
591
+ const statusCode = typeof error?.statusCode === 'number' ? error.statusCode : 400;
592
+ res.status(statusCode).json({ error: 'Invalid or expired pairing session' });
593
+ };
594
+
443
595
  const requireApiAuth = async (req, res, next) => {
444
596
  // Preview proxy requests carry a target-scoped capability token that the
445
597
  // preview proxy validates against the registered target id/TTL. Let those
@@ -588,7 +740,12 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
588
740
  await runWithClientManagementAuth(req, res, next, async (authContext) => {
589
741
  if (authContext.type === 'client') {
590
742
  const client = await clientRecordFromAuthContext(authContext);
591
- return res.json({ clients: client ? [client] : [] });
743
+ // The desktop shell's local client is the trusted operator of this
744
+ // server; it manages devices just like a browser UI session. Every
745
+ // other client token is scoped to its own record.
746
+ if (client?.clientKind !== 'desktop-local') {
747
+ return res.json({ clients: client ? [client] : [] });
748
+ }
592
749
  }
593
750
  const clients = await remoteClientAuthRuntime.listClients();
594
751
  res.json({ clients });
@@ -610,24 +767,178 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
610
767
  app.delete('/api/client-auth/clients/:id', async (req, res, next) => {
611
768
  await runWithClientManagementAuth(req, res, next, async (authContext) => {
612
769
  if (authContext.type === 'client') {
613
- const clientId = clientIdFromAuthContext(authContext);
614
- if (!clientId || clientId !== req.params?.id) {
615
- return res.status(403).json({ revoked: false, error: 'Client tokens can only revoke themselves' });
770
+ const actingClient = await clientRecordFromAuthContext(authContext);
771
+ // The desktop shell's local client manages every device; other client
772
+ // tokens may only revoke themselves.
773
+ if (actingClient?.clientKind !== 'desktop-local') {
774
+ const clientId = clientIdFromAuthContext(authContext);
775
+ if (!clientId || clientId !== req.params?.id) {
776
+ return res.status(403).json({ revoked: false, error: 'Client tokens can only revoke themselves' });
777
+ }
616
778
  }
617
779
  }
618
780
  const result = await remoteClientAuthRuntime.revokeClient(req.params?.id);
619
781
  if (!result.revoked) {
620
782
  return res.status(404).json({ revoked: false, error: 'Client not found' });
621
783
  }
784
+ void reconcileRelay();
622
785
  res.json(result);
623
786
  });
624
787
  });
625
788
 
626
789
  app.delete('/api/client-auth/clients', async (req, res, next) => {
627
- await runWithUiAuth(req, res, next, async () => {
790
+ await runWithClientManagementAuth(req, res, next, async (authContext) => {
791
+ if (authContext.type === 'client') {
792
+ const actingClient = await clientRecordFromAuthContext(authContext);
793
+ // Purging revoked devices is a whole-server management action; only the
794
+ // trusted desktop shell client (or a UI session) may do it.
795
+ if (actingClient?.clientKind !== 'desktop-local') {
796
+ return res.status(403).json({ purged: 0, error: 'Client tokens cannot purge revoked devices' });
797
+ }
798
+ }
628
799
  const result = await remoteClientAuthRuntime.purgeRevokedClients();
800
+ void reconcileRelay();
629
801
  res.json(result);
630
- }, { sessionOnly: true });
802
+ });
803
+ });
804
+
805
+ app.post('/api/client-auth/pairing/sessions', express.json({ limit: '64kb' }), async (req, res, next) => {
806
+ await runWithClientCreateAuth(req, res, next, async (authContext) => {
807
+ const candidates = await pairingServerCandidates(req, {
808
+ preferredServerUrl: req.body?.serverUrl,
809
+ includeRelay: typeof req.body?.includeRelay === 'boolean' ? req.body.includeRelay : undefined,
810
+ includeDirect: req.body?.includeDirect !== false,
811
+ });
812
+ const usesRelay = candidates.some((candidate) => candidate.type === 'relay');
813
+ const result = await clientPairingRuntime.createPairingSession({
814
+ label: req.body?.label,
815
+ allowedClientKinds: req.body?.allowedClientKinds,
816
+ createdByClientId: clientIdFromAuthContext(authContext),
817
+ usesRelay,
818
+ });
819
+ void reconcileRelay();
820
+ res.setHeader('Cache-Control', 'no-store');
821
+ res.status(201).json({
822
+ ...result,
823
+ server: { label: getServerLabel(), candidates },
824
+ });
825
+ });
826
+ });
827
+
828
+ // Current reachable transports for an ALREADY-PAIRED device. Pairing-payload
829
+ // candidates are a snapshot: when DHCP hands this machine a new address, the
830
+ // device's saved LAN candidate goes stale and it is stuck on the relay forever.
831
+ // A client that connected over any live transport calls this to learn the
832
+ // server's present LAN URLs (plus the relay candidate when enabled) and update
833
+ // its saved candidate set. `serverId` lets the client bind the response — and
834
+ // later /health probes of the learned addresses — to this server's identity
835
+ // before trusting them with its bearer token.
836
+ // Auth: UI session or client bearer; never the short-lived URL token.
837
+ app.get('/api/client-auth/connection/candidates', async (req, res, next) => {
838
+ await runWithClientManagementAuth(req, res, next, async () => {
839
+ const candidates = [];
840
+ const directUrls = (() => {
841
+ try {
842
+ const urls = getDirectCandidateUrls(req);
843
+ return Array.isArray(urls) ? urls : [];
844
+ } catch {
845
+ return [];
846
+ }
847
+ })();
848
+ for (const url of directUrls) {
849
+ const normalized = normalizeCandidateUrl(url);
850
+ if (normalized) candidates.push({ type: 'lan', url: normalized, priority: 10 });
851
+ }
852
+ try {
853
+ const relayCandidate = await getRelayPairingCandidate({ ensureEnabled: false });
854
+ if (relayCandidate) candidates.push(relayCandidate);
855
+ } catch {
856
+ // Relay status failure must not break the direct-candidate refresh.
857
+ }
858
+ let serverId = null;
859
+ try {
860
+ const value = await getServerId();
861
+ serverId = typeof value === 'string' && value.trim() ? value.trim() : null;
862
+ } catch {
863
+ serverId = null;
864
+ }
865
+ res.setHeader('Cache-Control', 'no-store');
866
+ res.json({ label: getServerLabel(), ...(serverId ? { serverId } : {}), candidates });
867
+ });
868
+ });
869
+
870
+ // Direct transports the server can be reached on (for the create-device dialog).
871
+ app.get('/api/client-auth/pairing/transports', async (req, res, next) => {
872
+ await runWithClientCreateAuth(req, res, next, async () => {
873
+ res.setHeader('Cache-Control', 'no-store');
874
+ res.json(getPairingTransports(req));
875
+ });
876
+ });
877
+
878
+ // Pending pairing sessions (link created, device not yet connected) for the
879
+ // "pending devices" list. Secrets are never included.
880
+ app.get('/api/client-auth/pairing/sessions', async (req, res, next) => {
881
+ await runWithClientCreateAuth(req, res, next, async () => {
882
+ const pending = await clientPairingRuntime.listPendingSessions();
883
+ res.setHeader('Cache-Control', 'no-store');
884
+ res.json({ pending });
885
+ });
886
+ });
887
+
888
+ app.delete('/api/client-auth/pairing/sessions/:id', async (req, res, next) => {
889
+ await runWithClientCreateAuth(req, res, next, async () => {
890
+ const result = await clientPairingRuntime.cancelPairingSession(req.params?.id);
891
+ if (!result.cancelled) {
892
+ return res.status(404).json({ cancelled: false, error: 'Pairing session not found' });
893
+ }
894
+ void reconcileRelay();
895
+ res.json(result);
896
+ });
897
+ });
898
+
899
+ app.post('/api/client-auth/pairing/redeem', express.json({ limit: '64kb' }), async (req, res, next) => {
900
+ try {
901
+ const rateLimit = checkPairingRedeemRateLimit(req);
902
+ res.setHeader('X-RateLimit-Limit', PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS);
903
+ res.setHeader('X-RateLimit-Remaining', rateLimit.remaining);
904
+ res.setHeader('X-RateLimit-Reset', rateLimit.reset);
905
+ if (!rateLimit.allowed) {
906
+ res.setHeader('Retry-After', rateLimit.retryAfter);
907
+ return res.status(429).json({ error: 'Invalid or expired pairing session' });
908
+ }
909
+ const result = await clientPairingRuntime.redeemPairingSession({
910
+ pairingId: req.body?.pairingId,
911
+ secret: req.body?.secret,
912
+ clientLabel: req.body?.clientLabel,
913
+ clientKind: req.body?.clientKind,
914
+ deviceName: req.body?.deviceName,
915
+ devicePlatform: req.body?.devicePlatform,
916
+ deviceModel: req.body?.deviceModel,
917
+ appVersion: req.body?.appVersion,
918
+ dedupeKey: req.body?.dedupeKey,
919
+ });
920
+ clearPairingRedeemRateLimit(req);
921
+ // The session became a device: relay demand may have moved from the pending
922
+ // session to the paired device (or a non-relay redeem may drop it).
923
+ void reconcileRelay();
924
+ res.setHeader('Cache-Control', 'no-store');
925
+ res.json({
926
+ ok: true,
927
+ server: {
928
+ label: getServerLabel(),
929
+ url: requestOrigin(req),
930
+ fingerprint: result.pairing?.fingerprint || null,
931
+ },
932
+ client: result.client,
933
+ clientToken: result.token,
934
+ });
935
+ } catch (error) {
936
+ if (error?.message === 'Invalid or expired pairing session') {
937
+ sendPairingRedeemError(res, error);
938
+ return;
939
+ }
940
+ next(error);
941
+ }
631
942
  });
632
943
 
633
944
  app.get('/connect', async (req, res) => {
@@ -758,8 +1069,10 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
758
1069
  req.path.startsWith('/api/opencode') ||
759
1070
  req.path.startsWith('/api/push') ||
760
1071
  req.path.startsWith('/api/notifications') ||
1072
+ req.path.startsWith('/api/permission-auto-accept') ||
761
1073
  req.path.startsWith('/api/session-folders') ||
762
1074
  req.path.startsWith('/api/small-model') ||
1075
+ req.path.startsWith('/api/goals') ||
763
1076
  req.path.startsWith('/api/text') ||
764
1077
  req.path.startsWith('/api/voice') ||
765
1078
  req.path.startsWith('/api/tts') ||