dsh-builtin-browser 1.0.1 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/tool-reference.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- package/dsh-host-patch/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +0 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -44
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -36
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +15 -12
- package/scripts/fix-exports.mjs +6 -16
- package/scripts/install-electron.mjs +55 -5
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +26 -15
- package/skills/dsh-builtin-browser/SKILL.md +27 -2
- package/skills/dsh-builtin-browser/references/batch.md +15 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/runtime.ts +18 -0
- package/src/browser/takeover-target.ts +16 -7
- package/src/browser/types.ts +56 -3
- package/src/browser-electron/authenticated-route.ts +29 -4
- package/src/browser-electron/automatic-maintenance.ts +23 -13
- package/src/browser-electron/bridge-connection.ts +11 -10
- package/src/browser-electron/bridge-install.ts +2 -1
- package/src/browser-electron/bridge-status.ts +61 -22
- package/src/browser-electron/desktop-bridge-host.ts +9 -7
- package/src/browser-electron/desktop-identity.ts +38 -5
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/electron-provision.ts +104 -18
- package/src/browser-electron/entry.ts +1378 -1299
- package/src/browser-electron/extension-browser.ts +11 -4
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +3 -2
- package/src/browser-electron/guest-route.ts +180 -32
- package/src/browser-electron/guest-runtime.ts +61 -10
- package/src/browser-electron/guest-storage.ts +5 -2
- package/src/browser-electron/history-store.ts +3 -6
- package/src/browser-electron/host-main.ts +8 -4
- package/src/browser-electron/host-patch-maintenance.ts +18 -9
- package/src/browser-electron/maintenance-route.ts +2 -1
- package/src/browser-electron/missing-system-browser.ts +11 -10
- package/src/browser-electron/preferred-browser.ts +13 -3
- package/src/browser-electron/preview-route.ts +9 -12
- package/src/browser-electron/process-ownership.ts +9 -3
- package/src/browser-electron/profile-command.ts +2 -1
- package/src/browser-electron/profile-extension.ts +5 -0
- package/src/browser-electron/profile-lease.ts +131 -35
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +158 -4063
- package/src/browser-electron/reference-route.ts +598 -608
- package/src/browser-electron/remote-host.ts +118 -42
- package/src/browser-electron/runtime-status.ts +80 -13
- package/src/browser-electron/settings-store.ts +10 -6
- package/src/browser-electron/sidebar-only-host.ts +4 -2
- package/src/browser-electron/system-browser.ts +537 -184
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/virtual-cursor.ts +24 -14
- package/src/browser-reference/service.ts +38 -7
- package/src/browser-reference/web-sources.ts +4 -1
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +3 -3
- package/src/client/browser/IframeImpl.ts +182 -176
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/web-reference-source.ts +5 -1
- package/src/client/definition.tsx +36 -30
- package/src/client/electron/ElectronWebViewImpl.ts +20 -13
- package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
- package/src/client/electron/NativeChildPresentation.ts +11 -3
- package/src/client/electron/NativeViewPage.ts +19 -5
- package/src/client/index.ts +333 -293
- package/src/client/locales.ts +9 -6
- package/src/client/reference/client/plugin.ts +21 -2
- package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
- package/src/client/reference/client/production/assembly.ts +4 -28
- package/src/client/reference/client/production/availability.ts +0 -2
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/draft-adapter.ts +4 -0
- package/src/client/reference/client/production/http-transport.ts +0 -5
- package/src/client/reference/client/production/production-submission.ts +50 -290
- package/src/client/reference/client/production/protocol.ts +7 -4
- package/src/client/reference/client/production/runtime.ts +41 -86
- package/src/client/reference/client/production/source-marker.ts +49 -13
- package/src/client/reference/client/production/user-text-rule.ts +10 -1
- package/src/client/reference/client/reveal.ts +3 -1
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/settings/index.ts +8 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +163 -52
- package/src/client/startpage/controller.ts +3 -6
- package/src/client/view/BrowserBody.tsx +2 -1
- package/src/client/view/IframePresentation.ts +37 -16
- package/src/client/view/StartPage.tsx +2 -1
- package/src/compat/host-features.ts +92 -0
- package/src/reference-source.ts +1 -1
- package/src/reference-text.ts +23 -1
- package/src/takeover-protocol.ts +11 -2
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +173 -19
- package/src/tool-browser/code-worker.ts +101 -15
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +66 -3534
- package/src/tool-browser/page-probe.ts +229 -28
- package/src/tool-browser/panel-page.ts +3 -1
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +3 -2
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/web-guest.ts +35 -34
- package/dist/client.cjs +0 -43167
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/src/browser-reference/submission-receipts.ts +0 -122
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { lstatSync, mkdirSync, realpathSync } from 'node:fs'
|
|
3
|
+
import { writeFileNoReplace } from './file-write.ts'
|
|
4
|
+
import { dirname, isAbsolute, resolve, sep } from 'node:path'
|
|
5
|
+
import type { BrowserScreenshotRequest, BrowserSessionId, ExportedCookie } from '../browser/types.ts'
|
|
6
|
+
import { BrowserError } from '../browser/types.ts'
|
|
7
|
+
import { PROVIDER_TIMEOUTS, CDP_PAGE_CAPTURE_SCREENSHOT, layoutSize, toExportedCookies, toCdpCookie, withTimeout } from './provider-core.ts'
|
|
8
|
+
import { ProviderInteraction } from './provider-interaction.ts'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Whether a directory entry exists at `path`, judging the ENTRY rather than what it
|
|
12
|
+
* points at.
|
|
13
|
+
*
|
|
14
|
+
* `existsSync` follows links, so a DANGLING symlink — a link whose target does not
|
|
15
|
+
* exist — reads as "nothing here", and a write to that path creates the target
|
|
16
|
+
* instead: outside `downloadDir` whenever the link points out of it. `lstatSync`
|
|
17
|
+
* sees the link itself, which is the only correct answer to "is this name free".
|
|
18
|
+
* @param path - the path to judge.
|
|
19
|
+
* @returns true when any entry (file, directory, link) occupies the name.
|
|
20
|
+
*/
|
|
21
|
+
function entryExists(path: string): boolean {
|
|
22
|
+
try {
|
|
23
|
+
lstatSync(path)
|
|
24
|
+
return true
|
|
25
|
+
} catch {
|
|
26
|
+
return false
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The real path of the deepest existing ancestor of `path` — `path` itself when it
|
|
32
|
+
* exists, otherwise the nearest directory above it that does.
|
|
33
|
+
*
|
|
34
|
+
* `resolve()` normalizes `..` but never follows a link, so nothing textual can tell
|
|
35
|
+
* that `<downloadDir>/link/x.png` leaves the directory through `link`. The first
|
|
36
|
+
* ancestor that exists (judged by lstat, so a dangling link counts — the write would
|
|
37
|
+
* go through it) is the last component whose real location still determines where
|
|
38
|
+
* the bytes land, so that is the one to resolve and check.
|
|
39
|
+
* @param path - an absolute path that may not exist yet.
|
|
40
|
+
* @returns the resolved real path of its deepest existing ancestor.
|
|
41
|
+
*/
|
|
42
|
+
function realAncestorOf(path: string): string {
|
|
43
|
+
let current = path
|
|
44
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
45
|
+
if (entryExists(current)) {
|
|
46
|
+
try {
|
|
47
|
+
return realpathSync(current)
|
|
48
|
+
} catch {
|
|
49
|
+
// The entry vanished between the two calls, or cannot be resolved: the
|
|
50
|
+
// textual path is the best available answer, and the write reports the rest.
|
|
51
|
+
return current
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const parent = dirname(current)
|
|
55
|
+
if (parent === current) return current
|
|
56
|
+
current = parent
|
|
57
|
+
}
|
|
58
|
+
return current
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Bounds for one passive preview frame.
|
|
63
|
+
*
|
|
64
|
+
* The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
|
|
65
|
+
* enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
|
|
66
|
+
* behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
|
|
67
|
+
* target is what lets several viewers share a single capture.
|
|
68
|
+
*/
|
|
69
|
+
const PREVIEW_CAPTURE_MS = 2_000
|
|
70
|
+
|
|
71
|
+
const PREVIEW_QUALITY = 70
|
|
72
|
+
|
|
73
|
+
const PREVIEW_MAX_WIDTH = 1280
|
|
74
|
+
|
|
75
|
+
const PREVIEW_MAX_HEIGHT = 720
|
|
76
|
+
|
|
77
|
+
export abstract class ProviderMedia extends ProviderInteraction {
|
|
78
|
+
/**
|
|
79
|
+
* Admit a caller-supplied save path for a file the browser writes to disk.
|
|
80
|
+
* ONE gate for both `dsh_browser_download` and `dsh_browser_screenshot`: the path
|
|
81
|
+
* must be absolute, must resolve inside `downloadDir`, and must not already
|
|
82
|
+
* exist. Without it a prompt-injected agent could write — or silently
|
|
83
|
+
* replace — any file the DSH process can reach, which also escapes the file
|
|
84
|
+
* sandbox every other tool in the set runs under.
|
|
85
|
+
* @param savePath - the caller's target path.
|
|
86
|
+
* @param kind - the operation, used in the error code and message.
|
|
87
|
+
* @returns the resolved absolute target path.
|
|
88
|
+
* @throws BrowserError when the path is relative, outside the directory, or occupied.
|
|
89
|
+
*/
|
|
90
|
+
private admitSavePath(savePath: string, kind: 'download' | 'screenshot'): string {
|
|
91
|
+
const code = kind === 'download' ? 'BROWSER_DOWNLOAD_BLOCKED' : 'BROWSER_SCREENSHOT_BLOCKED'
|
|
92
|
+
if (!isAbsolute(savePath)) {
|
|
93
|
+
throw new BrowserError(`browser: ${kind} savePath must be an absolute path`, code)
|
|
94
|
+
}
|
|
95
|
+
const file = resolve(savePath)
|
|
96
|
+
if (this.downloadDir !== undefined) {
|
|
97
|
+
const dir = resolve(this.downloadDir)
|
|
98
|
+
// Windows paths are case-insensitive and resolve() does not normalize case, so there
|
|
99
|
+
// the containment check folds case — otherwise %USERPROFILE%\Downloads and
|
|
100
|
+
// %userprofile%\downloads would read as different roots. Everywhere else the fold is
|
|
101
|
+
// REMOVED: a case-sensitive filesystem (Linux) treats /home/u/DOWNLOADS and
|
|
102
|
+
// /home/u/Downloads as different directories, so folding case there let a savePath
|
|
103
|
+
// that merely differed in case pass admission — a directory-confinement escape, and
|
|
104
|
+
// one that mkdirSync below would then happily create.
|
|
105
|
+
const fold = process.platform === 'win32' ? (value: string): string => value.toLowerCase() : (value: string): string => value
|
|
106
|
+
const dirKey = fold(dir)
|
|
107
|
+
const fileKey = fold(file)
|
|
108
|
+
// The directory ITSELF is refused, not accepted: a save path that IS downloadDir names
|
|
109
|
+
// a directory, so there is no file to write — and mkdirSync would have created the
|
|
110
|
+
// directory when it did not exist. Two paths are "inside" only when the file path is
|
|
111
|
+
// strictly below the directory, which the separator check below already expresses.
|
|
112
|
+
if (!fileKey.startsWith(dirKey + fold(sep))) {
|
|
113
|
+
throw new BrowserError(`browser: ${kind} savePath must be inside downloadDir "${dir}"`, code)
|
|
114
|
+
}
|
|
115
|
+
// The check above is textual, and a symlink defeats it: resolve() normalizes `..`
|
|
116
|
+
// but never follows a link, so `<downloadDir>/out/x.png` passed every test above
|
|
117
|
+
// while `out` pointed at a directory outside the gate — and the write then landed
|
|
118
|
+
// there. Resolve the REAL location of the deepest existing ancestor (which is what
|
|
119
|
+
// decides where the bytes go) and require it to be inside the real directory too.
|
|
120
|
+
// A legitimate path is unaffected: its ancestor resolves to the directory itself.
|
|
121
|
+
//
|
|
122
|
+
// The directory is created first so that it can be resolved at all — mkdirSync is a
|
|
123
|
+
// no-op for one that already exists — and a directory that cannot be created or
|
|
124
|
+
// resolved falls back to its textual form, leaving the real filesystem error to the
|
|
125
|
+
// write instead of inventing one here.
|
|
126
|
+
let realDir: string
|
|
127
|
+
try {
|
|
128
|
+
mkdirSync(dir, { recursive: true })
|
|
129
|
+
realDir = fold(realpathSync(dir))
|
|
130
|
+
} catch {
|
|
131
|
+
realDir = fold(dir)
|
|
132
|
+
}
|
|
133
|
+
const realAncestor = fold(realAncestorOf(file))
|
|
134
|
+
if (realAncestor !== realDir && !realAncestor.startsWith(realDir + fold(sep))) {
|
|
135
|
+
throw new BrowserError(`browser: ${kind} savePath resolves outside downloadDir "${dir}" (a symlink leaves it)`, code)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Never replace an existing file: its previous content is unrecoverable,
|
|
139
|
+
// and the admitted directory may hold files the human put there. A new
|
|
140
|
+
// name is one tool call away.
|
|
141
|
+
//
|
|
142
|
+
// Judged with lstat (see {@link entryExists}), not existsSync: existsSync FOLLOWS
|
|
143
|
+
// links, so a DANGLING symlink read as "nothing here" and the write below created
|
|
144
|
+
// its target — outside the directory whenever the link pointed out of it. It is the
|
|
145
|
+
// directory entry that has to be free, whatever that entry points at.
|
|
146
|
+
if (entryExists(file)) {
|
|
147
|
+
throw new BrowserError(`browser: refusing to overwrite existing file "${file}" — use another name`, code)
|
|
148
|
+
}
|
|
149
|
+
return file
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Download an HTTP(S) URL with the session's cookies to a local file.
|
|
154
|
+
* Admission is the shared {@link admitSavePath} gate. The carrier downloads
|
|
155
|
+
* with its own authenticated browser session. Both admitted paths and screenshots are confined
|
|
156
|
+
* to `downloadDir`, so a prompt-injected agent cannot write arbitrary
|
|
157
|
+
* machine paths.
|
|
158
|
+
* @param session - the session whose cookies are used.
|
|
159
|
+
* @param request - the URL plus the absolute target path.
|
|
160
|
+
* @param signal - optional cancellation.
|
|
161
|
+
* @returns the path the file was written to.
|
|
162
|
+
*/
|
|
163
|
+
async download(session: BrowserSessionId, request: { readonly url: string; readonly savePath: string }, signal?: AbortSignal): Promise<{ readonly path: string }> {
|
|
164
|
+
// Before admission, and before the session is even resolved: a switched-off action is
|
|
165
|
+
// not a path problem, and the caller should hear the real reason.
|
|
166
|
+
this.assertActionAllowed('download')
|
|
167
|
+
const s = this.session(session)
|
|
168
|
+
const { handle } = this.activeTab(s)
|
|
169
|
+
signal?.throwIfAborted()
|
|
170
|
+
// URL admission: HTTP(S) only (mirrors the navigation guard). The seam
|
|
171
|
+
// intentionally does not block private/localhost targets — a shared real
|
|
172
|
+
// browser legitimately reaches local dev servers.
|
|
173
|
+
let parsed: URL
|
|
174
|
+
try {
|
|
175
|
+
parsed = new URL(request.url)
|
|
176
|
+
} catch {
|
|
177
|
+
throw new BrowserError(`browser: refusing download of unparseable URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED')
|
|
178
|
+
}
|
|
179
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
180
|
+
throw new BrowserError(`browser: refusing download of non-HTTP(S) URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED')
|
|
181
|
+
}
|
|
182
|
+
// savePath admission: the shared gate — absolute, inside `downloadDir`,
|
|
183
|
+
// and never an existing file. Screenshots use the very same one.
|
|
184
|
+
const savePath = this.admitSavePath(request.savePath, 'download')
|
|
185
|
+
const downloadable = handle
|
|
186
|
+
if (typeof downloadable.download !== 'function') {
|
|
187
|
+
throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED')
|
|
188
|
+
}
|
|
189
|
+
// The child fetches and writes the file; a slow/hung network can block
|
|
190
|
+
// it well past the tool budget, so bound it. NOTE: unlike CDP calls,
|
|
191
|
+
// there is no child-side abort mechanism for the RPC download — when the
|
|
192
|
+
// parent's timeout fires the child continues writing. The parent's pending
|
|
193
|
+
// entry is cleaned up (the promise settles) and the child's eventual
|
|
194
|
+
// reply is harmlessly consumed by the RPC layer.
|
|
195
|
+
const timeoutMs = PROVIDER_TIMEOUTS.download
|
|
196
|
+
await withTimeout(
|
|
197
|
+
downloadable.download(request.url, savePath),
|
|
198
|
+
timeoutMs,
|
|
199
|
+
signal,
|
|
200
|
+
`browser: download timed out after ${timeoutMs}ms`,
|
|
201
|
+
)
|
|
202
|
+
this.record(s, 'download', { url: request.url, savePath }, true, { result: savePath })
|
|
203
|
+
return { path: savePath }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Export the session's cookies (login state) as serializable objects.
|
|
208
|
+
* Self-hosted only; the desktop shell's embedded views use the real profile.
|
|
209
|
+
*/
|
|
210
|
+
async flushAuth(session: BrowserSessionId): Promise<readonly ExportedCookie[]> {
|
|
211
|
+
// The settings panel offers "allow the agent to read cookies / export login state".
|
|
212
|
+
// Until now nothing read that switch, so turning it off changed nothing at all —
|
|
213
|
+
// the tool exported every cookie regardless.
|
|
214
|
+
if (this.settingsSource?.().credentials.allowRead === false) {
|
|
215
|
+
throw new BrowserError('browser: reading cookies is switched off in settings (Browser → credentials)', 'BROWSER_AUTH_DISABLED')
|
|
216
|
+
}
|
|
217
|
+
const s = this.session(session)
|
|
218
|
+
const { handle } = this.activeTab(s)
|
|
219
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
|
|
220
|
+
// The self-hosted carrier has a native path (the child reads its own session), which
|
|
221
|
+
// is worth preferring: it reports exactly what the browser persisted.
|
|
222
|
+
const native = handle
|
|
223
|
+
if (typeof native.flushAuth === 'function') {
|
|
224
|
+
const cookies = await withTimeout(native.flushAuth(), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`)
|
|
225
|
+
this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies` })
|
|
226
|
+
return cookies
|
|
227
|
+
}
|
|
228
|
+
// Every other carrier drives a real browser over CDP, and cookies are part of CDP —
|
|
229
|
+
// the sidebar goes through the shell's webContents.debugger, an installed Chrome or
|
|
230
|
+
// Edge is the browser itself. So this works everywhere rather than only self-hosted.
|
|
231
|
+
// Scoped to the page this session is on. The jar itself is SHARED on purpose — every
|
|
232
|
+
// window and every task drives the same browser, so signing in once works everywhere,
|
|
233
|
+
// which is the whole point of "use your own browser". What must not be shared is the
|
|
234
|
+
// HANDING OVER: an unfiltered read puts every domain every task has visited, plus
|
|
235
|
+
// whatever the human is signed into, in front of one task's caller. Least exposure,
|
|
236
|
+
// not isolation.
|
|
237
|
+
//
|
|
238
|
+
// Two corrections to the previous attempt. It called Storage.getCookies with a `urls`
|
|
239
|
+
// parameter, but that method takes only browserContextId and ignores everything else, so
|
|
240
|
+
// the filter did nothing and the whole jar was still exported; `urls` belongs to
|
|
241
|
+
// Network.getCookies. And it silently fell back to an unfiltered read when the page URL
|
|
242
|
+
// was unavailable — an error path that asked for MORE than the normal one. Both are
|
|
243
|
+
// fixed: the method that honours the filter, and a failure that refuses instead of
|
|
244
|
+
// widening.
|
|
245
|
+
const cookiesUrl = await this.currentUrl(handle).catch(() => '')
|
|
246
|
+
if (cookiesUrl === '') {
|
|
247
|
+
throw new BrowserError(
|
|
248
|
+
'browser: cannot export cookies without knowing which page this session is on — the URL was unavailable, and reading the whole cookie jar would expose every other session\'s logins',
|
|
249
|
+
'BROWSER_AUTH_SCOPE_UNKNOWN',
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
const result = await withTimeout(
|
|
253
|
+
handle.sendCommand('Network.getCookies', { urls: [cookiesUrl] }),
|
|
254
|
+
timeoutMs,
|
|
255
|
+
undefined,
|
|
256
|
+
`browser: auth export timed out after ${timeoutMs}ms`,
|
|
257
|
+
)
|
|
258
|
+
const cookies = toExportedCookies(result.cookies)
|
|
259
|
+
this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies (CDP)` })
|
|
260
|
+
return cookies
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Import cookies into the session (restore login state). Self-hosted only. */
|
|
264
|
+
async restoreAuth(session: BrowserSessionId, cookies: readonly ExportedCookie[]): Promise<number> {
|
|
265
|
+
// Restore WRITES cookies, so it answers to the write switch — not to
|
|
266
|
+
// `credentials.allowRead`. It used to consult the read switch and report "reading
|
|
267
|
+
// cookies is switched off", which is both the wrong gate and the wrong sentence: an
|
|
268
|
+
// operator who allowed reading but wanted logins left alone had no switch at all,
|
|
269
|
+
// and one who turned reading off lost the restore path for the wrong reason.
|
|
270
|
+
this.assertActionAllowed('credentialWrite')
|
|
271
|
+
const s = this.session(session)
|
|
272
|
+
const { handle } = this.activeTab(s)
|
|
273
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
|
|
274
|
+
const native = handle
|
|
275
|
+
if (typeof native.restoreAuth === 'function') {
|
|
276
|
+
const restored = await withTimeout(native.restoreAuth(cookies), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`)
|
|
277
|
+
this.record(s, 'restoreAuth', { count: cookies.length }, true, { result: `${restored} cookies` })
|
|
278
|
+
return restored
|
|
279
|
+
}
|
|
280
|
+
// CDP again, for the same reason as the export: any carrier that drives a real
|
|
281
|
+
// browser can set cookies on it. Storage.setCookies needs the cookie fields spelled
|
|
282
|
+
// the CDP way, including the sameSite spelling and seconds rather than milliseconds.
|
|
283
|
+
//
|
|
284
|
+
// toCdpCookie returns undefined for a cookie it cannot place (no usable domain), and
|
|
285
|
+
// `cookies.map(...)` passed that undefined straight through: the array then held a
|
|
286
|
+
// JSON `null`, CDP rejected the WHOLE call, and every valid cookie failed with an error
|
|
287
|
+
// naming none of them. Filter the unusable ones out and say how many went.
|
|
288
|
+
const mapped = cookies.map(toCdpCookie)
|
|
289
|
+
const convertible = mapped.filter((cookie): cookie is Record<string, unknown> => cookie !== undefined)
|
|
290
|
+
const dropped = mapped.length - convertible.length
|
|
291
|
+
if (dropped > 0) {
|
|
292
|
+
process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`)
|
|
293
|
+
}
|
|
294
|
+
await withTimeout(
|
|
295
|
+
handle.sendCommand('Storage.setCookies', { cookies: convertible }),
|
|
296
|
+
timeoutMs,
|
|
297
|
+
undefined,
|
|
298
|
+
`browser: auth restore timed out after ${timeoutMs}ms`,
|
|
299
|
+
)
|
|
300
|
+
// Storage.setCookies returns nothing, so the count comes from what was actually sent.
|
|
301
|
+
// An earlier version read result.cookies here; it was always undefined and rendered as
|
|
302
|
+
// "Restored 0 cookies." even though the write had succeeded.
|
|
303
|
+
const restored = convertible.length
|
|
304
|
+
this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` })
|
|
305
|
+
return restored
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Capture the active page WITHOUT presenting it.
|
|
310
|
+
*
|
|
311
|
+
* `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
|
|
312
|
+
* that the human sees what the model just captured. It is also what makes that path unusable for a
|
|
313
|
+
* live preview: presenting on every frame would move focus, switch tabs and expand windows on the
|
|
314
|
+
* host's screen — exactly the side effects a viewer must not cause (issue #34).
|
|
315
|
+
*
|
|
316
|
+
* So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
|
|
317
|
+
* preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
|
|
318
|
+
* preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
|
|
319
|
+
* design forbids: no page means "nothing to watch", not "open one".
|
|
320
|
+
* @param session - the session whose active page to capture.
|
|
321
|
+
* @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
|
|
322
|
+
* is not painted, which the caller turns into a "paused" state rather than an error.
|
|
323
|
+
*/
|
|
324
|
+
async capturePassive(session: BrowserSessionId): Promise<{
|
|
325
|
+
readonly dataUrl: string
|
|
326
|
+
readonly width?: number
|
|
327
|
+
readonly height?: number
|
|
328
|
+
}> {
|
|
329
|
+
const s = this.session(session)
|
|
330
|
+
const { handle } = this.activeTab(s)
|
|
331
|
+
const timeoutMs = PREVIEW_CAPTURE_MS
|
|
332
|
+
const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`
|
|
333
|
+
// The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
|
|
334
|
+
// produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
|
|
335
|
+
if (typeof handle.capture === 'function') {
|
|
336
|
+
const shot = await withTimeout(
|
|
337
|
+
handle.capture({
|
|
338
|
+
format: 'jpeg',
|
|
339
|
+
quality: PREVIEW_QUALITY,
|
|
340
|
+
maxWidth: PREVIEW_MAX_WIDTH,
|
|
341
|
+
maxHeight: PREVIEW_MAX_HEIGHT,
|
|
342
|
+
}),
|
|
343
|
+
timeoutMs,
|
|
344
|
+
undefined,
|
|
345
|
+
timeoutMessage,
|
|
346
|
+
)
|
|
347
|
+
if (shot.base64 === '') {
|
|
348
|
+
// A hidden or minimized window is not a failure to report as one: the design says the
|
|
349
|
+
// viewer shows pause and does not open a window to fix it.
|
|
350
|
+
throw new BrowserError(
|
|
351
|
+
'browser: preview unavailable (the page is not painted; the window may be hidden or minimized)',
|
|
352
|
+
'BROWSER_PREVIEW_UNAVAILABLE',
|
|
353
|
+
)
|
|
354
|
+
}
|
|
355
|
+
return {
|
|
356
|
+
dataUrl: `data:${shot.mime};base64,${shot.base64}`,
|
|
357
|
+
...shot.width !== undefined && shot.height !== undefined
|
|
358
|
+
? { width: shot.width, height: shot.height }
|
|
359
|
+
: {},
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
|
|
363
|
+
// the whole document, which is neither what a viewer shows nor bounded in size.
|
|
364
|
+
//
|
|
365
|
+
// `present: false` is load-bearing (issue #46): a preview is read-only, so it must not reach the
|
|
366
|
+
// carrier's present path, which for the sidebar asks the shell to display this conversation —
|
|
367
|
+
// the reported symptom was the sidebar browser panel jumping to the front when someone opened
|
|
368
|
+
// the preview. A page that is not displayed now reads as "unavailable", which the route already
|
|
369
|
+
// turns into the panel's paused state.
|
|
370
|
+
const result = await withTimeout(
|
|
371
|
+
handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
|
|
372
|
+
format: 'jpeg',
|
|
373
|
+
quality: PREVIEW_QUALITY,
|
|
374
|
+
fromSurface: true,
|
|
375
|
+
captureBeyondViewport: false,
|
|
376
|
+
}, { present: false }),
|
|
377
|
+
timeoutMs,
|
|
378
|
+
undefined,
|
|
379
|
+
timeoutMessage,
|
|
380
|
+
) as { data?: unknown }
|
|
381
|
+
const base64 = typeof result?.data === 'string' ? result.data : ''
|
|
382
|
+
if (base64 === '') {
|
|
383
|
+
throw new BrowserError(
|
|
384
|
+
'browser: preview unavailable (the carrier returned no image)',
|
|
385
|
+
'BROWSER_PREVIEW_UNAVAILABLE',
|
|
386
|
+
)
|
|
387
|
+
}
|
|
388
|
+
return { dataUrl: `data:image/jpeg;base64,${base64}` }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
|
|
392
|
+
async screenshot( session: BrowserSessionId,
|
|
393
|
+
request?: BrowserScreenshotRequest,
|
|
394
|
+
signal?: AbortSignal,
|
|
395
|
+
): Promise<{ readonly dataUrl: string; readonly path?: string; readonly width?: number; readonly height?: number }> {
|
|
396
|
+
const s = this.session(session)
|
|
397
|
+
const { handle } = this.activeTab(s)
|
|
398
|
+
signal?.throwIfAborted()
|
|
399
|
+
const format = request?.format ?? 'png'
|
|
400
|
+
// Native capturePage path (self-hosted): CDP Page.captureScreenshot can
|
|
401
|
+
// hang indefinitely on a view once another (hidden) WebContentsView exists
|
|
402
|
+
// in the window; capturePage is fast for visible views and resolves
|
|
403
|
+
// immediately (empty) for hidden ones. JPEG and downscaling are encoded
|
|
404
|
+
// in the child from the NativeImage, so this path is the only one that
|
|
405
|
+
// can produce JPEG (CDP JPEG hangs on Electron 43).
|
|
406
|
+
const capturable = handle
|
|
407
|
+
// A region capture must go through CDP: the native NativeImage path has no
|
|
408
|
+
// clip and would present/activate the window (a quiet-mode violation).
|
|
409
|
+
if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
|
|
410
|
+
// Ensure the target view is the visible one before capturing — unless quiet mode is on.
|
|
411
|
+
// There, presenting the view is exactly what the user asked to avoid (it restores and
|
|
412
|
+
// raises the window); the host switches the visible tab inside the window and, if the
|
|
413
|
+
// window has no surface to capture, falls through to CDP.
|
|
414
|
+
if (!this.isQuiet()) this.showActive(s)
|
|
415
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
|
|
416
|
+
const shot = await withTimeout(
|
|
417
|
+
capturable.capture({
|
|
418
|
+
...format === 'jpeg' ? { format, quality: request?.quality } : {},
|
|
419
|
+
...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
|
|
420
|
+
...request?.maxHeight !== undefined ? { maxHeight: request.maxHeight } : {},
|
|
421
|
+
quiet: this.isQuiet(),
|
|
422
|
+
}),
|
|
423
|
+
timeoutMs,
|
|
424
|
+
signal,
|
|
425
|
+
`browser: screenshot timed out after ${timeoutMs}ms`,
|
|
426
|
+
)
|
|
427
|
+
if (shot.base64 === '') {
|
|
428
|
+
throw new BrowserError('browser: capture returned an empty image (view not painted); retry shortly', 'BROWSER_SCREENSHOT_FAILED')
|
|
429
|
+
}
|
|
430
|
+
// The native capture describes the VIEW it was taken from, and that view is not always the
|
|
431
|
+
// page's own layout surface: an off-screen parked window answered a full-width capture with a
|
|
432
|
+
// 231×960 image while the page itself was 1254×707 (issue #140). A capture whose aspect ratio
|
|
433
|
+
// disagrees with the page's layout viewport was taken from another surface, so it is replaced
|
|
434
|
+
// by a CDP clip of the viewport below instead of being handed to the caller.
|
|
435
|
+
const nativeShape = await this.captureMatchesViewport(handle, shot.width, shot.height)
|
|
436
|
+
if (nativeShape) return this.saveScreenshot(
|
|
437
|
+
shot.base64,
|
|
438
|
+
request?.savePath,
|
|
439
|
+
shot.mime ?? 'image/png',
|
|
440
|
+
// The child measured these after applying any downscale, and they describe the image
|
|
441
|
+
// the caller receives. Without them this path — the default self-hosted one — could
|
|
442
|
+
// never answer the width/height its own tool schema declares.
|
|
443
|
+
shot.width !== undefined && shot.height !== undefined
|
|
444
|
+
? { width: shot.width, height: shot.height }
|
|
445
|
+
: undefined,
|
|
446
|
+
)
|
|
447
|
+
}
|
|
448
|
+
// Fallback: a handle without a native capture() (the sidebar, or an installed Chrome
|
|
449
|
+
// or Edge) uses CDP; full-page needs `captureBeyondViewport`, which capturePage lacks.
|
|
450
|
+
//
|
|
451
|
+
// JPEG: Electron 43's CDP hangs on it, which is why the sidebar stays PNG. An
|
|
452
|
+
// installed Chrome or Edge is the real browser and has no such defect, so it says so
|
|
453
|
+
// through `supportsCdpJpeg` and gets the format it asked for, and the same for
|
|
454
|
+
// downscaling, which CDP performs through a full-document clip.
|
|
455
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
|
|
456
|
+
const params: Record<string, unknown> = {}
|
|
457
|
+
const region = request?.clip
|
|
458
|
+
if (region !== undefined) {
|
|
459
|
+
const valid = [region.x, region.y, region.width, region.height].every(
|
|
460
|
+
value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192,
|
|
461
|
+
) && region.width > 0 && region.height > 0
|
|
462
|
+
if (!valid) throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED')
|
|
463
|
+
params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 }
|
|
464
|
+
params.fromSurface = true
|
|
465
|
+
params.captureBeyondViewport = false
|
|
466
|
+
}
|
|
467
|
+
if (region === undefined && request?.fullPage === true) {
|
|
468
|
+
// `captureBeyondViewport` captures the full scrollable content; without
|
|
469
|
+
// a clip this yields the full-page image (CDP default is the viewport).
|
|
470
|
+
params.captureBeyondViewport = true
|
|
471
|
+
}
|
|
472
|
+
// A viewport capture is defined by the PAGE's layout viewport, never by whatever surface the
|
|
473
|
+
// window happens to have when the screenshot is taken (issue #140).
|
|
474
|
+
if (region === undefined && request?.fullPage !== true && params.clip === undefined) {
|
|
475
|
+
const metrics = await withTimeout(handle.sendCommand('Page.getLayoutMetrics', {}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`)
|
|
476
|
+
const size = layoutSize(metrics as Record<string, unknown>)
|
|
477
|
+
if (size !== undefined && size.viewportWidth > 0 && size.viewportHeight > 0) {
|
|
478
|
+
params.clip = { x: 0, y: 0, width: size.viewportWidth, height: size.viewportHeight, scale: 1 }
|
|
479
|
+
params.fromSurface = true
|
|
480
|
+
params.captureBeyondViewport = false
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const supportsJpeg = (handle as { supportsCdpJpeg?: boolean }).supportsCdpJpeg === true
|
|
484
|
+
if (format === 'jpeg' && supportsJpeg) {
|
|
485
|
+
params.format = 'jpeg'
|
|
486
|
+
// CDP range is 0-100 and defaults to 80 when omitted.
|
|
487
|
+
if (request?.quality !== undefined) params.quality = request.quality
|
|
488
|
+
}
|
|
489
|
+
// Downscaling on this path: CDP scales through `clip.scale`, and a clip only applies
|
|
490
|
+
// to the region it names, so it has to cover the whole document. The page's own size
|
|
491
|
+
// is read first; when that is unavailable the capture proceeds unscaled rather than
|
|
492
|
+
// failing — an image the caller can shrink itself beats no image at all.
|
|
493
|
+
let rendered: { width: number; height: number } | undefined
|
|
494
|
+
if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
|
|
495
|
+
const metrics = await withTimeout(
|
|
496
|
+
handle.sendCommand('Page.getLayoutMetrics', {}),
|
|
497
|
+
timeoutMs,
|
|
498
|
+
signal,
|
|
499
|
+
`browser: screenshot timed out after ${timeoutMs}ms`,
|
|
500
|
+
)
|
|
501
|
+
const size = layoutSize(metrics)
|
|
502
|
+
if (size !== undefined) {
|
|
503
|
+
const height = request.fullPage === true ? size.height : size.viewportHeight
|
|
504
|
+
const byWidth = request.maxWidth !== undefined && size.width > 0 ? request.maxWidth / size.width : 1
|
|
505
|
+
const byHeight = request.maxHeight !== undefined && height > 0 ? request.maxHeight / height : 1
|
|
506
|
+
const scale = Math.min(1, byWidth, byHeight)
|
|
507
|
+
// What the caller will actually receive. Recorded before the branch below, because the
|
|
508
|
+
// size is worth reporting even when no scaling happened (scale 1).
|
|
509
|
+
rendered = { width: Math.round(size.width * scale), height: Math.round(height * scale) }
|
|
510
|
+
if (scale < 1) {
|
|
511
|
+
params.clip = { x: 0, y: 0, width: size.width, height, scale }
|
|
512
|
+
// The clip defines the captured area; captureBeyondViewport must not also apply.
|
|
513
|
+
delete params.captureBeyondViewport
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
// A region capture is a read: it must never present the conversation or
|
|
518
|
+
// raise a window. Every other screenshot keeps the original call shape.
|
|
519
|
+
const result = await withTimeout(
|
|
520
|
+
region === undefined
|
|
521
|
+
? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
|
|
522
|
+
: handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }),
|
|
523
|
+
timeoutMs,
|
|
524
|
+
signal,
|
|
525
|
+
`browser: screenshot timed out after ${timeoutMs}ms`,
|
|
526
|
+
)
|
|
527
|
+
const data = result.data
|
|
528
|
+
if (typeof data !== 'string') {
|
|
529
|
+
throw new BrowserError('browser: screenshot returned no image data', 'BROWSER_SCREENSHOT_FAILED')
|
|
530
|
+
}
|
|
531
|
+
// The mime must name the format that was ACTUALLY requested (params.format), not PNG
|
|
532
|
+
// unconditionally: a carrier that sets supportsCdpJpeg asks for `format: 'jpeg'`, so
|
|
533
|
+
// hardcoding the PNG mime announced a JPEG body as a PNG — the data URL then carried a
|
|
534
|
+
// mislabelled image, and a caller that decodes by mime wrote the wrong file.
|
|
535
|
+
const mime = params.format === 'jpeg' ? 'image/jpeg' : 'image/png'
|
|
536
|
+
return this.saveScreenshot(data, request?.savePath, mime, rendered)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Does a native capture describe the page's own layout viewport?
|
|
541
|
+
*
|
|
542
|
+
* Aspect ratio is the DPR-independent test: a correct capture keeps the viewport's shape whatever
|
|
543
|
+
* the device scale factor is, while a capture of another surface (an off-screen window's tiny
|
|
544
|
+
* backing store, a narrow panel view) does not. Absent metrics, the capture is trusted — this is a
|
|
545
|
+
* repair for a wrong surface, not a second guess at a right one.
|
|
546
|
+
*/
|
|
547
|
+
private async captureMatchesViewport(
|
|
548
|
+
handle: { sendCommand(method: string, params: Record<string, unknown>, options?: { present?: boolean }): Promise<unknown> },
|
|
549
|
+
width: number | undefined,
|
|
550
|
+
height: number | undefined,
|
|
551
|
+
): Promise<boolean> {
|
|
552
|
+
if (width === undefined || height === undefined || width <= 0 || height <= 0) return true
|
|
553
|
+
try {
|
|
554
|
+
const size = layoutSize(await handle.sendCommand('Page.getLayoutMetrics', {}) as Record<string, unknown>)
|
|
555
|
+
if (size === undefined || size.viewportWidth <= 0 || size.viewportHeight <= 0) return true
|
|
556
|
+
const captured = width / height
|
|
557
|
+
const viewport = size.viewportWidth / size.viewportHeight
|
|
558
|
+
return Math.abs(captured - viewport) / viewport <= 0.05
|
|
559
|
+
} catch { return true }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Build the data URL and optionally write the image to disk. The caller's
|
|
564
|
+
* path goes through the SAME {@link admitSavePath} gate as a download — it
|
|
565
|
+
* must be absolute, resolve inside `downloadDir`, and not be an existing
|
|
566
|
+
* file — so a screenshot cannot be used to write to, or silently replace,
|
|
567
|
+
* files anywhere the DSH process happens to have permission (issue #13).
|
|
568
|
+
*/
|
|
569
|
+
private saveScreenshot(
|
|
570
|
+
base64: string,
|
|
571
|
+
savePath: string | undefined,
|
|
572
|
+
mime: string,
|
|
573
|
+
rendered?: { width: number; height: number },
|
|
574
|
+
): { dataUrl: string; path?: string; width?: number; height?: number } {
|
|
575
|
+
if (savePath !== undefined) {
|
|
576
|
+
// Admission failures propagate unchanged: they describe the caller's
|
|
577
|
+
// path, not a disk problem.
|
|
578
|
+
const target = this.admitSavePath(savePath, 'screenshot')
|
|
579
|
+
try {
|
|
580
|
+
writeFileNoReplace(target, Buffer.from(base64, 'base64'))
|
|
581
|
+
return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered }
|
|
582
|
+
} catch (error) {
|
|
583
|
+
// Report the write problem but keep the capture usable.
|
|
584
|
+
throw new BrowserError(`browser: screenshot save to "${target}" failed: ${String(error)}`, 'BROWSER_SCREENSHOT_SAVE_FAILED', { cause: error })
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return { dataUrl: `data:${mime};base64,${base64}`, ...rendered }
|
|
588
|
+
}
|
|
589
|
+
}
|