@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
@@ -0,0 +1,142 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import crypto from 'node:crypto';
6
+
7
+ import { createClientPairingRuntime } from './pairing.js';
8
+
9
+ const makeRuntime = async (options = {}) => {
10
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'openchamber-pairing-test-'));
11
+ const createdClients = [];
12
+ const remoteClientAuthRuntime = options.remoteClientAuthRuntime || {
13
+ createClient: vi.fn(async (input) => {
14
+ const client = {
15
+ id: `client-${createdClients.length + 1}`,
16
+ label: input.label,
17
+ clientKind: input.clientKind,
18
+ authMethod: input.authMethod,
19
+ pairingId: input.pairingId,
20
+ deviceName: input.deviceName ?? null,
21
+ };
22
+ createdClients.push(client);
23
+ return { client, token: `token-${createdClients.length}` };
24
+ }),
25
+ };
26
+ const runtime = createClientPairingRuntime({
27
+ fsPromises: fs,
28
+ path,
29
+ crypto,
30
+ storePath: path.join(dir, 'pairing.json'),
31
+ remoteClientAuthRuntime,
32
+ ttlMs: options.ttlMs ?? 10 * 60 * 1000,
33
+ });
34
+ return { dir, runtime, remoteClientAuthRuntime, createdClients };
35
+ };
36
+
37
+ describe('client auth pairing runtime', () => {
38
+ it('redeems a pairing session once and propagates client metadata', async () => {
39
+ const { runtime, remoteClientAuthRuntime } = await makeRuntime();
40
+ const created = await runtime.createPairingSession({ allowedClientKinds: ['mobile'] });
41
+
42
+ const result = await runtime.redeemPairingSession({
43
+ pairingId: created.pairing.id,
44
+ secret: created.pairing.secret,
45
+ clientLabel: 'Iryna iPhone',
46
+ clientKind: 'mobile',
47
+ deviceName: 'Iryna iPhone',
48
+ dedupeKey: 'device-key',
49
+ });
50
+
51
+ expect(result.token).toBe('token-1');
52
+ expect(result.client).toMatchObject({
53
+ label: 'Iryna iPhone',
54
+ clientKind: 'mobile',
55
+ authMethod: 'pairing',
56
+ pairingId: created.pairing.id,
57
+ deviceName: 'Iryna iPhone',
58
+ });
59
+ expect(remoteClientAuthRuntime.createClient).toHaveBeenCalledWith(expect.objectContaining({
60
+ authMethod: 'pairing',
61
+ pairingId: created.pairing.id,
62
+ clientKind: 'mobile',
63
+ dedupeKey: 'device-key',
64
+ }));
65
+
66
+ await expect(runtime.redeemPairingSession({
67
+ pairingId: created.pairing.id,
68
+ secret: created.pairing.secret,
69
+ clientKind: 'mobile',
70
+ })).rejects.toThrow('Invalid or expired pairing session');
71
+ });
72
+
73
+ it('rejects expired, cancelled, wrong-secret, and disallowed-kind redemption', async () => {
74
+ const { runtime: expiredRuntime } = await makeRuntime({ ttlMs: -1000 });
75
+ const expired = await expiredRuntime.createPairingSession();
76
+ await expect(expiredRuntime.redeemPairingSession({
77
+ pairingId: expired.pairing.id,
78
+ secret: expired.pairing.secret,
79
+ clientKind: 'mobile',
80
+ })).rejects.toThrow('Invalid or expired pairing session');
81
+
82
+ const { runtime } = await makeRuntime();
83
+ const cancelled = await runtime.createPairingSession();
84
+ await runtime.cancelPairingSession(cancelled.pairing.id);
85
+ await expect(runtime.redeemPairingSession({
86
+ pairingId: cancelled.pairing.id,
87
+ secret: cancelled.pairing.secret,
88
+ clientKind: 'mobile',
89
+ })).rejects.toThrow('Invalid or expired pairing session');
90
+
91
+ const wrongSecret = await runtime.createPairingSession();
92
+ await expect(runtime.redeemPairingSession({
93
+ pairingId: wrongSecret.pairing.id,
94
+ secret: 'wrong',
95
+ clientKind: 'mobile',
96
+ })).rejects.toThrow('Invalid or expired pairing session');
97
+
98
+ const desktopOnly = await runtime.createPairingSession({ allowedClientKinds: ['desktop'] });
99
+ await expect(runtime.redeemPairingSession({
100
+ pairingId: desktopOnly.pairing.id,
101
+ secret: desktopOnly.pairing.secret,
102
+ clientKind: 'mobile',
103
+ })).rejects.toThrow('Invalid or expired pairing session');
104
+ });
105
+
106
+ it('does not consume the pairing session if client issuance fails', async () => {
107
+ const createClient = vi.fn()
108
+ .mockRejectedValueOnce(new Error('disk failed'))
109
+ .mockResolvedValueOnce({ client: { id: 'client-1' }, token: 'token-1' });
110
+ const { runtime } = await makeRuntime({ remoteClientAuthRuntime: { createClient } });
111
+ const created = await runtime.createPairingSession();
112
+
113
+ await expect(runtime.redeemPairingSession({
114
+ pairingId: created.pairing.id,
115
+ secret: created.pairing.secret,
116
+ clientKind: 'mobile',
117
+ })).rejects.toThrow('disk failed');
118
+
119
+ await expect(runtime.redeemPairingSession({
120
+ pairingId: created.pairing.id,
121
+ secret: created.pairing.secret,
122
+ clientKind: 'mobile',
123
+ })).resolves.toMatchObject({ token: 'token-1' });
124
+ expect(createClient).toHaveBeenLastCalledWith(expect.objectContaining({
125
+ dedupeKey: `pairing:${created.pairing.id}`,
126
+ }));
127
+ });
128
+
129
+ it('sweeps expired never-used sessions from the store on the next create', async () => {
130
+ const { dir, runtime } = await makeRuntime({ ttlMs: -1000 });
131
+ // Immediately expired (negative TTL), never used or cancelled.
132
+ const expired = await runtime.createPairingSession({ label: 'stale' });
133
+
134
+ // The next create sweeps the store; only the fresh session should remain.
135
+ const storePath = path.join(dir, 'pairing.json');
136
+ await runtime.createPairingSession({ label: 'fresh' });
137
+ const store = JSON.parse(await fs.readFile(storePath, 'utf8'));
138
+ const ids = store.sessions.map((session) => session.id);
139
+ expect(ids).not.toContain(expired.pairing.id);
140
+ expect(ids).toHaveLength(1);
141
+ });
142
+ });
@@ -25,6 +25,15 @@ const normalizeOptionalString = (value) => {
25
25
  return trimmed.length > 0 ? trimmed : null;
26
26
  };
27
27
 
28
+ const normalizeMetadata = (client) => ({
29
+ authMethod: normalizeOptionalString(client.authMethod),
30
+ pairingId: normalizeOptionalString(client.pairingId),
31
+ deviceName: normalizeOptionalString(client.deviceName),
32
+ devicePlatform: normalizeOptionalString(client.devicePlatform),
33
+ deviceModel: normalizeOptionalString(client.deviceModel),
34
+ appVersion: normalizeOptionalString(client.appVersion),
35
+ });
36
+
28
37
  const safeJsonParse = (raw) => {
29
38
  try {
30
39
  return JSON.parse(raw);
@@ -77,6 +86,9 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
77
86
  expiresAt: normalizeTimestamp(client.expiresAt),
78
87
  clientKind: normalizeOptionalString(client.clientKind),
79
88
  dedupeKey: normalizeOptionalString(client.dedupeKey),
89
+ usesRelay: client.usesRelay === true,
90
+ lastTransport: client.lastTransport === 'relay' || client.lastTransport === 'direct' ? client.lastTransport : null,
91
+ ...normalizeMetadata(client),
80
92
  }))
81
93
  .filter((client) => client.tokenHash.length > 0)
82
94
  : [],
@@ -108,6 +120,14 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
108
120
  revokedAt: client.revokedAt,
109
121
  expiresAt: client.expiresAt,
110
122
  clientKind: client.clientKind,
123
+ authMethod: client.authMethod,
124
+ pairingId: client.pairingId,
125
+ deviceName: client.deviceName,
126
+ devicePlatform: client.devicePlatform,
127
+ deviceModel: client.deviceModel,
128
+ appVersion: client.appVersion,
129
+ usesRelay: client.usesRelay === true,
130
+ lastTransport: client.lastTransport ?? null,
111
131
  });
112
132
 
113
133
  const listClients = async () => {
@@ -117,7 +137,34 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
117
137
  });
118
138
  };
119
139
 
120
- const createClient = async ({ label, expiresAt, clientKind, dedupeKey } = {}) => {
140
+ // Relay-transport demand from paired devices: any non-revoked, non-expired
141
+ // client that was paired over the relay.
142
+ const hasActiveRelayClients = async () => {
143
+ return withStoreMutation(async () => {
144
+ const store = await readStore();
145
+ const now = Date.now();
146
+ return store.clients.some((client) => {
147
+ if (client.usesRelay !== true) return false;
148
+ if (client.revokedAt) return false;
149
+ const expires = Date.parse(client.expiresAt || '');
150
+ return !Number.isFinite(expires) || expires > now;
151
+ });
152
+ });
153
+ };
154
+
155
+ const createClient = async ({
156
+ label,
157
+ expiresAt,
158
+ clientKind,
159
+ dedupeKey,
160
+ authMethod,
161
+ pairingId,
162
+ deviceName,
163
+ devicePlatform,
164
+ deviceModel,
165
+ appVersion,
166
+ usesRelay,
167
+ } = {}) => {
121
168
  return withStoreMutation(async () => {
122
169
  const store = await readStore();
123
170
  const normalizedDedupeKey = normalizeOptionalString(dedupeKey);
@@ -132,6 +179,13 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
132
179
  expiresAt: normalizeTimestamp(expiresAt),
133
180
  clientKind: normalizeOptionalString(clientKind),
134
181
  dedupeKey: normalizedDedupeKey,
182
+ authMethod: normalizeOptionalString(authMethod),
183
+ pairingId: normalizeOptionalString(pairingId),
184
+ deviceName: normalizeOptionalString(deviceName),
185
+ devicePlatform: normalizeOptionalString(devicePlatform),
186
+ deviceModel: normalizeOptionalString(deviceModel),
187
+ appVersion: normalizeOptionalString(appVersion),
188
+ usesRelay: usesRelay === true,
135
189
  };
136
190
  if (normalizedDedupeKey) {
137
191
  store.clients = store.clients.filter((entry) => entry.dedupeKey !== normalizedDedupeKey);
@@ -177,10 +231,14 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
177
231
  });
178
232
  };
179
233
 
180
- const authenticateBearerToken = async (token) => {
234
+ const authenticateBearerToken = async (token, req) => {
181
235
  if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX)) {
182
236
  return null;
183
237
  }
238
+ // Which transport carried this request: the relay tunnel proxy stamps every
239
+ // forwarded request with x-openchamber-relay-connection; anything else is a
240
+ // direct (local/LAN/tunnel-URL) request. Display-only device metadata.
241
+ const transport = req?.headers?.['x-openchamber-relay-connection'] ? 'relay' : 'direct';
184
242
  return withStoreMutation(async () => {
185
243
  const tokenHash = hashToken(token);
186
244
  const store = await readStore();
@@ -189,8 +247,11 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
189
247
  if (client.expiresAt && Date.parse(client.expiresAt) <= Date.now()) return null;
190
248
  const now = Date.now();
191
249
  const lastUsedAt = Date.parse(client.lastUsedAt || '');
192
- if (!Number.isFinite(lastUsedAt) || now - lastUsedAt >= LAST_USED_WRITE_INTERVAL_MS) {
250
+ // Write on the throttle interval — or immediately when the transport
251
+ // changed, so a LAN⇄relay switch is visible right away, not a minute late.
252
+ if (!Number.isFinite(lastUsedAt) || now - lastUsedAt >= LAST_USED_WRITE_INTERVAL_MS || client.lastTransport !== transport) {
193
253
  client.lastUsedAt = new Date(now).toISOString();
254
+ client.lastTransport = transport;
194
255
  await writeStore(store);
195
256
  }
196
257
  return { ok: true, clientId: client.id, sessionToken: client.id, client: publicClient(client) };
@@ -201,6 +262,7 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
201
262
  authenticateBearerToken,
202
263
  createClient,
203
264
  listClients,
265
+ hasActiveRelayClients,
204
266
  purgeRevokedClients,
205
267
  revokeClient,
206
268
  };
@@ -9,6 +9,11 @@
9
9
  // Wired into the same trigger fanout as web push (see runtime.js); the relay carries only
10
10
  // generic, model-based text (no session content) — see APNS.md.
11
11
 
12
+ import {
13
+ getOrCreateRelaySigningKeypair,
14
+ signRelayMessage as signRelayMessageShared,
15
+ } from '../relay/signing-key.js';
16
+
12
17
  const APNS_TOKENS_VERSION = 1;
13
18
  const APNS_HOST_PRODUCTION = 'https://api.push.apple.com';
14
19
  const APNS_HOST_SANDBOX = 'https://api.sandbox.push.apple.com';
@@ -51,27 +56,15 @@ export const createApnsRuntime = (deps) => {
51
56
  // device token alone can't be used to push. Zero-config: the keypair generates on first use.
52
57
  // ---------------------------------------------------------------------------
53
58
 
59
+ // Key access lives in lib/relay/signing-key.js now (shared with the private
60
+ // relay identity — same keypair, same storage, same serverId derivation).
54
61
  const getOrCreateRelayKeypair = async () => {
55
62
  if (cachedRelayKey) return cachedRelayKey;
56
- const settings = await readSettingsFromDiskMigrated();
57
- const existing = settings?.relaySigningKey;
58
- if (existing && existing.privateJwk && existing.publicJwk) {
59
- cachedRelayKey = {
60
- privateKey: crypto.createPrivateKey({ key: existing.privateJwk, format: 'jwk' }),
61
- publicJwk: existing.publicJwk,
62
- };
63
- return cachedRelayKey;
64
- }
65
- const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
66
- const privateJwk = privateKey.export({ format: 'jwk' });
67
- const publicJwk = publicKey.export({ format: 'jwk' });
68
- await writeSettingsToDisk({ ...settings, relaySigningKey: { privateJwk, publicJwk } });
69
- cachedRelayKey = { privateKey, publicJwk };
63
+ cachedRelayKey = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
70
64
  return cachedRelayKey;
71
65
  };
72
66
 
73
- const signRelayMessage = (privateKey, message) =>
74
- crypto.sign('SHA256', Buffer.from(message), { key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');
67
+ const signRelayMessage = (privateKey, message) => signRelayMessageShared({ crypto }, privateKey, message);
75
68
 
76
69
  // Trim to the 4 fields the relay's schema accepts (and that feed the serverId hash).
77
70
  const relayPublicJwk = (publicJwk) => ({
@@ -22,6 +22,11 @@ export const createBootstrapRuntime = (dependencies) => {
22
22
  uiPassword,
23
23
  tunnelAuthController,
24
24
  remoteClientAuthRuntime,
25
+ clientPairingRuntime,
26
+ getRelayPairingCandidate,
27
+ reconcileRelay,
28
+ getPairingTransports,
29
+ getServerLabel,
25
30
  readSettingsFromDiskMigrated,
26
31
  normalizeTunnelSessionTtlMs,
27
32
  sayTTSCapability,
@@ -82,6 +87,11 @@ export const createBootstrapRuntime = (dependencies) => {
82
87
  tunnelAuthController,
83
88
  uiAuthController,
84
89
  remoteClientAuthRuntime,
90
+ clientPairingRuntime,
91
+ getRelayPairingCandidate,
92
+ reconcileRelay,
93
+ getPairingTransports,
94
+ getServerLabel,
85
95
  readSettingsFromDiskMigrated,
86
96
  normalizeTunnelSessionTtlMs,
87
97
  });
@@ -358,9 +358,26 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
358
358
  tunnelAuthController,
359
359
  uiAuthController,
360
360
  remoteClientAuthRuntime,
361
+ clientPairingRuntime,
361
362
  readSettingsFromDiskMigrated,
362
363
  normalizeTunnelSessionTtlMs,
364
+ // Returns the relay pairing candidate ({ type:'relay', relayUrl, serverId,
365
+ // hostEncPubJwk, priority }) when the host relay is enabled, else null.
366
+ // Injected lazily because the relay service is constructed after these routes.
367
+ getRelayPairingCandidate = async () => null,
368
+ // Re-evaluate the relay lifecycle after pairing/device changes.
369
+ reconcileRelay = async () => {},
370
+ // Returns { local, lan, relayAvailable } — the direct transport URLs the
371
+ // server can actually be reached on (LAN derived from the server bind, not
372
+ // the UI origin), for the create-device dialog.
373
+ getPairingTransports = () => ({ local: null, lan: null, relayAvailable: true }),
374
+ // Display name a paired device shows for THIS server (issuing machine's
375
+ // hostname), distinct from the per-device pairing label typed by the operator.
376
+ getServerLabel = () => 'OpenChamber',
363
377
  } = dependencies;
378
+ const PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS = 5 * 60 * 1000;
379
+ const PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS = 10;
380
+ const pairingRedeemAttempts = new Map();
364
381
 
365
382
  const runWithUiAuth = async (req, res, next, handler, options = {}) => {
366
383
  try {
@@ -440,6 +457,112 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
440
457
  return clients.find((client) => client.id === clientId) || null;
441
458
  };
442
459
 
460
+ const requestOrigin = (req) => {
461
+ const forwardedProto = typeof req.headers?.['x-forwarded-proto'] === 'string'
462
+ ? req.headers['x-forwarded-proto'].split(',')[0].trim()
463
+ : '';
464
+ const protocol = forwardedProto || (req.socket?.encrypted ? 'https' : 'http');
465
+ const host = typeof req.headers?.host === 'string' ? req.headers.host.trim() : '';
466
+ if (!host) return null;
467
+ return `${protocol}://${host}`;
468
+ };
469
+
470
+ const requestIp = (req) => {
471
+ // Do not use req.ip here: Express rewrites it from X-Forwarded-For when
472
+ // trust proxy is enabled, and redeem is unauthenticated before this limit.
473
+ return req.socket?.remoteAddress || req.connection?.remoteAddress || 'unknown';
474
+ };
475
+
476
+ const pairingIdFromRequest = (req) => {
477
+ const raw = typeof req.body?.pairingId === 'string' ? req.body.pairingId.trim() : '';
478
+ return raw || 'missing';
479
+ };
480
+
481
+ const checkPairingRedeemRateLimit = (req) => {
482
+ const now = Date.now();
483
+ const key = `${requestIp(req)}:${pairingIdFromRequest(req)}`;
484
+ for (const [entryKey, entry] of pairingRedeemAttempts.entries()) {
485
+ if (!entry || now - entry.firstAttemptAt >= PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) {
486
+ pairingRedeemAttempts.delete(entryKey);
487
+ }
488
+ }
489
+ const entry = pairingRedeemAttempts.get(key);
490
+ if (!entry) {
491
+ pairingRedeemAttempts.set(key, { count: 1, firstAttemptAt: now });
492
+ return { allowed: true, remaining: PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS - 1, reset: Math.ceil((now + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) / 1000) };
493
+ }
494
+ const reset = Math.ceil((entry.firstAttemptAt + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS) / 1000);
495
+ if (entry.count >= PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS) {
496
+ return {
497
+ allowed: false,
498
+ remaining: 0,
499
+ reset,
500
+ retryAfter: Math.max(1, Math.ceil((entry.firstAttemptAt + PAIRING_REDEEM_RATE_LIMIT_WINDOW_MS - now) / 1000)),
501
+ };
502
+ }
503
+ entry.count += 1;
504
+ return { allowed: true, remaining: PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS - entry.count, reset };
505
+ };
506
+
507
+ const clearPairingRedeemRateLimit = (req) => {
508
+ pairingRedeemAttempts.delete(`${requestIp(req)}:${pairingIdFromRequest(req)}`);
509
+ };
510
+
511
+ const normalizeCandidateUrl = (value) => {
512
+ if (typeof value !== 'string' || !value.trim()) return null;
513
+ try {
514
+ const parsed = new URL(value.trim());
515
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
516
+ parsed.hash = '';
517
+ parsed.search = '';
518
+ return parsed.toString().replace(/\/+$/, '');
519
+ } catch {
520
+ return null;
521
+ }
522
+ };
523
+
524
+ // `preferredServerUrl` is the caller-supplied externally reachable URL (the
525
+ // desktop UI reaches its own server over loopback, so the request origin is not
526
+ // scannable — it passes the LAN URL instead). Falls back to the request origin
527
+ // for remote callers where the Host header IS the reachable address.
528
+ //
529
+ // `includeRelay` is the per-link transport choice from the create-link dialog:
530
+ // true → add the relay candidate, enabling the relay host on demand;
531
+ // false → direct only, never relay;
532
+ // undefined → legacy: advertise relay only if it is already enabled.
533
+ // `includeDirect === false` produces a relay-only link (no direct candidate).
534
+ const pairingServerCandidates = async (req, { preferredServerUrl, includeRelay, includeDirect = true } = {}) => {
535
+ const candidates = [];
536
+ if (includeDirect) {
537
+ const direct = normalizeCandidateUrl(preferredServerUrl) || requestOrigin(req);
538
+ if (direct) {
539
+ let type = 'lan';
540
+ try {
541
+ const parsed = new URL(direct);
542
+ type = parsed.protocol === 'https:' ? 'tunnel' : 'lan';
543
+ } catch {
544
+ }
545
+ candidates.push({ type, url: direct, priority: 10 });
546
+ }
547
+ }
548
+ // The client races candidates and falls back to relay only if the direct URL
549
+ // is unreachable (relay carries a higher priority number).
550
+ if (includeRelay !== false) {
551
+ try {
552
+ const relayCandidate = await getRelayPairingCandidate({ ensureEnabled: includeRelay === true });
553
+ if (relayCandidate) candidates.push(relayCandidate);
554
+ } catch {
555
+ // A relay enable/status failure must not break direct pairing.
556
+ }
557
+ }
558
+ return candidates;
559
+ };
560
+
561
+ const sendPairingRedeemError = (res, error) => {
562
+ const statusCode = typeof error?.statusCode === 'number' ? error.statusCode : 400;
563
+ res.status(statusCode).json({ error: 'Invalid or expired pairing session' });
564
+ };
565
+
443
566
  const requireApiAuth = async (req, res, next) => {
444
567
  // Preview proxy requests carry a target-scoped capability token that the
445
568
  // preview proxy validates against the registered target id/TTL. Let those
@@ -588,7 +711,12 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
588
711
  await runWithClientManagementAuth(req, res, next, async (authContext) => {
589
712
  if (authContext.type === 'client') {
590
713
  const client = await clientRecordFromAuthContext(authContext);
591
- return res.json({ clients: client ? [client] : [] });
714
+ // The desktop shell's local client is the trusted operator of this
715
+ // server; it manages devices just like a browser UI session. Every
716
+ // other client token is scoped to its own record.
717
+ if (client?.clientKind !== 'desktop-local') {
718
+ return res.json({ clients: client ? [client] : [] });
719
+ }
592
720
  }
593
721
  const clients = await remoteClientAuthRuntime.listClients();
594
722
  res.json({ clients });
@@ -610,24 +738,136 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
610
738
  app.delete('/api/client-auth/clients/:id', async (req, res, next) => {
611
739
  await runWithClientManagementAuth(req, res, next, async (authContext) => {
612
740
  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' });
741
+ const actingClient = await clientRecordFromAuthContext(authContext);
742
+ // The desktop shell's local client manages every device; other client
743
+ // tokens may only revoke themselves.
744
+ if (actingClient?.clientKind !== 'desktop-local') {
745
+ const clientId = clientIdFromAuthContext(authContext);
746
+ if (!clientId || clientId !== req.params?.id) {
747
+ return res.status(403).json({ revoked: false, error: 'Client tokens can only revoke themselves' });
748
+ }
616
749
  }
617
750
  }
618
751
  const result = await remoteClientAuthRuntime.revokeClient(req.params?.id);
619
752
  if (!result.revoked) {
620
753
  return res.status(404).json({ revoked: false, error: 'Client not found' });
621
754
  }
755
+ void reconcileRelay();
622
756
  res.json(result);
623
757
  });
624
758
  });
625
759
 
626
760
  app.delete('/api/client-auth/clients', async (req, res, next) => {
627
- await runWithUiAuth(req, res, next, async () => {
761
+ await runWithClientManagementAuth(req, res, next, async (authContext) => {
762
+ if (authContext.type === 'client') {
763
+ const actingClient = await clientRecordFromAuthContext(authContext);
764
+ // Purging revoked devices is a whole-server management action; only the
765
+ // trusted desktop shell client (or a UI session) may do it.
766
+ if (actingClient?.clientKind !== 'desktop-local') {
767
+ return res.status(403).json({ purged: 0, error: 'Client tokens cannot purge revoked devices' });
768
+ }
769
+ }
628
770
  const result = await remoteClientAuthRuntime.purgeRevokedClients();
771
+ void reconcileRelay();
629
772
  res.json(result);
630
- }, { sessionOnly: true });
773
+ });
774
+ });
775
+
776
+ app.post('/api/client-auth/pairing/sessions', express.json({ limit: '64kb' }), async (req, res, next) => {
777
+ await runWithClientCreateAuth(req, res, next, async (authContext) => {
778
+ const candidates = await pairingServerCandidates(req, {
779
+ preferredServerUrl: req.body?.serverUrl,
780
+ includeRelay: typeof req.body?.includeRelay === 'boolean' ? req.body.includeRelay : undefined,
781
+ includeDirect: req.body?.includeDirect !== false,
782
+ });
783
+ const usesRelay = candidates.some((candidate) => candidate.type === 'relay');
784
+ const result = await clientPairingRuntime.createPairingSession({
785
+ label: req.body?.label,
786
+ allowedClientKinds: req.body?.allowedClientKinds,
787
+ createdByClientId: clientIdFromAuthContext(authContext),
788
+ usesRelay,
789
+ });
790
+ void reconcileRelay();
791
+ res.setHeader('Cache-Control', 'no-store');
792
+ res.status(201).json({
793
+ ...result,
794
+ server: { label: getServerLabel(), candidates },
795
+ });
796
+ });
797
+ });
798
+
799
+ // Direct transports the server can be reached on (for the create-device dialog).
800
+ app.get('/api/client-auth/pairing/transports', async (req, res, next) => {
801
+ await runWithClientCreateAuth(req, res, next, async () => {
802
+ res.setHeader('Cache-Control', 'no-store');
803
+ res.json(getPairingTransports(req));
804
+ });
805
+ });
806
+
807
+ // Pending pairing sessions (link created, device not yet connected) for the
808
+ // "pending devices" list. Secrets are never included.
809
+ app.get('/api/client-auth/pairing/sessions', async (req, res, next) => {
810
+ await runWithClientCreateAuth(req, res, next, async () => {
811
+ const pending = await clientPairingRuntime.listPendingSessions();
812
+ res.setHeader('Cache-Control', 'no-store');
813
+ res.json({ pending });
814
+ });
815
+ });
816
+
817
+ app.delete('/api/client-auth/pairing/sessions/:id', async (req, res, next) => {
818
+ await runWithClientCreateAuth(req, res, next, async () => {
819
+ const result = await clientPairingRuntime.cancelPairingSession(req.params?.id);
820
+ if (!result.cancelled) {
821
+ return res.status(404).json({ cancelled: false, error: 'Pairing session not found' });
822
+ }
823
+ void reconcileRelay();
824
+ res.json(result);
825
+ });
826
+ });
827
+
828
+ app.post('/api/client-auth/pairing/redeem', express.json({ limit: '64kb' }), async (req, res, next) => {
829
+ try {
830
+ const rateLimit = checkPairingRedeemRateLimit(req);
831
+ res.setHeader('X-RateLimit-Limit', PAIRING_REDEEM_RATE_LIMIT_MAX_ATTEMPTS);
832
+ res.setHeader('X-RateLimit-Remaining', rateLimit.remaining);
833
+ res.setHeader('X-RateLimit-Reset', rateLimit.reset);
834
+ if (!rateLimit.allowed) {
835
+ res.setHeader('Retry-After', rateLimit.retryAfter);
836
+ return res.status(429).json({ error: 'Invalid or expired pairing session' });
837
+ }
838
+ const result = await clientPairingRuntime.redeemPairingSession({
839
+ pairingId: req.body?.pairingId,
840
+ secret: req.body?.secret,
841
+ clientLabel: req.body?.clientLabel,
842
+ clientKind: req.body?.clientKind,
843
+ deviceName: req.body?.deviceName,
844
+ devicePlatform: req.body?.devicePlatform,
845
+ deviceModel: req.body?.deviceModel,
846
+ appVersion: req.body?.appVersion,
847
+ dedupeKey: req.body?.dedupeKey,
848
+ });
849
+ clearPairingRedeemRateLimit(req);
850
+ // The session became a device: relay demand may have moved from the pending
851
+ // session to the paired device (or a non-relay redeem may drop it).
852
+ void reconcileRelay();
853
+ res.setHeader('Cache-Control', 'no-store');
854
+ res.json({
855
+ ok: true,
856
+ server: {
857
+ label: getServerLabel(),
858
+ url: requestOrigin(req),
859
+ fingerprint: result.pairing?.fingerprint || null,
860
+ },
861
+ client: result.client,
862
+ clientToken: result.token,
863
+ });
864
+ } catch (error) {
865
+ if (error?.message === 'Invalid or expired pairing session') {
866
+ sendPairingRedeemError(res, error);
867
+ return;
868
+ }
869
+ next(error);
870
+ }
631
871
  });
632
872
 
633
873
  app.get('/connect', async (req, res) => {