barebrowse 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +2 -2
- package/barebrowse.context.md +6 -5
- package/cli.js +3 -0
- package/mcp-server.js +74 -14
- package/package.json +1 -1
- package/src/auth.js +24 -14
- package/src/chromium.js +44 -33
- package/src/daemon.js +84 -45
- package/src/firefox-page.js +1 -11
- package/src/firefox.js +25 -17
- package/src/index.js +2 -7
- package/src/output-clean.js +37 -0
- package/src/with-timeout.js +16 -0
- package/types/auth.d.ts +14 -0
- package/types/output-clean.d.ts +8 -0
- package/types/with-timeout.d.ts +12 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,70 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.24.0] - 2026-10-23
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Switch browser engine mid-session.** The MCP server has a new
|
|
8
|
+
`switch_engine` tool (`chromium` or `firefox`), so an agent no longer needs a
|
|
9
|
+
server restart to try the other engine. The page, tabs and refs are reset
|
|
10
|
+
(call `goto` again); logins from your real browser are re-injected on the next
|
|
11
|
+
`goto`. Expect about 2s to Chromium and 4-5s to Firefox. Switching to the
|
|
12
|
+
active engine is a no-op.
|
|
13
|
+
- **`barebrowse switch-engine <chromium|firefox>` for CLI sessions.** Swaps the
|
|
14
|
+
daemon's browser in place. The new browser is connected first, so a failed
|
|
15
|
+
launch leaves the old one running. Refused when the session was opened with
|
|
16
|
+
`--port` (attached to your own browser). Console and network capture are
|
|
17
|
+
re-attached to the new browser.
|
|
18
|
+
- **MCP `capabilities` reports the last cookie injection.** It now returns a
|
|
19
|
+
`cookies` field with the URL, how many cookies were injected, and each as
|
|
20
|
+
`name @ domain/path`, plus any read error, so an agent can tell "logged out"
|
|
21
|
+
from "no cookie found" from "the cookie read failed". Names, domains and paths
|
|
22
|
+
only, never values.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- **Same-name cookies on different paths are no longer dropped.** The default
|
|
27
|
+
merge of Chromium and Firefox cookie jars keyed cookies by name and domain, so
|
|
28
|
+
two cookies differing only by path collapsed into one. They are now keyed by
|
|
29
|
+
name, domain and path.
|
|
30
|
+
- **Partitioned (CHIPS) Firefox cookies are skipped.** A partitioned cookie
|
|
31
|
+
sharing a name, domain and path with the top-level cookie could replace it in
|
|
32
|
+
the injected set, so a site saw the embed's value instead of your login
|
|
33
|
+
cookie. Only top-level cookies are injected.
|
|
34
|
+
- **A non-numeric `wait_for` timeout no longer resets the page.** A value like
|
|
35
|
+
`"abc"` made the deadline invalid, which fired after about 1ms and wiped the
|
|
36
|
+
page. Numeric strings are now accepted, and anything not a positive number
|
|
37
|
+
falls back to the 30s default.
|
|
38
|
+
- **A browser that fails to start no longer leaks.** When Chromium or Firefox
|
|
39
|
+
timed out, exited early or failed to spawn, the process and its temporary
|
|
40
|
+
profile directory were left behind forever (and could hang a test run). Both
|
|
41
|
+
are now killed and removed before the error is raised.
|
|
42
|
+
- **Chromium cleanup kills helper processes even after the main process
|
|
43
|
+
exited.** Helpers sharing its process group used to survive and keep the
|
|
44
|
+
deleted profile directory open.
|
|
45
|
+
|
|
46
|
+
### Docs
|
|
47
|
+
|
|
48
|
+
- The CLI skill docs now mention the 7-day output cleanup at `barebrowse open`.
|
|
49
|
+
|
|
50
|
+
## [0.23.0] - 2026-10-14
|
|
51
|
+
|
|
52
|
+
### Added
|
|
53
|
+
|
|
54
|
+
- **barebrowse cleans up its own old output files.** Snapshots, screenshots,
|
|
55
|
+
articles and logs piled up in `.barebrowse/` forever. Files older than 7 days
|
|
56
|
+
are now removed once at MCP server start and once at `barebrowse open`
|
|
57
|
+
(honours `--output-dir`). Only barebrowse's exact timestamped names match, so
|
|
58
|
+
`session.json`, `state-*.json` (saved logins) and your own files are never
|
|
59
|
+
touched.
|
|
60
|
+
|
|
61
|
+
### Fixed
|
|
62
|
+
|
|
63
|
+
- **An absurd `wait_for` timeout no longer resets the page.** A timeout above
|
|
64
|
+
`setTimeout`'s maximum made the outer deadline overflow and fire after about
|
|
65
|
+
1ms; the resulting transient "timed out" error then wiped the page. The
|
|
66
|
+
deadline is now capped at the maximum.
|
|
67
|
+
|
|
3
68
|
## [0.22.0] - 2026-10-14
|
|
4
69
|
|
|
5
70
|
### Added
|
package/README.md
CHANGED
|
@@ -50,7 +50,7 @@ barebrowse click 8 # Click element
|
|
|
50
50
|
barebrowse close # End session
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
-
Outputs go to `.barebrowse/` as files -- agents read them with their file tools, no token waste in tool responses.
|
|
53
|
+
Outputs go to `.barebrowse/` as files -- agents read them with their file tools, no token waste in tool responses. Output files older than 7 days are auto-removed at session start; saved state files (`state-*.json`) are kept.
|
|
54
54
|
|
|
55
55
|
**Teach your agent the commands** by installing the skill file (a markdown reference the agent reads as context). The CLI tool itself still needs `npm install barebrowse` -- the skill just teaches the agent how to use it.
|
|
56
56
|
|
|
@@ -96,7 +96,7 @@ Or manually add to your config (`claude_desktop_config.json`, `.cursor/mcp.json`
|
|
|
96
96
|
}
|
|
97
97
|
```
|
|
98
98
|
|
|
99
|
-
MCP tools: `browse`, `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`, `capabilities` (reports the active engine — chromium or firefox — and what the session can do; no side effects). Plus `assess` (privacy scan) if [wearehere](https://github.com/hamr0/wearehere) is installed. Plus opt-in `eval` (`BAREBROWSE_MCP_EVAL=1`) — runs JS in the authenticated session, off by default because it can read cookies/localStorage. Session runs in hybrid mode with automatic cookie injection. Per-tool timeouts (goto/reload/wait_for 60s, back/forward 30s, interactive ops 15s, pdf/screenshot/upload 45s) with auto-retry on transient failures (idempotent only — mutating tools fail loudly to avoid double-submits).
|
|
99
|
+
MCP tools: `browse`, `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`, `capabilities` (reports the active engine — chromium or firefox — and what the session can do, plus a `cookies` field naming the cookies injected on the last goto — names only, never values; no side effects), `switch_engine` (swap chromium/firefox without restarting; page, tabs and refs reset, so call `goto` after). Plus `assess` (privacy scan) if [wearehere](https://github.com/hamr0/wearehere) is installed. Plus opt-in `eval` (`BAREBROWSE_MCP_EVAL=1`) — runs JS in the authenticated session, off by default because it can read cookies/localStorage. Session runs in hybrid mode with automatic cookie injection. Per-tool timeouts (goto/reload/wait_for 60s, back/forward 30s, interactive ops 15s, pdf/screenshot/upload 45s) with auto-retry on transient failures (idempotent only — mutating tools fail loudly to avoid double-submits).
|
|
100
100
|
|
|
101
101
|
**Idle release.** An MCP server can outlive its conversation, so it closes its browser after `BAREBROWSE_IDLE_MINUTES` (default `15`, `0` = never, blank/invalid = default, fractional allowed, capped at ~24.8 days) with no tool call in flight. The next call opens a fresh browser (a new job, not a resume — a page left open, e.g. a solved captcha in the headed window, is gone). A transient browser error also closes the broken browser rather than orphaning it; an ordinary `wait_for` timeout does not reset the page.
|
|
102
102
|
|
package/barebrowse.context.md
CHANGED
|
@@ -95,7 +95,7 @@ const snapshot = await browse('https://example.com', {
|
|
|
95
95
|
| `cdp` | -- | object | Raw CDP session (getter — survives hybrid fallback and switchTab) for escape hatch: `page.cdp.send(method, params)` |
|
|
96
96
|
| `createTab()` | -- | tab handle | New tab in same browser. Returns `{ goto, botBlocked, injectCookies, waitForNetworkIdle, cdp, close }`. Tab close doesn't affect session. |
|
|
97
97
|
| `engine` | -- | `'chromium'`\|`'firefox'` | Which engine drives this session. Always readable (both shapes carry it); a typed literal, so it also narrows the union: `if (page.engine === 'firefox') page.bidi.…`. |
|
|
98
|
-
| `capabilities` | -- | object | Feature introspection: `{ engine, mode, attach, escapeHatch, reloadIgnoreCache, downloads, stealth, cookieInjection }`. Ask "what can this session do?" without probing for `cdp`/`bidi`. All fields are launch-fixed except `stealth`, which is a live getter reflecting the session's current headed/headless state (it can flip mid-session after a hybrid bot-challenge relaunch). `reloadIgnoreCache` is false on Firefox (upstream BiDi gap); `downloads`/`stealth`/`cookieInjection` reflect mode + attach + incognito. |
|
|
98
|
+
| `capabilities` | -- | object | Feature introspection: `{ engine, mode, attach, escapeHatch, reloadIgnoreCache, downloads, stealth, cookieInjection }`. Ask "what can this session do?" without probing for `cdp`/`bidi`. All fields are launch-fixed except `stealth`, which is a live getter reflecting the session's current headed/headless state (it can flip mid-session after a hybrid bot-challenge relaunch). `reloadIgnoreCache` is false on Firefox (upstream BiDi gap); `downloads`/`stealth`/`cookieInjection` reflect mode + attach + incognito. The MCP tool also returns `cookies: { url, injected, cookies: ["name @ domain/path"], error? }` for the last goto (names only, never values; `{ url, injected: 0, incognito: true }` under incognito; `null` before any goto). |
|
|
99
99
|
| `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless). The tab close is bounded (2.5s), so a dead/hung browser still gets killed and its profile + owned download dir removed. Attach mode never kills your browser |
|
|
100
100
|
|
|
101
101
|
**connect() options** (in addition to mode/port/consent):
|
|
@@ -207,7 +207,7 @@ barebrowse can inject cookies from the user's real browser sessions, bypassing l
|
|
|
207
207
|
| Ad / tracker URL blocking | v0.10.0: CDP `Network.setBlockedURLs` with 128 curated patterns (Google/FB/Amazon/MS/Adobe ad+analytics, the major SaaS analytics + session-replay stacks, content-rec, supply-side ad networks, marketing automation). v0.10.1 added long-tail: AppsFlyer/Branch/Adjust, Cloudflare Web Analytics, Matomo Cloud, broader Outbrain (`amplify`/`log`) and PostHog (`/static/array.js`). Default on for launched browsers, off in attach mode. `opts.blockUrls` extends; `opts.blockAds: false` disables. Shrinks ARIA snapshots and speeds loads. v0.10.1: regression-tested across `switchTab()` in attach mode; one-time `console.warn` if Chromium lacks the CDP method. | Launched |
|
|
208
208
|
| iframe / OOPIF content (Stripe, reCAPTCHA, embedded forms) | v0.9.0 (H2): `Target.setAutoAttach({flatten:true})` registers a CDP session per iframe; `ariaTree()` walks `Page.getFrameTree`, fetches each frame's AX tree on the right session, splices children under iframe placeholders via `DOM.getFrameOwner`. Refs route via `{session, backendNodeId}` so clicks dispatch in the iframe's Input domain. `--site-per-process` launch flag forces every iframe — including same-origin — into OOPIF so coords work. | Both |
|
|
209
209
|
| Downloads | v0.9.0 (H7): `Browser.setDownloadBehavior({behavior:'allowAndName', downloadPath, eventsEnabled:true})` + listeners populate `page.downloads`. Files land at `savedPath` (under `--download-path` if supplied, else per-session `/tmp/barebrowse-dl-*`). | Headless + Headed (skipped in attach mode) |
|
|
210
|
-
| Profile locking | Unique temp dir per headless instance | Headless |
|
|
210
|
+
| Profile locking | Unique temp dir per headless instance. A launch that fails (start timeout, early exit, bad endpoint — both engines) SIGKILLs the browser's whole process group and removes that temp dir before rejecting | Headless |
|
|
211
211
|
| Shared memory crash (Linux) | `--disable-dev-shm-usage` flag prevents `/dev/shm` exhaustion | Headless |
|
|
212
212
|
| ARIA noise | 9-step pruning: wrapper collapse, noise removal, landmark promotion | Both |
|
|
213
213
|
|
|
@@ -246,7 +246,7 @@ Action tools (click, type, press, scroll, hover, goto, back, forward, reload, dr
|
|
|
246
246
|
|
|
247
247
|
## CLI session mode
|
|
248
248
|
|
|
249
|
-
For coding agents (Claude Code, Copilot, Cursor) and quick interactive testing. Commands output files to `.barebrowse/` -- agents read them with file tools, avoiding token waste in tool responses.
|
|
249
|
+
For coding agents (Claude Code, Copilot, Cursor) and quick interactive testing. Commands output files to `.barebrowse/` -- agents read them with file tools, avoiding token waste in tool responses. Output files older than 7 days are auto-removed at session start (CLI `open` and MCP startup); saved state files (`state-*.json`) are kept.
|
|
250
250
|
|
|
251
251
|
```bash
|
|
252
252
|
barebrowse open https://example.com # Start daemon + navigate
|
|
@@ -262,6 +262,7 @@ barebrowse pdf # → .barebrowse/page-<timestamp>.pdf
|
|
|
262
262
|
barebrowse wait-for --text="Success" # Wait for content to appear
|
|
263
263
|
barebrowse tabs # List open tabs
|
|
264
264
|
barebrowse save-state # → .barebrowse/state-<timestamp>.json
|
|
265
|
+
barebrowse switch-engine firefox # Swap chromium/firefox in place (page/tabs/refs reset; goto after; not with --port; cookies re-injected for open's URL only)
|
|
265
266
|
barebrowse close # Kill daemon + browser
|
|
266
267
|
```
|
|
267
268
|
|
|
@@ -293,7 +294,7 @@ barebrowse ships an MCP server for direct use with Claude Desktop, Cursor, or an
|
|
|
293
294
|
}
|
|
294
295
|
```
|
|
295
296
|
|
|
296
|
-
|
|
297
|
+
21 core tools: `browse` (one-shot), `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`, `capabilities` (engine + feature report, plus a `cookies` field naming the last goto's injected cookies — names only, never values), `switch_engine` (swap chromium/firefox without restarting; page, tabs and refs reset, so `goto` after). Plus `assess` (privacy scan) if `wearehere` is installed (`npm install wearehere`). Plus the **opt-in `eval` tool** gated by `BAREBROWSE_MCP_EVAL=1` (default OFF) — `Runtime.evaluate` in the user's authenticated session can read cookies/localStorage and hit any same-origin endpoint, so opt-in only.
|
|
297
298
|
|
|
298
299
|
**Idle release:** the MCP server closes its browser after `BAREBROWSE_IDLE_MINUTES` of no tool calls (default `15`; `0` = off; blank/invalid = default; capped at ~24.8 days; calls in flight postpone it). The next call opens a fresh browser — page state (open tabs, a solved captcha) is not resumed. Transient browser errors close the broken browser instead of orphaning it; a `wait_for` that merely times out keeps the page (its outer deadline is `max(60s, timeout+5s)`).
|
|
299
300
|
|
|
@@ -386,7 +387,7 @@ Useful for agent threshold decisions: "skip sites above score 40", "warn if term
|
|
|
386
387
|
|
|
387
388
|
9. **Screenshot returns base64.** Write to file with `fs.writeFileSync('shot.png', Buffer.from(base64, 'base64'))` or pass directly to a vision model.
|
|
388
389
|
|
|
389
|
-
10. **Two engines.** The default is CDP, which drives Chrome, Chromium, Edge, Brave, Vivaldi (~80% desktop share). Firefox is driven over WebDriver BiDi (CDP is deprecated there) — select it with `connect({ engine: 'firefox' })`, CLI `--engine firefox`, or MCP `BAREBROWSE_ENGINE=firefox`. Same `page.*` API on both; feature parity reached in v0.19.x, with the only remaining gap being `reload()` ignoring `ignoreCache` (upstream BiDi limitation).
|
|
390
|
+
10. **Two engines.** The default is CDP, which drives Chrome, Chromium, Edge, Brave, Vivaldi (~80% desktop share). Firefox is driven over WebDriver BiDi (CDP is deprecated there) — select it with `connect({ engine: 'firefox' })`, CLI `--engine firefox`, or MCP `BAREBROWSE_ENGINE=firefox`. Same `page.*` API on both; feature parity reached in v0.19.x, with the only remaining gap being `reload()` ignoring `ignoreCache` (upstream BiDi limitation). The engine is chosen at launch and can be swapped at runtime via MCP `switch_engine` or CLI `switch-engine <chromium|firefox>` (page, tabs and refs reset, so call `goto` after; not available in attach mode). See the `engine` connect() option below for the full parity timeline.
|
|
390
391
|
|
|
391
392
|
11. **`--site-per-process` is on by default (v0.9.0).** Required for iframe support — without it, same-origin iframes stay in the parent process and `Input.dispatchMouseEvent` coords don't match `DOM.getBoxModel` coords for iframe-internal elements. Memory cost: +50-150MB per cross-origin frame. Real Chrome does this for cross-origin by default; we just extend it to all iframes. If you attach via `connect({port})`, the user's browser is whatever they launched it as — for iframe interaction reliability, start it with `--site-per-process` too.
|
|
392
393
|
|
package/cli.js
CHANGED
|
@@ -88,6 +88,8 @@ if (args.includes('--daemon-internal')) {
|
|
|
88
88
|
await cmdProxy('save-state');
|
|
89
89
|
} else if (cmd === 'dialog-log') {
|
|
90
90
|
await cmdProxy('dialog-log');
|
|
91
|
+
} else if (cmd === 'switch-engine' && args[1]) {
|
|
92
|
+
await cmdProxy('switch-engine', { engine: args[1] });
|
|
91
93
|
} else {
|
|
92
94
|
printUsage();
|
|
93
95
|
}
|
|
@@ -613,6 +615,7 @@ Debugging:
|
|
|
613
615
|
barebrowse dialog-log JS dialog log -> .barebrowse/dialogs-*.json
|
|
614
616
|
barebrowse downloads List Content-Disposition downloads + savedPath (JSON)
|
|
615
617
|
barebrowse save-state Cookies + localStorage -> .barebrowse/state-*.json
|
|
618
|
+
barebrowse switch-engine <chromium|firefox> Swap the browser in place (page, tabs, refs are lost)
|
|
616
619
|
|
|
617
620
|
One-shot:
|
|
618
621
|
barebrowse browse <url> [mode] Browse + print snapshot to stdout
|
package/mcp-server.js
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
|
|
13
13
|
import { browse, connect } from './src/index.js';
|
|
14
14
|
import { formatReadable } from './src/readable.js';
|
|
15
|
+
import { cleanOld } from './src/output-clean.js';
|
|
16
|
+
import { scopedCookiesForUrl } from './src/auth.js';
|
|
15
17
|
import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
|
16
18
|
import { join, dirname } from 'node:path';
|
|
17
19
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
@@ -119,6 +121,22 @@ export function saveSnapshot(text, { prefix = 'page', ext = 'yml' } = {}) {
|
|
|
119
121
|
|
|
120
122
|
let _page = null;
|
|
121
123
|
let _pageConnecting = null;
|
|
124
|
+
// Active engine: starts from BAREBROWSE_ENGINE, changed at runtime by switch_engine.
|
|
125
|
+
let _engine = process.env.BAREBROWSE_ENGINE === 'firefox' ? 'firefox' : 'chromium';
|
|
126
|
+
// Last goto's cookie injection (names/domains/paths only, never values), so an
|
|
127
|
+
// agent can tell "logged out" from "no cookie found" from "the read failed".
|
|
128
|
+
let _lastCookies = null;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Shape the capabilities `cookies` field. Takes cookie objects but copies only
|
|
132
|
+
* name, domain and path, so a value can never leak into the report.
|
|
133
|
+
*/
|
|
134
|
+
export function cookieReport(url, { cookies = [], error, incognito } = {}) {
|
|
135
|
+
if (incognito) return { url, injected: 0, incognito: true };
|
|
136
|
+
const r = { url, injected: cookies.length, cookies: cookies.map((c) => `${c.name} @ ${c.domain}${c.path}`) };
|
|
137
|
+
if (error) r.error = error;
|
|
138
|
+
return r;
|
|
139
|
+
}
|
|
122
140
|
|
|
123
141
|
/**
|
|
124
142
|
* Forget the current session AND close its browser. A bare `_page = null`
|
|
@@ -128,9 +146,13 @@ let _pageConnecting = null;
|
|
|
128
146
|
function resetPage() {
|
|
129
147
|
const p = _page;
|
|
130
148
|
_page = null;
|
|
149
|
+
_lastCookies = null;
|
|
131
150
|
if (p) p.close().catch(() => {});
|
|
132
151
|
}
|
|
133
152
|
|
|
153
|
+
// setTimeout's max delay; larger values overflow and fire after ~1ms.
|
|
154
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
155
|
+
|
|
134
156
|
// Idle TTL: a server can outlive its conversation by days, holding a browser
|
|
135
157
|
// (GBs) the whole time. After BAREBROWSE_IDLE_MINUTES (default 15, 0 = off)
|
|
136
158
|
// with no tools/call in flight, release it; the next call opens a fresh one.
|
|
@@ -142,7 +164,13 @@ function resetPage() {
|
|
|
142
164
|
* the page.
|
|
143
165
|
*/
|
|
144
166
|
export function waitForDeadline(timeout) {
|
|
145
|
-
return Math.max(TIMEOUTS.wait_for, (timeout
|
|
167
|
+
return Math.min(Math.max(TIMEOUTS.wait_for, waitTimeout(timeout) + 5000), MAX_TIMER_MS);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** wait_for's requested wait in ms. MCP doesn't enforce schema types, so "abc" must not become NaN. */
|
|
171
|
+
export function waitTimeout(timeout) {
|
|
172
|
+
const n = Number(timeout);
|
|
173
|
+
return Number.isFinite(n) && n > 0 ? n : 30000;
|
|
146
174
|
}
|
|
147
175
|
|
|
148
176
|
export function idleMs(raw) {
|
|
@@ -150,7 +178,7 @@ export function idleMs(raw) {
|
|
|
150
178
|
if (raw === undefined || String(raw).trim() === '') return DEFAULT;
|
|
151
179
|
const n = Number(raw);
|
|
152
180
|
if (!Number.isFinite(n) || n < 0) return DEFAULT;
|
|
153
|
-
return Math.min(n * 60_000,
|
|
181
|
+
return Math.min(n * 60_000, MAX_TIMER_MS);
|
|
154
182
|
}
|
|
155
183
|
const IDLE_MS = idleMs(process.env.BAREBROWSE_IDLE_MINUTES);
|
|
156
184
|
let _inflight = 0;
|
|
@@ -164,16 +192,16 @@ function armIdle() {
|
|
|
164
192
|
}
|
|
165
193
|
|
|
166
194
|
/**
|
|
167
|
-
* The engine + mode this server is
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
195
|
+
* The engine + mode this server is using, WITHOUT launching a browser. Both
|
|
196
|
+
* engines ship in the library; the starting engine is BAREBROWSE_ENGINE and the
|
|
197
|
+
* `switch_engine` tool changes it at runtime (one browser is connected and
|
|
198
|
+
* reused across tool calls; a switch replaces it). Surfaced to the
|
|
171
199
|
* agent via `initialize.instructions`, the `capabilities` tool, and the `browse`
|
|
172
200
|
* tool description so the Firefox engine is discoverable — it was invisible
|
|
173
201
|
* before, and a session concluded (wrongly) that only Chromium was supported.
|
|
174
202
|
*/
|
|
175
203
|
function engineInfo() {
|
|
176
|
-
const engine =
|
|
204
|
+
const engine = _engine;
|
|
177
205
|
const mode = process.env.BAREBROWSE_MODE || 'hybrid';
|
|
178
206
|
const incognito = process.env.BAREBROWSE_INCOGNITO === '1';
|
|
179
207
|
return {
|
|
@@ -181,10 +209,10 @@ function engineInfo() {
|
|
|
181
209
|
mode,
|
|
182
210
|
incognito,
|
|
183
211
|
availableEngines: ['chromium', 'firefox'],
|
|
184
|
-
//
|
|
212
|
+
// BAREBROWSE_ENGINE only sets the starting engine; the agent can switch.
|
|
185
213
|
switchEngine:
|
|
186
|
-
|
|
187
|
-
+
|
|
214
|
+
'To use the other engine, call the "switch_engine" tool (the page, tabs and refs are lost; '
|
|
215
|
+
+ 'takes a few seconds). BAREBROWSE_ENGINE sets the starting engine.',
|
|
188
216
|
};
|
|
189
217
|
}
|
|
190
218
|
|
|
@@ -201,7 +229,7 @@ async function getPage() {
|
|
|
201
229
|
// across tool calls, so it's an env var (BAREBROWSE_INCOGNITO=1), not a
|
|
202
230
|
// per-request flag. Skips all auth injection for a clean, logged-out session.
|
|
203
231
|
const incognito = process.env.BAREBROWSE_INCOGNITO === '1';
|
|
204
|
-
const connectOpts =
|
|
232
|
+
const connectOpts = _engine === 'firefox'
|
|
205
233
|
? { engine: 'firefox', mode: process.env.BAREBROWSE_MODE || 'hybrid', incognito }
|
|
206
234
|
: { mode: process.env.BAREBROWSE_MODE || 'hybrid', incognito };
|
|
207
235
|
_pageConnecting = connect(connectOpts);
|
|
@@ -433,9 +461,20 @@ export const TOOLS = [
|
|
|
433
461
|
required: ['ref'],
|
|
434
462
|
},
|
|
435
463
|
},
|
|
464
|
+
{
|
|
465
|
+
name: 'switch_engine',
|
|
466
|
+
description: 'Switch the browser engine (chromium or firefox) without restarting the MCP server. LOSES all in-session state: the current page, tabs, refs, and any logins or form state made inside the session. Logins from your real browser are re-injected on the next goto. Costs a few seconds (about 2s to chromium, 4-5s to firefox) as the new browser launches on your next call. After switching, call goto. Same engine as the active one is a no-op.',
|
|
467
|
+
inputSchema: {
|
|
468
|
+
type: 'object',
|
|
469
|
+
properties: {
|
|
470
|
+
engine: { type: 'string', enum: ['chromium', 'firefox'], description: 'Engine to switch to' },
|
|
471
|
+
},
|
|
472
|
+
required: ['engine'],
|
|
473
|
+
},
|
|
474
|
+
},
|
|
436
475
|
{
|
|
437
476
|
name: 'capabilities',
|
|
438
|
-
description: 'Report which browser engine this session drives (chromium or firefox) and what it can do — no navigation, no side effects. Use it to answer "can this drive Firefox?" or "is this an authenticated session?". Returns the active engine + mode, that both engines are supported, how to switch (
|
|
477
|
+
description: 'Report which browser engine this session drives (chromium or firefox) and what it can do — no navigation, no side effects. Use it to answer "can this drive Firefox?" or "is this an authenticated session?". Returns the active engine + mode, that both engines are supported, how to switch (the switch_engine tool), and, if a page is already open, its live capability flags. Also returns `cookies`: the cookie injection of the last goto as { url, injected, cookies: ["name @ domain/path", ...], error? } (names, domains and paths only, never values; { url, injected: 0, incognito: true } under incognito; null before any goto or after the browser is released). Use it to tell "logged out" from "no cookie found" from "the cookie read failed".',
|
|
439
478
|
inputSchema: { type: 'object', properties: {} },
|
|
440
479
|
},
|
|
441
480
|
];
|
|
@@ -488,8 +527,20 @@ async function handleToolCall(name, args) {
|
|
|
488
527
|
info.connected = false;
|
|
489
528
|
info.capabilities = null; // populated on first navigation
|
|
490
529
|
}
|
|
530
|
+
info.cookies = _lastCookies; // null until a goto
|
|
491
531
|
return info;
|
|
492
532
|
}
|
|
533
|
+
case 'switch_engine': {
|
|
534
|
+
const target = args.engine;
|
|
535
|
+
if (target !== 'chromium' && target !== 'firefox') throw new Error('engine must be "chromium" or "firefox"');
|
|
536
|
+
if (target === _engine) return `already on ${target}; nothing changed`;
|
|
537
|
+
// A launch in progress would land as _page with the old engine after the
|
|
538
|
+
// switch. Let it finish (its outcome is irrelevant), then close it.
|
|
539
|
+
if (_pageConnecting) await _pageConnecting.catch(() => {});
|
|
540
|
+
resetPage();
|
|
541
|
+
_engine = target;
|
|
542
|
+
return `switched to ${target} — the previous page, tabs and refs are gone; call goto`;
|
|
543
|
+
}
|
|
493
544
|
case 'browse': {
|
|
494
545
|
let timer;
|
|
495
546
|
const text = await Promise.race([
|
|
@@ -506,7 +557,15 @@ async function handleToolCall(name, args) {
|
|
|
506
557
|
}
|
|
507
558
|
case 'goto': return withRetry(async () => {
|
|
508
559
|
const page = await getPage();
|
|
509
|
-
|
|
560
|
+
if (process.env.BAREBROWSE_INCOGNITO === '1') {
|
|
561
|
+
_lastCookies = cookieReport(args.url, { incognito: true });
|
|
562
|
+
} else {
|
|
563
|
+
let cookies = [];
|
|
564
|
+
let error;
|
|
565
|
+
try { cookies = scopedCookiesForUrl(args.url); } catch (e) { error = e.message; }
|
|
566
|
+
try { await page.injectCookies(args.url); } catch (e) { error ??= e.message; }
|
|
567
|
+
_lastCookies = cookieReport(args.url, { cookies, error });
|
|
568
|
+
}
|
|
510
569
|
await page.goto(args.url);
|
|
511
570
|
return 'ok';
|
|
512
571
|
}, TIMEOUTS.goto);
|
|
@@ -601,7 +660,7 @@ async function handleToolCall(name, args) {
|
|
|
601
660
|
}, TIMEOUTS.screenshot);
|
|
602
661
|
case 'wait_for': return withRetry(async () => {
|
|
603
662
|
const page = await getPage();
|
|
604
|
-
await page.waitFor({ text: args.text, selector: args.selector, timeout: args.timeout });
|
|
663
|
+
await page.waitFor({ text: args.text, selector: args.selector, timeout: waitTimeout(args.timeout) });
|
|
605
664
|
return 'ok';
|
|
606
665
|
}, waitForDeadline(args.timeout), { retry: false });
|
|
607
666
|
case 'tabs': return withRetry(async () => {
|
|
@@ -771,6 +830,7 @@ async function handleMessage(msg) {
|
|
|
771
830
|
// runStdio() explicitly. Tests import TIMEOUTS/TOOLS without calling it.
|
|
772
831
|
|
|
773
832
|
export function runStdio() {
|
|
833
|
+
cleanOld(OUTPUT_DIR);
|
|
774
834
|
// One-line startup banner to stderr (stderr because stdout is the JSON-RPC
|
|
775
835
|
// channel — must not contain non-JSON-RPC bytes). Captured by Claude Code's
|
|
776
836
|
// MCP log, makes "I added barebrowse twice and got the wrong one" issues
|
package/package.json
CHANGED
package/src/auth.js
CHANGED
|
@@ -181,14 +181,16 @@ function extractChromiumCookies(dbPath, domain) {
|
|
|
181
181
|
* @param {string} [domain] - Filter by domain
|
|
182
182
|
* @returns {Array<object>} Cookies in CDP Network.setCookie format
|
|
183
183
|
*/
|
|
184
|
-
function extractFirefoxCookies(dbPath, domain) {
|
|
184
|
+
export function extractFirefoxCookies(dbPath, domain) {
|
|
185
185
|
const db = new DatabaseSync(`file://${dbPath}?immutable=1`, { readOnly: true });
|
|
186
186
|
|
|
187
|
+
// Partitioned (CHIPS) cookies carry partitionKey in originAttributes and can
|
|
188
|
+
// share name+domain+path with the top-level cookie; inject only top-level ones.
|
|
187
189
|
let sql = `SELECT host, name, value, path, expiry, isSecure, isHttpOnly, sameSite
|
|
188
|
-
FROM moz_cookies`;
|
|
190
|
+
FROM moz_cookies WHERE originAttributes NOT LIKE '%partitionKey=%'`;
|
|
189
191
|
const params = [];
|
|
190
192
|
if (domain) {
|
|
191
|
-
sql += `
|
|
193
|
+
sql += ` AND host LIKE ?`;
|
|
192
194
|
params.push(`%${domain}%`);
|
|
193
195
|
}
|
|
194
196
|
|
|
@@ -235,19 +237,27 @@ export function extractCookies(opts = {}) {
|
|
|
235
237
|
return extractChromiumCookies(path, domain);
|
|
236
238
|
}
|
|
237
239
|
|
|
238
|
-
// Auto: try all browsers, merge (last-write-wins by name+domain)
|
|
239
|
-
const all = new Map();
|
|
240
|
+
// Auto: try all browsers, merge (last-write-wins by name+domain+path)
|
|
240
241
|
const chromium = findChromiumCookieDb();
|
|
241
|
-
if (chromium) {
|
|
242
|
-
for (const c of extractChromiumCookies(chromium.path, domain))
|
|
243
|
-
all.set(`${c.name}@${c.domain}`, c);
|
|
244
|
-
}
|
|
245
242
|
const firefox = findFirefoxCookieDb();
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
if (
|
|
243
|
+
const lists = [];
|
|
244
|
+
if (chromium) lists.push(extractChromiumCookies(chromium.path, domain));
|
|
245
|
+
if (firefox) lists.push(extractFirefoxCookies(firefox, domain));
|
|
246
|
+
const merged = mergeCookies(lists);
|
|
247
|
+
if (merged.length === 0) throw new Error('No browser cookie database found');
|
|
248
|
+
return merged;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Merge cookie lists; a later list wins on an identical cookie. Identity is
|
|
253
|
+
* name + domain + path (RFC 6265): the same name on two paths are two cookies.
|
|
254
|
+
* @param {Array<Array<object>>} lists
|
|
255
|
+
* @returns {Array<object>}
|
|
256
|
+
*/
|
|
257
|
+
export function mergeCookies(lists) {
|
|
258
|
+
const all = new Map();
|
|
259
|
+
for (const list of lists)
|
|
260
|
+
for (const c of list) all.set(`${c.name}@${c.domain}${c.path}`, c);
|
|
251
261
|
return [...all.values()];
|
|
252
262
|
}
|
|
253
263
|
|
package/src/chromium.js
CHANGED
|
@@ -181,38 +181,47 @@ export async function launch(opts = {}) {
|
|
|
181
181
|
detached: true,
|
|
182
182
|
});
|
|
183
183
|
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
184
|
+
// Not in activeBrowsers yet, so nothing else would reap it: any failure
|
|
185
|
+
// before registration (start timeout, spawn error, early exit, bad URL)
|
|
186
|
+
// must kill the process group and remove the profile dir itself.
|
|
187
|
+
let wsUrl, actualPort;
|
|
188
|
+
try {
|
|
189
|
+
// Parse the WebSocket URL from stderr
|
|
190
|
+
// Chrome prints: "DevTools listening on ws://127.0.0.1:PORT/devtools/browser/UUID"
|
|
191
|
+
wsUrl = await new Promise((resolve, reject) => {
|
|
192
|
+
let stderr = '';
|
|
193
|
+
const timeout = setTimeout(() => {
|
|
194
|
+
reject(new Error(`Browser failed to start within 10s. stderr: ${stderr}`));
|
|
195
|
+
}, 10000);
|
|
191
196
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
197
|
+
child.stderr.on('data', (chunk) => {
|
|
198
|
+
stderr += chunk.toString();
|
|
199
|
+
const match = stderr.match(/ws:\/\/[^\s]+/);
|
|
200
|
+
if (match) {
|
|
201
|
+
clearTimeout(timeout);
|
|
202
|
+
resolve(match[0]);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
200
205
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
206
|
+
child.on('error', (err) => {
|
|
207
|
+
clearTimeout(timeout);
|
|
208
|
+
reject(new Error(`Failed to launch browser: ${err.message}`));
|
|
209
|
+
});
|
|
205
210
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
+
child.on('exit', (code) => {
|
|
212
|
+
clearTimeout(timeout);
|
|
213
|
+
if (!stderr.includes('ws://')) {
|
|
214
|
+
reject(new Error(`Browser exited with code ${code}. stderr: ${stderr}`));
|
|
215
|
+
}
|
|
216
|
+
});
|
|
211
217
|
});
|
|
212
|
-
});
|
|
213
218
|
|
|
214
|
-
|
|
215
|
-
|
|
219
|
+
// Extract port from wsUrl
|
|
220
|
+
actualPort = parseInt(new URL(wsUrl).port, 10);
|
|
221
|
+
} catch (err) {
|
|
222
|
+
await cleanupBrowser({ process: child, ownedProfileDir });
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
216
225
|
|
|
217
226
|
const browser = { wsUrl, process: child, port: actualPort, ownedProfileDir };
|
|
218
227
|
|
|
@@ -243,12 +252,14 @@ export async function cleanupBrowser(browser) {
|
|
|
243
252
|
});
|
|
244
253
|
try { browser.process.kill(); } catch {}
|
|
245
254
|
await exited;
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
255
|
+
}
|
|
256
|
+
// SIGKILL the whole Chromium process group — unconditionally, even if the
|
|
257
|
+
// parent already exited or was already signalled: renderer/GPU/network
|
|
258
|
+
// children (separate processes under --site-per-process) can outlive it,
|
|
259
|
+
// and they hold profile-dir file handles. Because launch() spawned with
|
|
260
|
+
// detached:true, the children share Chromium's pgid (not Node's), so a
|
|
261
|
+
// negative PID reaps the whole group without touching anything else.
|
|
262
|
+
if (browser.process?.pid != null) {
|
|
252
263
|
try { process.kill(-browser.process.pid, 'SIGKILL'); } catch {
|
|
253
264
|
// ESRCH = group already gone; anything else is best-effort here.
|
|
254
265
|
}
|
package/src/daemon.js
CHANGED
|
@@ -12,6 +12,7 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
|
12
12
|
import { join, resolve } from 'node:path';
|
|
13
13
|
import { connect } from './index.js';
|
|
14
14
|
import { formatReadable } from './readable.js';
|
|
15
|
+
import { cleanOld } from './output-clean.js';
|
|
15
16
|
|
|
16
17
|
/** Owner-only file write helper — daemon artifacts can hold authenticated content. */
|
|
17
18
|
function writeFilePrivate(path, data) {
|
|
@@ -210,6 +211,7 @@ export async function startDaemon(opts, outputDir, initialUrl) {
|
|
|
210
211
|
export async function runDaemon(opts, outputDir, initialUrl) {
|
|
211
212
|
const absDir = resolve(outputDir);
|
|
212
213
|
mkdirSync(absDir, { recursive: true, mode: 0o700 });
|
|
214
|
+
cleanOld(absDir);
|
|
213
215
|
|
|
214
216
|
// Per-session auth token. The daemon binds to loopback, but loopback is
|
|
215
217
|
// shared across local users — without a token any local user/process could
|
|
@@ -217,9 +219,10 @@ export async function runDaemon(opts, outputDir, initialUrl) {
|
|
|
217
219
|
// token is written into session.json (mode 0600) so only the owner reads it.
|
|
218
220
|
const authToken = randomBytes(32).toString('hex');
|
|
219
221
|
|
|
220
|
-
// Connect to browser
|
|
221
|
-
|
|
222
|
-
|
|
222
|
+
// Connect to browser. Engine is a parameter so `switch-engine` can reuse the
|
|
223
|
+
// exact same open options with a different one.
|
|
224
|
+
const connectPage = (engine) => connect({
|
|
225
|
+
engine,
|
|
223
226
|
mode: opts.mode || 'headless',
|
|
224
227
|
port: opts.port ? Number(opts.port) : undefined,
|
|
225
228
|
consent: opts.consent,
|
|
@@ -235,6 +238,7 @@ export async function runDaemon(opts, outputDir, initialUrl) {
|
|
|
235
238
|
// is the legacy per-open equivalent. Either yields a logged-out session.
|
|
236
239
|
incognito: opts.incognito || opts.cookies === false,
|
|
237
240
|
});
|
|
241
|
+
let page = await connectPage(opts.engine);
|
|
238
242
|
|
|
239
243
|
// Console + network log capture. CDP uses Runtime/Network events off
|
|
240
244
|
// page.cdp; the Firefox/BiDi engine (page.bidi) captures the same shape over
|
|
@@ -244,52 +248,56 @@ export async function runDaemon(opts, outputDir, initialUrl) {
|
|
|
244
248
|
const networkLogs = [];
|
|
245
249
|
const pendingRequests = new Map();
|
|
246
250
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
page.cdp
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
251
|
+
// Wire capture onto a page; called again for the new page after a switch.
|
|
252
|
+
async function attachCapture(page) {
|
|
253
|
+
if (page.cdp) {
|
|
254
|
+
await page.cdp.send('Runtime.enable');
|
|
255
|
+
page.cdp.on('Runtime.consoleAPICalled', (params) => {
|
|
256
|
+
consoleLogs.push({
|
|
257
|
+
type: params.type,
|
|
258
|
+
timestamp: new Date().toISOString(),
|
|
259
|
+
args: params.args.map((a) => a.value ?? a.description ?? a.type),
|
|
260
|
+
});
|
|
254
261
|
});
|
|
255
|
-
});
|
|
256
262
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
+
// Network log capture (Network.enable already called by connect)
|
|
264
|
+
page.cdp.on('Network.requestWillBeSent', (params) => {
|
|
265
|
+
pendingRequests.set(params.requestId, {
|
|
266
|
+
url: params.request.url,
|
|
267
|
+
method: params.request.method,
|
|
268
|
+
timestamp: new Date().toISOString(),
|
|
269
|
+
});
|
|
263
270
|
});
|
|
264
|
-
});
|
|
265
271
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
272
|
+
page.cdp.on('Network.responseReceived', (params) => {
|
|
273
|
+
const req = pendingRequests.get(params.requestId);
|
|
274
|
+
if (req) {
|
|
275
|
+
networkLogs.push({
|
|
276
|
+
...req,
|
|
277
|
+
status: params.response.status,
|
|
278
|
+
statusText: params.response.statusText,
|
|
279
|
+
mimeType: params.response.mimeType,
|
|
280
|
+
});
|
|
281
|
+
pendingRequests.delete(params.requestId);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
278
284
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
285
|
+
page.cdp.on('Network.loadingFailed', (params) => {
|
|
286
|
+
const req = pendingRequests.get(params.requestId);
|
|
287
|
+
if (req) {
|
|
288
|
+
networkLogs.push({
|
|
289
|
+
...req,
|
|
290
|
+
status: 0,
|
|
291
|
+
error: params.errorText,
|
|
292
|
+
});
|
|
293
|
+
pendingRequests.delete(params.requestId);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
} else if (page.bidi) {
|
|
297
|
+
await attachBiDiCapture(page.bidi, { consoleLogs, networkLogs, pendingRequests });
|
|
298
|
+
}
|
|
292
299
|
}
|
|
300
|
+
await attachCapture(page);
|
|
293
301
|
|
|
294
302
|
// Navigate to initial URL if provided
|
|
295
303
|
if (initialUrl) {
|
|
@@ -503,6 +511,34 @@ export async function runDaemon(opts, outputDir, initialUrl) {
|
|
|
503
511
|
return { ok: true, file, count: logs.length };
|
|
504
512
|
},
|
|
505
513
|
|
|
514
|
+
async 'switch-engine'({ engine }) {
|
|
515
|
+
if (engine !== 'chromium' && engine !== 'firefox') {
|
|
516
|
+
return { ok: false, error: 'engine must be "chromium" or "firefox"' };
|
|
517
|
+
}
|
|
518
|
+
if (engine === page.engine) return { ok: true, value: `already on ${engine}; nothing changed` };
|
|
519
|
+
if (opts.port) return { ok: false, error: 'cannot switch engines on an attached browser (--port)' };
|
|
520
|
+
// Connect the new browser first: if it fails to launch, the old page
|
|
521
|
+
// keeps serving. Only then retire the old one.
|
|
522
|
+
const next = await connectPage(engine);
|
|
523
|
+
try {
|
|
524
|
+
await attachCapture(next);
|
|
525
|
+
if (initialUrl && opts.cookies !== false) {
|
|
526
|
+
try { await next.injectCookies(initialUrl, { browser: opts.browser }); } catch { /* no cookies */ }
|
|
527
|
+
}
|
|
528
|
+
} catch (err) {
|
|
529
|
+
await next.close().catch(() => {});
|
|
530
|
+
throw err;
|
|
531
|
+
}
|
|
532
|
+
const old = page;
|
|
533
|
+
page = next;
|
|
534
|
+
consoleLogs.length = 0;
|
|
535
|
+
networkLogs.length = 0;
|
|
536
|
+
pendingRequests.clear();
|
|
537
|
+
await old.close().catch(() => {});
|
|
538
|
+
writeSession();
|
|
539
|
+
return { ok: true, value: `switched to ${engine} — the previous page, tabs and refs are gone; run goto` };
|
|
540
|
+
},
|
|
541
|
+
|
|
506
542
|
async close() {
|
|
507
543
|
await page.close();
|
|
508
544
|
// Clean up session file
|
|
@@ -605,16 +641,19 @@ export async function runDaemon(opts, outputDir, initialUrl) {
|
|
|
605
641
|
// Write session.json so parent/clients can find us. Owner-only: it carries
|
|
606
642
|
// the auth token that gates /command.
|
|
607
643
|
const sessionPath = join(absDir, SESSION_FILE);
|
|
608
|
-
|
|
644
|
+
const startedAt = new Date().toISOString();
|
|
645
|
+
// Rewritten by switch-engine so status/doctor see the live engine.
|
|
646
|
+
const writeSession = () => writeFilePrivate(sessionPath, JSON.stringify({
|
|
609
647
|
port,
|
|
610
648
|
pid: process.pid,
|
|
611
649
|
token: authToken,
|
|
612
|
-
startedAt
|
|
650
|
+
startedAt,
|
|
613
651
|
// Persisted so `status`/`doctor` can report the live engine + feature set
|
|
614
652
|
// without an HTTP round-trip (page.engine/capabilities, added in v0.21.0).
|
|
615
653
|
engine: page.engine,
|
|
616
654
|
capabilities: page.capabilities,
|
|
617
655
|
}));
|
|
656
|
+
writeSession();
|
|
618
657
|
|
|
619
658
|
// Handle SIGTERM gracefully
|
|
620
659
|
process.on('SIGTERM', async () => {
|
package/src/firefox-page.js
CHANGED
|
@@ -25,6 +25,7 @@ import { dismissConsentFirefox } from './consent-firefox.js';
|
|
|
25
25
|
import { waitForNetworkIdleBiDi } from './network-idle.js';
|
|
26
26
|
import { decideDialog, dialogLogEntry } from './dialog.js';
|
|
27
27
|
import { isChallengePage, countNodes } from './challenge.js';
|
|
28
|
+
import { withTimeout } from './with-timeout.js';
|
|
28
29
|
|
|
29
30
|
/** BiDi/WebDriver normalized key values for named keys (U+E000 block). */
|
|
30
31
|
const BIDI_KEYS = {
|
|
@@ -174,17 +175,6 @@ export async function createFirefoxPage(bidi, opts = {}) {
|
|
|
174
175
|
});
|
|
175
176
|
}
|
|
176
177
|
|
|
177
|
-
/**
|
|
178
|
-
* Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
|
|
179
|
-
* timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
|
|
180
|
-
* (a page that never loads) would otherwise hang the call forever.
|
|
181
|
-
*/
|
|
182
|
-
function withTimeout(p, ms, label) {
|
|
183
|
-
let timer;
|
|
184
|
-
const t = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms); });
|
|
185
|
-
return Promise.race([p, t]).finally(() => clearTimeout(timer));
|
|
186
|
-
}
|
|
187
|
-
|
|
188
178
|
// Download tracking, parity with the CDP `page.downloads` array. Firefox
|
|
189
179
|
// downloads land in `downloadDir` (a throwaway dir the caller sets via launch
|
|
190
180
|
// prefs — see connectFirefox / firefox.js), so `savedPath` is a real path the
|
package/src/firefox.js
CHANGED
|
@@ -169,25 +169,33 @@ export async function launchFirefox(opts = {}) {
|
|
|
169
169
|
// detached:true → own process group, so cleanup can signal the whole tree.
|
|
170
170
|
const child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
|
171
171
|
|
|
172
|
-
//
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
172
|
+
// Not in activeBrowsers yet, so nothing else would reap it: any failure
|
|
173
|
+
// before registration must kill the process group and remove the profile.
|
|
174
|
+
let wsUrl, actualPort;
|
|
175
|
+
try {
|
|
176
|
+
// Firefox prints the BiDi endpoint to stderr. Wait for it (or die trying).
|
|
177
|
+
wsUrl = await new Promise((resolve, reject) => {
|
|
178
|
+
let buf = '';
|
|
179
|
+
const timeout = setTimeout(() => reject(new Error(`Firefox BiDi did not start within 20s. stderr: ${buf}`)), 20000);
|
|
180
|
+
const scan = (chunk) => {
|
|
181
|
+
buf += chunk.toString();
|
|
182
|
+
const m = buf.match(/WebDriver BiDi listening on (ws:\/\/\S+)/);
|
|
183
|
+
if (m) { clearTimeout(timeout); resolve(m[1].replace(/\/?$/, '') + '/session'); }
|
|
184
|
+
};
|
|
185
|
+
child.stderr.on('data', scan);
|
|
186
|
+
child.stdout.on('data', scan);
|
|
187
|
+
child.on('error', (err) => { clearTimeout(timeout); reject(new Error(`Failed to launch Firefox: ${err.message}`)); });
|
|
188
|
+
child.on('exit', (code) => {
|
|
189
|
+
clearTimeout(timeout);
|
|
190
|
+
if (!buf.includes('WebDriver BiDi')) reject(new Error(`Firefox exited with code ${code}. stderr: ${buf}`));
|
|
191
|
+
});
|
|
187
192
|
});
|
|
188
|
-
});
|
|
189
193
|
|
|
190
|
-
|
|
194
|
+
actualPort = parseInt(new URL(wsUrl.replace('/session', '')).port, 10);
|
|
195
|
+
} catch (err) {
|
|
196
|
+
await cleanupFirefox({ process: child, ownedProfileDir: profileDir });
|
|
197
|
+
throw err;
|
|
198
|
+
}
|
|
191
199
|
const browser = { wsUrl, process: child, port: actualPort, ownedProfileDir: profileDir };
|
|
192
200
|
|
|
193
201
|
registerExitHandlers();
|
package/src/index.js
CHANGED
|
@@ -25,6 +25,7 @@ import { resolveBlocklistPatterns } from './blocklist.js';
|
|
|
25
25
|
import { waitForNetworkIdle } from './network-idle.js';
|
|
26
26
|
import { decideDialog, dialogLogEntry } from './dialog.js';
|
|
27
27
|
import { isChallengePage } from './challenge.js';
|
|
28
|
+
import { withTimeout } from './with-timeout.js';
|
|
28
29
|
import { readable as extractReadable } from './readable.js';
|
|
29
30
|
import { assertNavigable, assertUploadAllowed } from './url-guard.js';
|
|
30
31
|
import { join as pathJoin } from 'node:path';
|
|
@@ -811,13 +812,7 @@ export async function connect(opts = {}) {
|
|
|
811
812
|
async close() {
|
|
812
813
|
// Polite tab close is best-effort and bounded: a dead or hung browser
|
|
813
814
|
// must not skip the hard cleanup below (the profile dir / process leak).
|
|
814
|
-
|
|
815
|
-
try {
|
|
816
|
-
await Promise.race([
|
|
817
|
-
cdp.send('Target.closeTarget', { targetId: page.targetId }),
|
|
818
|
-
new Promise((r) => { timer = setTimeout(r, 2500); }),
|
|
819
|
-
]);
|
|
820
|
-
} catch {} finally { clearTimeout(timer); }
|
|
815
|
+
try { await withTimeout(cdp.send('Target.closeTarget', { targetId: page.targetId }), 2500, 'close'); } catch {}
|
|
821
816
|
try { cdp.close(); } catch {}
|
|
822
817
|
try {
|
|
823
818
|
await cleanupBrowser(browser); // no-op in attach mode (process: null)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* output-clean.js -- Age-based cleanup of barebrowse's own output files.
|
|
3
|
+
*
|
|
4
|
+
* Matches only `<prefix>-<timestamp>.<ext>` files barebrowse itself writes.
|
|
5
|
+
* session.json, state-*.json (deliberate saved logins) and any other file are never touched.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readdirSync, statSync, unlinkSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
|
|
11
|
+
// toISOString() with [:.] -> '-': YYYY-MM-DDTHH-MM-SS-mmmZ. Exact, so a user's own
|
|
12
|
+
// `screenshot-2026-01-01.png` in a shared --output-dir is never matched.
|
|
13
|
+
const STAMP = '\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z';
|
|
14
|
+
const OURS = new RegExp(
|
|
15
|
+
`^(?:page-${STAMP}\\.(?:yml|pdf)|screenshot-${STAMP}\\.(?:png|jpeg|webp)|article-${STAMP}\\.txt|(?:console|network|dialogs)-${STAMP}\\.json)$`,
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Delete barebrowse output files older than `days` in `dir` (non-recursive).
|
|
20
|
+
* Never throws; a missing dir or any per-file error is ignored.
|
|
21
|
+
* @param {string} dir
|
|
22
|
+
* @param {number} [days]
|
|
23
|
+
* @param {number} [now] - epoch ms, injectable for tests
|
|
24
|
+
*/
|
|
25
|
+
export function cleanOld(dir, days = 7, now = Date.now()) {
|
|
26
|
+
try {
|
|
27
|
+
const cutoff = now - days * 86400000;
|
|
28
|
+
for (const name of readdirSync(dir)) {
|
|
29
|
+
if (!OURS.test(name)) continue;
|
|
30
|
+
try {
|
|
31
|
+
const path = join(dir, name);
|
|
32
|
+
const st = statSync(path);
|
|
33
|
+
if (st.isFile() && st.mtimeMs < cutoff) unlinkSync(path);
|
|
34
|
+
} catch {}
|
|
35
|
+
}
|
|
36
|
+
} catch {}
|
|
37
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
|
|
3
|
+
* timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
|
|
4
|
+
* (a page that never loads) would otherwise hang the call forever. Also bounds
|
|
5
|
+
* the best-effort tab close on both engines.
|
|
6
|
+
* @template T
|
|
7
|
+
* @param {Promise<T>} p
|
|
8
|
+
* @param {number} ms
|
|
9
|
+
* @param {string} label
|
|
10
|
+
* @returns {Promise<T>}
|
|
11
|
+
*/
|
|
12
|
+
export function withTimeout(p, ms, label) {
|
|
13
|
+
let timer;
|
|
14
|
+
const t = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms); });
|
|
15
|
+
return Promise.race([p, t]).finally(() => clearTimeout(timer));
|
|
16
|
+
}
|
package/types/auth.d.ts
CHANGED
|
@@ -11,6 +11,13 @@ export function findChromiumCookieDb(): {
|
|
|
11
11
|
* @returns {string | null} Path to cookies.sqlite
|
|
12
12
|
*/
|
|
13
13
|
export function findFirefoxCookieDb(): string | null;
|
|
14
|
+
/**
|
|
15
|
+
* Extract cookies from Firefox (no encryption).
|
|
16
|
+
* @param {string} dbPath - Path to cookies.sqlite
|
|
17
|
+
* @param {string} [domain] - Filter by domain
|
|
18
|
+
* @returns {Array<object>} Cookies in CDP Network.setCookie format
|
|
19
|
+
*/
|
|
20
|
+
export function extractFirefoxCookies(dbPath: string, domain?: string): Array<object>;
|
|
14
21
|
/**
|
|
15
22
|
* Extract cookies from the user's browser, auto-detecting which browser to use.
|
|
16
23
|
* @param {object} [opts]
|
|
@@ -22,6 +29,13 @@ export function extractCookies(opts?: {
|
|
|
22
29
|
browser?: string | undefined;
|
|
23
30
|
domain?: string | undefined;
|
|
24
31
|
}): Array<object>;
|
|
32
|
+
/**
|
|
33
|
+
* Merge cookie lists; a later list wins on an identical cookie. Identity is
|
|
34
|
+
* name + domain + path (RFC 6265): the same name on two paths are two cookies.
|
|
35
|
+
* @param {Array<Array<object>>} lists
|
|
36
|
+
* @returns {Array<object>}
|
|
37
|
+
*/
|
|
38
|
+
export function mergeCookies(lists: Array<Array<object>>): Array<object>;
|
|
25
39
|
/**
|
|
26
40
|
* Inject cookies into a CDP session via Network.setCookie.
|
|
27
41
|
* @param {object} session - CDP session handle (from cdp.session())
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delete barebrowse output files older than `days` in `dir` (non-recursive).
|
|
3
|
+
* Never throws; a missing dir or any per-file error is ignored.
|
|
4
|
+
* @param {string} dir
|
|
5
|
+
* @param {number} [days]
|
|
6
|
+
* @param {number} [now] - epoch ms, injectable for tests
|
|
7
|
+
*/
|
|
8
|
+
export function cleanOld(dir: string, days?: number, now?: number): void;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
|
|
3
|
+
* timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
|
|
4
|
+
* (a page that never loads) would otherwise hang the call forever. Also bounds
|
|
5
|
+
* the best-effort tab close on both engines.
|
|
6
|
+
* @template T
|
|
7
|
+
* @param {Promise<T>} p
|
|
8
|
+
* @param {number} ms
|
|
9
|
+
* @param {string} label
|
|
10
|
+
* @returns {Promise<T>}
|
|
11
|
+
*/
|
|
12
|
+
export function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T>;
|