@openchamber/web 1.14.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
  8. package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
  9. package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
  10. package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
  12. package/dist/assets/es-r0_jT91q.js +15 -0
  13. package/dist/assets/fr-Bo8rtAJ1.js +13 -0
  14. package/dist/assets/index-8J6waVO6.js +2 -0
  15. package/dist/assets/index-DEMqM4Lz.css +1 -0
  16. package/dist/assets/ja-BPWtkG-c.js +15 -0
  17. package/dist/assets/ko-Bv0k-0E3.js +15 -0
  18. package/dist/assets/main-B-GA5Tg5.js +237 -0
  19. package/dist/assets/main-Dfm-VKZ9.js +2 -0
  20. package/dist/assets/miniChat-CfmCFFfu.js +2 -0
  21. package/dist/assets/mobile-CXJqeDlm.js +2 -0
  22. package/dist/assets/pl-CiTP50bz.js +15 -0
  23. package/dist/assets/pt-BR-DadIjX5L.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
  25. package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
  27. package/dist/assets/uk-2RpsWGoZ.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
  31. package/dist/assets/zh-TW--f_BqBpD.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +236 -2
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  41. package/server/lib/notifications/apns-runtime.js +11 -16
  42. package/server/lib/notifications/runtime.js +135 -33
  43. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  44. package/server/lib/opencode/agents.js +3 -0
  45. package/server/lib/opencode/bootstrap-runtime.js +15 -0
  46. package/server/lib/opencode/core-routes.js +321 -8
  47. package/server/lib/opencode/core-routes.test.js +329 -9
  48. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  49. package/server/lib/opencode/network-runtime.js +14 -1
  50. package/server/lib/opencode/network-runtime.test.js +29 -9
  51. package/server/lib/opencode/proxy.js +47 -6
  52. package/server/lib/opencode/settings-helpers.js +24 -0
  53. package/server/lib/opencode/settings-helpers.test.js +25 -0
  54. package/server/lib/opencode/settings-normalization-runtime.js +21 -4
  55. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  56. package/server/lib/opencode/settings-runtime.js +25 -0
  57. package/server/lib/opencode/shutdown-runtime.js +2 -0
  58. package/server/lib/opencode/tunnel-auth.js +4 -9
  59. package/server/lib/package-manager.js +18 -5
  60. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  61. package/server/lib/permission-auto-accept/runtime.js +263 -0
  62. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  63. package/server/lib/projects/project-config.js +8 -0
  64. package/server/lib/quota/DOCUMENTATION.md +5 -2
  65. package/server/lib/quota/credentials/providers.js +43 -0
  66. package/server/lib/quota/credentials/store.js +48 -0
  67. package/server/lib/quota/credentials/store.test.js +26 -0
  68. package/server/lib/quota/opencode-go-credentials.js +11 -0
  69. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  70. package/server/lib/quota/providers/codex.js +7 -4
  71. package/server/lib/quota/providers/codex.test.js +48 -0
  72. package/server/lib/quota/providers/cursor.js +28 -39
  73. package/server/lib/quota/providers/index.js +7 -0
  74. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  75. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  76. package/server/lib/quota/providers/opencode-go.js +70 -0
  77. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  78. package/server/lib/quota/routes.js +78 -7
  79. package/server/lib/quota/routes.test.js +40 -0
  80. package/server/lib/relay/DOCUMENTATION.md +98 -0
  81. package/server/lib/relay/cross-compat.test.js +135 -0
  82. package/server/lib/relay/e2ee.js +341 -0
  83. package/server/lib/relay/e2ee.test.js +124 -0
  84. package/server/lib/relay/host-client.js +389 -0
  85. package/server/lib/relay/host-client.test.js +280 -0
  86. package/server/lib/relay/host-lock.js +101 -0
  87. package/server/lib/relay/host-lock.test.js +129 -0
  88. package/server/lib/relay/identity.js +93 -0
  89. package/server/lib/relay/identity.test.js +78 -0
  90. package/server/lib/relay/service.js +334 -0
  91. package/server/lib/relay/signing-key.js +73 -0
  92. package/server/lib/relay/tunnel-codec.js +373 -0
  93. package/server/lib/relay/tunnel-codec.test.js +58 -0
  94. package/server/lib/relay/tunnel-host.js +462 -0
  95. package/server/lib/scheduled-tasks/runtime.js +104 -0
  96. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  97. package/server/lib/session-goal/objectives.js +61 -0
  98. package/server/lib/session-goal/routes.js +36 -0
  99. package/server/lib/session-goal/runtime.js +764 -0
  100. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  101. package/server/lib/ui-auth/ui-auth.js +10 -0
  102. package/server/opencode-proxy.test.js +38 -0
  103. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  104. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  105. package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
  106. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  107. package/dist/assets/es-bWcuDy_2.js +0 -15
  108. package/dist/assets/fr-DzRs3OzV.js +0 -13
  109. package/dist/assets/index-KnWk9fmM.css +0 -1
  110. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  111. package/dist/assets/ja-BqUX_UD3.js +0 -15
  112. package/dist/assets/ko-BQo10SNx.js +0 -15
  113. package/dist/assets/main-BDoqLlQB.js +0 -236
  114. package/dist/assets/main-DUGyTrDt.js +0 -2
  115. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  116. package/dist/assets/mobile-DnghtOCb.js +0 -2
  117. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  118. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  119. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  120. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  121. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  122. package/dist/assets/uk-C9k8SP8q.js +0 -15
  123. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  124. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
@@ -0,0 +1,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
+ };
@@ -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
  };
@@ -45,7 +45,7 @@ This module provides notification message preparation utilities for the web serv
45
45
  - Returned API:
46
46
  - `maybeSendPushForTrigger(payload)`
47
47
  - Owns:
48
- - completion/error/question/permission trigger routing
48
+ - completion/error/question/permission trigger routing; permission suppression consults the authoritative permission-auto-accept runtime
49
49
  - session parent cache for subtask suppression
50
50
  - template resolution and fallback behavior
51
51
  - native notification fanout and web push payload fanout
@@ -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';
@@ -37,6 +42,8 @@ export const createApnsRuntime = (deps) => {
37
42
  APNS_TOKENS_FILE_PATH,
38
43
  readSettingsFromDiskMigrated,
39
44
  writeSettingsToDisk,
45
+ // Strict settings reader gating identity regeneration (see signing-key.js).
46
+ readSettingsStrict,
40
47
  } = deps;
41
48
 
42
49
  let persistLock = Promise.resolve();
@@ -51,27 +58,15 @@ export const createApnsRuntime = (deps) => {
51
58
  // device token alone can't be used to push. Zero-config: the keypair generates on first use.
52
59
  // ---------------------------------------------------------------------------
53
60
 
61
+ // Key access lives in lib/relay/signing-key.js now (shared with the private
62
+ // relay identity — same keypair, same storage, same serverId derivation).
54
63
  const getOrCreateRelayKeypair = async () => {
55
64
  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 };
65
+ cachedRelayKey = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
70
66
  return cachedRelayKey;
71
67
  };
72
68
 
73
- const signRelayMessage = (privateKey, message) =>
74
- crypto.sign('SHA256', Buffer.from(message), { key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');
69
+ const signRelayMessage = (privateKey, message) => signRelayMessageShared({ crypto }, privateKey, message);
75
70
 
76
71
  // Trim to the 4 fields the relay's schema accepts (and that feed the serverId hash).
77
72
  const relayPublicJwk = (publicJwk) => ({