dsh-builtin-browser 0.4.15 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +116 -33
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +108 -29
  56. package/src/tool-browser/index.ts +13 -1
@@ -0,0 +1,38 @@
1
+ /** Versions reported by the running child, never inferred from an npm package or path. */
2
+ interface RuntimeVersions {
3
+ readonly electron?: string
4
+ readonly chrome?: string
5
+ readonly node?: string
6
+ }
7
+
8
+ /**
9
+ * Startup diagnostics only: an explicit runtime remains the user's choice.
10
+ * Keep this pure so availability checks never spawn Electron or download it.
11
+ */
12
+ export function electronRuntimeDiagnosticLines(
13
+ versions: RuntimeVersions,
14
+ stamp = new Date().toISOString(),
15
+ ): string[] {
16
+ const electron = versions.electron?.trim() || 'unknown'
17
+ const lines = [
18
+ `${stamp} runtime: electron=${electron} chromium=${versions.chrome?.trim() || 'unknown'} node=${versions.node?.trim() || 'unknown'}`,
19
+ ]
20
+ const parsed = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(electron)
21
+ const continuing = 'continuing with the selected runtime. Update its installation, or change/remove ELECTRON_PATH if that override selects it.'
22
+ if (parsed === null || Number(parsed[1]) !== 44) {
23
+ // Other maintained branches can be patched for the advisory below. An
24
+ // untested major is a compatibility warning, not a vulnerability claim.
25
+ lines.push(`${stamp} warning: Electron ${electron} is not verified for this plugin; expected stable Electron 44.x >=44.9.1; ${continuing}`)
26
+ return lines
27
+ }
28
+ const minor = Number(parsed[2])
29
+ const patch = Number(parsed[3])
30
+ const prerelease = parsed[4] !== undefined
31
+ // A prerelease of 44.9.1 sorts before the patched stable release.
32
+ if (minor < 9 || (minor === 9 && (patch < 1 || (patch === 1 && prerelease)))) {
33
+ lines.push(`${stamp} warning: Electron ${electron} is below the 44.x security minimum 44.9.1 (GHSA-jr5w-w6x2-84p9); ${continuing}`)
34
+ } else if (prerelease) {
35
+ lines.push(`${stamp} warning: Electron ${electron} is a prerelease and is not verified for this plugin; expected stable Electron 44.x >=44.9.1; ${continuing}`)
36
+ }
37
+ return lines
38
+ }
@@ -4,8 +4,8 @@
4
4
  * they survive the browser process and DSH restarts.
5
5
  *
6
6
  * Every field is optional on disk and falls back to a default, so a hand-edited
7
- * or older file never breaks startup; an unreadable file is treated as "all
8
- * defaults" rather than an error.
7
+ * or older file never breaks startup; an unreadable document refuses capability
8
+ * gates while retaining the defaults for presentation and other conveniences.
9
9
  * @module dsh-browser/browser-electron/settings-store
10
10
  */
11
11
 
@@ -76,6 +76,19 @@ export interface BrowserSettings {
76
76
  readonly credentials: {
77
77
  readonly allowRead: boolean
78
78
  }
79
+ /**
80
+ * Live view of the browser for a remote operator (issue #34).
81
+ *
82
+ * OFF by default, and that default is the feature's main safety property: a live browser frame can
83
+ * contain a CAPTCHA, an account name, or logged-in content, so nobody should be able to watch
84
+ * without the host having said yes first. The remote side also cannot turn it on: this file is
85
+ * written through the plugin's own settings route, which admits only same-origin requests from the
86
+ * host's own UI, and the frame endpoint refuses everything when this is false.
87
+ */
88
+ readonly remoteView: {
89
+ /** Serve browser frames to a remote viewer. */
90
+ readonly enabled: boolean
91
+ }
79
92
  /**
80
93
  * What the agent is allowed to DO, as opposed to what it may look at.
81
94
  *
@@ -105,6 +118,9 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
105
118
  // it starts a real Chrome/Edge with its own profile.
106
119
  browser: { channel: 'bundled', headless: 'auto' },
107
120
  credentials: { allowRead: true },
121
+ // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
122
+ // content, so watching is an explicit decision rather than something a remote client can arrange.
123
+ remoteView: { enabled: false },
108
124
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
109
125
  }
110
126
 
@@ -254,7 +270,8 @@ function section(source: Record<string, unknown>, key: string): Record<string, u
254
270
  * @returns the resolved settings.
255
271
  */
256
272
  export function resolveSettings(raw: unknown, warn?: (message: string) => void): BrowserSettings {
257
- const source = typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : {}
273
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return SETTINGS_WHEN_UNREADABLE
274
+ const source = raw as Record<string, unknown>
258
275
  const history = section(source, 'history')
259
276
  const cookies = section(source, 'cookies')
260
277
  const ui = section(source, 'ui')
@@ -262,6 +279,7 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
262
279
  const credentials = section(source, 'credentials')
263
280
  const browser = section(source, 'browser')
264
281
  const actions = section(source, 'actions')
282
+ const remoteView = section(source, 'remoteView')
265
283
  // A section that is present but unreadable refuses its gates rather than defaulting them
266
284
  // open. The rest of a broken section keeps its defaults: refusing history or presentation
267
285
  // would punish the user for a bad file without protecting anything.
@@ -302,6 +320,14 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
302
320
  ? false
303
321
  : gate(actionsUsable.allowCredentialWrite, DEFAULT_SETTINGS.actions.allowCredentialWrite),
304
322
  },
323
+ // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
324
+ // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
325
+ // are "on", this one has no safe default other than off.
326
+ remoteView: {
327
+ enabled: remoteView === undefined
328
+ ? false
329
+ : gate((remoteView as { enabled?: unknown }).enabled, false),
330
+ },
305
331
  }
306
332
  }
307
333
 
@@ -336,8 +362,14 @@ export class SettingsStore {
336
362
  // stat directly: existsSync costs about thirteen times what the stat does, and the
337
363
  // stat already throws when the file is missing — which the catch below handles.
338
364
  mtimeMs = statSync(this.file).mtimeMs
339
- } catch {
340
- // Unreadable file: fall through to defaults below.
365
+ } catch (error) {
366
+ // Only an absent document means first-run defaults. Access/storage errors do not
367
+ // erase the operator's decisions, even when an earlier read was cached.
368
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
369
+ this.cached = undefined
370
+ this.cachedMtimeMs = -1
371
+ return SETTINGS_WHEN_UNREADABLE
372
+ }
341
373
  mtimeMs = -1
342
374
  }
343
375
  // Return the cache BEFORE reading. The read used to happen first "just in case", which
@@ -1146,9 +1146,38 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1146
1146
  const session = cachedView !== undefined && cachedView.client === client
1147
1147
  ? cachedView.session
1148
1148
  : await this.ensureSession(viewId)
1149
+ /**
1150
+ * Send one page command, rebuilding the attach once if the browser no longer knows the
1151
+ * session.
1152
+ *
1153
+ * "Session with given id not found" means the session id is stale, and the causes differ:
1154
+ * a replaced client (handled where the client is dropped), a target the browser destroyed,
1155
+ * or a detach the page performed on itself. What they share is that the id is worthless and
1156
+ * the VIEW is fine, so the right answer is one fresh attach — not an error to the caller and
1157
+ * not a new page. Measured while solving a sudoku on a canvas page: after a tab switch every
1158
+ * command failed with this text and nothing in the plugin ever recovered it.
1159
+ *
1160
+ * Retried exactly once: a failure that survives a fresh attach is not a stale id, and
1161
+ * repeating it would turn an error into a loop.
1162
+ */
1163
+ const sendWithAttach = async (target: string): Promise<Record<string, unknown>> => {
1164
+ try {
1165
+ const result = await client.send(method, params, target)
1166
+ return (result ?? {}) as Record<string, unknown>
1167
+ } catch (error) {
1168
+ const message = error instanceof Error ? error.message : String(error)
1169
+ if (!/Session with given id not found|No session with given id/i.test(message)) throw error
1170
+ // Drop the dead attach so `ensureSession` builds a new one instead of returning the same id.
1171
+ const stale = this.views.get(viewId)
1172
+ if (stale !== undefined) this.views.delete(viewId)
1173
+ this.sessions.delete(target)
1174
+ const rebuilt = await this.ensureSession(viewId)
1175
+ const retried = await client.send(method, params, rebuilt)
1176
+ return (retried ?? {}) as Record<string, unknown>
1177
+ }
1178
+ }
1149
1179
  try {
1150
- const result = await client.send(method, params, session)
1151
- return (result ?? {}) as Record<string, unknown>
1180
+ return await sendWithAttach(session)
1152
1181
  } catch (error) {
1153
1182
  // A CDP protocol error means the browser ANSWERED and refused this one command, so the
1154
1183
  // connection is healthy and must be kept. Deciding by the error TEXT misfires both
@@ -1288,23 +1317,28 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1288
1317
  dying.once('exit', () => { clearTimeout(timer) })
1289
1318
  }
1290
1319
  const ephemeral = this.ephemeralDir
1291
- if (ephemeral !== undefined && this.child !== undefined) {
1292
- // The browser flushes its profile while shutting down, so deleting later avoids
1293
- // racing it. Leftovers are only a stray temp directory, never a live credential.
1294
- //
1295
- // The timer is unref'd, so it never holds the process open — which also means that a
1296
- // process which exits inside this 3s window (a CLI probe, a DSH restart) leaves the
1297
- // directory behind for good, silently contradicting the user's "keep no profile"
1298
- // choice. The exit hook below is the same delete, run synchronously as a last resort;
1299
- // the callback is idempotent, so whichever runs first wins and the other is a no-op.
1320
+ if (ephemeral !== undefined) {
1300
1321
  const removeEphemeral = (): void => {
1301
1322
  try { rmSync(ephemeral, { recursive: true, force: true }) } catch { /* best effort */ }
1302
1323
  }
1303
- setTimeout(removeEphemeral, 3_000).unref?.()
1304
- process.once('exit', removeEphemeral)
1305
- } else if (ephemeral !== undefined) {
1306
- // Never started, so nothing can be holding it open.
1307
- try { rmSync(ephemeral, { recursive: true, force: true }) } catch { /* best effort */ }
1324
+ // `this.child` was cleared above; the saved processes still own the profile until
1325
+ // their exit events arrive. Deleting it now races Chromium's final cookie flush.
1326
+ const live = doomed.filter(child => child.exitCode === null && child.signalCode === null)
1327
+ if (live.length > 0) {
1328
+ const remaining = new Set(live)
1329
+ for (const child of live) child.once('exit', () => {
1330
+ remaining.delete(child)
1331
+ if (remaining.size === 0) removeEphemeral()
1332
+ })
1333
+ } else if (client !== undefined) {
1334
+ // A handed-off browser has no process handle. Give its graceful close time to
1335
+ // finish; abandoned profiles remain eligible for the next startup's safe sweep.
1336
+ setTimeout(() => {
1337
+ if (!client.isAlive()) removeEphemeral()
1338
+ }, CLOSE_GRACE_MS).unref?.()
1339
+ } else {
1340
+ removeEphemeral()
1341
+ }
1308
1342
  }
1309
1343
  }
1310
1344
 
@@ -1332,22 +1366,64 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1332
1366
  /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
1333
1367
  private async buildSession(viewId: string): Promise<string> {
1334
1368
  const client = await this.ensureClient()
1335
- // Adopt a blank page the browser opened on its own before creating another one.
1336
- //
1337
- // Chrome starts with more than one page when handed a URL on top of its own start page, so
1338
- // creating a target here discarded the original and left it behind as a tab that is not in
1339
- // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1340
- // through the tools. Taking the blank instead makes the page the browser already opened the
1341
- // one the caller gets.
1342
- const adopted = await this.adoptBlankTarget(client)
1343
- const targetId = adopted ?? await this.createTarget(client)
1369
+ // Different views can initialise concurrently. Selecting an unclaimed page and attaching
1370
+ // it must be one transaction, including when the page is created by a preceding view.
1371
+ const previous = this.targetBuilds.get(client) ?? Promise.resolve()
1372
+ let release!: () => void
1373
+ const building = new Promise<void>(resolve => { release = resolve })
1374
+ this.targetBuilds.set(client, building)
1375
+ await previous
1376
+ try {
1377
+ // Adopt a blank page the browser opened on its own before creating another one.
1378
+ //
1379
+ // Chrome starts with more than one page when handed a URL on top of its own start page, so
1380
+ // creating a target here discarded the original and left it behind as a tab that is not in
1381
+ // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1382
+ // through the tools. Taking the blank instead makes the page the browser already opened the
1383
+ // one the caller gets.
1384
+ const adopted = await this.adoptBlankTarget(client)
1385
+ const targetId = adopted ?? await this.createTarget(client)
1386
+ const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1387
+ const sessionId = attached?.sessionId
1388
+ if (typeof sessionId !== 'string') throw new Error('dsh-builtin-browser: the browser did not attach to the new page')
1389
+ // The session id is what page commands ride; the target id is what closes it.
1390
+ this.sessions.set(sessionId, targetId)
1391
+ this.views.set(viewId, { session: sessionId, client })
1392
+ return sessionId
1393
+ } finally {
1394
+ release()
1395
+ if (this.targetBuilds.get(client) === building) this.targetBuilds.delete(client)
1396
+ }
1397
+ }
1398
+
1399
+ /**
1400
+ * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
1401
+ *
1402
+ * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
1403
+ * produced a SECOND page, because the only tab the provider knew about was one it created itself.
1404
+ * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
1405
+ * could be closed, but not read or driven — the opposite of what "the page you are looking at"
1406
+ * means.
1407
+ *
1408
+ * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
1409
+ * target this plugin has a session on. The page is not moved, reloaded or focused, and its
1410
+ * existing session (logins, scroll position, form state) is untouched.
1411
+ * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1412
+ * @returns a handle for that page, in the same shape {@link createView} returns.
1413
+ */
1414
+ async adoptPage(targetId: string): Promise<ElectronViewHandle> {
1415
+ const handle = this.createView()
1416
+ const client = await this.ensureClient()
1344
1417
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1345
1418
  const sessionId = attached?.sessionId
1346
- if (typeof sessionId !== 'string') throw new Error('dsh-builtin-browser: the browser did not attach to the new page')
1347
- // The session id is what page commands ride; the target id is what closes it.
1419
+ if (typeof sessionId !== 'string') {
1420
+ throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`)
1421
+ }
1422
+ // Point the view `createView` just made at the page that already exists, instead of the one it
1423
+ // would otherwise build on first use.
1348
1424
  this.sessions.set(sessionId, targetId)
1349
- this.views.set(viewId, { session: sessionId, client })
1350
- return sessionId
1425
+ this.views.set(handle.id, { session: sessionId, client })
1426
+ return handle
1351
1427
  }
1352
1428
 
1353
1429
  /**
@@ -1439,6 +1515,9 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1439
1515
  /** Views whose session is being created right now, so a second caller waits for the first. */
1440
1516
  private readonly sessionBuilding = new Map<string, Promise<string>>()
1441
1517
 
1518
+ /** Serialises page selection/creation and attachment for each browser connection. */
1519
+ private readonly targetBuilds = new WeakMap<CdpClient, Promise<void>>()
1520
+
1442
1521
  /** sessionId -> targetId, so a destroyed view can close the right page. */
1443
1522
  private readonly sessions = new Map<string, string>()
1444
1523
  }
@@ -298,11 +298,23 @@ function formatSnapshot(snapshot: {
298
298
  elements: readonly { ref: number; kind: string; label: string; x: number; y: number; frame?: boolean; selector?: string }[]
299
299
  truncated?: boolean
300
300
  challenge?: { blocked: boolean; kind?: string; reason?: string }
301
+ blank?: boolean
302
+ note?: string
303
+ canvas?: boolean
301
304
  }, options: { coords?: boolean } = {}): string {
302
305
  const showCoords = options.coords === true
303
306
  const lines = snapshot.elements.map(el => `[${el.ref}] ${el.kind}: ${el.label}${el.selector !== undefined && el.selector !== '' ? ` {${el.selector}}` : ''}${el.frame === true ? ' (iframe)' : ''}${showCoords ? ` (${el.x},${el.y})` : ''}`)
304
307
  const header = `URL: ${snapshot.url}${snapshot.title !== undefined ? `\nTitle: ${snapshot.title}` : ''}`
305
- const body = lines.length > 0 ? lines.join('\n') : '(no interactive elements found)'
308
+ // A blank page, a canvas page and a page with nothing interactive are three different facts, and
309
+ // the old wording reported all of them as "no interactive elements found" — which reads as a
310
+ // successful look. Each now says what it is and what to do next.
311
+ const body = snapshot.blank === true
312
+ ? `BLANK PAGE: ${snapshot.note ?? 'nothing has been opened in this browser'}. `
313
+ + 'Do not drive this page — open a URL first (`dsh_browser_open`).'
314
+ : snapshot.canvas === true
315
+ ? `CANVAS PAGE: ${snapshot.note ?? 'this page draws its interface on a canvas'}. `
316
+ + 'A DOM snapshot cannot describe it; use `dsh_browser_screenshot` and coordinate clicks.'
317
+ : lines.length > 0 ? lines.join('\n') : '(no interactive elements found)'
306
318
  const tail = snapshot.truncated === true ? '\n(snapshot truncated)' : ''
307
319
  const banner = snapshot.challenge?.blocked === true
308
320
  ? `\n\nCHALLENGE: ${snapshot.challenge.reason ?? 'human-verification'}. Do NOT keep retrying — ask the human to complete it in the shared browser window, then re-snapshot.`