@browserless.io/cli 0.5.2 → 0.6.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.
- package/CHANGELOG.md +93 -75
- package/README.md +73 -19
- package/build/agent/ws-client.js +1 -1
- package/build/api/client.js +1 -1
- package/build/api/profiles.js +1 -1
- package/build/api/upload.js +1 -1
- package/build/auth/disclaimer.js +7 -3
- package/build/auth/server-url.js +2 -2
- package/build/browsers/discover.js +5 -5
- package/build/capture/cdp-pipe.js +1 -0
- package/build/capture/cdp.js +3 -3
- package/build/capture/cleanup.js +1 -0
- package/build/capture/copy-profile.js +1 -1
- package/build/capture/index.js +1 -1
- package/build/capture/launch.js +7 -7
- package/build/capture/profile-lock.js +5 -5
- package/build/cli-utils/agent-format.js +5 -3
- package/build/cli-utils/capture-runner.js +7 -26
- package/build/cli-utils/client.js +2 -2
- package/build/cli.js +4 -4
- package/build/commands/agent/chat.js +12 -9
- package/build/commands/auth/login.js +1 -1
- package/build/commands/profile/delete.js +1 -1
- package/build/commands/profile/launch.js +3 -3
- package/build/commands/profile/list.js +1 -1
- package/build/commands/profile/refresh.js +2 -2
- package/build/commands/profile/rename.js +1 -1
- package/build/commands/profile/show.js +1 -1
- package/build/commands/profile/sources/add.js +1 -1
- package/build/commands/profile/upload.js +2 -2
- package/build/errors.js +1 -1
- package/build/regions.js +1 -1
- package/build/telemetry/api.js +1 -1
- package/build/telemetry/index.js +2 -2
- package/build/utils/interrupt.js +1 -0
- package/build/utils/spinner.js +3 -3
- package/build/utils/terminal.js +3 -0
- package/build/version.js +1 -1
- package/package.json +20 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,142 +1,160 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.6.1 (2026-11-13)
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
### Bug Fixes
|
|
7
7
|
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* bound decoded API responses and body deadlines
|
|
9
|
+
* capture over a private pipe instead of a local debugging port, and stop the headless browser and delete the temporary profile copy when a capture is interrupted
|
|
10
|
+
* escape remote agent terminal output
|
|
11
|
+
* escape terminal controls in error and profile displays
|
|
12
|
+
* pin custom browser registration paths
|
|
10
13
|
|
|
11
|
-
##
|
|
14
|
+
## 0.6.0 (2026-11-05)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### Features
|
|
18
|
+
|
|
19
|
+
* record failure category, code and HTTP status in CLI telemetry
|
|
20
|
+
|
|
21
|
+
## 0.5.2 (2026-10-30)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
### Bug Fixes
|
|
25
|
+
|
|
26
|
+
* reject authenticated API redirects
|
|
27
|
+
* isolate capture smoke state and replay
|
|
28
|
+
|
|
29
|
+
## 0.5.1 (2026-10-22)
|
|
12
30
|
|
|
13
31
|
|
|
14
32
|
### Bug Fixes
|
|
15
33
|
|
|
16
|
-
*
|
|
34
|
+
* detect the Windows cookie-file lock during profile capture
|
|
17
35
|
|
|
18
|
-
##
|
|
36
|
+
## 0.5.0 (2026-10-16)
|
|
19
37
|
|
|
20
38
|
|
|
21
39
|
### Features
|
|
22
40
|
|
|
23
|
-
*
|
|
41
|
+
* add profile terms command
|
|
24
42
|
|
|
25
|
-
##
|
|
43
|
+
## 0.4.2 (2026-10-13)
|
|
26
44
|
|
|
27
45
|
|
|
28
46
|
### Bug Fixes
|
|
29
47
|
|
|
30
|
-
*
|
|
48
|
+
* enforce secure server URLs before sending tokens
|
|
31
49
|
|
|
32
|
-
##
|
|
50
|
+
## 0.4.1 (2026-10-06)
|
|
33
51
|
|
|
34
52
|
|
|
35
53
|
### Bug Fixes
|
|
36
54
|
|
|
37
|
-
*
|
|
55
|
+
* restrict telemetry to trusted API hosts
|
|
38
56
|
|
|
39
|
-
##
|
|
57
|
+
## 0.4.0 (2026-09-22)
|
|
40
58
|
|
|
41
59
|
|
|
42
60
|
### Features
|
|
43
61
|
|
|
44
|
-
*
|
|
62
|
+
* track CLI profile setup attempts
|
|
45
63
|
|
|
46
|
-
##
|
|
64
|
+
## 0.3.0 (2026-08-04)
|
|
47
65
|
|
|
48
66
|
|
|
49
67
|
### Features
|
|
50
68
|
|
|
51
|
-
* Profile refresh replays the capture settings a profile was created with — no flags needed
|
|
69
|
+
* Profile refresh replays the capture settings a profile was created with — no flags needed
|
|
52
70
|
|
|
53
|
-
##
|
|
71
|
+
## 0.2.0 (2026-06-18)
|
|
54
72
|
|
|
55
73
|
|
|
56
74
|
### Features
|
|
57
75
|
|
|
58
|
-
* add usage telemetry
|
|
76
|
+
* add usage telemetry
|
|
59
77
|
|
|
60
|
-
##
|
|
78
|
+
## 0.1.0 (2026-06-05)
|
|
61
79
|
|
|
62
80
|
|
|
63
81
|
### Features
|
|
64
82
|
|
|
65
|
-
* Interactive agent chat via `browserless agent`
|
|
83
|
+
* Interactive agent chat via `browserless agent`
|
|
66
84
|
|
|
67
|
-
##
|
|
85
|
+
## 0.0.3 (2026-06-05)
|
|
68
86
|
|
|
69
87
|
|
|
70
88
|
### Bug Fixes
|
|
71
89
|
|
|
72
|
-
* **capture:** connect to the browser CDP endpoint, not a default page target
|
|
73
|
-
* **capture:** retry the default-target CDP connect on "No inspectable targets"
|
|
74
|
-
* **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets")
|
|
75
|
-
* **cli:** set process.exitCode instead of process.exit() on error path
|
|
76
|
-
* **cli:** windows/macos flaky tests
|
|
90
|
+
* **capture:** connect to the browser CDP endpoint, not a default page target
|
|
91
|
+
* **capture:** retry the default-target CDP connect on "No inspectable targets"
|
|
92
|
+
* **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets")
|
|
93
|
+
* **cli:** set process.exitCode instead of process.exit() on error path
|
|
94
|
+
* **cli:** windows/macos flaky tests
|
|
77
95
|
|
|
78
|
-
##
|
|
96
|
+
## 0.0.2 (2026-05-27)
|
|
79
97
|
|
|
80
98
|
|
|
81
99
|
### Features
|
|
82
100
|
|
|
83
|
-
* --region sfo|lon|ams shortcut + region config key
|
|
84
|
-
* Add the Browserless CLI for authenticated profile management
|
|
85
|
-
* **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt
|
|
86
|
-
* **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions
|
|
87
|
-
* **ci:** cli-smoke integration test invokes every command on every OS via stub server
|
|
88
|
-
* **disclaimer:** include privacy-policy link in liability disclaimer text
|
|
89
|
-
* **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it
|
|
90
|
-
* **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup
|
|
91
|
-
* **sources:** surface broken custom-browser registrations in sources list
|
|
101
|
+
* --region sfo|lon|ams shortcut + region config key
|
|
102
|
+
* Add the Browserless CLI for authenticated profile management
|
|
103
|
+
* **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt
|
|
104
|
+
* **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions
|
|
105
|
+
* **ci:** cli-smoke integration test invokes every command on every OS via stub server
|
|
106
|
+
* **disclaimer:** include privacy-policy link in liability disclaimer text
|
|
107
|
+
* **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it
|
|
108
|
+
* **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup
|
|
109
|
+
* **sources:** surface broken custom-browser registrations in sources list
|
|
92
110
|
|
|
93
111
|
|
|
94
112
|
### Bug Fixes
|
|
95
113
|
|
|
96
|
-
* address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests)
|
|
97
|
-
* **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/)
|
|
98
|
-
* **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery
|
|
99
|
-
* **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium
|
|
100
|
-
* **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins
|
|
101
|
-
* **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge
|
|
102
|
-
* **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed
|
|
103
|
-
* **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself
|
|
104
|
-
* **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture
|
|
105
|
-
* **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI
|
|
106
|
-
* **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI
|
|
107
|
-
* **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows)
|
|
108
|
-
* **capture:** surface browser stderr in CDP-timeout error for diagnostics
|
|
109
|
-
* **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T
|
|
110
|
-
* **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount
|
|
111
|
-
* **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI
|
|
112
|
-
* **ci:** apt options go after apt-get, not after sudo
|
|
113
|
-
* **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source
|
|
114
|
-
* **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it)
|
|
115
|
-
* **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT
|
|
116
|
-
* **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot)
|
|
117
|
-
* **ci:** restore apt-get update before gnome-keyring install — cached lists go stale
|
|
118
|
-
* **ci:** same Chrome seed fix for linux smoke
|
|
119
|
-
* **ci:** seed Chrome user-data-dir directly instead of racing first-run boot
|
|
120
|
-
* **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces
|
|
121
|
-
* **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture)
|
|
122
|
-
* **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting
|
|
123
|
-
* **commands:** add missing region?: string to upload/refresh Options interfaces
|
|
124
|
-
* **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir
|
|
125
|
-
* **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains
|
|
126
|
-
* **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames)
|
|
127
|
-
* **lock:** Windows lockfile is an empty marker — presence = locked (no PID)
|
|
128
|
-
* **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs
|
|
129
|
-
* **sh:** drop duplicate Linux pattern in verify-chrome.sh case
|
|
130
|
-
* **sources:** validate --path and --user-data-dir at sources add time
|
|
131
|
-
* **test:** bound chrome.exe warmup to 30s so it can't hang CI
|
|
132
|
-
* **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation)
|
|
133
|
-
* **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals)
|
|
134
|
-
* **trim-state:** don't treat unparseable origins as protected by --keep-domain
|
|
114
|
+
* address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests)
|
|
115
|
+
* **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/)
|
|
116
|
+
* **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery
|
|
117
|
+
* **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium
|
|
118
|
+
* **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins
|
|
119
|
+
* **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge
|
|
120
|
+
* **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed
|
|
121
|
+
* **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself
|
|
122
|
+
* **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture
|
|
123
|
+
* **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI
|
|
124
|
+
* **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI
|
|
125
|
+
* **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows)
|
|
126
|
+
* **capture:** surface browser stderr in CDP-timeout error for diagnostics
|
|
127
|
+
* **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T
|
|
128
|
+
* **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount
|
|
129
|
+
* **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI
|
|
130
|
+
* **ci:** apt options go after apt-get, not after sudo
|
|
131
|
+
* **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source
|
|
132
|
+
* **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it)
|
|
133
|
+
* **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT
|
|
134
|
+
* **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot)
|
|
135
|
+
* **ci:** restore apt-get update before gnome-keyring install — cached lists go stale
|
|
136
|
+
* **ci:** same Chrome seed fix for linux smoke
|
|
137
|
+
* **ci:** seed Chrome user-data-dir directly instead of racing first-run boot
|
|
138
|
+
* **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces
|
|
139
|
+
* **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture)
|
|
140
|
+
* **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting
|
|
141
|
+
* **commands:** add missing region?: string to upload/refresh Options interfaces
|
|
142
|
+
* **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir
|
|
143
|
+
* **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains
|
|
144
|
+
* **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames)
|
|
145
|
+
* **lock:** Windows lockfile is an empty marker — presence = locked (no PID)
|
|
146
|
+
* **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs
|
|
147
|
+
* **sh:** drop duplicate Linux pattern in verify-chrome.sh case
|
|
148
|
+
* **sources:** validate --path and --user-data-dir at sources add time
|
|
149
|
+
* **test:** bound chrome.exe warmup to 30s so it can't hang CI
|
|
150
|
+
* **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation)
|
|
151
|
+
* **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals)
|
|
152
|
+
* **trim-state:** don't treat unparseable origins as protected by --keep-domain
|
|
135
153
|
|
|
136
154
|
|
|
137
155
|
### Reverts
|
|
138
156
|
|
|
139
|
-
* drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario
|
|
157
|
+
* drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario
|
|
140
158
|
|
|
141
159
|
## Changelog
|
|
142
160
|
|
package/README.md
CHANGED
|
@@ -52,12 +52,15 @@
|
|
|
52
52
|
- [Privacy & Domain Filtering](#-privacy--domain-filtering)
|
|
53
53
|
- [Managing Artifact Size](#-managing-artifact-size)
|
|
54
54
|
- [Custom Chromium Browsers](#-custom-chromium-browsers)
|
|
55
|
+
- [Hosted Agent](#-hosted-agent)
|
|
55
56
|
- [Shared Flags](#-shared-flags)
|
|
56
57
|
- [Configuration](#-configuration)
|
|
57
58
|
- [Environment Variables](#-environment-variables)
|
|
58
59
|
- [Usage Analytics](#-usage-analytics)
|
|
59
60
|
- [Exit Codes](#-exit-codes)
|
|
60
61
|
- [Why use the CLI?](#-why-use-the-cli)
|
|
62
|
+
- [Contributing](#-contributing)
|
|
63
|
+
- [Security](#-security)
|
|
61
64
|
- [Licensing](#-licensing)
|
|
62
65
|
|
|
63
66
|
## 🚀 Get Started in Seconds!
|
|
@@ -73,10 +76,12 @@ Requires Node.js ≥ 24.
|
|
|
73
76
|
### Step 2: Log in
|
|
74
77
|
|
|
75
78
|
```bash
|
|
76
|
-
#
|
|
77
|
-
# it out of shell history.
|
|
78
|
-
browserless auth login <your-token>
|
|
79
|
+
# Recommended: pipe the token via stdin (or paste it at the prompt)
|
|
79
80
|
echo $TOKEN | browserless auth login
|
|
81
|
+
|
|
82
|
+
# Also works, but a token passed as an argument is visible to other local
|
|
83
|
+
# users in the process list and lands in your shell history
|
|
84
|
+
browserless auth login <your-token>
|
|
80
85
|
```
|
|
81
86
|
|
|
82
87
|
Tokens are stored in your **OS keychain** when available (Keychain on
|
|
@@ -286,16 +291,43 @@ If the binary or `user-data-dir` later goes missing, `profile sources
|
|
|
286
291
|
list` flags the entry under "Registered custom browsers with missing
|
|
287
292
|
paths" so you can clean it up with `profile sources rm`.
|
|
288
293
|
|
|
294
|
+
## 🤖 Hosted Agent
|
|
295
|
+
|
|
296
|
+
`browserless agent` opens an interactive chat with the Browserless hosted
|
|
297
|
+
agent. The model runs on Browserless and drives a cloud browser for you; the
|
|
298
|
+
terminal shows its replies and each browser action as it happens.
|
|
299
|
+
|
|
300
|
+
```bash
|
|
301
|
+
# Start a chat, optionally with the first task
|
|
302
|
+
browserless agent "find the opening hours of the Louvre"
|
|
303
|
+
|
|
304
|
+
# Scripts: stdout carries only the final result as JSON (progress goes to stderr)
|
|
305
|
+
browserless agent "find the opening hours of the Louvre" --json
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
- Follow-up messages continue the same session. Ctrl-C stops the current
|
|
309
|
+
turn; press it again (or send an empty line) to exit.
|
|
310
|
+
- When the agent pauses for input — for example a one-time code — the CLI
|
|
311
|
+
prompts you for it.
|
|
312
|
+
- If your first message asks the agent to log in somewhere, the CLI asks
|
|
313
|
+
for a username and password (the password is masked) and sends them to
|
|
314
|
+
the hosted agent together with your task. Leave the prompts blank to
|
|
315
|
+
skip.
|
|
316
|
+
- Prompts you type are kept in `~/.browserless/agent_history` (mode 0600,
|
|
317
|
+
last 200) so the up arrow recalls them across sessions; usernames,
|
|
318
|
+
passwords and codes are never written there. `--no-history` turns the
|
|
319
|
+
file off.
|
|
320
|
+
|
|
289
321
|
## ⚙️ Shared Flags
|
|
290
322
|
|
|
291
323
|
Every command that hits the cloud API accepts:
|
|
292
324
|
|
|
293
|
-
| Flag | Effect
|
|
294
|
-
| ----------------- |
|
|
295
|
-
| `--token <tok>` | Override token resolution (flag > env > keychain > config file) |
|
|
296
|
-
| `--server <url>` | Override the configured server URL
|
|
297
|
-
| `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server`
|
|
298
|
-
| `--json` | Emit the server response as JSON (script-friendly)
|
|
325
|
+
| Flag | Effect |
|
|
326
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
|
327
|
+
| `--token <tok>` | Override token resolution (flag > env > keychain > config file). Visible in the process list; prefer `BROWSERLESS_TOKEN` for scripts |
|
|
328
|
+
| `--server <url>` | Override the configured server URL |
|
|
329
|
+
| `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
|
|
330
|
+
| `--json` | Emit the server response as JSON (script-friendly) |
|
|
299
331
|
|
|
300
332
|
Capture commands (`upload`, `refresh`, `inspect`) also accept:
|
|
301
333
|
|
|
@@ -364,13 +396,21 @@ authenticated with your token and targeted a Browserless cloud region:
|
|
|
364
396
|
|
|
365
397
|
- the command that ran (e.g. `profile upload`) and the **names** of the flags
|
|
366
398
|
you passed — never their values
|
|
367
|
-
- the outcome: `ok` / `error`, the exit code, and the error class
|
|
368
|
-
|
|
399
|
+
- the outcome: `ok` / `error`, the exit code, and on failure the error class,
|
|
400
|
+
a short error code (e.g. `cdp-timeout`, `not-found`), a category (e.g.
|
|
401
|
+
`network`) and the server's HTTP status when there is one — never the error message
|
|
369
402
|
- duration, CLI version, OS / architecture / Node major, whether it's running
|
|
370
403
|
under CI
|
|
371
404
|
- the production region (`sfo` / `lon` / `ams`) — never a raw server URL
|
|
372
405
|
- a random per-install id (`cli_device_id`), stored in
|
|
373
406
|
`~/.browserless/telemetry-device-id`
|
|
407
|
+
- for `profile upload` / `profile refresh`, a few setup-progress events
|
|
408
|
+
(`Profile Setup Method Selected`, `Profile Setup Started`,
|
|
409
|
+
`Profile Setup Ready`, `Profile Save Submitted`, and
|
|
410
|
+
`Profile Setup Failed` with a short reason code) that share a random
|
|
411
|
+
`attempt_id`. Pass `--attempt-id <UUID>` to keep your own id across
|
|
412
|
+
retries; the same id is sent to the Browserless server with the upload as
|
|
413
|
+
the `x-browserless-attempt-id` header
|
|
374
414
|
|
|
375
415
|
**What's never in the analytics data:** your API token, profile names,
|
|
376
416
|
captured URLs or domains, cookies, or any captured auth state. The token is
|
|
@@ -421,16 +461,30 @@ touched; sensitive domains never leave your machine.
|
|
|
421
461
|
Once uploaded, any Browserless cloud session can attach the profile
|
|
422
462
|
via `?profile=<name>` and start _already authenticated_.
|
|
423
463
|
|
|
424
|
-
##
|
|
464
|
+
## 🤝 Contributing
|
|
465
|
+
|
|
466
|
+
Pull requests are welcome. [AGENTS.md](AGENTS.md) is the contributor guide —
|
|
467
|
+
architecture, local setup, testing patterns and conventions (coding agents
|
|
468
|
+
read the same file). Before opening a PR:
|
|
469
|
+
|
|
470
|
+
```bash
|
|
471
|
+
npm run build && npm run lint && npm test
|
|
472
|
+
```
|
|
425
473
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
474
|
+
PR titles follow [Conventional Commits](https://www.conventionalcommits.org/)
|
|
475
|
+
and become the changelog entry.
|
|
476
|
+
|
|
477
|
+
## 🔒 Security
|
|
478
|
+
|
|
479
|
+
Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md).
|
|
480
|
+
Don't open a public issue for a security problem.
|
|
481
|
+
|
|
482
|
+
## 📜 Licensing
|
|
429
483
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
484
|
+
The Browserless CLI is open source under the [MIT License](LICENSE).
|
|
485
|
+
Using it with the hosted Browserless service is also covered by your
|
|
486
|
+
Browserless account terms and the
|
|
487
|
+
[privacy policy](https://www.browserless.io/privacy-policy).
|
|
434
488
|
|
|
435
489
|
<div align="center">
|
|
436
490
|
|
package/build/agent/ws-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var c=(i,e)=>p(i,"name",{value:e,configurable:!0});import{EventEmitter as f}from"node:events";import h from"ws";import{ApiError as d,PreconditionError as w}from"../errors.js";import{terminalSafe as u}from"../utils/terminal.js";const S=new Set([1e3,1001,1005]),g=c((i,e)=>{const r=i.replace(/^http/i,"ws").replace(/\/+$/,""),s=new URL(`${r}/chromium/cli`);return s.searchParams.set("token",e),s.toString()},"buildCliWsUrl");class W extends f{static{c(this,"AgentClient")}ws=null;server;token;WebSocketImpl;constructor(e){super(),this.server=e.server,this.token=e.token,this.WebSocketImpl=e.WebSocketImpl??h}connect(){const e=g(this.server,this.token);return new Promise((r,s)=>{const n=new this.WebSocketImpl(e);let l=!1;const m=c(t=>{if(!l)if(l=!0,t){try{n.terminate()}catch{}s(t)}else this.ws=n,r()},"settle");n.once("open",()=>m()),n.once("unexpected-response",(t,a)=>{const o=a.statusCode??0;m(this.mapUpgradeError(o,a.statusMessage??""))}),n.on("error",t=>{if(!l){m(new d(`WebSocket connection failed: ${t.message}`,0,void 0,"websocket-failed"));return}this.emit("agent_error",{code:"ws-error",message:t.message,retryable:!1})}),n.on("message",t=>this.handleMessage(t)),n.on("close",(t,a)=>{const o=a?.toString("utf8")??"";if(!S.has(t)){this.emit("agent_error",{code:`ws-closed-${t}`,message:`WebSocket closed abnormally (code ${t}${o?`: ${o}`:""})`,retryable:!1});return}this.emit("close",{code:t,reason:o})})})}start(e){this.sendFrame({type:"start",prompt:e})}send(e){this.sendFrame({type:"send",prompt:e})}stop(){this.sendFrame({type:"stop"})}close(){this.ws&&this.ws.readyState===h.OPEN&&this.ws.close()}sendFrame(e){if(!this.ws||this.ws.readyState!==h.OPEN)throw new d("Cannot send a frame: WebSocket is not open.",0,void 0,"websocket-not-open");this.ws.send(JSON.stringify(e))}handleMessage(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}typeof r.type=="string"&&this.emit(r.type==="error"?"agent_error":r.type,r)}mapUpgradeError(e,r){const s=r?` \u2014 ${u(r)}`:"";return e===401||e===403?new w(`Authentication failed (HTTP ${e}${s}). Check your token and server.`,"invalid-token"):new d(`Server rejected the agent connection (HTTP ${e}${s}).`,e)}}export{W as AgentClient,g as buildCliWsUrl};
|
package/build/api/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var u=(e,t)=>p(e,"name",{value:t,configurable:!0});import{ApiError as c}from"../errors.js";import{terminalSafe as i}from"../utils/terminal.js";const b=3e4,$=10*1024*1024,g=u(e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?e.toLowerCase():void 0,"profileAttemptId"),T=u((e,t,d,r)=>{const n=e.endsWith("/")?e:`${e}/`,h=t.replace(/^\/+/,""),f=new URL(h,n);if(f.searchParams.set("token",d),r)for(const[m,l]of Object.entries(r))l!==void 0&&f.searchParams.set(m,String(l));return f},"buildUrl"),S=u((e,t,d)=>{if(!d)return`HTTP ${e} ${i(t)}`;try{const n=JSON.parse(d);if(n?.message&&typeof n.message=="string")return i(n.message)}catch{}const r=d.trim();return r.length>200?`HTTP ${e} ${i(t)}: ${i(r.slice(0,200))}\u2026`:`HTTP ${e} ${i(t)}: ${i(r)}`},"messageFromBody"),A=u(async(e,t)=>{const d=T(e.server,t.path,e.token,t.query),r={method:t.method,redirect:"error"};let n;t.rawBody!==void 0?n=t.rawBody:t.body!==void 0&&(n=JSON.stringify(t.body)),n!==void 0&&(r.body=n,r.headers={"Content-Type":"application/json"});const h=g(t.attemptId);h&&(r.headers={...r.headers,"x-browserless-attempt-id":h});const f=t.timeoutMs??b,m=new AbortController,l=setTimeout(()=>m.abort(),f);r.signal=m.signal;let s,a="";try{s=await fetch(d,r);const o=new TextDecoder;let w=0;if(s.body){for await(const y of s.body){if(w+=y.byteLength,w>$)throw m.abort(),new c(`Response exceeds the ${$}-byte decoded body limit`,0,void 0,"response-too-large");a+=o.decode(y,{stream:!0})}a+=o.decode()}}catch(o){throw o instanceof c?o:o?.name==="AbortError"?new c(`Request to ${e.server}${t.path} timed out after ${f}ms`,0,void 0,"request-timeout"):new c(s?`Failed to read response from ${e.server}${t.path}: ${o?.message??o}`:`Failed to reach ${e.server}: ${o?.message??o}`,0,void 0,s?"response-read-failed":"network-unreachable")}finally{clearTimeout(l)}if(!s.ok)throw new c(S(s.status,s.statusText,a),s.status,a);if(!(s.status===204||!a))try{return JSON.parse(a)}catch{throw new c(`Server returned non-JSON response: ${i(a)}`,s.status,a,"invalid-response")}},"apiFetch");export{A as apiFetch,g as profileAttemptId};
|
package/build/api/profiles.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var n=Object.defineProperty;var t=(e,o)=>n(e,"name",{value:o,configurable:!0});import{apiFetch as i}from"./client.js";import{UsageError as l}from"../errors.js";const c=t(async(e,o={})=>i(e,{method:"GET",path:"/profiles",query:{...o.limit!==void 0?{limit:o.limit}:{},...o.offset!==void 0?{offset:o.offset}:{}}}),"listProfiles"),r=t(e=>{if(e==="."||e==="..")throw new l(`"${e}" is not a valid profile name.`);return`/profile/${encodeURIComponent(e)}`},"profilePath"),h=t(async(e,o)=>i(e,{method:"GET",path:r(o)}),"getProfile"),m=t(async(e,o,f)=>i(e,{method:"PUT",path:r(o),body:{name:f}}),"renameProfile"),a=t(async(e,o)=>i(e,{method:"DELETE",path:r(o)}),"deleteProfile");export{a as deleteProfile,h as getProfile,c as listProfiles,m as renameProfile};
|
package/build/api/upload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=Object.defineProperty;var i=(t,e)=>o(t,"name",{value:e,configurable:!0});import{apiFetch as n}from"./client.js";import{ApiError as s}from"../errors.js";import{version as a}from"../version.js";const d=i(t=>{const e=t.serialized??JSON.stringify(t.state),r=t.captureSettings===void 0?"":`,"captureSettings":${JSON.stringify(t.captureSettings)}`;return`{"name":${JSON.stringify(t.name)},"state":${e}${r}}`},"buildProfileBody"),p=i((t,e)=>{throw!(t instanceof s)||t.status!==400||!/additional propert/i.test(`${t.body??""} ${t.message}`)?t:new s(`The server at ${e} rejected the profile capture settings this CLI (v${a}) sends \u2014 it predates either the field itself or one of its members. Deploy the server to every region before using this CLI against it. Server said: ${t.message}`,400,t.body,"capture-settings-rejected")},"rethrowCaptureSettingsSkew"),h=i(async(t,e)=>{try{return await n(t,{method:"POST",path:"/profile/upload",rawBody:d(e),attemptId:e.attemptId})}catch(r){return p(r,t.server)}},"uploadProfile");export{d as buildProfileBody,p as rethrowCaptureSettingsSkew,h as uploadProfile};
|
package/build/auth/disclaimer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as
|
|
1
|
+
var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as s,stdout as n}from"node:process";import{readConfig as m,updateConfig as c}from"../config/store.js";import{DEFAULT_TERMS_TTL_DAYS as f}from"../config/schema.js";import{PreconditionError as l}from"../errors.js";const h=`
|
|
2
2
|
Heads up \u2014 uploading a profile sends authentication state to Browserless:
|
|
3
3
|
|
|
4
4
|
\u2022 Cookies, localStorage and IndexedDB from the browser profile you select
|
|
@@ -7,10 +7,14 @@ Heads up \u2014 uploading a profile sends authentication state to Browserless:
|
|
|
7
7
|
\u2022 Only upload profiles you have authority to share. Cookies for banking,
|
|
8
8
|
healthcare, employer-SSO or other sensitive sites should be added to the
|
|
9
9
|
domain exclusion list (\`browserless profile exclude add <domain>\`).
|
|
10
|
+
\u2022 Each cloud profile keeps the exclusion list it was captured with, and a
|
|
11
|
+
later \`profile refresh\` reuses it. To apply a domain you excluded
|
|
12
|
+
since, refresh with \`--exclude-domain <domain>\`: that replaces the
|
|
13
|
+
stored list with this machine's list plus the domain.
|
|
10
14
|
\u2022 Your local browser profile is never modified \u2014 the CLI runs against a
|
|
11
15
|
temporary copy and cleans it up after capture.
|
|
12
16
|
|
|
13
17
|
By continuing you confirm you understand the above and accept responsibility
|
|
14
18
|
for the contents of the upload. Privacy policy: https://www.browserless.io/privacy-policy
|
|
15
|
-
`,
|
|
16
|
-
Type "${
|
|
19
|
+
`,p="I accept",w=o(()=>!!process.env.CI,"isCi"),y=o((t,e)=>{if(!t||e<=0)return!1;const r=Date.parse(t);if(!Number.isFinite(r))return!1;const i=Date.now()-r;return i>=0&&i<e*24*60*60*1e3},"isWithinTtl"),S=o(async t=>{n.write(t);const e=u.createInterface({input:s,output:n});try{return await e.question(`
|
|
20
|
+
Type "${p}" to continue: `)}finally{e.close()}},"defaultPrompt"),x=o(async(t,e={})=>{const r=await m(),i=t.ttlDaysOverride??r.terms_ttl_days??f;if(y(r.accepted_terms_at,i))return;if(t.acceptViaFlag||process.env.BROWSERLESS_ACCEPT_TERMS==="1"){await c(a=>{a.accepted_terms_at=new Date().toISOString()});return}if(!(e.isInteractive??(s.isTTY&&!w())))throw new l("Liability disclaimer must be acknowledged before uploading. Re-run with `--accept-terms` or set BROWSERLESS_ACCEPT_TERMS=1 in non-interactive environments.","terms-not-accepted");if((await(e.prompt??S)(h)).trim()!==p)throw new l("Disclaimer not accepted \u2014 aborting.","terms-not-accepted");await c(a=>{a.accepted_terms_at=new Date().toISOString()})},"ensureTermsAccepted");export{h as DISCLAIMER_TEXT,x as ensureTermsAccepted,w as isCi};
|
package/build/auth/server-url.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var s=Object.defineProperty;var
|
|
2
|
-
`),
|
|
1
|
+
var s=Object.defineProperty;var t=(e,r)=>s(e,"name",{value:r,configurable:!0});import{PreconditionError as n,UsageError as o}from"../errors.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const i="BROWSERLESS_ALLOW_INSECURE_HTTP",S=t(e=>{let r;try{r=new URL(e)}catch{throw new o(`server must be a valid URL (got "${e}")`,"invalid-server-url")}if(r.protocol==="https:")return e;if(r.protocol==="http:"){if(p(r.hostname))return e;if(process.env[i]==="1")return process.stderr.write(`warning: sending your Browserless token over unencrypted http:// to ${r.host} (BROWSERLESS_ALLOW_INSECURE_HTTP is set)
|
|
2
|
+
`),e;throw new n(`Refusing to send your Browserless token over unencrypted http:// to ${r.host}. Use https://, or set BROWSERLESS_ALLOW_INSECURE_HTTP=1 to override.`,"insecure-server-url")}throw new o(`server must use https:// (got "${r.protocol}")`,"unsupported-server-scheme")},"assertSecureServerUrl");export{i as ALLOW_INSECURE_ENV,S as assertSecureServerUrl};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);throw new
|
|
3
|
-
${
|
|
4
|
-
`);throw new
|
|
5
|
-
${
|
|
1
|
+
var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import y from"node:fs/promises";import f from"node:path";import{spawn as N}from"node:child_process";import{BUILT_IN_BROWSERS as P}from"./registry.js";import{readCustomBrowsers as d}from"./custom.js";import{PreconditionError as C,UsageError as p}from"../errors.js";import{pathExists as m}from"../utils/fs.js";import{terminalSafe as c}from"../utils/terminal.js";const k=n(e=>new Promise(r=>{const t=N("which",[e],{stdio:["ignore","pipe","ignore"]});let i="";t.stdout?.on("data",o=>{i+=o.toString()}),t.on("error",()=>r(null)),t.on("exit",o=>r(o===0&&i.trim()?i.trim():null))}),"whichOnPath"),$=n(async e=>{for(const r of e)if(await m(r))return r;return null},"firstExistingPath"),B=n(async e=>{const r=await $(e);if(r)return r;if(process.platform==="linux")for(const t of e){const i=f.basename(t);if(!i)continue;const o=await k(i);if(o)return o}return null},"firstExistingBinary"),L=n(async e=>{const r=f.join(e,"Local State");try{const t=await y.readFile(r,"utf-8"),o=JSON.parse(t)?.profile?.info_cache??{};return Object.fromEntries(Object.entries(o).map(([s,l])=>[s,l?.name??s]))}catch{return{}}},"readProfileDisplayNames"),x=n(async e=>await m(f.join(e,"Preferences"))||await m(f.join(e,"Cookies"))||await m(f.join(e,"Network","Cookies")),"looksLikeProfile"),D=n(async(e,r,t,i)=>{const o=await L(e);let s;try{s=await y.readdir(e,{withFileTypes:!0})}catch{return[]}const l=s.filter(a=>a.isDirectory()).filter(a=>a.name==="Default"||/^Profile \d+$/.test(a.name));return(await Promise.all(l.map(async a=>{const u=f.join(e,a.name);return await x(u)?{browserKey:t,browserDisplayName:i,profileDirName:a.name,profileDisplayName:o[a.name]??a.name,userDataDir:e,profilePath:u,binaryPath:r}:null}))).filter(a=>a!==null)},"profilesUnder"),j=n(async e=>{const r=e.userDataDirByPlatform[process.platform],t=e.binaryPathByPlatform[process.platform]??[];if(!r||t.length===0)return[];const i=Array.isArray(r)?r:[r],o=await B(t);if(!o)return[];for(const s of i){if(!await m(s))continue;const l=await D(s,o,e.key,e.displayName);if(l.length>0)return l}return[]},"discoverBuiltIn"),v=n(async e=>{if(!f.isAbsolute(e.binaryPath)||!f.isAbsolute(e.userDataDir))throw new C(`Custom browser "${e.name}" has relative paths. Remove it with \`profile sources rm <name>\` and re-register it with \`profile sources add\` from its original directory.`,"invalid-custom-browsers-file");return await m(e.userDataDir)?await m(e.binaryPath)?D(e.userDataDir,e.binaryPath,e.name,e.name):[]:[]},"discoverCustom"),E=n(async()=>{const[e,r]=await Promise.all([Promise.all(P.map(j)),d().then(t=>Promise.all(t.map(v)))]);return[...e.flat(),...r.flat()]},"discoverProfiles"),q=n(async()=>{const e=await d();return(await Promise.all(e.map(async t=>{const[i,o]=await Promise.all([m(t.binaryPath),m(t.userDataDir)]);return i&&o?null:{name:t.name,binaryPath:t.binaryPath,userDataDir:t.userDataDir,missingBinary:!i,missingUserDataDir:!o}}))).filter(t=>t!==null)},"findBrokenCustomSources"),b=n((e,r)=>{const t=e.trim().toLowerCase();return r.browserKey.toLowerCase()===t||r.browserDisplayName.toLowerCase()===t},"matchesBrowser"),S=n((e,r)=>{const t=e.trim().toLowerCase();return r.profileDirName.toLowerCase()===t||r.profileDisplayName.toLowerCase()===t},"matchesProfile"),O=n((e,r,t,i)=>{const o=e.trim().toLowerCase();if(!t.some(a=>a.key.toLowerCase()===o||a.displayName.toLowerCase()===o))throw new p(`Unknown browser "${c(e)}". Run \`browserless profile sources list\` to see detected browsers, or register a custom one with \`profile sources add\`.`,"unknown-browser");const l=i.filter(a=>b(e,a)&&S(r,a));if(l.length===1)return l[0];if(l.length===0){const a=i.filter(w=>b(e,w));if(a.length===0)throw new p(`Browser "${c(e)}" is registered but has no detected profiles on this machine.`,"browser-has-no-profiles");const u=a.map(w=>` - ${c(w.profileDisplayName)} (${c(w.profileDirName)})`).join(`
|
|
2
|
+
`);throw new p(`No profile named "${c(r)}" under ${c(e)}. Available profiles:
|
|
3
|
+
${u}`,"local-profile-not-found")}const h=l.map(a=>` - ${c(a.profileDisplayName)} (dir: ${c(a.profileDirName)}) under ${c(a.browserDisplayName)}`).join(`
|
|
4
|
+
`);throw new p(`Profile "${c(r)}" matches multiple entries \u2014 disambiguate by passing the directory name to --profile:
|
|
5
|
+
${h}`,"local-profile-ambiguous")},"resolveProfileFromCandidates"),z=n(async(e,r)=>{const t=await d(),i=[...P.map(s=>({key:s.key,displayName:s.displayName})),...t.map(s=>({key:s.name,displayName:s.name}))],o=await E();return O(e,r,i,o)},"resolveProfile");export{E as discoverProfiles,q as findBrokenCustomSources,z as resolveProfile,O as resolveProfileFromCandidates,k as whichOnPath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var C=Object.defineProperty;var o=(f,c)=>C(f,"name",{value:c,configurable:!0});const l="CDP pipe closed",D=o((f,c)=>{let P=1,i=null;const a=new Map,d=new Map,w=new Set;let m=[];const $=o((r,e)=>`${r??""}\0${e}`,"key"),g=o(r=>{if(!i){i=r;for(const{reject:e}of a.values())e(r);a.clear();for(const e of w)e(r);w.clear(),d.clear()}},"fail"),S=o(r=>{let e;try{e=JSON.parse(r)}catch{return}if(typeof e?.id=="number"){const n=a.get(e.id);if(!n)return;a.delete(e.id),e.error?n.reject(new Error(`${n.method}: ${e.error.message??"protocol error"}`)):n.resolve(e.result??{});return}if(typeof e?.method=="string"){const n=d.get($(e.sessionId,e.method));for(const t of[...n??[]])t(e.params)}},"dispatch");c.on("data",r=>{let e=0,n=r.indexOf(0);for(;n!==-1;){m.push(r.subarray(e,n));const t=Buffer.concat(m).toString("utf8");m=[],S(t),e=n+1,n=r.indexOf(0,e)}e<r.length&&m.push(r.subarray(e))}),c.on("end",()=>g(new Error(l))),c.on("close",()=>g(new Error(l))),c.on("error",r=>g(new Error(`${l}: ${r.message}`))),f.on("error",r=>g(new Error(`${l}: ${r.message}`)));const h=o((r,e={},n)=>{if(i)return Promise.reject(i);const t=P++;return new Promise((s,p)=>{a.set(t,{method:r,resolve:s,reject:p});const O=n?{id:t,method:r,params:e,sessionId:n}:{id:t,method:r,params:e};f.write(`${JSON.stringify(O)}\0`,u=>{!u||!a.has(t)||(a.delete(t),p(new Error(`${l}: ${u.message}`)))})})},"send"),y=o((r,e,n)=>{if(i)return()=>{};const t=$(r,e),s=d.get(t)??new Set;return s.add(n),d.set(t,s),()=>{s.delete(n),s.size===0&&d.get(t)===s&&d.delete(t)}},"on"),x=o((r,e)=>new Promise((n,t)=>{if(i){t(i);return}w.add(t);const s=y(r,e,p=>{s(),w.delete(t),n(p)})}),"once"),E=o(r=>({send:o((e,n)=>h(e,n,r),"send"),on:o((e,n)=>y(r,e,n),"on"),once:o(e=>x(r,e),"once")}),"sessionFor");return{...E(void 0),session:o(r=>E(r),"session"),close:o(()=>{g(new Error(l)),f.destroy(),c.destroy()},"close")}},"connectCdpPipe");export{l as CDP_PIPE_CLOSED,D as connectCdpPipe};
|
package/build/capture/cdp.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var u=(e,t)=>I(e,"name",{value:t,configurable:!0});import x from"node:fs/promises";import E from"node:path";import{CaptureError as w}from"../errors.js";import{errMessage as T}from"../utils/errors.js";import{applyExclusions as A,originAllowedBy as P,originMatchesAny as R}from"./exclusion.js";const v=50,D=5,$=1e3,O=3,M=15e3,N=u((e,t,n)=>{let s;return Promise.race([e.finally(()=>{s&&clearTimeout(s)}),new Promise((c,r)=>{s=setTimeout(()=>r(new Error(`${n} timed out after ${t}ms`)),t)})])},"withTimeout"),j=u(e=>/CDP pipe closed|ECONNREFUSED|EPIPE|socket hang up/i.test(e),"isTransportDeadError"),b=u(e=>{const t=e.startsWith(".")?e.slice(1):e;return!!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t===""||t.includes(":"))},"isPrivateCookieDomain"),_=u(e=>{try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?!0:b(t.hostname)}catch{return!0}},"isPrivateOrigin"),C=new Set(["ntp.msn.com"]),B=u(e=>{try{return C.has(new URL(e).hostname)}catch{return!1}},"isVendorNtpOrigin"),q=u(async e=>{const t=E.join(e,"Local Storage","leveldb");let n;try{n=await x.readdir(t)}catch{return[]}const s=new Set;let c=0;const r=10*1024*1024,i=/https?:\/\/[a-zA-Z0-9.-]+(?::\d+)?/g;for(const a of n)if(!(!a.endsWith(".log")&&!a.endsWith(".ldb"))){if(c>=r)break;try{const d=await x.readFile(E.join(t,a));c+=d.byteLength;const p=d.toString("latin1");for(const f of p.matchAll(i))try{const l=new URL(f[0]);(l.protocol==="https:"||l.protocol==="http:")&&!b(l.hostname)&&!C.has(l.hostname)&&s.add(l.origin)}catch{}}catch{}}return[...s]},"enumerateLocalStorageOrigins"),F=u(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:typeof e.expires=="number"?e.expires:-1,size:e.size,httpOnly:!!e.httpOnly,secure:!!e.secure,session:!!e.session,...e.sameSite?{sameSite:e.sameSite}:{},...e.sourceScheme?{sourceScheme:e.sourceScheme}:{},...e.sourcePort?{sourcePort:e.sourcePort}:{}}),"cookieFromCdp"),L=3e4,U=u(async e=>{const{cookies:t}=await N(e.send("Storage.getCookies"),L,"Storage.getCookies").catch(n=>{throw new w(`Reading cookies from the headless browser failed: ${T(n)}`,"cdp-timeout")});return t.filter(n=>!b(n.domain)).map(F)},"captureCookies"),H=Buffer.from("<html></html>").toString("base64"),X=u(async e=>{const{cdp:t}=e,{targetId:n}=await t.send("Target.createTarget",{url:"about:blank"});if(!n)return null;let s,c=u(()=>{},"stopIntercepting");try{({sessionId:s}=await t.send("Target.attachToTarget",{targetId:n,flatten:!0}));const r=t.session(s);await r.send("Page.enable"),await r.send("Network.enable"),await r.send("Fetch.enable",{patterns:[{urlPattern:"*"}]});const i=new Set([`${e.origin}/`]);c=r.on("Fetch.requestPaused",S=>{const{requestId:y,request:o}=S;i.has(o.url)?(i.delete(o.url),r.send("Fetch.fulfillRequest",{requestId:y,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/html"}],body:H}).catch(()=>{})):r.send("Fetch.failRequest",{requestId:y,errorReason:"BlockedByClient"}).catch(()=>{})});const a=r.once("Page.loadEventFired").catch(()=>{});await r.send("Page.navigate",{url:`${e.origin}/`}),await a;const d=await r.send("Runtime.evaluate",{expression:`
|
|
2
2
|
(() => {
|
|
3
3
|
const out = {};
|
|
4
4
|
for (let i = 0; i < localStorage.length; i++) {
|
|
@@ -7,7 +7,7 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
|
|
|
7
7
|
}
|
|
8
8
|
return JSON.stringify(out);
|
|
9
9
|
})()
|
|
10
|
-
`,returnByValue:!0,awaitPromise:!1}),
|
|
10
|
+
`,returnByValue:!0,awaitPromise:!1}),p=d?.result?.value?JSON.parse(d.result.value):{},f=await r.send("Runtime.evaluate",{expression:`
|
|
11
11
|
(async (MAX_DBS, MAX_ENTRIES) => {
|
|
12
12
|
if (typeof indexedDB.databases !== 'function') return [];
|
|
13
13
|
const dbInfos = await indexedDB.databases();
|
|
@@ -59,4 +59,4 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
|
|
|
59
59
|
}
|
|
60
60
|
return JSON.stringify(out);
|
|
61
61
|
})(${D}, ${$})
|
|
62
|
-
`,returnByValue:!0,awaitPromise:!0}),l=
|
|
62
|
+
`,returnByValue:!0,awaitPromise:!0}),l=f?.result?.value?JSON.parse(f.result.value):[];return Object.keys(p).length===0&&l.length===0?null:{origin:e.origin,localStorage:p,...l.length>0?{indexedDBs:l}:{}}}finally{if(c(),s){const r=t.session(s);await r.send("Fetch.disable").catch(()=>{}),await r.send("Network.disable").catch(()=>{}),await t.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{})}await t.send("Target.closeTarget",{targetId:n}).catch(()=>{})}},"captureOrigin"),W=u(async(e,t,n,s,c=[])=>{const r=[],i=[];let a=!1,d=0,p=0,f=0,l=0;const S=e.filter(o=>!_(o)).filter(o=>!B(o)).filter(o=>!R(o,t)).filter(o=>c.length===0||P(o,c)).length,y=Math.min(S,v);for(const o of e){if(l>=v){a=!0;break}if(!_(o)&&!B(o)){if(R(o,t)){d++;continue}if(c.length>0&&!P(o,c)){p++;continue}l++,s?.({attempted:l,total:y,origin:o});try{const g=await n(o);g&&r.push(g),f=0}catch(g){const h=T(g);if(j(h)){if(f++,f>=O)throw new w(`Headless browser appears to have crashed mid-capture \u2014 ${O} consecutive transport errors on the CDP connection. Last failure on "${o}": ${h}. Retry the capture; if it persists, try a smaller profile or a different --password-store value.`,"browser-crashed-during-capture")}else f=0;let k="unknown";const m=h.toLowerCase();m.includes("timeout")||m.includes("timed out")?k="navigation-timeout":(m.includes("websocket")||m.includes("not connected")||m.includes("connection closed")||m.includes("pipe closed"))&&(k="cdp-disconnected"),i.push({origin:o,error:h,kind:k})}}}if(r.length===0&&i.length>0){const o=i.slice(0,3).map(h=>`${h.origin}: ${h.error}`).join("; "),g=i.length>3?` (+${i.length-3} more)`:"";throw new w(`All ${i.length} attempted origin(s) failed to capture; nothing usable was produced. Sample: ${o}${g}`,"all-origins-failed")}return{origins:r,failedOrigins:i,capHit:a,originCountSkippedByExclusion:d,originCountSkippedByOnlyDomain:p}},"runOriginCaptureLoop"),Q=u(async(e,t,n=[],s,c=[])=>{const r=await U(t),i=await q(e.profilePath),a=await W(i,n,p=>N(X({cdp:t,origin:p}),M,`per-origin capture of ${p}`),s,c),d=A({cookies:r,origins:a.origins},n);return{state:d.state,capHit:a.capHit,cookieCountTotal:r.length,cookieCountExcluded:r.length-d.state.cookies.length,originCountSkippedByExclusion:a.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:a.originCountSkippedByOnlyDomain,failedOrigins:a.failedOrigins}},"captureViaCdp");export{L as COOKIE_READ_TIMEOUT_MS,w as CaptureError,Q as captureViaCdp,F as cookieFromCdp,q as enumerateLocalStorageOrigins,b as isPrivateCookieDomain,_ as isPrivateOrigin,j as isTransportDeadError,B as isVendorNtpOrigin,W as runOriginCaptureLoop,N as withTimeout};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import d from"node:fs/promises";import{killBrowser as f}from"./launch.js";const p=i((e,r,n=f,c=()=>{})=>{let o;return()=>o??=(async()=>{c();const t=await r()?.catch(()=>{});t&&await n(t.child);const a=e();a&&await d.rm(a,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}).catch(()=>{})})()},"createCaptureCleanup");export{p as createCaptureCleanup};
|