dsh-codex-style-computer-use 2.3.5 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1048 @@
1
+ // lib/browser/bridge.js — the local browser bridge.
2
+ //
3
+ // Derived from DoYourWeb 0.2.6 `src/bridge.js` (MIT, see NOTICE). Kept: pairing,
4
+ // per-tab CDP relays, idle release. Dropped: annotations, app management,
5
+ // network capture, WebMCP.
6
+ //
7
+ // Four rules this file exists to enforce:
8
+ // 1. Nothing crosses from a web page. The extension socket requires a
9
+ // `chrome-extension://` Origin (a page cannot forge it); the CDP relay
10
+ // requires the bearer token and no Origin at all. Pairing needs a human.
11
+ // 2. Only the referenced tab is reachable — `page(ref)` relays one tab, and
12
+ // BrowserModel refuses `Target.createTarget`/`Target.closeTarget`.
13
+ // 3. The user's session stays in the browser: no cookie reads, no free CDP/JS
14
+ // surface, no persistent debugger port, no arbitrary page injection.
15
+ // 4. One bad message never costs the browser session.
16
+ //
17
+ // `ws` and `playwright-core` are the only runtime dependencies and both are
18
+ // imported lazily, so the desktop toolset keeps working without them.
19
+
20
+ import http from 'node:http'
21
+ import os from 'node:os'
22
+ import path from 'node:path'
23
+ import { EventEmitter } from 'node:events'
24
+ import { randomBytes, randomUUID } from 'node:crypto'
25
+ import { readFileSync } from 'node:fs'
26
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
27
+ import { fileURLToPath } from 'node:url'
28
+
29
+ import { BrowserModel } from './model.js'
30
+ import { LocalApproval } from './approval.js'
31
+ import { Pairings, isExtensionOrigin, newBridgeToken, pinnedExtensionId, validBridgeToken } from './pairing.js'
32
+ import { setupCsp, setupPage } from './setup-page.js'
33
+ import {
34
+ DEFAULT_PORT, allowedTabUrl, bridgeProtocolRevision, normalizeBrowser,
35
+ parseRef, sameSecret, sessionWebUrl, tabRef, urlRefusal, validProfileId,
36
+ } from './protocol.js'
37
+
38
+ const EXTENSION_DIR = new URL('./extension/', import.meta.url)
39
+
40
+ /** Generous for a local debugger command. */
41
+ const COMMAND_TIMEOUT_MS = 15_000
42
+
43
+ /**
44
+ * How long a released tab stays attached before the debugger detaches.
45
+ *
46
+ * A browser shows a "DSH is debugging this tab" bar while a tab is attached, so
47
+ * holding the attachment after the work is done costs the user something
48
+ * visible. Release is deferred because a task normally reads, acts and re-reads
49
+ * within seconds.
50
+ */
51
+ const DEFAULT_IDLE_TIMEOUT_MS = 120_000
52
+
53
+ /**
54
+ * The host version the extension is told about.
55
+ *
56
+ * The ONLY consumer is the extension popup's version line and its "update both
57
+ * together" hint, so an unset version is not cosmetic: it made a freshly
58
+ * installed host answer `dsh.pong` with `unknown`, which never equals the
59
+ * extension's own `chrome.runtime.getManifest().version`, so a healthy install
60
+ * reported a mismatch on first open. The extension ships FROM this package, so
61
+ * this package's own manifest is the version it should be compared with.
62
+ *
63
+ * An explicit `version` still wins (tests and hosts that identify themselves);
64
+ * a manifest that cannot be read keeps the old honest 'unknown' rather than
65
+ * inventing a number.
66
+ */
67
+ const PACKAGE_VERSION = (() => {
68
+ try {
69
+ const version = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version
70
+ return typeof version === 'string' && version.length > 0 ? version : 'unknown'
71
+ } catch { return 'unknown' }
72
+ })()
73
+
74
+ /** A promise that resolves after `ms`, unref'd so it never holds the process open. */
75
+ function after (ms) {
76
+ return new Promise(resolve => {
77
+ const timer = setTimeout(resolve, ms)
78
+ timer.unref?.()
79
+ })
80
+ }
81
+
82
+ /**
83
+ * Wrap a callback-style close so it always settles.
84
+ *
85
+ * The callback may be invoked twice (once by the resource, once by a grace
86
+ * timer) and a second `resolve` is a no-op, so this cannot double-settle. A
87
+ * throw from the close call itself is a settled failure, not a hang.
88
+ */
89
+ function settleWith (start) {
90
+ return new Promise(resolve => {
91
+ try { start(resolve) } catch { resolve() }
92
+ })
93
+ }
94
+
95
+ /** The one file that carries the bridge's pairing secret. */
96
+ const PAIRING_FILE = 'pairing.json'
97
+
98
+ /**
99
+ * How long a loser of the pairing-file race keeps re-reading.
100
+ *
101
+ * `writeFile` is not atomic: the winner's file can be observed a moment before its bytes are
102
+ * complete. A bounded re-read tolerates that window; it never rewrites anything.
103
+ */
104
+ const PAIRING_READ_ATTEMPTS = 5
105
+ const PAIRING_READ_DELAY_MS = 20
106
+
107
+ /** The parsed settings, or `undefined` when the file is absent or not yet a complete record. */
108
+ async function readPairingSettings (settingsPath) {
109
+ let raw
110
+ try {
111
+ raw = await readFile(settingsPath, 'utf8')
112
+ } catch (error) {
113
+ if (error?.code === 'ENOENT') return undefined
114
+ throw error
115
+ }
116
+ try {
117
+ const parsed = JSON.parse(raw)
118
+ return parsed !== null && typeof parsed === 'object' ? parsed : undefined
119
+ } catch {
120
+ // A partially written file from another instance looks like this for a few milliseconds.
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Read the pairing token, creating it EXACTLY ONCE.
127
+ *
128
+ * THE RACE THIS EXISTS FOR (measured on the real 3.0.0 browser panel): the panel requests `list`
129
+ * and `setup` together on first open, so the first `mkdir` is followed by several "no file yet"
130
+ * reads and several exclusive creates; the losers threw `EEXIST: file already exists, open …
131
+ * pairing.json` at a user who had done nothing wrong.
132
+ *
133
+ * The file IS the bridge's persisted pairing identity, so the winner's token is the same trust
134
+ * decision this process would have made itself: a loser adopts the completed file instead of
135
+ * failing or overwriting. Nothing is ever rewritten — an existing token, authorised extensions and
136
+ * the user's own data stay untouched. A file that is present but unusable is still an error.
137
+ */
138
+ async function readOrCreatePairing (settingsPath) {
139
+ const existing = await readPairingSettings(settingsPath)
140
+ if (existing !== undefined) return existing
141
+ const settings = { token: newBridgeToken() }
142
+ try {
143
+ await writeFile(settingsPath, JSON.stringify(settings), { mode: 0o600, flag: 'wx' })
144
+ return settings
145
+ } catch (error) {
146
+ // Only "someone else got there first" is recoverable; a permission or disk fault is not.
147
+ if (error?.code !== 'EEXIST') throw error
148
+ }
149
+ for (let attempt = 0; attempt < PAIRING_READ_ATTEMPTS; attempt++) {
150
+ const shared = await readPairingSettings(settingsPath)
151
+ if (shared !== undefined) return shared
152
+ await after(PAIRING_READ_DELAY_MS)
153
+ }
154
+ throw new Error(`${PAIRING_FILE} at ${settingsPath} exists but is not a usable pairing record; ` +
155
+ 'delete it and restart the plugin to pair the extension again')
156
+ }
157
+
158
+ export class BrowserBridge extends EventEmitter {
159
+ /**
160
+ * @param {object} options
161
+ * @param {string} [options.home] state directory; pairing.json lives here
162
+ * @param {number} [options.port] 0 asks the OS for a free port (tests do this)
163
+ * @param {string} [options.extensionSource] extension folder advertised in setup()
164
+ * @param {number} [options.idleTimeoutMs] release delay for an attached tab
165
+ * @param {boolean} [options.allowFile] list local file HTML pages
166
+ * @param {string} [options.version] host version reported to the extension; defaults to this package's version
167
+ */
168
+ constructor ({
169
+ home,
170
+ port = DEFAULT_PORT,
171
+ extensionSource,
172
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
173
+ allowFile = true,
174
+ version = PACKAGE_VERSION,
175
+ protectedPorts = [],
176
+ } = {}) {
177
+ super()
178
+ this.home = home || path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'browser-tabs')
179
+ this.port = port
180
+ this.extensionSource = extensionSource || fileURLToPath(EXTENSION_DIR)
181
+ this.extensionPath = this.extensionSource
182
+ this.idleTimeoutMs = idleTimeoutMs
183
+ this.allowFile = allowFile
184
+ // Reported by dsh.pong so the popup can show a version mismatch as a hint.
185
+ this.version = version
186
+ // Every host port that serves DSH's own UI (the web server the host passes in).
187
+ // A loopback page on one of these is the control surface — a model that could
188
+ // drive it could approve its own approvals — so it is refused at list, resolve,
189
+ // page and openTab. The bridge's own port is always included.
190
+ this.protectedPorts = protectedPorts
191
+ this.profiles = new Map()
192
+ this.relays = new Map()
193
+ this.pending = new Map()
194
+ this.detachments = new Map()
195
+ this.pairings = new Pairings()
196
+ this.approval = new LocalApproval()
197
+ this.sequence = 0
198
+ this.started = false
199
+ // Set while a start()/prepare() is in flight: every concurrent caller awaits THIS promise, so
200
+ // the browser panel's simultaneous first `list` and `setup` cannot open the same listener twice.
201
+ this.starting = undefined
202
+ this.preparing = undefined
203
+ this.prepared = false
204
+ // Set while a close is in flight; a second close() shares it (see `close`).
205
+ this.closing = undefined
206
+ // Set by the host after construction: the real Playwright module (injected by
207
+ // tests, lazily imported otherwise) and a per-page decoration/teardown hook.
208
+ this.playwright = undefined
209
+ this.decoratePage = undefined
210
+ this.beforeRelease = undefined
211
+ }
212
+
213
+ // ---- lifecycle -------------------------------------------------------------------------
214
+
215
+ /**
216
+ * Load the pairing token and (when the manifest pins one) the extension id.
217
+ *
218
+ * The token is generated once and lives in `home/pairing.json` with owner-only
219
+ * permissions. Nothing is copied into the extension folder: the user loads
220
+ * `lib/browser/extension/` as-is and the token travels over the socket.
221
+ *
222
+ * Safe to call concurrently, in this process and across two of them: see
223
+ * `readOrCreatePairing`. Repeating it on an already-prepared bridge is a no-op,
224
+ * so it never re-reads or re-writes the token an extension has already paired with.
225
+ */
226
+ async prepare () {
227
+ if (this.prepared) return this
228
+ this.preparing ??= this.performPrepare().finally(() => { this.preparing = undefined })
229
+ return this.preparing
230
+ }
231
+
232
+ async performPrepare () {
233
+ await mkdir(this.home, { recursive: true })
234
+ this.settings = await readOrCreatePairing(path.join(this.home, PAIRING_FILE))
235
+ if (!validBridgeToken(this.settings.token)) {
236
+ throw new Error(`${PAIRING_FILE} has no usable token; delete it and restart the plugin to pair the extension again`)
237
+ }
238
+ this.manifest = JSON.parse(await readFile(path.join(this.extensionSource, 'manifest.json'), 'utf8'))
239
+ // The extension folder SHIPPED with this package pins its public key, so the
240
+ // extension id is knowable in advance and the bridge accepts exactly that
241
+ // origin. There is no "trust whatever asks first" path: a keyless folder is a
242
+ // packaging error, not a user state, because users load the folder this
243
+ // package ships and can never change the id it was built with.
244
+ this.manifestId = pinnedExtensionId(this.manifest)
245
+ if (this.manifestId === undefined) {
246
+ throw new Error(`The bundled browser extension at ${this.extensionSource} does not pin a "key"; ` +
247
+ 'the bridge can only trust a known extension identity')
248
+ }
249
+ this.trustedOrigin = `chrome-extension://${this.manifestId}`
250
+ this.prepared = true
251
+ return this
252
+ }
253
+
254
+ /**
255
+ * Start listening, EXACTLY ONCE per bridge instance.
256
+ *
257
+ * The browser panel issues `list` and `setup` together on first open, and the host's
258
+ * `ensureStarted()` used to let both call through: two `start()` calls raced `prepare()` (the
259
+ * `EEXIST` above) and then each created a server, so one instance bound the port and the other
260
+ * reported it "already in use" — a user-visible failure for a successful start.
261
+ *
262
+ * Every concurrent caller now awaits ONE in-flight promise and gets the same bridge. A second
263
+ * caller after a successful start gets the already-started bridge instead of a second listener;
264
+ * after a FAILED start the latch is cleared, so the next call really retries and a genuine
265
+ * `EADDRINUSE` is still reported instead of being cached as a false failure.
266
+ */
267
+ async start () {
268
+ if (this.started) return this
269
+ this.starting ??= this.performStart().finally(() => { this.starting = undefined })
270
+ return this.starting
271
+ }
272
+
273
+ async performStart () {
274
+ await this.prepare()
275
+ const { WebSocketServer } = await import('ws')
276
+ // Built locally and assigned only once listening: a failed listen (EADDRINUSE, EACCES) must
277
+ // leave NO half-open server, no un-listened WebSocketServer and no dangling `upgrade` handler
278
+ // behind, because the retry path above starts again on this same object.
279
+ const server = http.createServer((request, response) => this.handleHttp(request, response))
280
+ let ws
281
+ try {
282
+ ws = new WebSocketServer({ noServer: true, maxPayload: 8 * 1024 * 1024 })
283
+ server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head))
284
+ await new Promise((resolve, reject) => {
285
+ // `once` handlers are removed on success: left attached, the first
286
+ // post-startup server error would settle an already-settled promise and
287
+ // silently detach, so the NEXT error would be unhandled and crash the host.
288
+ const failed = error => { server.off('listening', listening); reject(error) }
289
+ const listening = () => { server.off('error', failed); resolve() }
290
+ server.once('error', failed)
291
+ server.once('listening', listening)
292
+ server.listen(this.port, '127.0.0.1')
293
+ })
294
+ } catch (error) {
295
+ // Release this attempt's resources; neither is reachable from elsewhere. A server that never
296
+ // listened must NOT be closed: `close()` on it emits `ERR_SERVER_NOT_RUNNING` as an 'error'
297
+ // event, and with no listener attached that would throw from inside this catch — replacing a
298
+ // clean EADDRINUSE message with an uncaught exception. Nothing was accepted, so the correct
299
+ // release is to drop the reference and let GC take it.
300
+ try { ws?.close(() => {}) } catch { /* no client could have connected */ }
301
+ if (error?.code !== 'EADDRINUSE') throw error
302
+ throw new Error(`Browser bridge port ${this.port} is already in use. Another DSH instance, another ` +
303
+ 'application or a bridge leaked by an older plugin version owns it; stop that instance or set a ' +
304
+ 'different "port" in the plugin settings.')
305
+ }
306
+ this.server = server
307
+ this.ws = ws
308
+ // A permanent listener keeps a late server error (EMFILE on accept) from
309
+ // becoming an uncaught exception; the bridge stays usable and the failure is
310
+ // reported. `emit('error')` is deliberately avoided: an EventEmitter with no
311
+ // 'error' listener THROWS, which is exactly the crash this guards against.
312
+ this.server.on('error', error => this.report(error, 'server'))
313
+ // Port 0 answers with the port the OS chose, so tests never collide with a
314
+ // real installation and a caller can report the actual port.
315
+ this.port = this.server.address().port
316
+ this.url = `http://127.0.0.1:${this.port}/setup`
317
+ this.started = true
318
+ return this
319
+ }
320
+
321
+ /**
322
+ * Stop the bridge and release everything it created.
323
+ *
324
+ * SAFE IN EVERY PARTIAL STATE, which matters because `start()` can fail after
325
+ * creating nothing (a keyless manifest, a port clash) and hosts call `close()`
326
+ * in a `finally` regardless:
327
+ *
328
+ * * never started, or `prepare()` threw → `ws` and `server` are undefined;
329
+ * * `start()` created the server but the listen failed → server is not
330
+ * listening;
331
+ * * `close()` called twice → the second call must RETURN, not hang;
332
+ * * `close()` while `start()` is still in flight → the in-flight start is
333
+ * awaited first, so its listener cannot come up AFTER teardown and leak.
334
+ *
335
+ * Nothing here awaits an optional call blindly. `this.ws?.close(resolve)`
336
+ * with `ws` undefined short-circuits the whole expression, so `resolve` is
337
+ * never invoked and the await never settles — which surfaces as an unsettled
338
+ * top-level await (Node exit 13). Each resource is therefore checked for
339
+ * existence first, and every close also carries a short timer so a peer that
340
+ * never answers cannot hold teardown open.
341
+ */
342
+ async close () {
343
+ // Re-entrancy latch: a second close() (or one racing the first) shares the
344
+ // first one's work instead of starting a second teardown of half-gone state.
345
+ this.closing ??= this.performClose().finally(() => { this.closing = undefined })
346
+ return this.closing
347
+ }
348
+
349
+ async performClose () {
350
+ // A start() that has not finished yet is awaited first (its own failure is already that
351
+ // caller's answer). Without this, a teardown that raced startup could return first and leave a
352
+ // listening socket owned by an object nobody closes any more. `started` is cleared AFTER the
353
+ // wait so a start that completed during teardown cannot leave the flag set.
354
+ const starting = this.starting
355
+ if (starting !== undefined) await starting.catch(() => {})
356
+ this.started = false
357
+ this.approval.close()
358
+ this.pairings.clear()
359
+ for (const relay of [...this.relays.values()]) this.dropRelay(relay)
360
+ // Teardown must not inherit the 15 s command timeout: a throttled MV3 worker
361
+ // would otherwise hold plugin unload (and the bridge port) for that long.
362
+ await Promise.race([
363
+ Promise.all(this.detachments.values()),
364
+ after(1500),
365
+ ])
366
+ for (const client of this.ws?.clients ?? []) { try { client.close() } catch { /* already gone */ } }
367
+ for (const pending of this.pending.values()) {
368
+ clearTimeout(pending.timer)
369
+ pending.reject(new Error('Bridge stopped'))
370
+ }
371
+ this.pending.clear()
372
+
373
+ // Take each resource out of the instance BEFORE awaiting it, so a concurrent
374
+ // observer cannot touch a half-closed server.
375
+ const ws = this.ws
376
+ this.ws = undefined
377
+ if (ws !== undefined) await Promise.race([settleWith(cb => ws.close(cb)), after(1000)])
378
+
379
+ const server = this.server
380
+ this.server = undefined
381
+ if (server !== undefined && server.listening) {
382
+ await Promise.race([
383
+ settleWith(cb => {
384
+ server.close(cb)
385
+ // Idle keep-alive connections must not keep plugin unload waiting.
386
+ server.closeAllConnections?.()
387
+ }),
388
+ after(1000),
389
+ ])
390
+ }
391
+ }
392
+
393
+ // ---- setup surface ---------------------------------------------------------------------
394
+
395
+ /**
396
+ * Report a non-fatal fault.
397
+ *
398
+ * A host listens for `diagnostic` if it wants them; the bridge never uses
399
+ * `emit('error')`, because EventEmitter throws when nothing listens, and these
400
+ * are all cases the bridge deliberately survives.
401
+ */
402
+ report (error, method = 'bridge') {
403
+ try { this.emit('diagnostic', { method, error: error?.message ?? String(error) }) } catch { /* host listener threw */ }
404
+ }
405
+
406
+ /** A one-time URL the host hands the user. Only `setup` exists here. */
407
+ approvalUrl (scope = 'setup') {
408
+ if (scope !== 'setup') throw new Error('Invalid approval scope')
409
+ return `http://127.0.0.1:${this.port}/setup#approve=${this.approval.invite('setup')}`
410
+ }
411
+
412
+ /**
413
+ * The setup contract a host calls to offer "connect a browser".
414
+ *
415
+ * Returns the approval URL and the extension folder to load unpacked. A host
416
+ * that only wants to render a settings card needs nothing else.
417
+ */
418
+ setup () {
419
+ return { url: this.approvalUrl('setup'), extensionPath: this.extensionPath, port: this.port }
420
+ }
421
+
422
+ /** The origin actually allowed to connect, once known. */
423
+ get origin () {
424
+ return this.trustedOrigin
425
+ }
426
+
427
+ // ---- HTTP ------------------------------------------------------------------------------
428
+
429
+ handleHttp (request, response) {
430
+ const port = this.port
431
+ // A request addressed to another host name is DNS rebinding, not a user.
432
+ const host = String(request.headers.host ?? '').toLowerCase()
433
+ if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) { response.writeHead(403).end(); return }
434
+ const pathname = new URL(request.url, `http://127.0.0.1:${port}`).pathname
435
+
436
+ if (pathname === '/auth/session' && request.method === 'POST') return this.handleApproval(request, response)
437
+ if (pathname === '/setup/pair' && request.method === 'POST') return this.handlePairPost(request, response)
438
+ if (request.method !== 'GET') { response.writeHead(405).end(); return }
439
+ if (pathname !== '/setup') { response.writeHead(404).end(); return }
440
+
441
+ const nonce = randomBytes(16).toString('base64')
442
+ const html = setupPage({
443
+ nonce,
444
+ state: {
445
+ port, extensionPath: this.extensionPath, allowFile: this.allowFile,
446
+ connected: this.profiles.size > 0, pending: this.pairings.list(),
447
+ },
448
+ })
449
+ response.writeHead(200, {
450
+ 'Content-Type': 'text/html; charset=utf-8',
451
+ 'Cache-Control': 'no-store',
452
+ 'Referrer-Policy': 'no-referrer',
453
+ 'Content-Security-Policy': setupCsp(nonce),
454
+ })
455
+ response.end(html)
456
+ }
457
+
458
+ /** Trade a one-time invitation for a session key. */
459
+ handleApproval (request, response) {
460
+ const origin = `http://127.0.0.1:${this.port}`
461
+ if ((request.headers.origin && request.headers.origin !== origin) ||
462
+ (request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin') ||
463
+ request.headers['content-type']?.split(';')[0] !== 'application/json') { response.writeHead(403).end(); return }
464
+ let body = ''
465
+ let oversized = false
466
+ request.on('data', chunk => {
467
+ body += chunk
468
+ if (Buffer.byteLength(body) > 1024) { oversized = true; response.writeHead(413).end(); request.destroy() }
469
+ })
470
+ request.on('end', () => {
471
+ if (oversized) return
472
+ let value
473
+ try { value = JSON.parse(body) } catch { response.writeHead(400).end(); return }
474
+ const key = this.approval.exchange(value?.secret, value?.scope)
475
+ if (!key) { response.writeHead(403).end(); return }
476
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
477
+ .end(JSON.stringify({ key }))
478
+ })
479
+ }
480
+
481
+ /**
482
+ * Approve or deny one pairing request.
483
+ *
484
+ * Requires a live setup session: spoofing `Sec-Fetch-Site` grants nothing,
485
+ * because the key is only obtainable by a page the HOST opened.
486
+ */
487
+ handlePairPost (request, response) {
488
+ const sameOrigin = !request.headers['sec-fetch-site'] || request.headers['sec-fetch-site'] === 'same-origin'
489
+ if (!sameOrigin) { response.writeHead(403).end(); return }
490
+ let body = ''
491
+ request.on('data', chunk => { body += chunk; if (body.length > 4096) request.destroy() })
492
+ request.on('end', () => {
493
+ const fields = new URLSearchParams(body)
494
+ if (!this.approval.permits(fields.get('key'), 'setup')) { response.writeHead(403).end(); return }
495
+ const id = fields.get('id') ?? ''
496
+ if (fields.get('action') === 'allow') this.approvePairing(id)
497
+ else this.pairings.take(id)?.socket.close(1000, 'Pairing denied')
498
+ response.writeHead(303, { Location: '/setup', 'Cache-Control': 'no-store' }).end()
499
+ })
500
+ }
501
+
502
+ // ---- upgrades --------------------------------------------------------------------------
503
+
504
+ /**
505
+ * Decide whether an upgrade becomes a socket — and which kind.
506
+ *
507
+ * Synchronous on purpose: an `await` here would let a second pairing request
508
+ * race the caps in `Pairings`.
509
+ */
510
+ handleUpgrade (request, socket, head) {
511
+ const port = this.port
512
+ const host = String(request.headers.host ?? '').toLowerCase()
513
+ if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) return socket.destroy()
514
+ const pathname = new URL(request.url, `http://127.0.0.1:${port}`).pathname
515
+ const protocols = String(request.headers['sec-websocket-protocol'] ?? '')
516
+ .split(',').map(value => value.trim()).filter(Boolean)
517
+ const origin = typeof request.headers.origin === 'string' ? request.headers.origin : undefined
518
+
519
+ if (pathname === '/extension') {
520
+ // A page can never drive this bridge: its Origin is a web origin, and the
521
+ // extension origin is only producible by extension code.
522
+ if (!isExtensionOrigin(origin)) return socket.destroy()
523
+ const offered = protocols[1]
524
+ // The bundled folder pins its key, so the trusted origin is always known;
525
+ // anything else is refused before a pairing row exists.
526
+ if (origin !== this.trustedOrigin) return socket.destroy()
527
+ if (sameSecret(offered, this.settings.token)) {
528
+ this.ws.handleUpgrade(request, socket, head, ws => this.acceptExtension(ws, origin))
529
+ } else if (offered === undefined) {
530
+ // No token = "pair me". A WRONG token is a stale install or a probe and
531
+ // gets no code.
532
+ this.ws.handleUpgrade(request, socket, head, ws => this.acceptPairing(ws, origin))
533
+ } else socket.destroy()
534
+ return
535
+ }
536
+
537
+ if (pathname.startsWith('/cdp/')) {
538
+ const relay = this.relays.get(pathname)
539
+ // A browser page always sends an Origin; Playwright's CDP client does not.
540
+ if (!relay || relay.ws || origin !== undefined) return socket.destroy()
541
+ if (!sameSecret(request.headers.authorization, `Bearer ${this.settings.token}`)) return socket.destroy()
542
+ this.ws.handleUpgrade(request, socket, head, ws => this.acceptCDP(relay, ws))
543
+ return
544
+ }
545
+
546
+ socket.destroy()
547
+ }
548
+
549
+ // ---- pairing ---------------------------------------------------------------------------
550
+
551
+ acceptPairing (ws, origin) {
552
+ const pairing = this.pairings.request(ws, origin)
553
+ if (pairing === undefined) { ws.close(1008, 'Too many pairing requests'); return }
554
+ ws.on('error', () => {})
555
+ const expiry = setTimeout(() => {
556
+ this.pairings.drop(ws)
557
+ ws.close(1000, 'Pairing expired')
558
+ }, this.pairings.ttlMs)
559
+ expiry.unref?.()
560
+ ws.on('close', () => { clearTimeout(expiry); this.pairings.drop(ws) })
561
+ ws.send(JSON.stringify({ method: 'dsh.pairing', params: {
562
+ id: pairing.id, code: pairing.code, expiresAt: pairing.expires, port: this.port,
563
+ } }))
564
+ }
565
+
566
+ /**
567
+ * Hand the token to the one request the human approved.
568
+ *
569
+ * The origin is already fixed by the manifest key, so approval cannot change
570
+ * which extension is trusted — it only decides whether THIS install gets the
571
+ * token.
572
+ */
573
+ approvePairing (id) {
574
+ const pairing = this.pairings.take(id)
575
+ if (pairing === undefined) return false
576
+ if (pairing.socket.readyState !== 1) return false
577
+ pairing.socket.send(JSON.stringify({ method: 'dsh.paired', params: { token: this.settings.token, port: this.port } }))
578
+ // The extension stores the token and reconnects authenticated, so this
579
+ // request-only socket never becomes a control channel.
580
+ pairing.socket.close(1000, 'Paired')
581
+ return true
582
+ }
583
+
584
+ // ---- the extension socket --------------------------------------------------------------
585
+
586
+ acceptExtension (ws, origin) {
587
+ let profile
588
+ ws.on('error', () => {})
589
+ ws.on('message', raw => {
590
+ let data
591
+ // A parse failure is a protocol violation from the extension and closes the
592
+ // socket. An internal fault in one handler must NOT: closing here would
593
+ // drop the profile, reject every pending request and tear down every relay,
594
+ // costing the user their whole browser session over one bad message.
595
+ try { data = JSON.parse(raw.toString()) } catch { ws.close(1003, 'Invalid bridge message'); return }
596
+ try {
597
+ if (data.method === 'dsh.inventory') profile = this.acceptInventory(profile, data.params, origin, ws)
598
+ else if (data.id && this.pending.has(data.id)) this.settlePending(ws, data)
599
+ else if (profile && data.method === 'chrome.debugger.onEvent') this.forwardDebuggerEvent(profile, data.params)
600
+ else if (profile && data.method === 'chrome.debugger.onDetach') this.dropRelayForTab(profile, data.params?.[0]?.tabId)
601
+ else if (data.method === 'dsh.ping') {
602
+ ws.send(JSON.stringify({ method: 'dsh.pong', params: {
603
+ version: this.version, protocolRevision: bridgeProtocolRevision,
604
+ } }))
605
+ }
606
+ } catch (error) {
607
+ // Keep the connection: one malformed or failing message must not end the
608
+ // user's browser session. It is still reported.
609
+ this.report(error, 'extension_message')
610
+ }
611
+ })
612
+ ws.on('close', () => {
613
+ if (profile && this.profiles.get(profile.id) === profile) {
614
+ this.profiles.delete(profile.id)
615
+ // A host listener that throws must not break the teardown of the rest of
616
+ // this socket's state, so the emit is guarded like every other host call.
617
+ try { this.emit('inventoryChanged', profile.id) } catch (error) { this.report(error, 'inventoryChanged') }
618
+ }
619
+ for (const [id, pending] of this.pending) {
620
+ if (pending.ws !== ws) continue
621
+ this.pending.delete(id)
622
+ clearTimeout(pending.timer)
623
+ // The caller may itself have gone away with the socket; a rejection
624
+ // nothing observes is still a rejection, so it is marked handled. The
625
+ // live caller already holds this promise and still sees the error.
626
+ try { pending.reject(new Error('Browser extension disconnected')) } catch { /* no waiter */ }
627
+ }
628
+ for (const relay of [...this.relays.values()]) if (relay.profile === profile) this.dropRelay(relay)
629
+ })
630
+ }
631
+
632
+ /**
633
+ * Apply one metadata refresh from the extension.
634
+ *
635
+ * The profile identity is pinned for the life of the connection: a message that
636
+ * claims a different saved profile or browser session on an established socket
637
+ * is a protocol violation, not a new tab list. Every tab is re-filtered through
638
+ * the URL policy here, so the bridge — not the extension — is the authority on
639
+ * what is controllable.
640
+ */
641
+ acceptInventory (current, info, origin, ws) {
642
+ const next = readInventory(this, current, info, origin)
643
+ if (current) {
644
+ current.tabs = next.tabs
645
+ current.windows = next.windows
646
+ current.browser = next.browser
647
+ current.extensionVersion = next.extensionVersion
648
+ current.protocolRevision = next.protocolRevision
649
+ current.compatibilityWarning = next.compatibilityWarning
650
+ // A relay whose tab vanished holds a debugger attachment to nothing.
651
+ for (const relay of [...this.relays.values()]) {
652
+ if (relay.profile === current && !current.tabs.has(relay.tabId)) void this.dropRelay(relay)
653
+ }
654
+ this.emit('inventoryChanged', current.id)
655
+ return current
656
+ }
657
+ next.ws = ws
658
+ // One profile per saved browser profile: a reconnect replaces the old
659
+ // connection instead of listing the same browser twice.
660
+ for (const old of [...this.profiles.values()]) {
661
+ if (old.sourceId !== next.sourceId || old.id === next.id) continue
662
+ this.profiles.delete(old.id)
663
+ try { old.ws.close(1000, 'Reconnected') } catch { /* already closed */ }
664
+ }
665
+ this.profiles.set(next.id, next)
666
+ this.emit('inventoryChanged', next.id)
667
+ return next
668
+ }
669
+
670
+ settlePending (ws, data) {
671
+ const pending = this.pending.get(data.id)
672
+ if (pending.ws !== ws) throw new Error('Wrong connection for response')
673
+ this.pending.delete(data.id)
674
+ clearTimeout(pending.timer)
675
+ if (data.error) pending.reject(new Error(data.error))
676
+ else pending.resolve(data.result)
677
+ }
678
+
679
+ forwardDebuggerEvent (profile, params) {
680
+ const [source, method, payload] = params ?? []
681
+ if (source?.tabId === undefined) return
682
+ try { this.emit('debuggerEvent', profile, source, method, payload) } catch (error) { this.report(error, 'debuggerEvent') }
683
+ for (const relay of this.relays.values()) {
684
+ // A relay without a model is skipped rather than dereferenced: this runs on
685
+ // the extension's event path, where a throw would cost the whole session.
686
+ if (relay.profile === profile && relay.tabId === source.tabId && relay.model?.onDebuggerEvent) {
687
+ try { relay.model.onDebuggerEvent(source, method, payload) } catch (error) { this.report(error, 'debuggerEvent') }
688
+ }
689
+ }
690
+ }
691
+
692
+ dropRelayForTab (profile, tabId) {
693
+ for (const relay of [...this.relays.values()]) {
694
+ if (relay.profile === profile && relay.tabId === tabId) this.dropRelay(relay)
695
+ }
696
+ }
697
+
698
+ // ---- commands --------------------------------------------------------------------------
699
+
700
+ /**
701
+ * Send one command to the extension and wait for its answer.
702
+ *
703
+ * `chrome.debugger.sendCommand` is named in the params array; every other
704
+ * method is the bridge's own (`dsh.openTab`, `dsh.focus`, ...).
705
+ */
706
+ request (profile, method, params) {
707
+ if (profile.ws.readyState !== 1) return Promise.reject(new Error('Browser extension disconnected'))
708
+ const id = ++this.sequence
709
+ const command = method === 'chrome.debugger.sendCommand' ? params[1] : method
710
+ return new Promise((resolve, reject) => {
711
+ const timer = setTimeout(() => {
712
+ this.pending.delete(id)
713
+ reject(new Error(`Browser command timed out: ${command} (request ${id})`))
714
+ }, COMMAND_TIMEOUT_MS)
715
+ this.pending.set(id, { resolve, reject, timer, ws: profile.ws, method: command })
716
+ try {
717
+ profile.ws.send(JSON.stringify({ id, method, params }))
718
+ } catch (error) {
719
+ // A send that throws delivers nothing, so the entry must not stay
720
+ // pending: its timer would later report a TIMEOUT for a command that was
721
+ // never dispatched and the caller would be rejected twice.
722
+ this.pending.delete(id)
723
+ clearTimeout(timer)
724
+ reject(error)
725
+ return
726
+ }
727
+ if (method === 'chrome.debugger.sendCommand') this.emit('commandSent', tabRef(profile.id, params[0].tabId), command)
728
+ })
729
+ }
730
+
731
+ /**
732
+ * Every port whose loopback pages are the control surface, never a target.
733
+ *
734
+ * The host passes its own web-server port; the bridge adds its own. Recomputed
735
+ * per call because `port` is only known after the listener binds (port 0).
736
+ */
737
+ get guardedPorts () {
738
+ return [...new Set([...(this.protectedPorts ?? []), this.port].map(Number)
739
+ .filter(value => Number.isSafeInteger(value) && value > 0))]
740
+ }
741
+
742
+ /** The URL policy with this bridge's own settings applied. */
743
+ urlAllowed (value, { file = this.allowFile } = {}) {
744
+ return allowedTabUrl(value, { ports: this.guardedPorts, allowFile: file })
745
+ }
746
+
747
+ // ---- the host-facing surface -----------------------------------------------------------
748
+
749
+ /**
750
+ * Every controllable tab, best match first.
751
+ *
752
+ * The metadata shape is upstream's, so a host that renders
753
+ * `{ref, title, url, windowId, active, browser, favicon, ref}` keeps working.
754
+ */
755
+ list (query = '') {
756
+ const needle = String(query ?? '').toLowerCase().trim()
757
+ return [...this.profiles.values()].flatMap(profile => [...profile.tabs.values()])
758
+ .filter(tab => !needle || `${tab.title} ${tab.url} ${tab.browser}`.toLowerCase().includes(needle))
759
+ .sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0))
760
+ .slice(0, 50)
761
+ }
762
+
763
+ /**
764
+ * Windows the host may offer for "open a new tab here".
765
+ *
766
+ * Only normal (non-incognito) windows with at least one controllable tab are
767
+ * listed, so the host cannot point a new tab at a window the user cannot see.
768
+ */
769
+ accessWindows () {
770
+ return [...this.profiles.values()].flatMap(profile => [...profile.windows].map(windowId => {
771
+ const tabs = [...profile.tabs.values()].filter(tab => tab.windowId === windowId)
772
+ return {
773
+ profile: profile.id,
774
+ windowId,
775
+ browser: profile.browser,
776
+ profileLabel: profile.sourceId.slice(0, 8),
777
+ activeTitle: tabs.find(tab => tab.active)?.title,
778
+ tabCount: tabs.length,
779
+ }
780
+ }))
781
+ }
782
+
783
+ /**
784
+ * Open a URL in a window the user enabled, and return its tab.
785
+ *
786
+ * The URL goes through the same policy as every other: ordinary http(s) only,
787
+ * no credentials, never this bridge's own port. The returned tab is re-checked
788
+ * against the window, so a browser that opened something else is an error, not
789
+ * a silently different page.
790
+ */
791
+ async openTab (profile, windowId, url) {
792
+ if (profile !== undefined && this.profiles.get(profile.id) !== profile) {
793
+ throw new Error('The selected browser is no longer connected')
794
+ }
795
+ if (!profile?.windows.has(windowId)) throw new Error('The selected browser window is no longer available')
796
+ // Opening a tab never implies local-file access: an ordinary web URL only.
797
+ const target = sessionWebUrl(url, { ports: this.guardedPorts })
798
+ if (!target) throw new Error('A regular HTTP/HTTPS URL without credentials is required')
799
+ const result = await this.request(profile, 'dsh.openTab', [windowId, target.href])
800
+ const tab = profile.tabs.get(result?.tabId)
801
+ if (!tab || tab.windowId !== windowId || !this.urlAllowed(tab.url) ||
802
+ this.profiles.get(profile.id) !== profile) {
803
+ throw new Error('The new tab is outside the selected window or did not load a supported web page. ' +
804
+ 'Check the browser before retrying.')
805
+ }
806
+ return tab
807
+ }
808
+
809
+ /** Resolve a reference or say plainly why it cannot be used. */
810
+ resolve (ref) {
811
+ const { profile: id, tabId } = parseRef(ref)
812
+ const profile = this.profiles.get(id)
813
+ if (!profile) {
814
+ throw new Error('Browser extension is offline or its browser session ended. Open the browser ' +
815
+ 'connection settings to reconnect, then select the tab with @ again.')
816
+ }
817
+ const tab = profile.tabs.get(tabId)
818
+ if (!tab) throw new Error('Referenced browser tab is closed or unsupported. Select a tab with @ again.')
819
+ // Re-checked here, not only at inventory time: the protected host ports and
820
+ // the file setting can change while a tab stays open.
821
+ if (!this.urlAllowed(tab.url)) throw new Error(urlRefusal(tab.url, { ports: this.guardedPorts }))
822
+ return { profile, tab, tabId }
823
+ }
824
+
825
+ /** Whether a reference currently resolves — the host's candidate filter. */
826
+ canResolve (ref) {
827
+ try { this.resolve(ref); return true } catch { return false }
828
+ }
829
+
830
+ /**
831
+ * The Playwright `Page` for one referenced tab.
832
+ *
833
+ * Playwright speaks CDP over a WebSocket; this bridge does not own a debugger
834
+ * port, so the relay forwards each command to the extension's debugger session
835
+ * for that single tab. The relay is pooled per reference: a second call for the
836
+ * same tab reuses the live connection.
837
+ */
838
+ async page (ref) {
839
+ await this.detachments.get(ref)
840
+ const { profile, tab, tabId } = this.resolve(ref)
841
+ const existing = [...this.relays.values()].find(relay => relay.profile === profile && relay.tabId === tabId)
842
+ if (existing) {
843
+ clearTimeout(existing.idleTimer)
844
+ existing.idleTimer = undefined
845
+ return existing.ready
846
+ }
847
+ // The URL can have navigated since inventory (a tab the user moved onto the
848
+ // harness is no longer a target), so it is re-read and re-admitted right
849
+ // before a debugger session is opened on it.
850
+ const current = await this.request(profile, 'dsh.tabState', [tabId]).catch(() => undefined)
851
+ if (current?.url && !this.urlAllowed(current.url)) {
852
+ throw new Error(urlRefusal(current.url, { ports: this.guardedPorts }))
853
+ }
854
+ const pathname = `/cdp/${randomUUID()}`
855
+ const model = new BrowserModel((method, params) => this.request(profile, method, params))
856
+ model.onTabCreated(tab)
857
+ const relay = { pathname, ref, profile, tabId, model }
858
+ this.relays.set(pathname, relay)
859
+ relay.ready = (async () => {
860
+ // Dynamic ESM import yields the module namespace (`chromium` on it); a host
861
+ // or test may instead inject the CommonJS module or `{ default: … }`. All
862
+ // three shapes are accepted so an injected fixture cannot fail on the
863
+ // destructuring rather than on the connection itself.
864
+ const loaded = this.playwright ?? await import('playwright-core')
865
+ const chromium = loaded?.chromium ?? loaded?.default?.chromium
866
+ if (chromium === undefined || typeof chromium.connectOverCDP !== 'function') {
867
+ throw new Error('playwright-core did not expose chromium.connectOverCDP; the browser relay cannot attach')
868
+ }
869
+ const browser = await chromium.connectOverCDP(`ws://127.0.0.1:${this.port}${pathname}`, {
870
+ // The paired extension and this host share the local filesystem. Without
871
+ // isLocal, Playwright converts upload paths into base64 payloads.
872
+ isLocal: true,
873
+ headers: { Authorization: `Bearer ${this.settings.token}` },
874
+ timeout: 15_000,
875
+ })
876
+ relay.browser = browser
877
+ browser.on('disconnected', () => this.dropRelay(relay))
878
+ const page = browser.contexts()[0]?.pages()[0]
879
+ if (!page) throw new Error('Browser did not expose the referenced tab')
880
+ page.setDefaultTimeout(8000)
881
+ page.setDefaultNavigationTimeout(12_000)
882
+ // Decoration is an optional host feature and never a precondition for
883
+ // reading a tab; a failure is reported, not propagated.
884
+ if (this.decoratePage) {
885
+ try { await this.decoratePage(ref, page) } catch (error) { this.report(error, 'decoratePage') }
886
+ }
887
+ return page
888
+ })().catch(error => { this.dropRelay(relay); throw error })
889
+ // `relay.ready` is retained for the pool's lifetime and may be awaited by a
890
+ // later `page()` call, or by none at all if the host gave up. Marking it as
891
+ // handled here keeps a failure from becoming an unhandled rejection when the
892
+ // only waiter has gone — the ORIGINAL promise is still returned, so callers
893
+ // that do await it still observe the error.
894
+ relay.ready.catch(() => {})
895
+ return relay.ready
896
+ }
897
+
898
+ /**
899
+ * Keep the tab attached for `idleTimeoutMs` after the last use.
900
+ *
901
+ * The host calls this when a task finishes. The tab itself is never closed;
902
+ * only the debugger attachment (and the browser's "being debugged" bar) goes.
903
+ */
904
+ release (ref) {
905
+ const relay = [...this.relays.values()].find(entry => entry.ref === ref)
906
+ if (!relay) return
907
+ clearTimeout(relay.idleTimer)
908
+ relay.idleTimer = setTimeout(() => void this.dropRelay(relay), this.idleTimeoutMs)
909
+ relay.idleTimer.unref?.()
910
+ }
911
+
912
+ /** Drop one relay: close Playwright, forward the detach, forget the cache. */
913
+ dropRelay (relay) {
914
+ if (!this.relays.delete(relay.pathname)) return this.detachments.get(relay.ref)
915
+ clearTimeout(relay.idleTimer)
916
+ try { this.emit('release', relay.ref) } catch (error) { this.report(error, 'release') }
917
+ const cleanup = (async () => {
918
+ try { await this.beforeRelease?.(relay.ref) } catch { /* detach must finish even if the page is gone */ }
919
+ try { relay.ws?.close() } catch { /* already closed */ }
920
+ const closing = relay.browser?.close().catch(() => {})
921
+ // The profile can be gone by now (its socket closed and the entry removed),
922
+ // which is exactly when a relay is being torn down; asking for a detach on
923
+ // a dead connection would only add a rejection nobody will read.
924
+ const detached = relay.profile?.ws?.readyState === 1
925
+ ? this.request(relay.profile, 'chrome.debugger.detach', [{ tabId: relay.tabId }]).catch(() => {})
926
+ : undefined
927
+ await Promise.all([closing, detached])
928
+ })().finally(() => {
929
+ if (this.detachments.get(relay.ref) === cleanup) this.detachments.delete(relay.ref)
930
+ })
931
+ this.detachments.set(relay.ref, cleanup)
932
+ // Stored for `page()` to await before reconnecting, but nothing guarantees a
933
+ // waiter: a release triggered by a closed socket usually has none.
934
+ cleanup.catch(() => {})
935
+ return cleanup
936
+ }
937
+
938
+ /** Activate the referenced tab and raise its window. */
939
+ async focus (ref) {
940
+ const { profile, tabId } = this.resolve(ref)
941
+ await this.request(profile, 'dsh.focus', [tabId])
942
+ }
943
+
944
+ // ---- the per-tab CDP relay -------------------------------------------------------------
945
+
946
+ /**
947
+ * Accept the one Playwright CDP socket for a relay.
948
+ *
949
+ * NEVER THROWS. This runs inside `ws`'s `completeUpgrade` callback, which is
950
+ * called from a `'upgrade'` event handler: an exception there is an uncaught
951
+ * synchronous throw that kills the whole plugin host — not a promise rejection
952
+ * something could catch. A relay without a model is a programming error, but it
953
+ * must cost that one socket, not the process.
954
+ */
955
+ acceptCDP (relay, ws) {
956
+ const model = relay.model
957
+ if (!model || typeof model.connectOverCDP !== 'function') {
958
+ this.report(new Error('CDP relay accepted without a tab model'), 'acceptCDP')
959
+ try { ws.close(1011, 'Relay is not ready') } catch { /* already gone */ }
960
+ this.dropRelay(relay)
961
+ return
962
+ }
963
+ relay.ws = ws
964
+ ws.on('error', () => {})
965
+ const send = message => { if (ws.readyState === 1) ws.send(JSON.stringify(message)) }
966
+ model.connectOverCDP(send)
967
+ ws.on('message', async raw => {
968
+ let message
969
+ try { message = JSON.parse(raw.toString()) } catch { this.dropRelay(relay); return }
970
+ // A CDP command without a numeric id can never be answered; dropping the
971
+ // relay surfaces one protocol violation instead of hanging the caller.
972
+ if (!Number.isSafeInteger(message?.id)) { this.dropRelay(relay); return }
973
+ try {
974
+ const result = await model.command(message.method, message.params, message.sessionId)
975
+ send({ id: message.id, sessionId: message.sessionId, result })
976
+ } catch (error) {
977
+ send({ id: message.id, sessionId: message.sessionId, error: { message: error.message } })
978
+ }
979
+ })
980
+ ws.on('close', () => { this.dropRelay(relay) })
981
+ }
982
+ }
983
+
984
+ /**
985
+ * Read one metadata refresh from the extension.
986
+ *
987
+ * Kept as a free function because it is the single place where extension data
988
+ * becomes bridge state, and it is worth being able to read in one screen: every
989
+ * field is validated, every tab is filtered through the URL policy, and the
990
+ * profile's identity is pinned for the life of the connection.
991
+ */
992
+ export function readInventory (bridge, current, info, origin) {
993
+ if (!validProfileId(info?.profile) || !Array.isArray(info.tabs) ||
994
+ (info.browserSession !== undefined && !validProfileId(info.browserSession))) {
995
+ throw new Error('Invalid inventory')
996
+ }
997
+ if (current && (info.profile !== current.sourceId || info.browserSession !== current.sessionId)) {
998
+ throw new Error('Profile identity changed')
999
+ }
1000
+ const protocolRevision = Number.isSafeInteger(info.protocolRevision) ? info.protocolRevision : undefined
1001
+ const extensionVersion = /^[\d.]{1,24}$/.test(info.extensionVersion ?? '') ? info.extensionVersion : undefined
1002
+ const profile = current ?? {
1003
+ // A persisted profile does not identify a browser lifetime: Chrome reuses tab
1004
+ // ids after a restart, so the connection id comes from the browser session
1005
+ // when the extension reports one.
1006
+ id: info.browserSession ?? randomUUID(),
1007
+ sourceId: info.profile,
1008
+ sessionId: info.browserSession,
1009
+ ws: undefined,
1010
+ origin,
1011
+ tabs: new Map(),
1012
+ windows: new Set(),
1013
+ }
1014
+ profile.browser = normalizeBrowser(info.browser)
1015
+ profile.extensionVersion = extensionVersion
1016
+ profile.protocolRevision = protocolRevision
1017
+ // A mismatch is a HINT, never a refusal: a stale extension must keep working
1018
+ // over the same messages, and refusing here would strand the user mid-upgrade.
1019
+ profile.compatibilityWarning = protocolRevision !== bridgeProtocolRevision
1020
+ ? 'The extension speaks a different protocol revision; update the host and the extension together.'
1021
+ : extensionVersion !== undefined && extensionVersion !== bridge.version
1022
+ ? 'Host and extension versions differ; update both together.'
1023
+ : ''
1024
+ profile.windows = new Set(Array.isArray(info.windows)
1025
+ ? info.windows.filter(window => Number.isSafeInteger(window?.id) && window.id >= 0).map(window => window.id)
1026
+ : [])
1027
+ profile.tabs = new Map(info.tabs
1028
+ .filter(tab => Number.isSafeInteger(tab.id) && tab.id >= 0 && !tab.incognito &&
1029
+ Number.isSafeInteger(tab.windowId) && profile.windows.has(tab.windowId) &&
1030
+ bridge.urlAllowed(tab.url))
1031
+ .map(tab => [tab.id, {
1032
+ id: tab.id,
1033
+ title: typeof tab.title === 'string' ? tab.title.slice(0, 500) : '',
1034
+ url: tab.url,
1035
+ windowId: tab.windowId,
1036
+ active: tab.active === true,
1037
+ lastAccessed: Number.isFinite(tab.lastAccessed) ? tab.lastAccessed : 0,
1038
+ status: typeof tab.status === 'string' ? tab.status : undefined,
1039
+ discarded: tab.discarded === true,
1040
+ frozen: tab.frozen === true,
1041
+ favicon: typeof tab.favicon === 'string' && tab.favicon.length <= 12_000 &&
1042
+ /^data:image\/png;base64,[a-zA-Z0-9+/=]+$/.test(tab.favicon) ? tab.favicon : undefined,
1043
+ browser: profile.browser,
1044
+ profile: profile.id,
1045
+ ref: tabRef(profile.id, tab.id),
1046
+ }]))
1047
+ return profile
1048
+ }