@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

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.
package/server.js ADDED
@@ -0,0 +1,2648 @@
1
+ // Standalone pairing + WebSocket gateway for the mobile companion.
2
+ // This file owns transport, security and framing; the DSH bridge owns runtime
3
+ // operations, so the server never touches Harness internals directly.
4
+ import { createHash, randomBytes } from 'node:crypto'
5
+ import { createServer } from 'node:http'
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { homedir, networkInterfaces } from 'node:os'
8
+ import { appendFile, readFile, writeFile, rename } from 'node:fs/promises'
9
+ import { join } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+
12
+ import { createAuth, equals } from './auth.js'
13
+ import { createPushService } from './push.js'
14
+ import { qrSvg } from './qr.js'
15
+
16
+ const VERSION = '0.0.6'
17
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
18
+ const MAX_MESSAGE_BYTES = 1024 * 1024
19
+ const MAX_BODY_BYTES = 64 * 1024
20
+ const COOKIE_NAME = 'dsh_rm_session'
21
+ // Web Push fan-out limits: process-wide rate, per-tag replay window and the
22
+ // "reply ready" quiet period per session.
23
+ const PUSH_MAX_PER_MINUTE = 30
24
+ const PUSH_RATE_WINDOW_MS = 60 * 1000
25
+ // The explicit test-notification action bypasses the automatic limiter, so it
26
+ // gets its own small per-device window; a device may also keep at most four
27
+ // push subscriptions (one browser usually registers one).
28
+ const PUSH_TEST_WINDOW_MS = 60 * 1000
29
+ const PUSH_TEST_MAX_PER_DEVICE = 6
30
+ const MAX_SUBSCRIPTIONS_PER_DEVICE = 4
31
+ const PUSH_TAG_TTL_MS = 5 * 60 * 1000
32
+ const PUSH_TAG_LIMIT = 200
33
+ const PUSH_REPLY_INTERVAL_MS = 60 * 1000
34
+ const PUSH_BODY_CHARS = 160
35
+ const STATIC_FILES = new Map([
36
+ ['/', { file: 'index.html', type: 'text/html; charset=utf-8' }],
37
+ ['/index.html', { file: 'index.html', type: 'text/html; charset=utf-8' }],
38
+ ['/app.js', { file: 'app.js', type: 'text/javascript; charset=utf-8' }],
39
+ ['/styles.css', { file: 'styles.css', type: 'text/css; charset=utf-8' }],
40
+ // Installable web app. The service worker must be served from the site root so
41
+ // its scope covers the whole app.
42
+ ['/manifest.webmanifest', { file: 'manifest.webmanifest', type: 'application/manifest+json; charset=utf-8' }],
43
+ ['/sw.js', { file: 'sw.js', type: 'text/javascript; charset=utf-8' }],
44
+ ['/icons/icon-192.png', { file: 'icons/icon-192.png', type: 'image/png' }],
45
+ ['/icons/icon-512.png', { file: 'icons/icon-512.png', type: 'image/png' }],
46
+ ['/icons/icon-maskable-512.png', { file: 'icons/icon-maskable-512.png', type: 'image/png' }],
47
+ ['/icons/apple-touch-icon.png', { file: 'icons/apple-touch-icon.png', type: 'image/png' }],
48
+ ['/favicon.svg', { file: 'favicon.svg', type: 'image/svg+xml' }],
49
+ ])
50
+
51
+ function normalizeIp(value) {
52
+ if (typeof value !== 'string') return 'unknown'
53
+ return value.startsWith('::ffff:') ? value.slice(7) : value
54
+ }
55
+
56
+ function parseCookies(header) {
57
+ const out = new Map()
58
+ if (typeof header !== 'string') return out
59
+ for (const part of header.split(';')) {
60
+ const at = part.indexOf('=')
61
+ if (at === -1) continue
62
+ const key = part.slice(0, at).trim()
63
+ const value = part.slice(at + 1).trim()
64
+ if (key.length > 0) out.set(key, value)
65
+ }
66
+ return out
67
+ }
68
+
69
+ function jsonResponse(res, status, body, extraHeaders = {}) {
70
+ const text = JSON.stringify(body)
71
+ res.writeHead(status, {
72
+ 'content-type': 'application/json; charset=utf-8',
73
+ 'cache-control': 'no-store',
74
+ 'x-content-type-options': 'nosniff',
75
+ ...extraHeaders,
76
+ })
77
+ res.end(text)
78
+ }
79
+
80
+ /**
81
+ * Collapse one client-supplied value into a bounded single-line log field.
82
+ * Diagnostics must never inject new lines (log forging) or unbounded text into
83
+ * the debug log.
84
+ */
85
+ function logField(value, max) {
86
+ if (typeof value !== 'string') return ''
87
+ return value
88
+ .replace(/[\u0000-\u001f\u007f]+/gu, ' ')
89
+ .replace(/\s+/gu, ' ')
90
+ .trim()
91
+ .slice(0, max)
92
+ }
93
+
94
+ /** Operator-configured additional push-service host suffixes. */
95
+ function pushEndpointSuffixes() {
96
+ const raw = process.env.PA_REMOTE_MOBILE_PUSH_HOSTS
97
+ if (typeof raw !== 'string' || raw.trim().length === 0) return []
98
+ return raw.split(',').map((item) => item.trim()).filter((item) => item.length > 0)
99
+ }
100
+
101
+ /** Read a request body with a hard byte cap; rejects with `body-too-large`. */
102
+ function readBodyBuffer(req, limit = MAX_BODY_BYTES) {
103
+ return new Promise((resolve, reject) => {
104
+ const chunks = []
105
+ let size = 0
106
+ req.on('data', (chunk) => {
107
+ size += chunk.length
108
+ if (size > limit) {
109
+ reject(new Error('body-too-large'))
110
+ req.destroy()
111
+ return
112
+ }
113
+ chunks.push(chunk)
114
+ })
115
+ req.on('end', () => resolve(Buffer.concat(chunks)))
116
+ req.on('error', reject)
117
+ })
118
+ }
119
+
120
+ async function readBody(req, limit = MAX_BODY_BYTES) {
121
+ return (await readBodyBuffer(req, limit)).toString('utf8')
122
+ }
123
+
124
+ async function readJsonBody(req, limit) {
125
+ const text = await readBody(req, limit)
126
+ if (text.length === 0) return {}
127
+ const parsed = JSON.parse(text)
128
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
129
+ throw new Error('body-not-object')
130
+ }
131
+ return parsed
132
+ }
133
+
134
+ /** Minimal RFC 6455 server-side connection: text JSON frames only. */
135
+ class WebSocketPeer {
136
+ constructor(socket, request, device, log) {
137
+ this.socket = socket
138
+ this.request = request
139
+ this.device = device
140
+ this.log = log
141
+ this.buffer = Buffer.alloc(0)
142
+ this.fragments = []
143
+ this.open = true
144
+ this.finished = false
145
+ this.lastActivity = Date.now()
146
+ this.listeners = { message: [], close: [] }
147
+ socket.on('data', (chunk) => this.onData(chunk))
148
+ socket.on('error', () => this.destroy())
149
+ // HTTP server sockets allow half-open TCP; without this a browser that
150
+ // disappears without a WebSocket close frame (tab killed, network lost)
151
+ // would stay in `peers` until the heartbeat times out.
152
+ socket.on('end', () => this.destroy())
153
+ socket.on('close', () => this.finish())
154
+ this.handshake()
155
+ }
156
+
157
+ handshake() {
158
+ const key = this.request.headers['sec-websocket-key']
159
+ if (typeof key !== 'string') {
160
+ this.destroy()
161
+ return
162
+ }
163
+ const accept = createHash('sha1').update(key + WS_GUID).digest('base64')
164
+ this.socket.write(
165
+ 'HTTP/1.1 101 Switching Protocols\r\n'
166
+ + 'Upgrade: websocket\r\n'
167
+ + 'Connection: Upgrade\r\n'
168
+ + `Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
169
+ )
170
+ }
171
+
172
+ on(event, callback) {
173
+ this.listeners[event].push(callback)
174
+ }
175
+
176
+ onData(chunk) {
177
+ this.lastActivity = Date.now()
178
+ this.buffer = Buffer.concat([this.buffer, chunk])
179
+ while (this.buffer.length >= 2) {
180
+ const first = this.buffer[0]
181
+ const second = this.buffer[1]
182
+ const fin = (first & 0x80) !== 0
183
+ const opcode = first & 0x0f
184
+ const masked = (second & 0x80) !== 0
185
+ let length = second & 0x7f
186
+ let offset = 2
187
+ if (length === 126) {
188
+ if (this.buffer.length < 4) return
189
+ length = this.buffer.readUInt16BE(2)
190
+ offset = 4
191
+ } else if (length === 127) {
192
+ if (this.buffer.length < 10) return
193
+ const big = this.buffer.readBigUInt64BE(2)
194
+ if (big > BigInt(MAX_MESSAGE_BYTES)) {
195
+ this.close(1009, 'message too large')
196
+ return
197
+ }
198
+ length = Number(big)
199
+ offset = 10
200
+ }
201
+ if (length > MAX_MESSAGE_BYTES) {
202
+ this.close(1009, 'message too large')
203
+ return
204
+ }
205
+ if (!masked) {
206
+ this.close(1002, 'client frames must be masked')
207
+ return
208
+ }
209
+ if (this.buffer.length < offset + 4 + length) return
210
+ const mask = this.buffer.subarray(offset, offset + 4)
211
+ const payload = Buffer.from(this.buffer.subarray(offset + 4, offset + 4 + length))
212
+ for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i % 4]
213
+ this.buffer = this.buffer.subarray(offset + 4 + length)
214
+ this.handleFrame(opcode, fin, payload)
215
+ }
216
+ }
217
+
218
+ handleFrame(opcode, fin, payload) {
219
+ if (opcode === 0x8) {
220
+ this.close(1000, 'bye')
221
+ return
222
+ }
223
+ if (opcode === 0x9) {
224
+ this.sendFrame(0x0a, payload)
225
+ return
226
+ }
227
+ if (opcode === 0x0a) return
228
+ if (opcode === 0x0 || opcode === 0x1) {
229
+ this.fragments.push(payload)
230
+ const total = this.fragments.reduce((sum, item) => sum + item.length, 0)
231
+ if (total > MAX_MESSAGE_BYTES) {
232
+ this.close(1009, 'message too large')
233
+ return
234
+ }
235
+ if (!fin) return
236
+ const text = Buffer.concat(this.fragments).toString('utf8')
237
+ this.fragments = []
238
+ let parsed
239
+ try {
240
+ parsed = JSON.parse(text)
241
+ } catch {
242
+ this.sendObject({ type: 'error', code: 'bad-request', message: 'invalid JSON frame' })
243
+ return
244
+ }
245
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
246
+ this.sendObject({ type: 'error', code: 'bad-request', message: 'frame must be an object' })
247
+ return
248
+ }
249
+ for (const listener of this.listeners.message) {
250
+ try {
251
+ listener(parsed)
252
+ } catch (error) {
253
+ this.log.warn?.(`remote-mobile: frame handler failed: ${error instanceof Error ? error.message : String(error)}`)
254
+ }
255
+ }
256
+ return
257
+ }
258
+ this.close(1003, 'unsupported opcode')
259
+ }
260
+
261
+ sendFrame(opcode, payload) {
262
+ if (!this.open || this.socket.destroyed) return
263
+ const length = payload.length
264
+ let header
265
+ if (length < 126) {
266
+ header = Buffer.from([0x80 | opcode, length])
267
+ } else if (length < 65536) {
268
+ header = Buffer.alloc(4)
269
+ header[0] = 0x80 | opcode
270
+ header[1] = 126
271
+ header.writeUInt16BE(length, 2)
272
+ } else {
273
+ header = Buffer.alloc(10)
274
+ header[0] = 0x80 | opcode
275
+ header[1] = 127
276
+ header.writeBigUInt64BE(BigInt(length), 2)
277
+ }
278
+ try {
279
+ this.socket.write(Buffer.concat([header, payload]))
280
+ } catch {
281
+ this.destroy()
282
+ }
283
+ }
284
+
285
+ sendObject(value) {
286
+ if (!this.open) return
287
+ if (this.socket.writableLength > 4 * 1024 * 1024) {
288
+ this.close(1011, 'client too slow')
289
+ return
290
+ }
291
+ this.sendFrame(0x01, Buffer.from(JSON.stringify(value), 'utf8'))
292
+ }
293
+
294
+ ping() {
295
+ this.sendFrame(0x09, Buffer.alloc(0))
296
+ }
297
+
298
+ close(code = 1000, reason = '') {
299
+ if (!this.open) return
300
+ try {
301
+ const status = Buffer.alloc(2)
302
+ status.writeUInt16BE(code, 0)
303
+ const text = Buffer.from(reason, 'utf8')
304
+ this.sendFrame(0x08, Buffer.concat([status, text]))
305
+ } catch {
306
+ // the socket may already be gone; the destroy below is the fallback
307
+ }
308
+ this.open = false
309
+ try {
310
+ this.socket.end()
311
+ } catch {
312
+ this.socket.destroy()
313
+ }
314
+ }
315
+
316
+ destroy() {
317
+ this.open = false
318
+ try {
319
+ this.socket.destroy()
320
+ } catch {
321
+ // already gone
322
+ }
323
+ }
324
+
325
+ finish() {
326
+ // Runs once, on the socket's own close event. `close()`/`destroy()` mark
327
+ // `open` false first, so this must not gate on it: the server's `close`
328
+ // listeners are what remove the peer from `peers`.
329
+ if (this.finished) return
330
+ this.finished = true
331
+ this.open = false
332
+ for (const listener of this.listeners.close) {
333
+ try {
334
+ listener()
335
+ } catch {
336
+ // ignore listener failures
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Rank local IPv4 addresses for the pairing URL. Real Wi-Fi/Ethernet interfaces
344
+ * beat virtual switches (Hyper-V, WSL, Docker) and Windows ICS/hotspot adapters,
345
+ * and Tailscale ranks just below a physical LAN interface so a phone on the
346
+ * tailnet can still be reached.
347
+ *
348
+ * @param {string} bindHost configured bind address
349
+ * @returns {Array<{ address: string, name: string }>}
350
+ */
351
+ function localAddressEntries(bindHost) {
352
+ if (typeof bindHost === 'string' && bindHost !== '0.0.0.0' && bindHost !== '::' && bindHost !== '::0') {
353
+ return [{ address: bindHost, name: 'configured bind address' }]
354
+ }
355
+ const entries = []
356
+ const interfaces = networkInterfaces()
357
+ for (const [name, group] of Object.entries(interfaces)) {
358
+ if (!group) continue
359
+ for (const entry of group) {
360
+ if (entry.family !== 'IPv4' || entry.internal) continue
361
+ if (entry.address.startsWith('169.254.')) continue
362
+ let score = 0
363
+ if (/tailscale/i.test(name)) score += 120
364
+ else if (/^wi-?fi$|^wlan|^wireless|^ethernet$/i.test(name)) score += 100
365
+ else if (/ethernet/i.test(name) && !/vethernet|virtual/i.test(name)) score += 80
366
+ else if (/vethernet|hyper-v|virtual|vmware|virtualbox|docker|wsl/i.test(name)) score -= 60
367
+ else if (/local area connection/i.test(name)) score -= 30
368
+ if (/^192\.168\./.test(entry.address)) score += 10
369
+ else if (/^10\./.test(entry.address)) score += 8
370
+ else if (/^172\.(1[6-9]|2\d|3[01])\./.test(entry.address)) score += 6
371
+ entries.push({ address: entry.address, name, score })
372
+ }
373
+ }
374
+ if (entries.length === 0) return [{ address: '127.0.0.1', name: 'loopback' }]
375
+ entries.sort((left, right) => right.score - left.score)
376
+ return entries.map((entry) => ({ address: entry.address, name: entry.name }))
377
+ }
378
+
379
+ function localAddresses(bindHost) {
380
+ return localAddressEntries(bindHost).map((entry) => entry.address)
381
+ }
382
+
383
+ /**
384
+ * Where pairing state lives. The CLI sets DSH_HOME, but a desktop-launched
385
+ * Host often does not, so fall back to the conventional `~/.dsh` directory
386
+ * (the same home that owns `.credentials.yaml`). No directory means memory-only.
387
+ */
388
+ function resolveStatePath() {
389
+ const fromEnv = process.env.DSH_HOME
390
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return join(fromEnv, 'remote-mobile-state.json')
391
+ try {
392
+ const fallback = join(homedir(), '.dsh')
393
+ if (existsSync(fallback)) return join(fallback, 'remote-mobile-state.json')
394
+ } catch {
395
+ // fall through to memory-only
396
+ }
397
+ return null
398
+ }
399
+
400
+ /**
401
+ * Optional advertised URL in front of the mobile server (for example a
402
+ * Tailscale Serve HTTPS endpoint). Configured with
403
+ * `PA_REMOTE_MOBILE_PUBLIC_URL` or a `<state>.public-url` file.
404
+ */
405
+ function resolvePublicUrl(statePath) {
406
+ const fromEnv = process.env.PA_REMOTE_MOBILE_PUBLIC_URL
407
+ if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim().replace(/\/+$/, '')
408
+ if (statePath !== null) {
409
+ try {
410
+ const text = readFileSync(`${statePath}.public-url`, 'utf8').trim()
411
+ if (text.length > 0) return text.replace(/\/+$/, '')
412
+ } catch {
413
+ // no public URL configured
414
+ }
415
+ }
416
+ return null
417
+ }
418
+
419
+ /**
420
+ * Whether the phone server should start with the Host. The desktop panel's
421
+ * on/off switch persists here; absent means enabled.
422
+ */
423
+ function resolveEnabled(statePath) {
424
+ if (statePath === null) return true
425
+ try {
426
+ return readFileSync(`${statePath}.enabled`, 'utf8').trim() !== '0'
427
+ } catch {
428
+ return true
429
+ }
430
+ }
431
+
432
+ /**
433
+ * The plugin's mobile server. `start()` is idempotent; `stop()` releases every
434
+ * socket, timer and listener.
435
+ */
436
+ export class RemoteMobileServer {
437
+ /**
438
+ * @param {object} ctx Cordis host context (accepted for parity with the other
439
+ * halves; the server logs through the injected `log` only)
440
+ * @param {object} config plugin config
441
+ * @param {object} bridge DSH bridge from bridge.js
442
+ * @param {object} log logger with info/warn/error
443
+ */
444
+ constructor(ctx, config, bridge, log) {
445
+ this.config = config ?? {}
446
+ this.bridge = bridge
447
+ this.log = log ?? console
448
+ this.port = Number.isInteger(this.config.port) ? this.config.port : 3456
449
+ this.bindHost = typeof this.config.host === 'string' ? this.config.host : '0.0.0.0'
450
+ this.started = false
451
+ this.server = null
452
+ this.auth = null
453
+ this.publicUrl = null
454
+ this.enabled = true
455
+ this.listening = false
456
+ this.deskKey = randomBytes(24).toString('hex')
457
+ this.peers = new Set()
458
+ this.pendingApprovals = new Map()
459
+ this.pendingQuestions = new Map()
460
+ // Which surface answered a pending interaction, keyed by request id, so the
461
+ // resolved frame can tell the phone "the desktop answered this one".
462
+ this.answerOrigins = new Map()
463
+ this.assistantBuffers = new Map()
464
+ // Pending queue-change coalescing, so an inbox splice and the following turn
465
+ // boundary cannot fan out duplicate `queue.changed` frames.
466
+ this.queueTimers = new Map()
467
+ this.queuedQueues = new Map()
468
+ this.staticCache = new Map()
469
+ this.heartbeat = null
470
+ this.flushTimer = null
471
+ this.saveTimer = null
472
+ this.savePending = false
473
+ this.statePath = null
474
+ this.unsubscribeBridge = null
475
+ this.sessionRefreshTimer = null
476
+ // Web Push service (VAPID key + subscriptions), created in start().
477
+ this.push = null
478
+ // deviceId -> whether that device currently has a foreground/visible phone
479
+ // page. Absent means "unknown", which is treated as not visible.
480
+ this.deviceVisibility = new Map()
481
+ this.pushTags = new Map()
482
+ this.pushWindowStart = 0
483
+ this.pushWindowCount = 0
484
+ // Per-device windows for the explicit "send test notification" action; the
485
+ // test path bypasses the automatic dispatch limiter, so it needs its own cap.
486
+ this.pushTestWindows = new Map()
487
+ this.replyPushAt = new Map()
488
+ // Per-session assistant text, so a "reply ready" push can carry a short
489
+ // excerpt instead of only the session title. Bounded to a few recent turns.
490
+ this.replyBuffer = new Map()
491
+ this.replyText = new Map()
492
+ }
493
+
494
+ baseUrl() {
495
+ const address = localAddresses(this.bindHost)[0]
496
+ return `http://${address}:${this.port}`
497
+ }
498
+
499
+ async start() {
500
+ if (this.started) return
501
+ this.started = true
502
+ this.statePath = resolveStatePath()
503
+ this.publicUrl = resolvePublicUrl(this.statePath)
504
+ this.enabled = resolveEnabled(this.statePath)
505
+ let persisted = null
506
+ if (this.statePath !== null) {
507
+ try {
508
+ persisted = JSON.parse(await readFile(this.statePath, 'utf8'))
509
+ } catch {
510
+ persisted = null
511
+ }
512
+ }
513
+ const secret = persisted !== null && typeof persisted.secret === 'string' && persisted.secret.length >= 32
514
+ ? persisted.secret
515
+ : randomBytes(32).toString('base64url')
516
+ this.auth = createAuth({ secret, log: this.log })
517
+ if (persisted !== null) this.auth.importState(persisted)
518
+ // Real Web Push: VAPID keys are generated once and restored from the same
519
+ // state file (the `push` field, absent in state files written by older
520
+ // versions). Subscriptions belong to paired devices and survive restarts.
521
+ this.push = createPushService({
522
+ log: this.log,
523
+ state: persisted !== null && typeof persisted === 'object' ? persisted.push ?? null : null,
524
+ allowedEndpointSuffixes: pushEndpointSuffixes(),
525
+ subject: typeof process.env.PA_REMOTE_MOBILE_VAPID_SUBJECT === 'string'
526
+ ? process.env.PA_REMOTE_MOBILE_VAPID_SUBJECT
527
+ : undefined,
528
+ })
529
+ // Persist a freshly generated VAPID key immediately: without this a Host
530
+ // restart before the first state save would rotate the key and silently
531
+ // invalidate every existing browser push subscription.
532
+ if (this.push !== null) this.scheduleSave()
533
+ // A per-process key gates the desktop panel's status endpoint. Persisting it
534
+ // under the owner-only state directory lets local tooling (and the user's own
535
+ // scripts) reach pairing status; it never grants network access on its own.
536
+ if (this.statePath !== null) {
537
+ try {
538
+ await writeFile(`${this.statePath}.desk-key`, this.deskKey, { mode: 0o600 })
539
+ } catch (error) {
540
+ this.log.warn?.(`remote-mobile: cannot persist desktop panel key: ${error instanceof Error ? error.message : String(error)}`)
541
+ }
542
+ }
543
+
544
+ for (const [route, spec] of STATIC_FILES) {
545
+ try {
546
+ const file = fileURLToPath(new URL(`./mobile/${spec.file}`, import.meta.url))
547
+ const body = await readFile(file)
548
+ this.staticCache.set(route, { body, type: spec.type })
549
+ } catch (error) {
550
+ this.log.warn?.(`remote-mobile: cannot read mobile/${spec.file}: ${error instanceof Error ? error.message : String(error)}`)
551
+ }
552
+ }
553
+
554
+ this.wireBridge()
555
+ if (this.enabled) {
556
+ try {
557
+ await this.listen()
558
+ } catch (error) {
559
+ this.log.error?.(`remote-mobile: server failed to start: ${error instanceof Error ? error.message : String(error)}`)
560
+ }
561
+ } else {
562
+ this.log.info?.('remote-mobile: disabled by the desktop switch')
563
+ }
564
+ }
565
+
566
+ async listen() {
567
+ if (this.listening) return
568
+ const server = createServer((req, res) => {
569
+ this.handleHttp(req, res).catch((error) => {
570
+ this.log.warn?.(`remote-mobile: request failed: ${error instanceof Error ? error.message : String(error)}`)
571
+ if (!res.headersSent) jsonResponse(res, 500, { error: 'internal' })
572
+ else res.destroy()
573
+ })
574
+ })
575
+ // The raw upgraded socket is ours after this point: keep an error listener on
576
+ // it from the first byte so a reset during the 401/handshake write cannot
577
+ // surface as an unhandled 'error' event.
578
+ server.on('upgrade', (req, socket, head) => {
579
+ socket.on('error', () => {
580
+ try {
581
+ socket.destroy()
582
+ } catch {
583
+ // already gone
584
+ }
585
+ })
586
+ try {
587
+ this.handleUpgrade(req, socket, head)
588
+ } catch {
589
+ try {
590
+ socket.destroy()
591
+ } catch {
592
+ // already gone
593
+ }
594
+ }
595
+ })
596
+ server.on('clientError', (_error, socket) => {
597
+ socket.on('error', () => {
598
+ try {
599
+ socket.destroy()
600
+ } catch {
601
+ // already gone
602
+ }
603
+ })
604
+ try {
605
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
606
+ } catch {
607
+ socket.destroy()
608
+ }
609
+ })
610
+ try {
611
+ await new Promise((resolve, reject) => {
612
+ const onError = (error) => {
613
+ server.off('listening', onListening)
614
+ reject(error)
615
+ }
616
+ const onListening = () => {
617
+ server.off('error', onError)
618
+ resolve()
619
+ }
620
+ server.once('error', onError)
621
+ server.once('listening', onListening)
622
+ server.listen(this.port, this.bindHost)
623
+ })
624
+ } catch (error) {
625
+ try {
626
+ server.close()
627
+ } catch {
628
+ // already closed
629
+ }
630
+ throw error
631
+ }
632
+ this.server = server
633
+ this.listening = true
634
+ const address = server.address()
635
+ if (address !== null && typeof address === 'object') this.port = address.port
636
+ this.startHeartbeat()
637
+ this.log.info?.(`remote-mobile: listening on ${this.bindHost}:${this.port} (${this.baseUrl()})`)
638
+ }
639
+
640
+ async closeListener() {
641
+ // Timers are cleared before the early return: `stop()` must release them even
642
+ // when the listener was never opened (disabled at boot, failed listen).
643
+ for (const timer of [this.heartbeat, this.flushTimer, this.saveTimer]) {
644
+ if (timer !== null) clearInterval(timer)
645
+ }
646
+ this.heartbeat = null
647
+ this.flushTimer = null
648
+ this.saveTimer = null
649
+ if (this.sessionRefreshTimer !== null) clearTimeout(this.sessionRefreshTimer)
650
+ this.sessionRefreshTimer = null
651
+ // No sockets survive a closed listener, so nothing is visibly foregrounded.
652
+ this.deviceVisibility.clear()
653
+ if (!this.listening) return
654
+ this.listening = false
655
+ this.assistantBuffers.clear()
656
+ for (const peer of [...this.peers]) peer.destroy()
657
+ this.peers.clear()
658
+ if (this.server !== null) {
659
+ const server = this.server
660
+ this.server = null
661
+ await new Promise((resolve) => {
662
+ try {
663
+ server.close(() => resolve())
664
+ } catch {
665
+ resolve()
666
+ }
667
+ server.closeAllConnections?.()
668
+ })
669
+ }
670
+ }
671
+
672
+ async persistEnabled() {
673
+ if (this.statePath === null) return
674
+ try {
675
+ await writeFile(`${this.statePath}.enabled`, this.enabled ? '1' : '0', { mode: 0o600 })
676
+ } catch (error) {
677
+ this.log.warn?.(`remote-mobile: cannot persist the enabled switch: ${error instanceof Error ? error.message : String(error)}`)
678
+ }
679
+ }
680
+
681
+ /**
682
+ * Turn the phone server on or off from the desktop panel. The plugin, bridge
683
+ * and pairing state stay loaded either way; only the listener and its sockets
684
+ * are opened or closed, so the switch is instant and reversible.
685
+ */
686
+ async setEnabled(flag) {
687
+ const next = flag === true
688
+ if (next === this.enabled && next === this.listening) {
689
+ return { ok: true, enabled: next }
690
+ }
691
+ if (next) {
692
+ if (this.started && !this.listening) {
693
+ try {
694
+ await this.listen()
695
+ } catch (error) {
696
+ this.enabled = false
697
+ await this.persistEnabled()
698
+ return { ok: false, enabled: false, error: error instanceof Error ? error.message : String(error) }
699
+ }
700
+ }
701
+ this.enabled = true
702
+ } else {
703
+ await this.closeListener()
704
+ this.enabled = false
705
+ }
706
+ await this.persistEnabled()
707
+ return { ok: true, enabled: this.enabled }
708
+ }
709
+
710
+ startHeartbeat() {
711
+ this.heartbeat = setInterval(() => {
712
+ const cut = Date.now() - 70 * 1000
713
+ for (const peer of this.peers) {
714
+ if (peer.lastActivity < cut) {
715
+ peer.close(1001, 'heartbeat timeout')
716
+ this.peers.delete(peer)
717
+ continue
718
+ }
719
+ peer.ping()
720
+ }
721
+ }, 25 * 1000)
722
+ this.heartbeat.unref?.()
723
+
724
+ this.flushTimer = setInterval(() => this.flushAssistantBuffers(), 33)
725
+ this.flushTimer.unref?.()
726
+
727
+ this.saveTimer = setInterval(() => {
728
+ if (this.savePending) void this.saveState()
729
+ }, 750)
730
+ this.saveTimer.unref?.()
731
+ }
732
+
733
+ wireBridge() {
734
+ if (this.bridge === null || typeof this.bridge.subscribe !== 'function') return
735
+ try {
736
+ this.unsubscribeBridge = this.bridge.subscribe({
737
+ onAssistant: (payload) => this.queueAssistant(payload),
738
+ onTool: (payload) => this.broadcastTool(payload),
739
+ onApproval: (payload) => this.broadcastApproval(payload),
740
+ onApprovalResolved: (payload) => this.broadcastApprovalResolved(payload),
741
+ onQuestion: (payload) => this.broadcastQuestion(payload),
742
+ onQuestionResolved: (payload) => this.broadcastQuestionResolved(payload),
743
+ onQueue: (payload) => this.broadcastQueue(payload),
744
+ onStatus: (payload) => this.broadcastStatus(payload),
745
+ })
746
+ } catch (error) {
747
+ this.log.warn?.(`remote-mobile: cannot subscribe to bridge: ${error instanceof Error ? error.message : String(error)}`)
748
+ }
749
+ }
750
+
751
+ async stop() {
752
+ if (!this.started) return
753
+ this.started = false
754
+ if (this.unsubscribeBridge !== null) {
755
+ try {
756
+ this.unsubscribeBridge()
757
+ } catch {
758
+ // ignore
759
+ }
760
+ this.unsubscribeBridge = null
761
+ }
762
+ await this.closeListener()
763
+ for (const timer of this.queueTimers.values()) clearTimeout(timer)
764
+ this.queueTimers.clear()
765
+ this.queuedQueues.clear()
766
+ await this.saveState()
767
+ try {
768
+ this.bridge?.dispose?.()
769
+ } catch {
770
+ // ignore
771
+ }
772
+ // The bridge settles its waiters on dispose; drop the mirrored state so a
773
+ // later start cannot inherit stale ids.
774
+ this.pendingApprovals.clear()
775
+ this.pendingQuestions.clear()
776
+ this.answerOrigins.clear()
777
+ this.deviceVisibility.clear()
778
+ this.pushTags.clear()
779
+ this.replyPushAt.clear()
780
+ this.replyBuffer.clear()
781
+ this.replyText.clear()
782
+ }
783
+
784
+ scheduleSave() {
785
+ this.savePending = true
786
+ }
787
+
788
+ async saveState() {
789
+ this.savePending = false
790
+ if (this.statePath === null || this.auth === null) return
791
+ const tmp = `${this.statePath}.tmp`
792
+ try {
793
+ const state = this.auth.exportState()
794
+ if (this.push !== null) {
795
+ // Drop subscriptions of devices that were revoked (or evicted by the
796
+ // pairing device cap), then persist the VAPID key and subscriptions
797
+ // beside the pairing state in the same 0600 file.
798
+ this.push.pruneToDevices(state.devices.map((device) => device.id))
799
+ state.push = this.push.exportState()
800
+ }
801
+ const payload = JSON.stringify(state, null, 2)
802
+ await writeFile(tmp, payload, { mode: 0o600 })
803
+ await rename(tmp, this.statePath)
804
+ } catch (error) {
805
+ this.log.warn?.(`remote-mobile: cannot persist pairing state: ${error instanceof Error ? error.message : String(error)}`)
806
+ }
807
+ }
808
+
809
+ isHttps(req) {
810
+ return Boolean(req.socket && req.socket.encrypted) || req.headers['x-forwarded-proto'] === 'https'
811
+ }
812
+
813
+ /**
814
+ * Settle one pending approval and record which surface answered it. The origin
815
+ * is always removed, even when the bridge call throws, so the map cannot leak.
816
+ * @returns the bridge result (`false` = no longer pending).
817
+ */
818
+ async answerApproval(requestId, decision, origin) {
819
+ this.answerOrigins.set(requestId, origin)
820
+ try {
821
+ return await this.callBridge('answerApproval', requestId, decision)
822
+ } finally {
823
+ this.answerOrigins.delete(requestId)
824
+ }
825
+ }
826
+
827
+ cookieHeader(req, value, maxAgeSeconds) {
828
+ const parts = [
829
+ `${COOKIE_NAME}=${value}`,
830
+ 'Path=/',
831
+ 'HttpOnly',
832
+ 'SameSite=Lax',
833
+ `Max-Age=${maxAgeSeconds}`,
834
+ ]
835
+ if (this.isHttps(req)) parts.push('Secure')
836
+ return parts.join('; ')
837
+ }
838
+
839
+ clearCookieHeader(req) {
840
+ const parts = [`${COOKIE_NAME}=`, 'Path=/', 'HttpOnly', 'SameSite=Lax', 'Max-Age=0']
841
+ if (this.isHttps(req)) parts.push('Secure')
842
+ return parts.join('; ')
843
+ }
844
+
845
+ currentDevice(req) {
846
+ if (this.auth === null) return null
847
+ const cookies = parseCookies(req.headers.cookie)
848
+ return this.auth.deviceFromCookie(cookies.get(COOKIE_NAME))
849
+ }
850
+
851
+ corsHeaders(req) {
852
+ const origin = req.headers.origin
853
+ if (typeof origin !== 'string') return {}
854
+ const allowed = this.allowedCorsOrigin(origin)
855
+ if (allowed === null) return {}
856
+ const headers = {
857
+ 'access-control-allow-origin': allowed,
858
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
859
+ 'access-control-allow-headers': 'content-type',
860
+ 'access-control-max-age': '600',
861
+ vary: 'origin',
862
+ }
863
+ if (req.headers['access-control-request-private-network'] === 'true') {
864
+ headers['access-control-allow-private-network'] = 'true'
865
+ }
866
+ return headers
867
+ }
868
+
869
+ /**
870
+ * The `Access-Control-Allow-Origin` value for a request origin, or null when
871
+ * the origin is untrusted. `null`/`file://` appear when the Desktop app renders
872
+ * the page from disk; those requests are only answered for a loopback peer.
873
+ */
874
+ allowedCorsOrigin(origin) {
875
+ if (origin === 'null' || origin.startsWith('file:')) return 'null'
876
+ try {
877
+ const host = new URL(origin).hostname
878
+ if (host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]') return origin
879
+ } catch {
880
+ return null
881
+ }
882
+ return null
883
+ }
884
+
885
+ deskKeyOk(value) {
886
+ return typeof value === 'string' && value.length > 0 && equals(value, this.deskKey)
887
+ }
888
+
889
+ /** True when the TCP peer is this machine (address is not spoofable). */
890
+ isLoopbackRequest(req) {
891
+ const address = normalizeIp(req.socket ? req.socket.remoteAddress : '')
892
+ return address === '127.0.0.1' || address === '::1'
893
+ }
894
+
895
+ /**
896
+ * The desktop pairing panel may call without the desk key when it runs on the
897
+ * same machine. A loopback client address is not spoofable, and CORS still
898
+ * confines the answer to a loopback page, so remote pages cannot read it.
899
+ */
900
+ deskRequestAllowed(req, url) {
901
+ if (this.deskKeyOk(url.searchParams.get('key'))) return true
902
+ if (!this.isLoopbackRequest(req)) return false
903
+ const origin = req.headers.origin
904
+ if (typeof origin !== 'string') return true
905
+ return this.allowedCorsOrigin(origin) !== null
906
+ }
907
+
908
+ /**
909
+ * Bounded diagnostic trail for the desktop panel endpoint. Contains no keys,
910
+ * tokens or cookies: method, path, origin, host, peer and outcome only.
911
+ */
912
+ appendDebug(text) {
913
+ if (this.statePath === null) return
914
+ appendFile(`${this.statePath}.debug.log`, `${new Date().toISOString()} ${text}\n`, { mode: 0o600 }).catch(() => {})
915
+ }
916
+
917
+ logDesktopRequest(req, path, allowed) {
918
+ if (this.statePath === null) return
919
+ const line = `${new Date().toISOString()} ${req.method ?? 'GET'} ${path} origin=${String(req.headers.origin ?? '-')} host=${String(req.headers.host ?? '-')} peer=${normalizeIp(req.socket ? req.socket.remoteAddress : '')} ${allowed ? 'allowed' : 'denied'} ua=${String(req.headers['user-agent'] ?? '-').slice(0, 80)}\n`
920
+ appendFile(`${this.statePath}.debug.log`, line, { mode: 0o600 }).catch(() => {})
921
+ }
922
+
923
+ /**
924
+ * Trail of non-loopback requests (phones and pairing attempts), so an
925
+ * unreachable device can be told apart from a blocked network path.
926
+ */
927
+ logAccess(req, path) {
928
+ if (this.statePath === null) return
929
+ if (this.isLoopbackRequest(req) && path !== '/api/pair') return
930
+ const line = `${new Date().toISOString()} ${req.method ?? '?'} ${path} peer=${normalizeIp(req.socket ? req.socket.remoteAddress : '')} ua=${String(req.headers['user-agent'] ?? '-').slice(0, 60)}\n`
931
+ appendFile(`${this.statePath}.access.log`, line, { mode: 0o600 }).catch(() => {})
932
+ }
933
+
934
+ async handleHttp(req, res) {
935
+ const url = new URL(req.url ?? '/', 'http://localhost')
936
+ const path = url.pathname
937
+ const method = req.method ?? 'GET'
938
+ this.logAccess(req, path)
939
+
940
+ if (path.startsWith('/api/desktop/')) {
941
+ const cors = this.corsHeaders(req)
942
+ if (method === 'OPTIONS') {
943
+ this.logDesktopRequest(req, path, true)
944
+ res.writeHead(204, { ...cors, 'access-control-allow-methods': 'GET, POST, OPTIONS', 'access-control-allow-headers': 'content-type' })
945
+ res.end()
946
+ return
947
+ }
948
+ const allowed = this.deskRequestAllowed(req, url)
949
+ this.logDesktopRequest(req, path, allowed)
950
+ if (!allowed) {
951
+ jsonResponse(res, 403, { error: 'forbidden' }, cors)
952
+ return
953
+ }
954
+ await this.handleDesktopApi(req, res, path, method, cors)
955
+ return
956
+ }
957
+
958
+ if (path === '/api/health' && method === 'GET') {
959
+ jsonResponse(res, 200, { ok: true, version: VERSION })
960
+ return
961
+ }
962
+
963
+ if (path === '/api/state' && method === 'GET') {
964
+ const device = this.currentDevice(req)
965
+ const authStatus = this.auth?.status()
966
+ jsonResponse(res, 200, {
967
+ paired: device !== null,
968
+ device: device === null ? null : {
969
+ id: device.id,
970
+ name: device.name,
971
+ createdAt: device.createdAt,
972
+ canApprove: device.canApprove !== false,
973
+ },
974
+ version: VERSION,
975
+ pinTtlMs: authStatus === undefined ? 0 : Math.max(0, authStatus.pinExpiresAt - Date.now()),
976
+ })
977
+ return
978
+ }
979
+
980
+ // Web Push bootstrap. The VAPID public key is safe to hand out (it is sent
981
+ // inside every push message anyway) and the SPA needs it before pairing can
982
+ // be assumed, so this is the one unauthenticated `/api/push/*` route.
983
+ if (path === '/api/push/key' && method === 'GET') {
984
+ if (this.push === null) {
985
+ jsonResponse(res, 200, { enabled: false, publicKey: null })
986
+ return
987
+ }
988
+ jsonResponse(res, 200, { enabled: true, publicKey: this.push.publicKey() })
989
+ return
990
+ }
991
+
992
+ if (path.startsWith('/api/push/') && method === 'POST') {
993
+ await this.handlePushApi(req, res, path)
994
+ return
995
+ }
996
+
997
+ // Web Share Target (manifest `share_target`, GET): Android's share sheet
998
+ // posts title/text/url here, and we bounce into the app with the payload in
999
+ // the query so the composer can pick it up after pairing/restore.
1000
+ if (path === '/share-target' && method === 'GET') {
1001
+ const payload = encodeURIComponent(JSON.stringify({
1002
+ title: (url.searchParams.get('title') ?? '').slice(0, 200),
1003
+ text: (url.searchParams.get('text') ?? '').slice(0, 4000),
1004
+ url: (url.searchParams.get('url') ?? '').slice(0, 2000),
1005
+ }))
1006
+ res.writeHead(302, {
1007
+ location: `/?share=${payload}`,
1008
+ 'cache-control': 'no-store',
1009
+ 'referrer-policy': 'no-referrer',
1010
+ })
1011
+ res.end()
1012
+ return
1013
+ }
1014
+
1015
+ if (path === '/api/preview' && method === 'GET') {
1016
+ const device = this.currentDevice(req)
1017
+ if (device === null) {
1018
+ jsonResponse(res, 401, { error: 'unauthenticated' })
1019
+ return
1020
+ }
1021
+ const sessionId = url.searchParams.get('session')
1022
+ const file = url.searchParams.get('path')
1023
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || typeof file !== 'string' || file.length === 0) {
1024
+ jsonResponse(res, 400, { error: 'bad-request' })
1025
+ return
1026
+ }
1027
+ try {
1028
+ const result = await this.bridge.readUpload(sessionId, file)
1029
+ if (!result || result.ok === false) {
1030
+ jsonResponse(res, 404, { error: 'not-found' })
1031
+ return
1032
+ }
1033
+ res.writeHead(200, {
1034
+ 'content-type': result.mediaType,
1035
+ 'cache-control': 'private, max-age=300',
1036
+ 'x-content-type-options': 'nosniff',
1037
+ })
1038
+ res.end(result.data)
1039
+ } catch {
1040
+ jsonResponse(res, 404, { error: 'not-found' })
1041
+ }
1042
+ return
1043
+ }
1044
+
1045
+ if (path === '/api/upload' && method === 'POST') {
1046
+ const device = this.currentDevice(req)
1047
+ if (device === null) {
1048
+ jsonResponse(res, 401, { error: 'unauthenticated' })
1049
+ return
1050
+ }
1051
+ const header = (value) => (Array.isArray(value) ? value[0] : value)
1052
+ const sessionId = header(req.headers['x-dsh-session'])
1053
+ const name = header(req.headers['x-dsh-filename'])
1054
+ const mediaType = header(req.headers['x-dsh-media-type']) ?? header(req.headers['content-type'])
1055
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
1056
+ jsonResponse(res, 400, { error: 'missing-session' })
1057
+ return
1058
+ }
1059
+ let body
1060
+ try {
1061
+ body = await readBodyBuffer(req, 32 * 1024 * 1024)
1062
+ } catch (error) {
1063
+ jsonResponse(res, error instanceof Error && error.message === 'body-too-large' ? 413 : 400, { error: 'bad-upload' })
1064
+ return
1065
+ }
1066
+ const result = await this.callBridgeResult('saveUpload', sessionId, {
1067
+ name: typeof name === 'string' ? name : 'attachment',
1068
+ mediaType: typeof mediaType === 'string' ? mediaType : 'application/octet-stream',
1069
+ data: body,
1070
+ })
1071
+ if (!result.ok) {
1072
+ const status = result.code === 'bad-request' ? 400 : result.code === 'not-found' ? 404 : 500
1073
+ jsonResponse(res, status, { error: result.code })
1074
+ return
1075
+ }
1076
+ jsonResponse(res, 200, result.value)
1077
+ return
1078
+ }
1079
+
1080
+ if (path === '/api/pair' && method === 'POST') {
1081
+ await this.handlePair(req, res)
1082
+ return
1083
+ }
1084
+
1085
+ if (path === '/api/rotate-pin' && method === 'POST') {
1086
+ const device = this.currentDevice(req)
1087
+ if (device === null) {
1088
+ jsonResponse(res, 401, { error: 'unauthenticated' })
1089
+ return
1090
+ }
1091
+ const { pin, pinExpiresAt } = this.auth.rotatePin()
1092
+ jsonResponse(res, 200, { pin, pinExpiresAt })
1093
+ return
1094
+ }
1095
+
1096
+ if (path === '/api/unpair' && method === 'POST') {
1097
+ const device = this.currentDevice(req)
1098
+ if (device !== null) {
1099
+ this.auth.revoke(device.id)
1100
+ this.push?.removeDevice(device.id)
1101
+ this.auth.rotateAll()
1102
+ this.scheduleSave()
1103
+ this.kickDevice(device.id)
1104
+ }
1105
+ jsonResponse(res, 200, { ok: true }, { 'set-cookie': this.clearCookieHeader(req) })
1106
+ return
1107
+ }
1108
+
1109
+ if (method === 'GET' || method === 'HEAD') {
1110
+ const stat = this.staticCache.get(path)
1111
+ if (stat !== undefined) {
1112
+ this.serveStatic(req, res, stat)
1113
+ return
1114
+ }
1115
+ }
1116
+
1117
+ if (path.startsWith('/api/')) {
1118
+ jsonResponse(res, 404, { error: 'not-found' })
1119
+ return
1120
+ }
1121
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
1122
+ res.end('Not found')
1123
+ }
1124
+
1125
+ serveStatic(req, res, stat) {
1126
+ const headers = {
1127
+ 'content-type': stat.type,
1128
+ 'cache-control': 'no-store, must-revalidate',
1129
+ 'x-content-type-options': 'nosniff',
1130
+ 'referrer-policy': 'no-referrer',
1131
+ 'permissions-policy': 'microphone=(), camera=(), geolocation=()',
1132
+ }
1133
+ // A root-scope service worker for the installable app.
1134
+ if (stat.type.startsWith('text/javascript') && req.url?.startsWith('/sw.js')) {
1135
+ headers['service-worker-allowed'] = '/'
1136
+ headers['cache-control'] = 'no-cache'
1137
+ }
1138
+ if (stat.type.startsWith('text/html')) {
1139
+ headers['content-security-policy'] = [
1140
+ "default-src 'self'",
1141
+ "script-src 'self'",
1142
+ "worker-src 'self'",
1143
+ "style-src 'self' 'unsafe-inline'",
1144
+ "img-src 'self' data: blob:",
1145
+ "connect-src 'self' ws: wss:",
1146
+ "font-src 'self'",
1147
+ "base-uri 'none'",
1148
+ "form-action 'none'",
1149
+ "frame-ancestors 'none'",
1150
+ ].join('; ')
1151
+ }
1152
+ res.writeHead(200, headers)
1153
+ if (req.method === 'HEAD') res.end()
1154
+ else res.end(stat.body)
1155
+ }
1156
+
1157
+ async handlePair(req, res) {
1158
+ let body
1159
+ try {
1160
+ body = await readJsonBody(req, 8 * 1024)
1161
+ } catch {
1162
+ jsonResponse(res, 400, { error: 'bad-request' })
1163
+ return
1164
+ }
1165
+ const address = normalizeIp(req.socket.remoteAddress)
1166
+ const agent = Array.isArray(req.headers['user-agent']) ? req.headers['user-agent'][0] : req.headers['user-agent']
1167
+ let result
1168
+ if (typeof body.token === 'string' && body.token.length > 0) {
1169
+ result = this.auth.pairWithToken(body.token, agent, address)
1170
+ if (!result.ok) {
1171
+ jsonResponse(res, 401, { error: result.error })
1172
+ return
1173
+ }
1174
+ } else if (typeof body.pin === 'string' && body.pin.length > 0) {
1175
+ result = this.auth.pairWithPin(body.pin, agent, address)
1176
+ if (!result.ok) {
1177
+ const status = result.error === 'rate-limited' ? 429 : 401
1178
+ jsonResponse(res, status, { error: result.error, retryAfterMs: result.retryAfterMs ?? 0 })
1179
+ return
1180
+ }
1181
+ } else {
1182
+ jsonResponse(res, 400, { error: 'missing-credentials' })
1183
+ return
1184
+ }
1185
+ this.scheduleSave()
1186
+ this.appendDebug(`pair method=${typeof body.token === 'string' && body.token.length > 0 ? 'token' : 'pin'} device=${result.device.name}`)
1187
+ jsonResponse(res, 200, { paired: true, device: result.device, version: VERSION }, {
1188
+ 'set-cookie': this.cookieHeader(req, this.auth.cookieValue(result.device.id), this.auth.cookieMaxAgeSeconds()),
1189
+ })
1190
+ }
1191
+
1192
+ /**
1193
+ * Web Push subscription management for the paired phone. Every route here
1194
+ * requires the device cookie; `/api/push/key` is handled in `handleHttp`
1195
+ * because it is intentionally public. A device can only remove its own
1196
+ * endpoint, never another paired device's.
1197
+ */
1198
+ async handlePushApi(req, res, path) {
1199
+ if (this.push === null) {
1200
+ jsonResponse(res, 503, { error: 'starting' })
1201
+ return
1202
+ }
1203
+ const device = this.currentDevice(req)
1204
+ if (device === null) {
1205
+ jsonResponse(res, 401, { error: 'unauthenticated' })
1206
+ return
1207
+ }
1208
+ let body
1209
+ try {
1210
+ body = await readJsonBody(req, 8 * 1024)
1211
+ } catch {
1212
+ jsonResponse(res, 400, { error: 'bad-request' })
1213
+ return
1214
+ }
1215
+ if (path === '/api/push/subscribe') {
1216
+ const endpoint = typeof body.subscription?.endpoint === 'string' ? body.subscription.endpoint : ''
1217
+ const owned = this.push.subscriptions(device.id)
1218
+ const isRefresh = owned.some((item) => item.endpoint === endpoint)
1219
+ if (!isRefresh && owned.length >= MAX_SUBSCRIPTIONS_PER_DEVICE) {
1220
+ jsonResponse(res, 429, { error: 'too-many-subscriptions' })
1221
+ return
1222
+ }
1223
+ const result = this.push.addSubscription(device.id, body.subscription)
1224
+ if (!result.ok) {
1225
+ jsonResponse(res, result.error === 'too-many-subscriptions' ? 429 : 400, { error: result.error })
1226
+ return
1227
+ }
1228
+ this.scheduleSave()
1229
+ jsonResponse(res, 200, { ok: true, deviceId: device.id })
1230
+ return
1231
+ }
1232
+ if (path === '/api/push/unsubscribe') {
1233
+ // The endpoint value is the browser's opaque push URL; it is never logged.
1234
+ const endpoint = typeof body.endpoint === 'string' ? body.endpoint : ''
1235
+ if (endpoint.length === 0) {
1236
+ jsonResponse(res, 400, { error: 'bad-request' })
1237
+ return
1238
+ }
1239
+ const owned = this.push.subscriptions(device.id).some((item) => item.endpoint === endpoint)
1240
+ if (owned) {
1241
+ this.push.removeSubscription(endpoint)
1242
+ this.scheduleSave()
1243
+ }
1244
+ jsonResponse(res, 200, { ok: true })
1245
+ return
1246
+ }
1247
+ if (path === '/api/push/report') {
1248
+ // Diagnostics from the service worker / SPA (bounded, never contains a
1249
+ // subscription endpoint, key material or payload content). Every field is
1250
+ // collapsed to one line so a client cannot forge log entries.
1251
+ const kind = logField(body.kind, 40) || 'unknown'
1252
+ const detail = logField(body.detail, 200)
1253
+ const scope = logField(body.scope, 120)
1254
+ const permission = logField(body.permission, 20)
1255
+ this.appendDebug(`push.report kind=${kind} permission=${permission} scope=${scope} detail=${detail}`)
1256
+ jsonResponse(res, 200, { ok: true })
1257
+ return
1258
+ }
1259
+ if (path === '/api/push/test') {
1260
+ const now = Date.now()
1261
+ const recent = (this.pushTestWindows.get(device.id) ?? []).filter((at) => now - at < PUSH_TEST_WINDOW_MS)
1262
+ if (recent.length >= PUSH_TEST_MAX_PER_DEVICE) {
1263
+ const retryAfterMs = PUSH_TEST_WINDOW_MS - (now - recent[0])
1264
+ jsonResponse(res, 429, { error: 'rate-limited', retryAfterMs })
1265
+ return
1266
+ }
1267
+ recent.push(now)
1268
+ this.pushTestWindows.set(device.id, recent)
1269
+ const payload = {
1270
+ kind: 'test',
1271
+ title: 'Test notification',
1272
+ body: 'Background push is working.',
1273
+ tag: `test:${device.id}:${Date.now()}`,
1274
+ sessionId: null,
1275
+ url: '/',
1276
+ }
1277
+ let sent = 0
1278
+ let gone = 0
1279
+ let failed = 0
1280
+ const statuses = new Set()
1281
+ for (const subscription of this.push.subscriptions(device.id)) {
1282
+ const result = await this.push.sendNotification(subscription, payload)
1283
+ if (result.ok === true) sent += 1
1284
+ else if (result.gone !== true) {
1285
+ failed += 1
1286
+ if (Number.isFinite(result.status)) statuses.add(result.status)
1287
+ }
1288
+ if (result.gone === true) gone += 1
1289
+ }
1290
+ if (gone > 0) this.scheduleSave()
1291
+ this.appendDebug(
1292
+ `push.test device=${device.id} subs=${this.push.subscriptions(device.id).length} sent=${sent} gone=${gone} failed=${failed}` +
1293
+ (statuses.size > 0 ? ` statuses=${[...statuses].join(',')}` : ''),
1294
+ )
1295
+ // The push service's error body is diagnostic only; keep it out of the
1296
+ // HTTP response so the phone cannot use this route as a response oracle.
1297
+ jsonResponse(res, 200, {
1298
+ ok: sent > 0,
1299
+ sent,
1300
+ gone,
1301
+ failed,
1302
+ })
1303
+ return
1304
+ }
1305
+ jsonResponse(res, 404, { error: 'not-found' })
1306
+ }
1307
+
1308
+ /** Newest `lastSeenAt` across the paired devices (0 when none). */
1309
+ lastConnectedAt(devices) {
1310
+ let latest = 0
1311
+ for (const device of devices) {
1312
+ if (Number.isFinite(device.lastSeenAt) && device.lastSeenAt > latest) latest = device.lastSeenAt
1313
+ }
1314
+ return latest
1315
+ }
1316
+
1317
+ /**
1318
+ * Pairing payload rendered by the desktop panel. `requestedAddress` selects one
1319
+ * of the detected interfaces (the panel's address chips); an unknown value
1320
+ * falls back to the preferred address, which is the Tailscale IP when the node
1321
+ * is on a tailnet.
1322
+ */
1323
+ desktopStatusPayload(requestedAddress = null) {
1324
+ const auth = this.auth
1325
+ if (auth === null) return null
1326
+ const entries = localAddressEntries(this.bindHost)
1327
+ if (this.publicUrl !== null) {
1328
+ entries.unshift({ address: this.publicUrl, name: 'Tailscale Serve (HTTPS)' })
1329
+ }
1330
+ const addresses = entries.map((entry) => entry.address)
1331
+ if (!this.enabled) {
1332
+ const devices = auth.devices()
1333
+ return {
1334
+ enabled: false,
1335
+ version: VERSION,
1336
+ port: this.port,
1337
+ bindHost: this.bindHost,
1338
+ addresses,
1339
+ address: null,
1340
+ addressDetails: [],
1341
+ url: null,
1342
+ qrSvg: null,
1343
+ pin: null,
1344
+ pinExpiresAt: 0,
1345
+ tokenExpiresAt: 0,
1346
+ devices,
1347
+ connectedDevices: 0,
1348
+ connectedNames: [],
1349
+ lastConnectedAt: this.lastConnectedAt(devices),
1350
+ loopbackOnly: false,
1351
+ }
1352
+ }
1353
+ auth.ensureFresh()
1354
+ const status = auth.status()
1355
+ const chosen = typeof requestedAddress === 'string' && addresses.includes(requestedAddress)
1356
+ ? requestedAddress
1357
+ : addresses[0]
1358
+ const url = chosen.startsWith('http')
1359
+ ? `${chosen}/?t=${encodeURIComponent(status.token)}`
1360
+ : `http://${chosen}:${this.port}/?t=${encodeURIComponent(status.token)}`
1361
+ const connectedNames = [...new Set([...this.peers].map((peer) => peer.device.name))]
1362
+ return {
1363
+ enabled: true,
1364
+ version: VERSION,
1365
+ port: this.port,
1366
+ bindHost: this.bindHost,
1367
+ addresses,
1368
+ address: chosen,
1369
+ addressDetails: entries,
1370
+ url,
1371
+ qrSvg: qrSvg(url, { cellSize: 6, margin: 2 }),
1372
+ pin: status.pin,
1373
+ pinExpiresAt: status.pinExpiresAt,
1374
+ tokenExpiresAt: status.tokenExpiresAt,
1375
+ devices: status.devices,
1376
+ connectedDevices: this.peers.size,
1377
+ connectedNames,
1378
+ lastConnectedAt: this.lastConnectedAt(status.devices),
1379
+ loopbackOnly: addresses.length === 1 && addresses[0] === '127.0.0.1',
1380
+ }
1381
+ }
1382
+
1383
+ rotateDesktopPairing() {
1384
+ const auth = this.auth
1385
+ if (auth === null) return null
1386
+ const { pin, pinExpiresAt } = auth.rotatePin()
1387
+ const { token, tokenExpiresAt } = auth.rotateToken()
1388
+ return { pin, pinExpiresAt, token, tokenExpiresAt }
1389
+ }
1390
+
1391
+ revokeDesktopDevices(body) {
1392
+ const auth = this.auth
1393
+ if (auth === null) return null
1394
+ if (body && body.all === true) {
1395
+ const devices = auth.devices()
1396
+ const count = auth.revokeAll()
1397
+ // Push subscriptions are per device: revoking the device revokes its
1398
+ // notification channel too.
1399
+ for (const device of devices) this.push?.removeDevice(device.id)
1400
+ for (const peer of [...this.peers]) {
1401
+ peer.close(4003, 'revoked')
1402
+ this.peers.delete(peer)
1403
+ }
1404
+ // Invalidate outstanding QR links too: a saved ?t= URL must not be able to
1405
+ // silently re-pair after the owner revoked every device.
1406
+ auth.rotateAll()
1407
+ this.scheduleSave()
1408
+ return { ok: true, revoked: count }
1409
+ }
1410
+ if (body && typeof body.deviceId === 'string' && body.deviceId.length > 0) {
1411
+ const removed = auth.revoke(body.deviceId)
1412
+ this.push?.removeDevice(body.deviceId)
1413
+ this.kickDevice(body.deviceId)
1414
+ auth.rotateAll()
1415
+ this.scheduleSave()
1416
+ return { ok: removed }
1417
+ }
1418
+ return {}
1419
+ }
1420
+
1421
+ /**
1422
+ * Flip one paired device's approval permission and persist the shared state.
1423
+ * @param {string} deviceId paired-device id
1424
+ * @param {boolean} canApprove whether the device may answer approvals
1425
+ * @returns the public device, or null when the id is unknown
1426
+ */
1427
+ setDeviceApproval(deviceId, canApprove) {
1428
+ if (this.auth === null) return null
1429
+ const device = this.auth.setCanApprove(deviceId, canApprove === true)
1430
+ if (device === null) return null
1431
+ this.scheduleSave()
1432
+ return device
1433
+ }
1434
+
1435
+ async handleDesktopApi(req, res, path, method, cors) {
1436
+ if (this.auth === null) {
1437
+ jsonResponse(res, 503, { error: 'starting' }, cors)
1438
+ return
1439
+ }
1440
+ if (path === '/api/desktop/status' && method === 'GET') {
1441
+ const url = new URL(req.url ?? '/', 'http://localhost')
1442
+ const payload = this.desktopStatusPayload(url.searchParams.get('address'))
1443
+ jsonResponse(res, 200, payload ?? { error: 'starting' }, cors)
1444
+ return
1445
+ }
1446
+ if (path === '/api/desktop/rotate' && method === 'POST') {
1447
+ const rotated = this.rotateDesktopPairing()
1448
+ jsonResponse(res, 200, rotated ?? { error: 'starting' }, cors)
1449
+ return
1450
+ }
1451
+ if (path === '/api/desktop/pending' && method === 'GET') {
1452
+ jsonResponse(res, 200, { approvals: this.pendingApprovalsSnapshot() }, cors)
1453
+ return
1454
+ }
1455
+ if (path === '/api/desktop/answer' && method === 'POST') {
1456
+ let body
1457
+ try {
1458
+ body = await readJsonBody(req, 8 * 1024)
1459
+ } catch {
1460
+ jsonResponse(res, 400, { error: 'bad-request' }, cors)
1461
+ return
1462
+ }
1463
+ if (typeof body.requestId !== 'string' || (body.decision !== 'allow' && body.decision !== 'reject')) {
1464
+ jsonResponse(res, 400, { error: 'bad-request' }, cors)
1465
+ return
1466
+ }
1467
+ const accepted = await this.answerApproval(body.requestId, body.decision, 'desktop')
1468
+ jsonResponse(res, 200, { ok: accepted !== false }, cors)
1469
+ return
1470
+ }
1471
+ if ((path === '/api/desktop/enable' || path === '/api/desktop/disable') && method === 'POST') {
1472
+ const result = await this.setEnabled(path === '/api/desktop/enable')
1473
+ jsonResponse(res, result.ok ? 200 : 500, result, cors)
1474
+ return
1475
+ }
1476
+ if (path === '/api/desktop/revoke' && method === 'POST') {
1477
+ let body
1478
+ try {
1479
+ body = await readJsonBody(req, 8 * 1024)
1480
+ } catch {
1481
+ jsonResponse(res, 400, { error: 'bad-request' }, cors)
1482
+ return
1483
+ }
1484
+ const result = this.revokeDesktopDevices(body)
1485
+ if (result === null) {
1486
+ jsonResponse(res, 503, { error: 'starting' }, cors)
1487
+ return
1488
+ }
1489
+ if (result.ok === undefined) {
1490
+ jsonResponse(res, 400, { error: 'missing-device' }, cors)
1491
+ return
1492
+ }
1493
+ jsonResponse(res, 200, result, cors)
1494
+ return
1495
+ }
1496
+ if (path === '/api/desktop/device' && method === 'POST') {
1497
+ let body
1498
+ try {
1499
+ body = await readJsonBody(req, 8 * 1024)
1500
+ } catch {
1501
+ jsonResponse(res, 400, { error: 'bad-request' }, cors)
1502
+ return
1503
+ }
1504
+ if (typeof body.deviceId !== 'string' || body.deviceId.length === 0 || typeof body.canApprove !== 'boolean') {
1505
+ jsonResponse(res, 400, { error: 'bad-request' }, cors)
1506
+ return
1507
+ }
1508
+ const device = this.setDeviceApproval(body.deviceId, body.canApprove)
1509
+ if (device === null) {
1510
+ jsonResponse(res, 404, { error: 'missing-device' }, cors)
1511
+ return
1512
+ }
1513
+ jsonResponse(res, 200, { ok: true, device }, cors)
1514
+ return
1515
+ }
1516
+ jsonResponse(res, 404, { error: 'not-found' }, cors)
1517
+ }
1518
+
1519
+ /**
1520
+ * Same-origin desktop route served by the DSH web server. This avoids CORS and
1521
+ * the page CSP entirely when the GUI is served over HTTP. Only loopback
1522
+ * requests with a loopback Host header are answered, so a remote page cannot
1523
+ * read pairing data even though this route carries no cookie.
1524
+ */
1525
+ async handlePairingRoute(req, res) {
1526
+ const url = new URL(req.url ?? '/', 'http://localhost')
1527
+ const method = req.method ?? 'GET'
1528
+ const rawHost = String(req.headers.host ?? '')
1529
+ const host = rawHost.startsWith('[') ? rawHost.slice(0, rawHost.indexOf(']') + 1) : rawHost.split(':')[0]
1530
+ const loopbackHost = host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]'
1531
+ if (!this.isLoopbackRequest(req) || !loopbackHost) {
1532
+ jsonResponse(res, 403, { error: 'forbidden' })
1533
+ return
1534
+ }
1535
+ if (this.auth === null) {
1536
+ jsonResponse(res, 503, { error: 'starting' })
1537
+ return
1538
+ }
1539
+ if (method === 'GET' && (url.pathname === '/remote-mobile/pairing' || url.pathname === '/remote-mobile/pairing/')) {
1540
+ jsonResponse(res, 200, this.desktopStatusPayload(url.searchParams.get('address')))
1541
+ return
1542
+ }
1543
+ if (method === 'GET' && url.pathname === '/remote-mobile/pairing/pending') {
1544
+ jsonResponse(res, 200, { approvals: this.pendingApprovalsSnapshot() })
1545
+ return
1546
+ }
1547
+ if (method === 'POST' && url.pathname === '/remote-mobile/pairing/answer') {
1548
+ let body
1549
+ try {
1550
+ body = await readJsonBody(req, 8 * 1024)
1551
+ } catch {
1552
+ jsonResponse(res, 400, { error: 'bad-request' })
1553
+ return
1554
+ }
1555
+ if (typeof body.requestId !== 'string' || (body.decision !== 'allow' && body.decision !== 'reject')) {
1556
+ jsonResponse(res, 400, { error: 'bad-request' })
1557
+ return
1558
+ }
1559
+ const accepted = await this.answerApproval(body.requestId, body.decision, 'desktop')
1560
+ jsonResponse(res, 200, { ok: accepted !== false })
1561
+ return
1562
+ }
1563
+ if (method === 'POST' && (url.pathname === '/remote-mobile/pairing/enable' || url.pathname === '/remote-mobile/pairing/disable')) {
1564
+ const result = await this.setEnabled(url.pathname.endsWith('/enable'))
1565
+ jsonResponse(res, result.ok ? 200 : 500, result)
1566
+ return
1567
+ }
1568
+ if (method === 'POST' && url.pathname === '/remote-mobile/pairing/device') {
1569
+ let body
1570
+ try {
1571
+ body = await readJsonBody(req, 8 * 1024)
1572
+ } catch {
1573
+ jsonResponse(res, 400, { error: 'bad-request' })
1574
+ return
1575
+ }
1576
+ if (typeof body.deviceId !== 'string' || body.deviceId.length === 0 || typeof body.canApprove !== 'boolean') {
1577
+ jsonResponse(res, 400, { error: 'bad-request' })
1578
+ return
1579
+ }
1580
+ const device = this.setDeviceApproval(body.deviceId, body.canApprove)
1581
+ if (device === null) {
1582
+ jsonResponse(res, 404, { error: 'missing-device' })
1583
+ return
1584
+ }
1585
+ jsonResponse(res, 200, { ok: true, device })
1586
+ return
1587
+ }
1588
+ if (method === 'POST' && url.pathname === '/remote-mobile/pairing/rotate') {
1589
+ jsonResponse(res, 200, this.rotateDesktopPairing())
1590
+ return
1591
+ }
1592
+ if (method === 'POST' && url.pathname === '/remote-mobile/pairing/revoke') {
1593
+ let body
1594
+ try {
1595
+ body = await readJsonBody(req, 8 * 1024)
1596
+ } catch {
1597
+ jsonResponse(res, 400, { error: 'bad-request' })
1598
+ return
1599
+ }
1600
+ const result = this.revokeDesktopDevices(body)
1601
+ if (result && result.ok === undefined) {
1602
+ jsonResponse(res, 400, { error: 'missing-device' })
1603
+ return
1604
+ }
1605
+ jsonResponse(res, 200, result)
1606
+ return
1607
+ }
1608
+ jsonResponse(res, 404, { error: 'not-found' })
1609
+ }
1610
+
1611
+ kickDevice(deviceId) {
1612
+ for (const peer of [...this.peers]) {
1613
+ if (peer.device.id === deviceId) {
1614
+ peer.close(4003, 'revoked')
1615
+ this.peers.delete(peer)
1616
+ }
1617
+ }
1618
+ }
1619
+
1620
+ handleUpgrade(req, socket, head) {
1621
+ const url = new URL(req.url ?? '/', 'http://localhost')
1622
+ this.logAccess(req, '/ws')
1623
+ if (url.pathname !== '/ws') {
1624
+ socket.destroy()
1625
+ return
1626
+ }
1627
+ const origin = req.headers.origin
1628
+ if (typeof origin === 'string') {
1629
+ try {
1630
+ const parsed = new URL(origin)
1631
+ if (parsed.host !== req.headers.host) {
1632
+ socket.destroy()
1633
+ return
1634
+ }
1635
+ } catch {
1636
+ socket.destroy()
1637
+ return
1638
+ }
1639
+ }
1640
+ if (this.auth === null) {
1641
+ socket.destroy()
1642
+ return
1643
+ }
1644
+ const cookies = parseCookies(req.headers.cookie)
1645
+ const device = this.auth.deviceFromCookie(cookies.get(COOKIE_NAME))
1646
+ if (device === null) {
1647
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
1648
+ return
1649
+ }
1650
+ if (head !== undefined && head.length > 0) {
1651
+ // Preserve bytes that arrived with the handshake by replaying them.
1652
+ socket.unshift(head)
1653
+ }
1654
+ const peer = new WebSocketPeer(socket, req, device, this.log)
1655
+ this.peers.add(peer)
1656
+ peer.on('close', () => {
1657
+ this.peers.delete(peer)
1658
+ this.refreshDeviceVisibility(peer.device.id)
1659
+ })
1660
+ peer.on('message', (frame) => {
1661
+ this.handleFrame(peer, frame).catch((error) => {
1662
+ const code = typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'internal'
1663
+ peer.sendObject({ type: 'error', code, message: String(error instanceof Error ? error.message : error) })
1664
+ })
1665
+ })
1666
+ this.sendWelcome(peer).catch((error) => {
1667
+ this.log.warn?.(`remote-mobile: welcome replay failed: ${error instanceof Error ? error.message : String(error)}`)
1668
+ })
1669
+ }
1670
+
1671
+ async sendWelcome(peer) {
1672
+ let sessions = []
1673
+ try {
1674
+ sessions = await this.callBridge('listSessions')
1675
+ } catch {
1676
+ sessions = []
1677
+ }
1678
+ // Project workspaces are optional/additive: an empty array when the Host
1679
+ // cannot list them, never a reason to fail the welcome.
1680
+ const workspaces = await this.fetchWorkspaces()
1681
+ // Image limits are optional/additive: absent when the Host cannot discover
1682
+ // the attachment store, never a reason to fail the welcome.
1683
+ let limits = null
1684
+ const limitResult = await this.callBridgeResult('imageLimits')
1685
+ if (limitResult.ok && limitResult.value !== undefined) limits = limitResult.value
1686
+ peer.sendObject({
1687
+ type: 'ready',
1688
+ version: VERSION,
1689
+ server: { name: 'DeepSeek Harness', port: this.port },
1690
+ device: {
1691
+ id: peer.device.id,
1692
+ name: peer.device.name,
1693
+ canApprove: peer.device.canApprove !== false,
1694
+ },
1695
+ sessions: Array.isArray(sessions) ? sessions : [],
1696
+ workspaces,
1697
+ activeSessionId: null,
1698
+ // No session is active for a fresh socket; queue state is replayed by
1699
+ // `session.opened` once the phone opens a session.
1700
+ queue: [],
1701
+ limits,
1702
+ })
1703
+ // Replay pending interactions so a reconnecting phone still sees questions
1704
+ // and approvals that arrived while its socket was down.
1705
+ for (const approval of this.pendingApprovals.values()) {
1706
+ peer.sendObject({
1707
+ type: 'approval.request',
1708
+ sessionId: approval.sessionId ?? null,
1709
+ requestId: approval.requestId,
1710
+ toolName: approval.toolName ?? 'tool',
1711
+ title: approval.title ?? 'Approval required',
1712
+ reason: approval.reason ?? '',
1713
+ displayReason: approval.displayReason ?? null,
1714
+ callId: approval.callId ?? null,
1715
+ ...(typeof approval.argsPreview === 'string' && approval.argsPreview.length > 0
1716
+ ? { argsPreview: approval.argsPreview }
1717
+ : {}),
1718
+ ...(typeof approval.argsKind === 'string' ? { argsKind: approval.argsKind } : {}),
1719
+ ...(approval.detail && typeof approval.detail === 'object' ? { detail: approval.detail } : {}),
1720
+ expiresAt: 0,
1721
+ })
1722
+ }
1723
+ for (const question of this.pendingQuestions.values()) {
1724
+ peer.sendObject({
1725
+ type: 'question.request',
1726
+ sessionId: question.sessionId ?? null,
1727
+ requestId: question.requestId,
1728
+ callId: question.callId ?? null,
1729
+ questions: question.questions,
1730
+ })
1731
+ }
1732
+ }
1733
+
1734
+ async callBridge(method, ...args) {
1735
+ if (this.bridge === null || typeof this.bridge[method] !== 'function') {
1736
+ throw new Error(`bridge method ${method} unavailable`)
1737
+ }
1738
+ const value = await this.bridge[method](...args)
1739
+ if (value !== null && typeof value === 'object' && value.ok === false) {
1740
+ const error = new Error(typeof value.error === 'string' ? value.error : `${method} failed`)
1741
+ if (typeof value.errorCode === 'string' && value.errorCode.length > 0) error.code = value.errorCode
1742
+ throw error
1743
+ }
1744
+ return value
1745
+ }
1746
+
1747
+ /**
1748
+ * Call a bridge method without throwing, preserving the protocol error code.
1749
+ * Used by the newer frames so a cold/unsupported operation surfaces a
1750
+ * friendly `{ type: 'error', code }` frame instead of a generic internal one.
1751
+ * @returns `{ ok: true, value }` or `{ ok: false, code, message }`.
1752
+ */
1753
+ async callBridgeResult(method, ...args) {
1754
+ if (this.bridge === null || typeof this.bridge[method] !== 'function') {
1755
+ return { ok: false, code: 'internal', message: `bridge method ${method} unavailable` }
1756
+ }
1757
+ try {
1758
+ const value = await this.bridge[method](...args)
1759
+ if (value !== null && typeof value === 'object' && value.ok === false) {
1760
+ return {
1761
+ ok: false,
1762
+ code: typeof value.errorCode === 'string' && value.errorCode.length > 0 ? value.errorCode : 'internal',
1763
+ message: typeof value.error === 'string' ? value.error : `${method} failed`,
1764
+ }
1765
+ }
1766
+ return { ok: true, value }
1767
+ } catch (error) {
1768
+ return {
1769
+ ok: false,
1770
+ code: typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'internal',
1771
+ message: error instanceof Error ? error.message : String(error),
1772
+ }
1773
+ }
1774
+ }
1775
+
1776
+ async handleFrame(peer, frame) {
1777
+ const type = typeof frame.type === 'string' ? frame.type : ''
1778
+ switch (type) {
1779
+ case 'ping':
1780
+ peer.sendObject({ type: 'pong', t: frame.t ?? 0 })
1781
+ return
1782
+ case 'client.visibility': {
1783
+ // The SPA reports whether its page is visible (foreground). While any
1784
+ // phone page is visible no Web Push is sent; unknown/backgrounded is the
1785
+ // default so a phone that never reports still receives notifications.
1786
+ const visible = frame.visible === true
1787
+ this.deviceVisibility.set(peer.device.id, visible)
1788
+ peer.sendObject({ type: 'visibility', visible })
1789
+ return
1790
+ }
1791
+ case 'sessions.list': {
1792
+ const sessions = await this.callBridge('listSessions')
1793
+ peer.sendObject({
1794
+ type: 'sessions',
1795
+ sessions: Array.isArray(sessions) ? sessions : [],
1796
+ workspaces: await this.fetchWorkspaces(),
1797
+ activeSessionId: null,
1798
+ })
1799
+ return
1800
+ }
1801
+ case 'sessions.open': {
1802
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1803
+ const opened = await this.callBridge('openSession', frame.sessionId)
1804
+ peer.sendObject({
1805
+ type: 'session.opened',
1806
+ session: opened?.session ?? null,
1807
+ history: opened?.history ?? [],
1808
+ queue: Array.isArray(opened?.queue) ? opened.queue : [],
1809
+ context: opened?.context ?? null,
1810
+ })
1811
+ return
1812
+ }
1813
+ case 'session.rename': {
1814
+ if (typeof frame.sessionId !== 'string' || typeof frame.title !== 'string') {
1815
+ throw new Error('sessionId and title required')
1816
+ }
1817
+ const result = await this.callBridgeResult('renameSession', frame.sessionId, frame.title)
1818
+ if (!result.ok) {
1819
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1820
+ return
1821
+ }
1822
+ const sessions = await this.fetchSessions()
1823
+ const session = sessions.find((item) => item && item.id === frame.sessionId) ?? null
1824
+ this.broadcast({
1825
+ type: 'session.updated',
1826
+ sessionId: frame.sessionId,
1827
+ title: result.value?.title ?? frame.title,
1828
+ session,
1829
+ })
1830
+ this.broadcast({ type: 'sessions', sessions, workspaces: await this.fetchWorkspaces(), activeSessionId: null })
1831
+ return
1832
+ }
1833
+ case 'session.fork': {
1834
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1835
+ const atSeq = Number.isInteger(frame.atSeq) && frame.atSeq >= 0 ? frame.atSeq : undefined
1836
+ const result = await this.callBridgeResult('forkSession', frame.sessionId, atSeq)
1837
+ if (!result.ok) {
1838
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1839
+ return
1840
+ }
1841
+ const forkId = result.value?.sessionId
1842
+ this.broadcastSessionRefresh()
1843
+ if (typeof forkId !== 'string') return
1844
+ // Open the fork for the requesting phone through the normal path; the
1845
+ // other devices get the new row from the `sessions` refresh.
1846
+ try {
1847
+ const opened = await this.callBridge('openSession', forkId)
1848
+ peer.sendObject({
1849
+ type: 'session.opened',
1850
+ session: opened?.session ?? null,
1851
+ history: opened?.history ?? [],
1852
+ queue: Array.isArray(opened?.queue) ? opened.queue : [],
1853
+ context: opened?.context ?? null,
1854
+ })
1855
+ } catch (error) {
1856
+ peer.sendObject({
1857
+ type: 'error',
1858
+ code: 'internal',
1859
+ message: `the fork was created but could not be opened: ${error instanceof Error ? error.message : String(error)}`,
1860
+ })
1861
+ }
1862
+ return
1863
+ }
1864
+ case 'sessions.search': {
1865
+ if (typeof frame.query !== 'string') throw new Error('query required')
1866
+ const result = await this.callBridgeResult('searchSessions', frame.query)
1867
+ if (!result.ok) {
1868
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1869
+ return
1870
+ }
1871
+ peer.sendObject({
1872
+ type: 'sessions.found',
1873
+ query: result.value?.query ?? frame.query,
1874
+ results: Array.isArray(result.value?.results) ? result.value.results : [],
1875
+ hasMore: result.value?.hasMore === true,
1876
+ })
1877
+ return
1878
+ }
1879
+ case 'session.pin':
1880
+ case 'session.unpin': {
1881
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1882
+ const result = await this.callBridgeResult('setSessionPinned', frame.sessionId, type === 'session.pin')
1883
+ if (!result.ok) {
1884
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1885
+ return
1886
+ }
1887
+ peer.sendObject({
1888
+ type: 'session.pinned',
1889
+ sessionId: frame.sessionId,
1890
+ pinned: result.value?.pinned === true,
1891
+ archived: result.value?.archived === true,
1892
+ })
1893
+ this.broadcastSessionRefresh()
1894
+ return
1895
+ }
1896
+ case 'session.archive':
1897
+ case 'session.unarchive': {
1898
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1899
+ const stopActivity = frame.stopActivity === true
1900
+ const result = await this.callBridgeResult(
1901
+ 'setSessionArchived',
1902
+ frame.sessionId,
1903
+ type === 'session.archive',
1904
+ stopActivity,
1905
+ )
1906
+ if (!result.ok) {
1907
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1908
+ return
1909
+ }
1910
+ peer.sendObject({
1911
+ type: 'session.archived',
1912
+ sessionId: frame.sessionId,
1913
+ archived: result.value?.archived === true,
1914
+ pinned: result.value?.pinned === true,
1915
+ })
1916
+ this.broadcastSessionRefresh()
1917
+ return
1918
+ }
1919
+ case 'queue.list': {
1920
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1921
+ const result = await this.callBridgeResult('listQueue', frame.sessionId)
1922
+ if (!result.ok) {
1923
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1924
+ return
1925
+ }
1926
+ peer.sendObject({
1927
+ type: 'queue',
1928
+ sessionId: frame.sessionId,
1929
+ items: Array.isArray(result.value?.items) ? result.value.items : [],
1930
+ pendingInput: Array.isArray(result.value?.pendingInput) ? result.value.pendingInput : [],
1931
+ running: result.value?.running === true,
1932
+ active: result.value?.active === true,
1933
+ })
1934
+ return
1935
+ }
1936
+ case 'queue.update': {
1937
+ if (typeof frame.sessionId !== 'string' || typeof frame.itemId !== 'string') {
1938
+ throw new Error('sessionId and itemId required')
1939
+ }
1940
+ const action = frame.action === 'edit' || frame.action === 'remove' || frame.action === 'steer'
1941
+ ? frame.action
1942
+ : null
1943
+ if (action === null) throw new Error('action must be edit, remove or steer')
1944
+ const result = await this.callBridgeResult(
1945
+ 'updateQueue',
1946
+ frame.sessionId,
1947
+ frame.itemId,
1948
+ action,
1949
+ typeof frame.text === 'string' ? frame.text : undefined,
1950
+ )
1951
+ if (!result.ok) {
1952
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1953
+ return
1954
+ }
1955
+ // Ack only to the requesting device; every device learns the new queue
1956
+ // from the bridge's own `queue.changed` push. Read the live state once
1957
+ // more so the ack carries the full queue-frame shape.
1958
+ const state = await this.callBridgeResult('listQueue', frame.sessionId)
1959
+ peer.sendObject({
1960
+ type: 'queue',
1961
+ sessionId: frame.sessionId,
1962
+ items: Array.isArray(result.value?.items) ? result.value.items : [],
1963
+ pendingInput: state.ok && Array.isArray(state.value?.pendingInput) ? state.value.pendingInput : [],
1964
+ running: state.ok ? state.value?.running === true : true,
1965
+ active: state.ok ? state.value?.active === true : true,
1966
+ })
1967
+ return
1968
+ }
1969
+ case 'context.get': {
1970
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1971
+ const result = await this.callBridgeResult('contextFor', frame.sessionId)
1972
+ if (!result.ok) {
1973
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1974
+ return
1975
+ }
1976
+ peer.sendObject({
1977
+ type: 'context',
1978
+ sessionId: frame.sessionId,
1979
+ usedTokens: result.value?.usedTokens ?? null,
1980
+ pressureTokens: result.value?.pressureTokens ?? null,
1981
+ projectedTokens: result.value?.projectedTokens ?? null,
1982
+ contextWindow: result.value?.contextWindow ?? null,
1983
+ basis: typeof result.value?.basis === 'string' ? result.value.basis : 'unknown',
1984
+ tokenUsage: result.value?.tokenUsage ?? null,
1985
+ })
1986
+ return
1987
+ }
1988
+ case 'changes.list': {
1989
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
1990
+ const result = await this.callBridgeResult('changesList', frame.sessionId, frame.limit)
1991
+ if (!result.ok) {
1992
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
1993
+ return
1994
+ }
1995
+ peer.sendObject({
1996
+ type: 'changes',
1997
+ sessionId: frame.sessionId,
1998
+ items: Array.isArray(result.value?.items) ? result.value.items : [],
1999
+ })
2000
+ return
2001
+ }
2002
+ case 'changes.diff': {
2003
+ if (typeof frame.sessionId !== 'string' || !Number.isInteger(frame.seq) || !Number.isInteger(frame.index)) {
2004
+ throw new Error('sessionId, seq and index required')
2005
+ }
2006
+ const result = await this.callBridgeResult('changesDiff', frame.sessionId, frame.seq, frame.index)
2007
+ if (!result.ok) {
2008
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
2009
+ return
2010
+ }
2011
+ peer.sendObject({
2012
+ type: 'changes.diff',
2013
+ sessionId: frame.sessionId,
2014
+ seq: result.value?.seq ?? frame.seq,
2015
+ index: result.value?.index ?? frame.index,
2016
+ kind: typeof result.value?.kind === 'string' ? result.value.kind : 'text',
2017
+ path: typeof result.value?.path === 'string' ? result.value.path : '',
2018
+ coarse: result.value?.coarse === true,
2019
+ hunks: Array.isArray(result.value?.hunks) ? result.value.hunks : [],
2020
+ })
2021
+ return
2022
+ }
2023
+ case 'commands.list': {
2024
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
2025
+ const result = await this.callBridgeResult('listCommands', frame.sessionId)
2026
+ if (!result.ok) {
2027
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
2028
+ return
2029
+ }
2030
+ peer.sendObject({
2031
+ type: 'commands',
2032
+ sessionId: frame.sessionId,
2033
+ available: result.value?.available === true,
2034
+ items: Array.isArray(result.value?.items) ? result.value.items : [],
2035
+ reason: typeof result.value?.reason === 'string' ? result.value.reason : null,
2036
+ })
2037
+ return
2038
+ }
2039
+ case 'commands.execute': {
2040
+ if (typeof frame.sessionId !== 'string' || typeof frame.line !== 'string') {
2041
+ throw new Error('sessionId and line required')
2042
+ }
2043
+ const result = await this.callBridgeResult('executeCommand', frame.sessionId, frame.line)
2044
+ if (!result.ok) {
2045
+ peer.sendObject({ type: 'error', code: result.code, message: result.message })
2046
+ return
2047
+ }
2048
+ peer.sendObject({
2049
+ type: 'command.result',
2050
+ sessionId: frame.sessionId,
2051
+ commandId: result.value?.commandId ?? null,
2052
+ name: typeof result.value?.name === 'string' ? result.value.name : '',
2053
+ kind: result.value?.kind === 'error' ? 'error' : 'success',
2054
+ text: typeof result.value?.text === 'string' ? result.value.text : null,
2055
+ sourceEventSeq: result.value?.sourceEventSeq ?? null,
2056
+ })
2057
+ return
2058
+ }
2059
+ case 'sessions.create': {
2060
+ const cwd = typeof frame.cwd === 'string' ? frame.cwd.trim() : ''
2061
+ const created = await this.callBridge('createSession', {
2062
+ preset: typeof frame.preset === 'string' ? frame.preset : undefined,
2063
+ cwd: cwd.length > 0 ? cwd : undefined,
2064
+ })
2065
+ peer.sendObject({
2066
+ type: 'sessions',
2067
+ sessions: await this.fetchSessions(),
2068
+ workspaces: await this.fetchWorkspaces(),
2069
+ activeSessionId: created?.id ?? null,
2070
+ })
2071
+ return
2072
+ }
2073
+ case 'history.load': {
2074
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
2075
+ const limit = Number.isInteger(frame.limit) ? Math.min(Math.max(frame.limit, 1), 200) : 50
2076
+ const items = await this.callBridge('history', frame.sessionId, { limit })
2077
+ peer.sendObject({ type: 'history', sessionId: frame.sessionId, items: Array.isArray(items) ? items : [], hasMore: false })
2078
+ return
2079
+ }
2080
+ case 'prompt': {
2081
+ const hasText = typeof frame.text === 'string' && frame.text.trim().length > 0
2082
+ const hasAttachments = Array.isArray(frame.attachments) && frame.attachments.length > 0
2083
+ if (typeof frame.sessionId !== 'string' || (!hasText && !hasAttachments)) {
2084
+ throw new Error('sessionId and text or attachments required')
2085
+ }
2086
+ await this.callBridge(
2087
+ 'prompt',
2088
+ frame.sessionId,
2089
+ typeof frame.text === 'string' ? frame.text : '',
2090
+ typeof frame.requestId === 'string' ? frame.requestId : undefined,
2091
+ Array.isArray(frame.attachments) ? frame.attachments : undefined,
2092
+ frame.mode === 'steer' ? 'steer' : 'queue',
2093
+ )
2094
+ return
2095
+ }
2096
+ case 'stop': {
2097
+ if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
2098
+ await this.callBridge('cancel', frame.sessionId)
2099
+ return
2100
+ }
2101
+ case 'approval.answer': {
2102
+ if (typeof frame.requestId !== 'string') throw new Error('requestId required')
2103
+ // Per-device permission: a device the owner restricted may not answer.
2104
+ if (peer.device.canApprove === false) {
2105
+ peer.sendObject({
2106
+ type: 'error',
2107
+ code: 'forbidden',
2108
+ message: 'this device is not allowed to answer approvals',
2109
+ })
2110
+ return
2111
+ }
2112
+ const decision = frame.decision === 'allow' ? 'allow' : frame.decision === 'reject' ? 'reject' : null
2113
+ if (decision === null) throw new Error('decision must be allow or reject')
2114
+ this.answerOrigins.set(frame.requestId, 'phone')
2115
+ let accepted
2116
+ try {
2117
+ accepted = await this.callBridge('answerApproval', frame.requestId, decision)
2118
+ } finally {
2119
+ this.answerOrigins.delete(frame.requestId)
2120
+ }
2121
+ this.appendDebug(`approval.answer req=${frame.requestId} decision=${decision} accepted=${accepted !== false}`)
2122
+ if (accepted === false) {
2123
+ peer.sendObject({ type: 'error', code: 'not-found', message: 'approval is no longer pending' })
2124
+ }
2125
+ return
2126
+ }
2127
+ case 'question.answer': {
2128
+ if (!Array.isArray(frame.answers)) throw new Error('answers required')
2129
+ const requestId = typeof frame.requestId === 'string' ? frame.requestId : undefined
2130
+ if (requestId !== undefined) this.answerOrigins.set(requestId, 'phone')
2131
+ let result
2132
+ try {
2133
+ result = await this.callBridge('answerQuestion', {
2134
+ requestId,
2135
+ sessionId: typeof frame.sessionId === 'string' ? frame.sessionId : undefined,
2136
+ callId: typeof frame.callId === 'string' ? frame.callId : undefined,
2137
+ answers: frame.answers,
2138
+ })
2139
+ } finally {
2140
+ if (requestId !== undefined) this.answerOrigins.delete(requestId)
2141
+ }
2142
+ if (result === false) {
2143
+ peer.sendObject({ type: 'error', code: 'not-found', message: 'the question is no longer open' })
2144
+ }
2145
+ return
2146
+ }
2147
+ case 'model.list': {
2148
+ const models = await this.callBridge('listModels')
2149
+ peer.sendObject({ type: 'models', catalog: models?.catalog ?? [], current: models?.current ?? null })
2150
+ return
2151
+ }
2152
+ case 'model.select': {
2153
+ if (typeof frame.sessionId !== 'string' || typeof frame.provider !== 'string' || typeof frame.model !== 'string') {
2154
+ throw new Error('sessionId, provider and model required')
2155
+ }
2156
+ await this.callBridge('selectModel', frame.sessionId, {
2157
+ provider: frame.provider,
2158
+ model: frame.model,
2159
+ reasoningEffort: frame.reasoningEffort ?? null,
2160
+ })
2161
+ return
2162
+ }
2163
+ case 'preset.list': {
2164
+ const presets = await this.callBridge('listPresets')
2165
+ peer.sendObject({ type: 'presets', presets: presets?.presets ?? [], current: presets?.current ?? null })
2166
+ return
2167
+ }
2168
+ case 'limits': {
2169
+ const result = await this.callBridgeResult('imageLimits')
2170
+ peer.sendObject({
2171
+ type: 'limits',
2172
+ image: result.ok && result.value && typeof result.value === 'object' ? result.value.image ?? null : null,
2173
+ })
2174
+ return
2175
+ }
2176
+ case 'preset.select': {
2177
+ if (typeof frame.sessionId !== 'string' || typeof frame.preset !== 'string') {
2178
+ throw new Error('sessionId and preset required')
2179
+ }
2180
+ await this.callBridge('selectPreset', frame.sessionId, frame.preset)
2181
+ return
2182
+ }
2183
+ default:
2184
+ peer.sendObject({ type: 'error', code: 'bad-request', message: `unknown frame type ${type}` })
2185
+ }
2186
+ }
2187
+
2188
+ broadcast(value) {
2189
+ for (const peer of this.peers) peer.sendObject(value)
2190
+ }
2191
+
2192
+ /**
2193
+ * Remember assistant text for the "reply ready" push. Runs even with no
2194
+ * connected peers: the push is exactly for the case where nobody is watching.
2195
+ */
2196
+ trackAssistantText(payload) {
2197
+ const sessionId = payload?.sessionId
2198
+ if (typeof sessionId !== 'string') return
2199
+ if (payload.phase === 'start') {
2200
+ this.replyBuffer.set(sessionId, '')
2201
+ return
2202
+ }
2203
+ if (payload.phase === 'delta') {
2204
+ if (typeof payload.text !== 'string' || payload.text.length === 0) return
2205
+ const current = this.replyBuffer.get(sessionId) ?? ''
2206
+ if (current.length < 6000) this.replyBuffer.set(sessionId, (current + payload.text).slice(0, 6000))
2207
+ return
2208
+ }
2209
+ if (payload.phase === 'end') {
2210
+ const full = this.replyBuffer.get(sessionId) ?? ''
2211
+ this.replyBuffer.delete(sessionId)
2212
+ if (full.trim().length === 0) return
2213
+ this.replyText.set(sessionId, full)
2214
+ if (this.replyText.size > 50) {
2215
+ const oldest = this.replyText.keys().next().value
2216
+ if (oldest !== undefined) this.replyText.delete(oldest)
2217
+ }
2218
+ }
2219
+ }
2220
+
2221
+ queueAssistant(payload) {
2222
+ this.trackAssistantText(payload)
2223
+ if (this.peers.size === 0) return
2224
+ const sessionId = payload?.sessionId
2225
+ if (typeof sessionId !== 'string') return
2226
+ if (payload.phase === 'start' || payload.phase === 'end') {
2227
+ this.flushAssistant(sessionId)
2228
+ this.broadcast({ type: `assistant.${payload.phase}`, sessionId, turn: payload.turn, step: payload.step })
2229
+ return
2230
+ }
2231
+ if (payload.phase !== 'delta') return
2232
+ let buffer = this.assistantBuffers.get(sessionId)
2233
+ if (buffer === undefined) {
2234
+ buffer = { text: '', reasoning: '' }
2235
+ this.assistantBuffers.set(sessionId, buffer)
2236
+ }
2237
+ buffer.text += typeof payload.text === 'string' ? payload.text : ''
2238
+ if (typeof payload.reasoning === 'string') buffer.reasoning += payload.reasoning
2239
+ }
2240
+
2241
+ flushAssistant(sessionId) {
2242
+ const buffer = this.assistantBuffers.get(sessionId)
2243
+ if (buffer === undefined) return
2244
+ this.assistantBuffers.delete(sessionId)
2245
+ if (buffer.text.length === 0 && buffer.reasoning.length === 0) return
2246
+ this.broadcast({
2247
+ type: 'assistant.delta',
2248
+ sessionId,
2249
+ text: buffer.text,
2250
+ reasoning: buffer.reasoning.length > 0 ? buffer.reasoning : null,
2251
+ })
2252
+ }
2253
+
2254
+ flushAssistantBuffers() {
2255
+ if (this.assistantBuffers.size === 0) return
2256
+ for (const sessionId of [...this.assistantBuffers.keys()]) this.flushAssistant(sessionId)
2257
+ }
2258
+
2259
+ broadcastTool(payload) {
2260
+ if (this.peers.size === 0 || payload === null || typeof payload !== 'object') return
2261
+ if (payload.phase === 'start') {
2262
+ this.broadcast({
2263
+ type: 'tool.start',
2264
+ sessionId: payload.sessionId,
2265
+ callId: payload.callId,
2266
+ name: payload.name,
2267
+ title: payload.title,
2268
+ argsPreview: payload.argsPreview,
2269
+ detail: payload.detail ?? null,
2270
+ question: payload.question ?? null,
2271
+ })
2272
+ return
2273
+ }
2274
+ if (payload.phase === 'end') {
2275
+ this.broadcast({
2276
+ type: 'tool.end',
2277
+ sessionId: payload.sessionId,
2278
+ callId: payload.callId,
2279
+ ok: payload.ok !== false,
2280
+ output: payload.output ?? '',
2281
+ durationMs: payload.durationMs ?? 0,
2282
+ detail: payload.detail ?? null,
2283
+ })
2284
+ }
2285
+ }
2286
+
2287
+ broadcastApproval(payload) {
2288
+ if (payload === null || typeof payload !== 'object' || typeof payload.requestId !== 'string') return
2289
+ this.appendDebug(`approval.request session=${String(payload.sessionId ?? '-')} tool=${String(payload.toolName ?? '-')}`)
2290
+ this.pendingApprovals.set(payload.requestId, {
2291
+ requestId: payload.requestId,
2292
+ sessionId: payload.sessionId ?? null,
2293
+ toolName: payload.toolName ?? 'tool',
2294
+ title: payload.title ?? 'Approval required',
2295
+ reason: payload.reason ?? '',
2296
+ displayReason: payload.displayReason ?? null,
2297
+ callId: payload.callId ?? null,
2298
+ // Additive, only present when the bridge correlated the tool call.
2299
+ ...(typeof payload.argsPreview === 'string' && payload.argsPreview.length > 0
2300
+ ? { argsPreview: payload.argsPreview }
2301
+ : {}),
2302
+ ...(typeof payload.argsKind === 'string' ? { argsKind: payload.argsKind } : {}),
2303
+ ...(payload.detail && typeof payload.detail === 'object' && !Array.isArray(payload.detail)
2304
+ ? { detail: payload.detail }
2305
+ : {}),
2306
+ createdAt: Date.now(),
2307
+ })
2308
+ this.broadcast({
2309
+ type: 'approval.request',
2310
+ sessionId: payload.sessionId ?? null,
2311
+ requestId: payload.requestId,
2312
+ toolName: payload.toolName ?? 'tool',
2313
+ title: payload.title ?? 'Approval required',
2314
+ reason: payload.reason ?? '',
2315
+ displayReason: payload.displayReason ?? null,
2316
+ callId: payload.callId ?? null,
2317
+ ...(typeof payload.argsPreview === 'string' && payload.argsPreview.length > 0
2318
+ ? { argsPreview: payload.argsPreview }
2319
+ : {}),
2320
+ ...(typeof payload.argsKind === 'string' ? { argsKind: payload.argsKind } : {}),
2321
+ ...(payload.detail && typeof payload.detail === 'object' && !Array.isArray(payload.detail)
2322
+ ? { detail: payload.detail }
2323
+ : {}),
2324
+ expiresAt: payload.expiresAt ?? 0,
2325
+ })
2326
+ this.requestSessionRefresh()
2327
+ // Lock-screen notification while the phone page is backgrounded/offscreen.
2328
+ this.pushApproval(payload)
2329
+ }
2330
+
2331
+ broadcastApprovalResolved(payload) {
2332
+ this.pendingApprovals.delete(payload.requestId)
2333
+ const by = this.answerOrigins.get(payload.requestId) ?? null
2334
+ this.answerOrigins.delete(payload.requestId)
2335
+ this.broadcast({
2336
+ type: 'approval.resolved',
2337
+ sessionId: payload.sessionId ?? null,
2338
+ requestId: payload.requestId,
2339
+ outcome: payload.outcome ?? 'cancelled',
2340
+ by,
2341
+ })
2342
+ }
2343
+
2344
+ /** Pending approvals for the desktop overlay (both devices show the same list). */
2345
+ pendingApprovalsSnapshot() {
2346
+ return [...this.pendingApprovals.values()].sort((left, right) => left.createdAt - right.createdAt)
2347
+ }
2348
+
2349
+ broadcastQuestion(payload) {
2350
+ if (payload === null || typeof payload !== 'object' || typeof payload.requestId !== 'string') return
2351
+ this.pendingQuestions.set(payload.requestId, {
2352
+ sessionId: payload.sessionId ?? null,
2353
+ requestId: payload.requestId,
2354
+ callId: payload.callId ?? null,
2355
+ questions: Array.isArray(payload.questions) ? payload.questions : [],
2356
+ })
2357
+ this.broadcast({
2358
+ type: 'question.request',
2359
+ sessionId: payload.sessionId ?? null,
2360
+ requestId: payload.requestId,
2361
+ callId: payload.callId ?? null,
2362
+ questions: Array.isArray(payload.questions) ? payload.questions : [],
2363
+ })
2364
+ this.pushQuestion(payload)
2365
+ }
2366
+
2367
+ broadcastQuestionResolved(payload) {
2368
+ if (typeof payload.requestId === 'string') this.pendingQuestions.delete(payload.requestId)
2369
+ const by = typeof payload.requestId === 'string'
2370
+ ? (this.answerOrigins.get(payload.requestId) ?? null)
2371
+ : null
2372
+ if (typeof payload.requestId === 'string') this.answerOrigins.delete(payload.requestId)
2373
+ this.broadcast({
2374
+ type: 'question.resolved',
2375
+ sessionId: payload.sessionId ?? null,
2376
+ requestId: payload.requestId ?? null,
2377
+ callId: payload.callId ?? null,
2378
+ answers: Array.isArray(payload.answers) ? payload.answers : null,
2379
+ outcome: payload.outcome ?? 'answered',
2380
+ by,
2381
+ })
2382
+ }
2383
+
2384
+ broadcastStatus(payload) {
2385
+ if (payload === null || typeof payload !== 'object') return
2386
+ this.broadcast({ type: 'session.status', sessionId: payload.sessionId, running: payload.running === true })
2387
+ this.requestSessionRefresh()
2388
+ // A turn ended: notify the phone through its service worker if no page is
2389
+ // currently visible. At most one such push per session per minute.
2390
+ if (payload.running !== true) this.pushReply(payload)
2391
+ }
2392
+
2393
+ /**
2394
+ * Drop a device's visibility flag once its last socket closed. A missing flag
2395
+ * is already "not visible", so nothing needs to be written for other devices.
2396
+ */
2397
+ refreshDeviceVisibility(deviceId) {
2398
+ for (const peer of this.peers) {
2399
+ if (peer.device.id === deviceId) return
2400
+ }
2401
+ this.deviceVisibility.delete(deviceId)
2402
+ }
2403
+
2404
+ /** True while any connected phone page reports itself foreground/visible. */
2405
+ hasVisiblePeer() {
2406
+ for (const peer of this.peers) {
2407
+ if (this.deviceVisibility.get(peer.device.id) === true) return true
2408
+ }
2409
+ return false
2410
+ }
2411
+
2412
+ /**
2413
+ * Bound and scrub push text: collapse control characters/whitespace, redact
2414
+ * secret-looking key/value pairs and truncate to `limit` characters. Push
2415
+ * bodies are rendered on a lock screen, so they must stay short and must not
2416
+ * carry more than the corresponding approval card.
2417
+ */
2418
+ pushSafeText(value, limit = PUSH_BODY_CHARS) {
2419
+ if (typeof value !== 'string') return ''
2420
+ let text = value
2421
+ .replace(/[\u0000-\u001f\u007f]+/gu, ' ')
2422
+ .replace(/\b(password|passwd|secret|token|api[_-]?key|credential)\b\s*[:=]\s*\S+/giu, '$1=[redacted]')
2423
+ .replace(/\s+/gu, ' ')
2424
+ .trim()
2425
+ if (text.length > limit) text = `${text.slice(0, Math.max(0, limit - 1))}…`
2426
+ return text
2427
+ }
2428
+
2429
+ /** Forget dedupe tags older than the replay window when the map grows. */
2430
+ prunePushTags(now) {
2431
+ if (this.pushTags.size <= PUSH_TAG_LIMIT) return
2432
+ for (const [tag, at] of this.pushTags) {
2433
+ if (now - at >= PUSH_TAG_TTL_MS) this.pushTags.delete(tag)
2434
+ }
2435
+ }
2436
+
2437
+ /**
2438
+ * Best-effort fan-out of one Web Push payload to every stored subscription.
2439
+ *
2440
+ * Gate order: no store -> skip; remote access switched off -> skip; a visible
2441
+ * phone page -> skip; tag seen in the last five minutes -> skip; process-wide
2442
+ * 30/min cap -> skip. The call is always detached from the WebSocket path
2443
+ * (`void`), never rejects, and logs only aggregate counts, never an endpoint,
2444
+ * subscription key or payload.
2445
+ */
2446
+ async dispatchPush(payload, tag) {
2447
+ try {
2448
+ if (this.push === null || !this.push.hasSubscriptions()) {
2449
+ return { ok: false, sent: 0, gone: 0, skipped: 'empty' }
2450
+ }
2451
+ // The desktop switch closes remote access entirely: keep the subscriptions
2452
+ // (they survive re-enable) but send nothing while it is off.
2453
+ if (!this.enabled) return { ok: false, sent: 0, gone: 0, skipped: 'disabled' }
2454
+ if (this.hasVisiblePeer()) return { ok: false, sent: 0, gone: 0, skipped: 'visible' }
2455
+ const now = Date.now()
2456
+ this.prunePushTags(now)
2457
+ const seenAt = this.pushTags.get(tag)
2458
+ if (typeof seenAt === 'number' && now - seenAt < PUSH_TAG_TTL_MS) {
2459
+ return { ok: false, sent: 0, gone: 0, skipped: 'duplicate' }
2460
+ }
2461
+ if (now - this.pushWindowStart >= PUSH_RATE_WINDOW_MS) {
2462
+ this.pushWindowStart = now
2463
+ this.pushWindowCount = 0
2464
+ }
2465
+ if (this.pushWindowCount >= PUSH_MAX_PER_MINUTE) {
2466
+ return { ok: false, sent: 0, gone: 0, skipped: 'rate-limited' }
2467
+ }
2468
+ this.pushWindowCount += 1
2469
+ this.pushTags.set(tag, now)
2470
+ let sent = 0
2471
+ let gone = 0
2472
+ for (const subscription of this.push.subscriptions()) {
2473
+ let result
2474
+ try {
2475
+ result = await this.push.sendNotification(subscription, payload)
2476
+ } catch {
2477
+ result = { ok: false }
2478
+ }
2479
+ if (result?.ok === true) sent += 1
2480
+ if (result?.gone === true) gone += 1
2481
+ }
2482
+ if (gone > 0) this.scheduleSave()
2483
+ return { ok: sent > 0, sent, gone }
2484
+ } catch (error) {
2485
+ this.log.warn?.(`remote-mobile: web push fan-out failed (${error instanceof Error ? error.name : 'Error'})`)
2486
+ return { ok: false, sent: 0, gone: 0 }
2487
+ }
2488
+ }
2489
+
2490
+ /** Push "approval needed" when no phone page is in the foreground. */
2491
+ pushApproval(payload) {
2492
+ const requestId = payload.requestId
2493
+ const sessionId = typeof payload.sessionId === 'string' && payload.sessionId.length > 0 ? payload.sessionId : null
2494
+ const toolName = this.pushSafeText(payload.toolName, 40) || 'tool'
2495
+ const reason = this.pushSafeText(payload.reason || payload.displayReason, 140)
2496
+ void this.dispatchPush({
2497
+ kind: 'approval',
2498
+ title: 'Approval needed',
2499
+ body: this.pushSafeText(reason.length > 0 ? `${toolName}: ${reason}` : toolName, PUSH_BODY_CHARS),
2500
+ tag: `approval:${requestId}`,
2501
+ sessionId,
2502
+ url: sessionId === null ? '/' : `/?session=${encodeURIComponent(sessionId)}`,
2503
+ }, `approval:${requestId}`)
2504
+ }
2505
+
2506
+ /** Push "question from Harness" with the first question text, bounded. */
2507
+ pushQuestion(payload) {
2508
+ const requestId = payload.requestId
2509
+ const sessionId = typeof payload.sessionId === 'string' && payload.sessionId.length > 0 ? payload.sessionId : null
2510
+ const questions = Array.isArray(payload.questions) ? payload.questions : []
2511
+ const first = questions.length > 0 && questions[0] !== null && typeof questions[0] === 'object' ? questions[0] : null
2512
+ const text = this.pushSafeText(
2513
+ first !== null && typeof first.question === 'string' && first.question.length > 0
2514
+ ? first.question
2515
+ : first !== null && typeof first.header === 'string' && first.header.length > 0
2516
+ ? first.header
2517
+ : '',
2518
+ PUSH_BODY_CHARS,
2519
+ )
2520
+ void this.dispatchPush({
2521
+ kind: 'question',
2522
+ title: 'Question from Harness',
2523
+ body: text.length > 0 ? text : 'The agent is waiting for your answer.',
2524
+ tag: `question:${requestId}`,
2525
+ sessionId,
2526
+ url: sessionId === null ? '/' : `/?session=${encodeURIComponent(sessionId)}`,
2527
+ }, `question:${requestId}`)
2528
+ }
2529
+
2530
+ /**
2531
+ * Turn assistant markdown into one short, plain-text notification line:
2532
+ * fenced code is dropped, inline markup flattened, whitespace collapsed.
2533
+ */
2534
+ pushSnippet(value, max) {
2535
+ const safe = this.pushSafeText(value, 2000)
2536
+ if (safe.length === 0) return ''
2537
+ let text = safe
2538
+ .replace(/```[\s\S]*?```/g, ' ')
2539
+ .replace(/`([^`]+)`/g, '$1')
2540
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
2541
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
2542
+ .replace(/[*_#>~]+/g, ' ')
2543
+ .replace(/\s+/g, ' ')
2544
+ .trim()
2545
+ if (text.length > max) text = `${text.slice(0, Math.max(0, max - 1)).trimEnd()}…`
2546
+ return text
2547
+ }
2548
+
2549
+ /**
2550
+ * Push "reply ready" when a session's turn ends. The notification carries the
2551
+ * session title plus a bounded excerpt of the assistant's actual reply, so the
2552
+ * user gets context without opening the app. Fire-and-forget: it can never
2553
+ * delay or fail the status frame. A per-session 60 s quiet period keeps a
2554
+ * burst of status events to one notification.
2555
+ */
2556
+ pushReply(payload) {
2557
+ const sessionId = typeof payload.sessionId === 'string' && payload.sessionId.length > 0 ? payload.sessionId : null
2558
+ if (sessionId === null || this.push === null || !this.push.hasSubscriptions()) return
2559
+ if (this.hasVisiblePeer()) return
2560
+ const now = Date.now()
2561
+ const last = this.replyPushAt.get(sessionId)
2562
+ if (typeof last === 'number' && now - last < PUSH_REPLY_INTERVAL_MS) return
2563
+ this.replyPushAt.set(sessionId, now)
2564
+ if (this.replyPushAt.size > PUSH_TAG_LIMIT) {
2565
+ for (const [id, at] of this.replyPushAt) {
2566
+ if (now - at >= PUSH_REPLY_INTERVAL_MS) this.replyPushAt.delete(id)
2567
+ }
2568
+ }
2569
+ void this.fetchSessions().then((sessions) => {
2570
+ const session = sessions.find((item) => item !== null && typeof item === 'object' && item.id === sessionId)
2571
+ const sessionTitle = this.pushSafeText(session?.title, 60)
2572
+ const snippet = this.pushSnippet(this.replyText.get(sessionId) ?? '', 150)
2573
+ const title = sessionTitle.length > 0 ? `Reply ready · ${sessionTitle}` : 'Reply ready'
2574
+ const tag = `reply:${sessionId}:${Math.floor(Date.now() / PUSH_REPLY_INTERVAL_MS)}`
2575
+ return this.dispatchPush({
2576
+ kind: 'reply',
2577
+ title: this.pushSafeText(title, 80),
2578
+ body: snippet.length > 0
2579
+ ? snippet
2580
+ : sessionTitle.length > 0 ? sessionTitle : 'The session finished a turn.',
2581
+ tag,
2582
+ sessionId,
2583
+ url: `/?session=${encodeURIComponent(sessionId)}`,
2584
+ }, tag)
2585
+ }).catch(() => {
2586
+ // Best-effort only: the phone still gets the status frame.
2587
+ })
2588
+ }
2589
+
2590
+ /** Read the session list without throwing (empty on failure). */
2591
+ async fetchSessions() {
2592
+ try {
2593
+ const sessions = await this.callBridge('listSessions')
2594
+ return Array.isArray(sessions) ? sessions : []
2595
+ } catch {
2596
+ return []
2597
+ }
2598
+ }
2599
+
2600
+ /** Read registered project workspaces without throwing (empty on failure). */
2601
+ async fetchWorkspaces() {
2602
+ const result = await this.callBridgeResult('listWorkspaces')
2603
+ return result.ok && Array.isArray(result.value) ? result.value : []
2604
+ }
2605
+
2606
+ /** Coalesced `sessions` push after a local session mutation. */
2607
+ broadcastSessionRefresh(delayMs = 120) {
2608
+ if (this.peers.size === 0) return
2609
+ if (this.sessionRefreshTimer !== null) return
2610
+ this.sessionRefreshTimer = setTimeout(() => {
2611
+ this.sessionRefreshTimer = null
2612
+ if (this.peers.size === 0) return
2613
+ Promise.all([this.fetchSessions(), this.fetchWorkspaces()])
2614
+ .then(([sessions, workspaces]) => this.broadcast({ type: 'sessions', sessions, workspaces, activeSessionId: null }))
2615
+ .catch((error) => {
2616
+ this.log.warn?.(`remote-mobile: session refresh failed: ${error instanceof Error ? error.message : String(error)}`)
2617
+ })
2618
+ }, delayMs)
2619
+ this.sessionRefreshTimer.unref?.()
2620
+ }
2621
+
2622
+ /**
2623
+ * Coalesced queue push. The bridge can emit a splice and a turn boundary for
2624
+ * the same change; one frame per session per ~120 ms is enough for the SPA.
2625
+ */
2626
+ broadcastQueue(payload) {
2627
+ if (this.peers.size === 0 || payload === null || typeof payload !== 'object') return
2628
+ const sessionId = payload.sessionId
2629
+ if (typeof sessionId !== 'string') return
2630
+ const items = Array.isArray(payload.items) ? payload.items : []
2631
+ this.queuedQueues.set(sessionId, items)
2632
+ if (this.queueTimers.has(sessionId)) return
2633
+ const timer = setTimeout(() => {
2634
+ this.queueTimers.delete(sessionId)
2635
+ const next = this.queuedQueues.get(sessionId) ?? items
2636
+ this.queuedQueues.delete(sessionId)
2637
+ if (this.peers.size > 0) this.broadcast({ type: 'queue.changed', sessionId, items: next })
2638
+ }, 120)
2639
+ timer.unref?.()
2640
+ this.queueTimers.set(sessionId, timer)
2641
+ }
2642
+
2643
+ requestSessionRefresh() {
2644
+ this.broadcastSessionRefresh(250)
2645
+ }
2646
+ }
2647
+
2648
+