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,540 @@
1
+ // lib/browser/access.js — WHO may touch WHICH browser tab, and why.
2
+ //
3
+ // Adapted from DoYourWeb 0.2.6 (MIT): src/grants.js (the @-citation grant store) and
4
+ // src/session-browser-access.js (per-session window access + revoke/abort). See NOTICE.md.
5
+ //
6
+ // The rules this file exists to enforce, each one measured against a failure it prevents:
7
+ //
8
+ // 1. ONLY A REAL USER CITATION GRANTS A TAB. `@[title](dsh-browser://profile/42)` arriving in a
9
+ // user-authored message is the whole authorization. An assistant message, a tool result, a
10
+ // page's own text or a subagent's prose can never add a grant: the citation is re-read from
11
+ // the CLAIMED USER INPUT before any context is appended (see lib/browser/host.js), and the
12
+ // text handed here is only ever that user text. This is the difference between "the page
13
+ // said it may be clicked" and "the human pointed at it".
14
+ //
15
+ // 2. A DELEGATED CHILD NEVER INHERITS. `@deepseek-ai/dsh-subagent` pins every child's approval
16
+ // policy to `never` and copies the parent sandbox, so a child that inherited a grant would
17
+ // drive the human's authenticated session with no prompt and no human in the loop. Grants are
18
+ // therefore keyed by session id AND refused outright for a delegated session (the same test
19
+ // lib/approval-env.js uses for the desktop gate, so the two cannot disagree).
20
+ //
21
+ // 3. WINDOW ACCESS IS OPT-IN AND OFF BY DEFAULT. Nothing is enabled until the human picks a
22
+ // browser window in the sidebar for THIS conversation. That switch is what allows OPENING a
23
+ // new tab and FINDING an existing one; it is not a blanket grant over every tab in the window.
24
+ // A found tab becomes usable only after the human confirms it on the native question card.
25
+ //
26
+ // 4. ACCESS IS REVOKED BY FACTS, NOT BY HOPE. Closing the window, disconnecting the extension,
27
+ // the human pressing "off" in the sidebar, or the tab leaving the authorized window aborts
28
+ // every in-flight operation on the affected tab through its own AbortSignal — the page is
29
+ // never left half-driven because a human flipped a switch mid-batch.
30
+ //
31
+ // 5. THE GRANT IS PINNED TO THE PAGE IT WAS GIVEN FOR. A tab reference that is still valid can
32
+ // point at a different site after the human navigates it (or a site redirects it). Same-origin
33
+ // navigation is ordinary SPA behaviour and stays allowed; a CROSS-ORIGIN change means the
34
+ // thing the human pointed at is gone, so the operation is refused until they cite the page
35
+ // again — or the agent itself names the navigation in the batch (`navigate` step), which is a
36
+ // declared intent rather than a silent target swap.
37
+
38
+ // `parseRef` and the baseline URL policy come from the transport's protocol.js (its exports, its
39
+ // signatures); `admitUrl` and the output helpers are this partition's own (host-protocol.js).
40
+ import { parseRef } from './protocol.js'
41
+ import { admitUrl, clip, hostOf, originOf, urlRefusal } from './host-protocol.js'
42
+ import { readDelegation } from '../approval-env.js'
43
+
44
+ export const MAX_SESSIONS = 200
45
+ export const REFS_PER_SESSION = 50
46
+
47
+ const EMPTY = Object.freeze(new Set())
48
+
49
+ export class BrowserAccess {
50
+ /**
51
+ * @param {object} options
52
+ * @param {object} options.bridge the BrowserBridge (only `on`/`off`/`profiles`/`port` are read)
53
+ * @param {Iterable<number>} [options.guardedPorts] local ports that serve DSH/plugin surfaces
54
+ * @param {boolean} [options.allowFile] the human enabled local `.html`/`.htm` tabs at all
55
+ * @param {(message: string) => void} [options.warn]
56
+ */
57
+ constructor ({ bridge = null, guardedPorts = [], allowFile = false, warn = () => {}, log = null } = {}) {
58
+ this.bridge = bridge
59
+ this.guardedPorts = new Set([...guardedPorts].map(Number).filter(Number.isSafeInteger))
60
+ this.allowFile = allowFile === true
61
+ this.warn = warn
62
+ this.log = log
63
+ this.sessions = new Map()
64
+ this.onInventory = profileId => this.revalidate(profileId)
65
+ try { bridge?.on?.('inventoryChanged', this.onInventory) } catch { /* a stub bridge needs no events */ }
66
+ }
67
+
68
+ /** Every local port that must never become a browser target (the host's own surfaces). */
69
+ guardPort (port) {
70
+ const value = Number(port)
71
+ if (!Number.isSafeInteger(value) || value <= 0) return false
72
+ const added = !this.guardedPorts.has(value)
73
+ this.guardedPorts.add(value)
74
+ // The list/route path asks the host wiring for the CURRENT set; a port learned here (for
75
+ // example from `req.socket.localPort`) must be visible to that answer too, or the list route
76
+ // would keep serving a tab the access layer already refuses.
77
+ try { this.onGuardPort?.(value) } catch { /* reporting is an enhancement */ }
78
+ return added
79
+ }
80
+
81
+ /** The CURRENT protected-port set, however the owner of this instance keeps it. */
82
+ ports () {
83
+ if (typeof this.portSource === 'function') {
84
+ try {
85
+ const live = [...(this.portSource() ?? [])].map(Number).filter(port => Number.isSafeInteger(port) && port > 0)
86
+ return new Set([...this.guardedPorts, ...live])
87
+ } catch { /* fall through to the local set */ }
88
+ }
89
+ return this.guardedPorts
90
+ }
91
+
92
+ /**
93
+ * The one URL question this host asks. Every caller goes through it, so the file-page rule and
94
+ * the harness-surface guard can never drift apart between authorization, navigation and readback.
95
+ */
96
+ admit (value, { allowFile = false } = {}) {
97
+ return admitUrl(value, {
98
+ bridgePort: this.bridge?.port,
99
+ // A local page needs BOTH the human's explicit enablement and this tab's own citation.
100
+ allowFile: allowFile === true && this.allowFile === true,
101
+ guardedPorts: this.ports(),
102
+ })
103
+ }
104
+
105
+ /** The refusal for a page, using the SAME inputs `admit` was asked with. */
106
+ refusal (value, { allowFile = false } = {}) {
107
+ return urlRefusal(value, {
108
+ bridgePort: this.bridge?.port,
109
+ allowFile: allowFile === true && this.allowFile === true,
110
+ guardedPorts: this.ports(),
111
+ })
112
+ }
113
+
114
+ close () {
115
+ try { this.bridge?.off?.('inventoryChanged', this.onInventory) } catch { /* stub bridge */ }
116
+ for (const sessionId of [...this.sessions.keys()]) this.clear(sessionId)
117
+ this.sessions.clear()
118
+ }
119
+
120
+ /** One session's live record; created lazily so a session that never asked costs nothing. */
121
+ record (sessionId) {
122
+ if (typeof sessionId !== 'string' || sessionId === '') return null
123
+ let entry = this.sessions.get(sessionId)
124
+ if (!entry) {
125
+ entry = { sessionId, refs: new Map(), enabled: false, profile: undefined, windowId: undefined,
126
+ controller: new AbortController() }
127
+ this.sessions.set(sessionId, entry)
128
+ while (this.sessions.size > MAX_SESSIONS) this.sessions.delete(this.sessions.keys().next().value)
129
+ }
130
+ return entry
131
+ }
132
+
133
+ /** A revoked session is erased, not merely disabled: the next call must re-ask for a citation. */
134
+ clear (sessionId) {
135
+ const entry = this.sessions.get(sessionId)
136
+ if (!entry) return false
137
+ this.sessions.delete(sessionId)
138
+ const reason = new Error('Browser access for this conversation changed')
139
+ reason.code = 'BROWSER_ACCESS_CHANGED'
140
+ for (const grant of entry.refs.values()) {
141
+ try { grant.controller.abort(reason) } catch { /* already aborted */ }
142
+ }
143
+ try { entry.controller.abort(reason) } catch { /* already aborted */ }
144
+ return true
145
+ }
146
+
147
+ /**
148
+ * Add the references a user cited. Called ONLY with text from a user-authored message.
149
+ *
150
+ * @returns {{granted: string[], refused: string[], reason?: string}}
151
+ */
152
+ cite ({ sessionId, agent = null, refs = [], text = '' } = {}) {
153
+ if (readDelegation(agent?.session ?? agent)) {
154
+ return { granted: [], refused: [...refs], reason: 'delegated session: browser grants are never inherited by a child agent' }
155
+ }
156
+ const entry = this.record(sessionId)
157
+ if (!entry) return { granted: [], refused: [...refs], reason: 'no session' }
158
+ const granted = []
159
+ const refused = []
160
+ for (const ref of refs) {
161
+ let tab
162
+ try { tab = this.tabOf(ref) } catch (error) {
163
+ refused.push(ref)
164
+ this.log?.info?.(`browser: citation ${ref} refused (${error.message})`)
165
+ continue
166
+ }
167
+ if (!tab) { refused.push(ref); continue }
168
+ const file = String(tab.url || '').startsWith('file:')
169
+ if (!this.admit(tab.url, { allowFile: file })) {
170
+ refused.push(ref)
171
+ this.warn(`browser: ${ref} is not an admissible page (${this.refusal(tab.url, { allowFile: file })})`)
172
+ continue
173
+ }
174
+ const signal = entry.controller.signal
175
+ if (signal.aborted) break
176
+ // Re-citing keeps the page identity the grant is pinned to up to date.
177
+ const existing = entry.refs.get(ref)
178
+ if (existing) {
179
+ existing.origin = originOf(tab.url)
180
+ existing.grantedUrl = tab.url
181
+ existing.file = file
182
+ continue
183
+ }
184
+ entry.refs.set(ref, {
185
+ ref, tabId: tab.id, file, origin: originOf(tab.url), grantedUrl: tab.url,
186
+ controller: new AbortController(), citedAt: Date.now(), via: 'citation',
187
+ })
188
+ granted.push(ref)
189
+ while (entry.refs.size > REFS_PER_SESSION) entry.refs.delete(entry.refs.keys().next().value)
190
+ }
191
+ // A citation is the strongest possible statement by the human: it also re-arms a window
192
+ // scope's abort controller, so a session that revoked and re-cited works again.
193
+ if (entry.controller.signal.aborted && !entry.enabled) entry.controller = new AbortController()
194
+ return { granted, refused, ...(granted.length ? {} : refused.length ? { reason: 'no cited tab could be resolved to an open page' } : {}) }
195
+ }
196
+
197
+ /** The refs this session may use, most recent last. */
198
+ refs (sessionId) {
199
+ const entry = this.sessions.get(sessionId)
200
+ if (!entry) return EMPTY
201
+ const live = new Set()
202
+ for (const [ref, grant] of entry.refs) if (!grant.controller.signal.aborted) live.add(ref)
203
+ return live
204
+ }
205
+
206
+ /** A tab record from the live inventory, or undefined when it is not there right now. */
207
+ tabOf (ref) {
208
+ const bridge = this.bridge
209
+ if (!bridge) return undefined
210
+ const { profile: id, tabId } = parseRef(ref)
211
+ const profile = bridge.profiles?.get?.(id)
212
+ if (!profile) return undefined
213
+ return profile.tabs?.get?.(tabId)
214
+ }
215
+
216
+ windows () {
217
+ try { return typeof this.bridge?.accessWindows === 'function' ? this.bridge.accessWindows() : [] } catch { return [] }
218
+ }
219
+
220
+ /** The sidebar's access state for one conversation; `enabled:false` is the default. */
221
+ state (sessionId) {
222
+ const windows = this.windows()
223
+ const entry = this.sessions.get(sessionId)
224
+ const scopeAlive = !!entry && this.windowAlive(entry, windows)
225
+ return {
226
+ enabled: scopeAlive ? entry.enabled : false,
227
+ ...(scopeAlive && entry.profile !== undefined ? { profile: entry.profile, windowId: entry.windowId } : {}),
228
+ windows,
229
+ refs: [...this.refs(sessionId)].slice(0, 50),
230
+ }
231
+ }
232
+
233
+ windowAlive (entry, windows = this.windows()) {
234
+ if (entry.profile === undefined || entry.windowId === undefined) return false
235
+ return windows.some(window => window.profile === entry.profile && window.windowId === entry.windowId)
236
+ }
237
+
238
+ /**
239
+ * The human's sidebar switch. Refuses to enable a window that is not offered right now, so a
240
+ * stale id from a previous browser lifetime cannot silently authorize today's window.
241
+ *
242
+ * Enabling/disableing a window NEVER drops the tabs the user cited with @: those grants came from
243
+ * a different, stronger statement by the same human. Only changing which window is scoped revokes
244
+ * the window-scope signal, because a different window means a different set of pages.
245
+ */
246
+ set ({ sessionId, enabled, profile, windowId } = {}) {
247
+ if (!sessionId || typeof enabled !== 'boolean' || (profile === undefined) !== (windowId === undefined)) {
248
+ throw new Error('Choose a browser window for the current conversation')
249
+ }
250
+ if ((profile !== undefined || enabled) && !this.windows().some(window => window.profile === profile && window.windowId === windowId)) {
251
+ throw new Error('The selected browser window is unavailable. Connect or update the browser extension.')
252
+ }
253
+ const before = this.sessions.get(sessionId)
254
+ const movedWindow = !!before && (before.profile !== profile || before.windowId !== windowId)
255
+ if (movedWindow) {
256
+ // A different window invalidates the scope signal, but the citation grants stay: they are
257
+ // pinned to their own tabs and are re-checked against the inventory on every use.
258
+ const reason = new Error('The authorized browser window changed')
259
+ reason.code = 'BROWSER_ACCESS_CHANGED'
260
+ try { before.controller.abort(reason) } catch { /* already aborted */ }
261
+ before.controller = new AbortController()
262
+ }
263
+ const entry = this.record(sessionId)
264
+ entry.enabled = enabled
265
+ if (profile !== undefined) { entry.profile = profile; entry.windowId = windowId }
266
+ else if (!enabled) { entry.profile = undefined; entry.windowId = undefined }
267
+ return this.state(sessionId)
268
+ }
269
+
270
+ /** Does this tab sit in the window the human enabled, on an admissible page? */
271
+ eligible (sessionId, tab) {
272
+ const entry = this.sessions.get(sessionId)
273
+ if (!entry?.enabled || tab?.windowId !== entry.windowId) return false
274
+ const profile = this.bridge?.profiles?.get?.(entry.profile)
275
+ if (!profile || !profile.tabs?.has?.(tab.id)) return false
276
+ return !!this.admit(tab.url, { allowFile: false })
277
+ }
278
+
279
+ grant (sessionId, tab, via) {
280
+ const entry = this.record(sessionId)
281
+ if (!entry) throw new Error('no session')
282
+ let grant = entry.refs.get(tab.ref)
283
+ if (!grant) {
284
+ grant = { ref: tab.ref, tabId: tab.id, file: false, origin: originOf(tab.url), grantedUrl: tab.url,
285
+ controller: new AbortController(), citedAt: Date.now(), via }
286
+ entry.refs.set(tab.ref, grant)
287
+ while (entry.refs.size > REFS_PER_SESSION) entry.refs.delete(entry.refs.keys().next().value)
288
+ }
289
+ return grant
290
+ }
291
+
292
+ /**
293
+ * Resolve the tab a call wants, or throw the sentence that tells the model what to do instead.
294
+ *
295
+ * @param {{sessionId: string, agent: object, tab?: string}} request
296
+ */
297
+ select ({ sessionId, agent = null, tab } = {}) {
298
+ if (readDelegation(agent?.session ?? agent)) {
299
+ const error = new Error('Browser access is unavailable in a delegated subagent session: cite the page in the conversation that owns it and let that conversation act.')
300
+ error.code = 'BROWSER_DELEGATED'
301
+ throw error
302
+ }
303
+ const allowed = this.refs(sessionId)
304
+ if (!allowed.size) {
305
+ const error = new Error('No browser tab is authorized in this conversation. Ask the user to select the page with @ before it can be read or driven, or open one with computer_browser_open after they enable a browser window.')
306
+ error.code = 'BROWSER_NOT_AUTHORIZED'
307
+ throw error
308
+ }
309
+ let ref = tab
310
+ if (!ref) {
311
+ if (allowed.size === 1) [ref] = allowed
312
+ else {
313
+ const live = [...allowed].filter(candidate => this.tabOf(candidate))
314
+ if (live.length === 1) [ref] = live
315
+ }
316
+ }
317
+ if (!ref) {
318
+ const error = new Error(`Several browser tabs are authorized; pass the tab reference explicitly. Authorized: ${[...allowed].slice(0, 6).join(', ')}`)
319
+ error.code = 'BROWSER_TAB_AMBIGUOUS'
320
+ throw error
321
+ }
322
+ if (!allowed.has(ref)) {
323
+ const error = new Error('That tab was not referenced by the user or authorized in this conversation.')
324
+ error.code = 'BROWSER_NOT_AUTHORIZED'
325
+ throw error
326
+ }
327
+ const tab2 = this.tabOf(ref)
328
+ if (!tab2) {
329
+ const error = new Error('Referenced browser tab is closed or unsupported. Select a tab with @ again.')
330
+ error.code = 'BROWSER_TAB_GONE'
331
+ throw error
332
+ }
333
+ return { ref, tab: tab2 }
334
+ }
335
+
336
+ /**
337
+ * The per-call guard handed to the engine. It is checked BEFORE a read, BEFORE every dispatched
338
+ * step, and AFTER navigation, so a page that leaves the authorized origin stops the batch at the
339
+ * first step that would leave it — never halfway through an action that already landed.
340
+ */
341
+ pageAccess ({ sessionId, ref, signal }) {
342
+ const entry = this.sessions.get(sessionId)
343
+ const grant = entry?.refs.get(ref)
344
+ if (!grant) throw new Error('Browser access for this tab was revoked in this conversation')
345
+ // Captured locally: these methods must not depend on the `this` of whoever calls them.
346
+ // `allowFile` ANDs this tab's own citation with the human's explicit enablement.
347
+ const allowFile = grant.file === true && this.allowFile === true
348
+ const admit = value => this.admit(value, { allowFile })
349
+ const refusal = value => this.refusal(value, { allowFile })
350
+ const scoped = AbortSignal.any
351
+ ? AbortSignal.any([signal, grant.controller.signal, entry.controller.signal].filter(Boolean))
352
+ : signal || grant.controller.signal
353
+ return {
354
+ signal: scoped,
355
+ ref,
356
+ file: grant.file === true,
357
+ origin: grant.origin,
358
+ allowFile,
359
+ assertUrl (value) {
360
+ scoped.throwIfAborted()
361
+ // The tab's own page must still be an admissible page. Guarded ports are included here:
362
+ // a tab that navigates ITSELF onto a DSH surface must stop the batch, not continue on it.
363
+ if (!admit(value)) throw new Error(refusal(value))
364
+ const origin = originOf(value)
365
+ // Same origin is the page the human pointed at. `file:` pages have no origin to compare.
366
+ if (grant.file !== true && grant.origin && origin && origin !== grant.origin) {
367
+ const error = new Error(`That tab left the page the user authorized (${hostOf(grant.grantedUrl)} → ${hostOf(value)}). Read it again, and ask the user to cite the new page with @ if it moved on purpose.`)
368
+ error.code = 'BROWSER_ORIGIN_CHANGED'
369
+ throw error
370
+ }
371
+ return true
372
+ },
373
+ /**
374
+ * A declared navigation is the ONE way a batch may change the page identity: the destination
375
+ * is written in the call, checked against the URL policy, and the grant's origin moves only
376
+ * after the navigation really happened. A navigation never targets a local file.
377
+ *
378
+ * An arrow on purpose: the check must use THIS partition's `admit()` (with the human's file
379
+ * enablement and the guarded ports), never a `this` supplied by the caller.
380
+ */
381
+ declareNavigation: value => {
382
+ if (!this.admit(value, { allowFile: false })) throw new Error(this.refusal(value))
383
+ if (grant.file !== true && originOf(value) && grant.origin && originOf(value) !== grant.origin) {
384
+ grant.pendingOrigin = originOf(value)
385
+ }
386
+ return true
387
+ },
388
+ commitNavigation (value) {
389
+ if (grant.pendingOrigin && originOf(value) === grant.pendingOrigin) {
390
+ grant.origin = grant.pendingOrigin
391
+ grant.grantedUrl = value
392
+ }
393
+ delete grant.pendingOrigin
394
+ },
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Open a new tab in the window the human enabled, or find one they confirm.
400
+ *
401
+ * @param {'open'|'find'} kind
402
+ * @param {string} value URL (open) or keywords (find)
403
+ */
404
+ async authorize (kind, value, { sessionId, agent = null, signal = null, ask = null } = {}) {
405
+ if (readDelegation(agent?.session ?? agent)) {
406
+ const error = new Error('Browser access is unavailable in a delegated subagent session.')
407
+ error.code = 'BROWSER_DELEGATED'
408
+ throw error
409
+ }
410
+ const entry = this.sessions.get(sessionId)
411
+ if (!entry?.enabled || !this.windowAlive(entry)) {
412
+ throw new Error('Ask the user to enable browser access in the Browser settings for this conversation and choose a connected browser window. They can also select an existing tab with @.')
413
+ }
414
+ const scopeSignal = entry.controller.signal
415
+ const combined = signal && AbortSignal.any ? AbortSignal.any([signal, scopeSignal]) : (signal || scopeSignal)
416
+ combined.throwIfAborted()
417
+ const profile = this.bridge?.profiles?.get?.(entry.profile)
418
+ if (!profile || !profile.windows?.has?.(entry.windowId)) {
419
+ throw new Error('The selected browser window is no longer available')
420
+ }
421
+ let tab
422
+ if (kind === 'open') {
423
+ const url = this.admit(value, { allowFile: false })
424
+ if (!url) throw new Error(`Opening a page requires a regular HTTP/HTTPS URL without credentials. ${this.refusal(value)}`)
425
+ tab = await this.bridge.openTab(profile, entry.windowId, url.href)
426
+ } else {
427
+ const keywords = String(value).trim().normalize('NFKC').toLowerCase().split(/\s+/).filter(Boolean)
428
+ const candidates = [...profile.tabs.values()].filter(candidate => this.eligible(sessionId, candidate) &&
429
+ keywords.every(keyword => `${candidate.title || ''} ${candidate.url}`.normalize('NFKC').toLowerCase().includes(keyword)))
430
+ if (!candidates.length) {
431
+ throw new Error('No matching web page in the selected window. Try the page title or site name, or ask the user to select it with @.')
432
+ }
433
+ if (candidates.length > 6) throw new Error('Too many matching tabs. Use a more specific page title or site name.')
434
+ if (typeof ask !== 'function') {
435
+ throw new Error('Finding an open page needs a native confirmation, and this session cannot ask the human. Ask the user to select the page with @ instead.')
436
+ }
437
+ const id = `browser_find_${candidates[0].id}`
438
+ const choices = candidates.map((candidate, index) => ({
439
+ label: `${index + 1}. ${clip(candidate.title || hostOf(candidate.url), 120)}`,
440
+ description: clip(candidate.url, 200),
441
+ }))
442
+ let answer
443
+ try {
444
+ answer = await ask({ agent, signal: combined, questions: [{ id, header: '选择网页', question: '允许本会话访问哪个标签页?', options: [...choices, { label: '不授权' }] }] })
445
+ } catch (error) {
446
+ combined.throwIfAborted()
447
+ if (['NO_PROVIDER', 'DELEGATED_CALLER', 'CALLER_NOT_LIVE'].includes(error?.code)) {
448
+ throw new Error('Native tab confirmation is unavailable in this session. Ask the user to select the tab with @.')
449
+ }
450
+ throw error
451
+ }
452
+ combined.throwIfAborted()
453
+ const selected = answer?.answers?.find(item => item?.id === id)?.selected
454
+ const index = Array.isArray(selected) && selected.length === 1
455
+ ? choices.findIndex(choice => choice.label === selected[0]) : -1
456
+ if (index < 0) return { status: 'denied', message: 'The user did not authorize a tab.' }
457
+ const shown = candidates[index]
458
+ const current = await this.bridge.request(profile, 'dsh.tabState', [shown.id])
459
+ combined.throwIfAborted()
460
+ tab = profile.tabs.get(shown.id)
461
+ if ([current, tab].some(item => item?.url !== shown.url || item?.title !== shown.title ||
462
+ item?.windowId !== entry.windowId || item?.revision !== shown.revision)) {
463
+ throw new Error('The selected tab changed during confirmation. Ask for a fresh selection.')
464
+ }
465
+ }
466
+ combined.throwIfAborted()
467
+ if (this.bridge.profiles?.get?.(entry.profile) !== profile || !tab || tab.windowId !== entry.windowId) {
468
+ throw new Error('The browser tab or selected window changed. Check the browser before retrying.')
469
+ }
470
+ if (!this.admit(tab.url, { allowFile: false })) {
471
+ throw new Error(this.refusal(tab.url))
472
+ }
473
+ // A tab the human picked through the sidebar switch is still not a place a local file may be
474
+ // driven from: `file:` needs the human's own @ citation of that exact page.
475
+ this.grant(sessionId, tab, kind)
476
+ return { status: 'authorized', tab: tab.ref, title: clip(tab.title || '', 128), url: clip(tab.url, 512) }
477
+ }
478
+
479
+ /** The tab left the window / closed / the extension reconnected: abort only what is affected. */
480
+ revalidate (profileId) {
481
+ // Called with a profile id (an inventory change for THAT browser) or with NOTHING (the whole
482
+ // protected-port set changed and every session must be re-tested).
483
+ const scoped = typeof profileId === 'string' && profileId !== ''
484
+ for (const [sessionId, entry] of this.sessions) {
485
+ if (scoped && entry.profile !== undefined && entry.profile !== profileId) continue
486
+ const windows = this.windows()
487
+ if (!scoped && entry.profile !== undefined && !this.windowAlive(entry, windows)) {
488
+ this.clear(sessionId)
489
+ continue
490
+ }
491
+ for (const [ref, grant] of entry.refs) {
492
+ const tab = this.tabOf(ref)
493
+ // A tab is kept ONLY while it still exists, is still in the scoped window (a cited tab is
494
+ // exempt: it was authorized by its own citation), and is still an admitted page under the
495
+ // CURRENT port set. A newly-guarded port therefore revokes the grant that pointed at it.
496
+ if (tab && (entry.profile === undefined || tab.windowId === entry.windowId || grant.via === 'citation') &&
497
+ this.admit(tab.url, { allowFile: grant.file === true })) continue
498
+ const reason = new Error('The browser tab left the authorized window or web pages')
499
+ reason.code = 'BROWSER_ACCESS_CHANGED'
500
+ try { grant.controller.abort(reason) } catch { /* already aborted */ }
501
+ entry.refs.delete(ref)
502
+ }
503
+ }
504
+ }
505
+
506
+ /**
507
+ * Re-test a single tab by its CURRENT URL, for the hot path after a port is discovered.
508
+ *
509
+ * THE ANSWER IS ABOUT THE PAGE, NOT ABOUT THE GRANT (measured, 2026-11-28). The first version
510
+ * only examined sessions that still HELD a grant, so a tab whose grant had already been revoked
511
+ * fell through the loop and reported `true` — "still admissible" — even when the page had just
512
+ * become the DSH control surface. A caller asking "is this still a legitimate target?" must get
513
+ * an answer derived from the URL, so admission is tested FIRST, independently of any grant; only
514
+ * then are the grants on it revoked.
515
+ *
516
+ * @returns {boolean} true only when the tab still exists and its page is still an admitted target
517
+ */
518
+ recheckTab (ref) {
519
+ const tab = this.tabOf(ref)
520
+ if (!tab) return false
521
+ const offender = new Error('That tab became part of the DSH control surface and is no longer a browser target')
522
+ offender.code = 'BROWSER_ACCESS_CHANGED'
523
+ // Any grant on this ref, whichever session holds it, is the evidence needed to abort in-flight
524
+ // work. Gather it first so an inadmissible page can still abort every holder.
525
+ const holders = []
526
+ for (const entry of this.sessions.values()) {
527
+ const grant = entry.refs.get(ref)
528
+ if (grant) holders.push({ entry, grant })
529
+ }
530
+ const admitted = this.admit(tab.url, { allowFile: holders.some(holder => holder.grant.file === true) })
531
+ if (!admitted) {
532
+ for (const { entry, grant } of holders) {
533
+ try { grant.controller.abort(offender) } catch { /* already aborted */ }
534
+ entry.refs.delete(ref)
535
+ }
536
+ return false
537
+ }
538
+ return true
539
+ }
540
+ }
@@ -0,0 +1,82 @@
1
+ // lib/browser/approval.js — the local approval surface for pairing.
2
+ //
3
+ // A web page must never be able to mint or embed a credential, so the page that
4
+ // approves a pairing is one the HOST opened: `approvalUrl('setup')` mints a
5
+ // single-use invitation (60 s) carried in the URL fragment, which is not sent in
6
+ // Referer headers and is stripped from history on arrival. The page trades it
7
+ // for a short-lived session key at POST /auth/session, which requires same-origin
8
+ // + JSON content type, and approving a pairing needs that key. Browser headers
9
+ // alone grant nothing: looking same-origin is not authority.
10
+
11
+ import { randomBytes } from 'node:crypto'
12
+
13
+ const INVITE_TTL_MS = 60_000
14
+ const SESSION_TTL_MS = 30 * 60_000
15
+
16
+ export class LocalApproval {
17
+ constructor ({ now = () => Date.now(), bytes = (size) => randomBytes(size) } = {}) {
18
+ this.now = now
19
+ this.bytes = bytes
20
+ this.invitations = new Map()
21
+ this.sessions = new Map()
22
+ }
23
+
24
+ prune () {
25
+ for (const entries of [this.invitations, this.sessions]) {
26
+ for (const [key, entry] of entries) if (entry.expires <= this.now()) entries.delete(key)
27
+ }
28
+ }
29
+
30
+ invite (scope) {
31
+ this.prune()
32
+ const secret = this.bytes(32).toString('hex')
33
+ this.invitations.set(secret, { scope, expires: this.now() + INVITE_TTL_MS })
34
+ while (this.invitations.size > 32) this.invitations.delete(this.invitations.keys().next().value)
35
+ return secret
36
+ }
37
+
38
+ exchange (secret, scope) {
39
+ this.prune()
40
+ const invitation = this.invitations.get(secret)
41
+ if (!invitation || invitation.scope !== scope) return undefined
42
+ this.invitations.delete(secret)
43
+ const key = this.bytes(32).toString('hex')
44
+ this.sessions.set(key, { scope, expires: this.now() + SESSION_TTL_MS })
45
+ while (this.sessions.size > 128) this.sessions.delete(this.sessions.keys().next().value)
46
+ return key
47
+ }
48
+
49
+ /** Live session key for `scope`? Refreshes its LRU position on use. */
50
+ permits (key, scope) {
51
+ this.prune()
52
+ if (typeof key !== 'string') return false
53
+ const session = this.sessions.get(key)
54
+ if (!session || session.scope !== scope) return false
55
+ this.sessions.delete(key)
56
+ this.sessions.set(key, session)
57
+ return true
58
+ }
59
+
60
+ close () {
61
+ this.invitations.clear()
62
+ this.sessions.clear()
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The browser half of the exchange, as one self-contained script for the setup
68
+ * page's single nonce-bound inline `<script>`.
69
+ */
70
+ export function approvalScript (scope, hint) {
71
+ return `const approvalReady=(async()=>{` +
72
+ `const store=${JSON.stringify(`dsh-browser-approval-${scope}`)};` +
73
+ `const secret=new URLSearchParams(location.hash.slice(1)).get('approve');` +
74
+ `if(secret){history.replaceState(null,'',location.pathname);` +
75
+ `const response=await fetch('/auth/session',{method:'POST',headers:{'Content-Type':'application/json'},` +
76
+ `body:JSON.stringify({secret,scope:${JSON.stringify(scope)}})});` +
77
+ `if(!response.ok)throw Error('This setup link has expired; open it again from the DSH browser settings.');` +
78
+ `const value=await response.json();sessionStorage.setItem(store,value.key)}` +
79
+ `const key=sessionStorage.getItem(store);` +
80
+ `if(!key)throw Error(${JSON.stringify(hint)});` +
81
+ `return key})();`
82
+ }