@edlsh/browse-core 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Enzo Lucchesi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @edlsh/browse-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The host-neutral browser core behind [omp-browse](https://github.com/edlsh/omp-browse), [pi-browse](https://github.com/edlsh/pi-browse), and hermes-browse. It drives Browserbase sessions, local Chrome/Chromium, and remote browsers over CDP, runs Stagehand `act`/`observe`/`extract`, and implements JEV targeting, `ask`, HAR capture, cookie import, and the `/browse` settings command parser. Hosts add tool registration, a model adapter, and UI.
4
+
5
+ The package ships compiled ESM (`dist/`) so Bun and Node (including jiti) load it the same way.
6
+
7
+ ## Use
8
+
9
+ ```ts
10
+ import { BrowseSession, browserParameters, environmentConfig } from "@edlsh/browse-core";
11
+
12
+ const browser = new BrowseSession(environmentConfig, inference, hostClassify, { name: "MyHost", integration: "my-host-browse" });
13
+ const output = await browser.run(browserParameters.parse({ action: "start", backend: "local" }), { sessionId, profile, cwd });
14
+ ```
15
+
16
+ - `HostIdentity.name` appears in user-facing messages ("Use the MyHost model…"). `integration` tags Browserbase session metadata, names the HAR `creator`, and prefixes the default HAR temp directory.
17
+ - `ClientInference` supplies Stagehand's default inference. Without it, unconfigured AI calls use Browserbase Model Gateway.
18
+ - `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
19
+
20
+ Stagehand is pinned to 4.3.0 and used unmodified. `overrides` forces zod 4.6.7 because of GHSA-mrhx-c7xc-m3w5 in Stagehand's zod pin. Run both real-browser suites before upgrading Stagehand.
21
+
22
+ ## Develop
23
+
24
+ ```sh
25
+ bun install
26
+ bun run check && bun test && bun run build
27
+ CHROME_PATH=/path/to/chrome bun run test:local # real local browser
28
+ bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
29
+ ```
30
+
31
+ Releases go through release-please; publishing uses npm trusted publishing from `publish.yml`.
package/dist/ask.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type Classify, type ClassifyImage, type Cloudflare } from "./classifier.ts";
2
+ import type { AskFields } from "./schema.ts";
3
+ export declare const EXTRACT_MODEL = "@cf/cloudflare/clairic";
4
+ /** About 25k tokens: leaves room for the questions in Clairic's and Clef's 65k-token contexts. */
5
+ export declare const MAX_TEXT = 100000;
6
+ /** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
7
+ export declare const DECIDE_TEXT: Record<string, number>;
8
+ export interface PageState {
9
+ url: string;
10
+ title: string;
11
+ tree: string;
12
+ }
13
+ /** bool answers carry the probability of yes; other answers carry the model's confidence. */
14
+ export type Answer = {
15
+ value: boolean;
16
+ probability: number;
17
+ } | {
18
+ value: string | number | null;
19
+ confidence: number;
20
+ };
21
+ export interface AskResult {
22
+ answers: Record<string, Answer>;
23
+ truncated?: true;
24
+ }
25
+ /**
26
+ * Where ask's two halves run: values on Clairic (Workers AI), bool and choice on `decide`, which reads at most
27
+ * `decideText` characters and also judges `images`. Clairic reads text only.
28
+ */
29
+ export interface AskModels {
30
+ cloudflare?: Cloudflare;
31
+ decide?: Classify;
32
+ decideText?: number;
33
+ images?: ClassifyImage[];
34
+ }
35
+ /** Which models a set of fields needs: a decision classifier for bool and choice, Clairic for everything else. */
36
+ export declare function askNeeds(fields: AskFields): {
37
+ decide: boolean;
38
+ extract: boolean;
39
+ };
40
+ /**
41
+ * Readable text of a Stagehand snapshot tree: named nodes as `role: name`, text nodes as plain lines, and unnamed
42
+ * nodes only when they carry a state such as `checkbox [checked]`. Text repeating the line above is dropped.
43
+ */
44
+ export declare function pageText(tree: string): string;
45
+ /**
46
+ * Answers typed questions about one page from its snapshot text. Clairic extracts values and the decision classifier
47
+ * answers bool and choice questions; when a call needs both, they run in parallel.
48
+ */
49
+ export declare function askPage(models: AskModels, page: PageState, fields: AskFields, signal: AbortSignal): Promise<AskResult>;
package/dist/ask.js ADDED
@@ -0,0 +1,108 @@
1
+ import { z } from "zod";
2
+ import { cloudflareRefusal } from "./classifier.js";
3
+ const API = "https://api.cloudflare.com/client/v4/accounts";
4
+ export const EXTRACT_MODEL = "@cf/cloudflare/clairic";
5
+ /** About 25k tokens: leaves room for the questions in Clairic's and Clef's 65k-token contexts. */
6
+ export const MAX_TEXT = 100_000;
7
+ /** Clef Flash reads 24,576 tokens: about 72k characters of page text leaves room for the questions. */
8
+ export const DECIDE_TEXT = { "@cf/cloudflare/clef-flash": 72_000 };
9
+ /** Bool and choice questions go to the decision classifier (Clef by default); every other field type is a value Clairic reads from the page. */
10
+ const DECISIONS = { bool: true, choice: true };
11
+ const envelope = z.object({ result: z.object({ answers: z.record(z.string(), z.unknown()) }) });
12
+ // Clairic answers null when the page does not determine the value (p_null above its default 0.5).
13
+ const extracted = z.object({ value: z.union([z.string(), z.number(), z.null()]), confidence: z.number().optional() });
14
+ /** Which models a set of fields needs: a decision classifier for bool and choice, Clairic for everything else. */
15
+ export function askNeeds(fields) {
16
+ const types = Object.values(fields).map(field => field.type);
17
+ return { decide: types.some(type => Object.hasOwn(DECISIONS, type)), extract: types.some(type => !Object.hasOwn(DECISIONS, type)) };
18
+ }
19
+ /**
20
+ * Readable text of a Stagehand snapshot tree: named nodes as `role: name`, text nodes as plain lines, and unnamed
21
+ * nodes only when they carry a state such as `checkbox [checked]`. Text repeating the line above is dropped.
22
+ */
23
+ export function pageText(tree) {
24
+ const lines = [];
25
+ for (const line of tree.split("\n")) {
26
+ const text = /^\s*\[\d+-\d+\] (.+)$/.exec(line)?.[1];
27
+ if (!text)
28
+ continue;
29
+ const role = text.split(/[:\s]/, 1)[0];
30
+ if (role === "InlineTextBox" || role === "LineBreak")
31
+ continue;
32
+ const name = text.startsWith(`${role}: `) ? text.slice(role.length + 2) : "";
33
+ if (!name && !text.includes("["))
34
+ continue;
35
+ const entry = role === "StaticText" ? name : text;
36
+ const previous = lines.at(-1);
37
+ if (previous !== entry && !(name && previous?.endsWith(name)))
38
+ lines.push(entry);
39
+ }
40
+ return lines.join("\n");
41
+ }
42
+ /** One Clairic run; a network error, 429, or 5xx gets one immediate retry. Response bodies are not echoed. */
43
+ async function extractValues(cloudflare, input, signal) {
44
+ for (let attempt = 1;; attempt++) {
45
+ let response;
46
+ try {
47
+ response = await fetch(`${API}/${encodeURIComponent(cloudflare.accountId)}/ai/run/${EXTRACT_MODEL}`, {
48
+ method: "POST", signal, body: JSON.stringify(input),
49
+ headers: { Authorization: `Bearer ${cloudflare.apiKey}`, "Content-Type": "application/json" },
50
+ });
51
+ }
52
+ catch (error) {
53
+ if (signal.aborted || attempt === 2)
54
+ throw signal.aborted ? error : new Error("Workers AI request failed with a network error.");
55
+ continue;
56
+ }
57
+ if (response.ok) {
58
+ const parsed = envelope.safeParse(await response.json().catch(() => undefined));
59
+ if (!parsed.success)
60
+ throw new Error("Workers AI returned an unexpected response.");
61
+ return parsed.data.result.answers;
62
+ }
63
+ const transient = response.status === 429 || response.status >= 500;
64
+ if (!transient || attempt === 2)
65
+ throw new Error(cloudflareRefusal(response.status));
66
+ }
67
+ }
68
+ /**
69
+ * Answers typed questions about one page from its snapshot text. Clairic extracts values and the decision classifier
70
+ * answers bool and choice questions; when a call needs both, they run in parallel.
71
+ */
72
+ export async function askPage(models, page, fields, signal) {
73
+ const full = pageText(page.tree);
74
+ const decideLimit = Math.min(models.decideText ?? MAX_TEXT, MAX_TEXT);
75
+ const entries = Object.entries(fields);
76
+ const decide = entries.filter(([, field]) => Object.hasOwn(DECISIONS, field.type));
77
+ const extract = entries.filter(([, field]) => !Object.hasOwn(DECISIONS, field.type));
78
+ const questions = Object.fromEntries(decide.map(([name, field]) => [name, field.type === "bool"
79
+ ? { type: "bool", instructions: field.instructions }
80
+ : { type: "choice", instructions: field.instructions, criteria: Object.fromEntries(field.options.map(option => [option, option])) }]));
81
+ const [decided, read] = await Promise.all([
82
+ decide.length ? models.decide({ state: { url: page.url, title: page.title, text: full.slice(0, decideLimit) }, questions, ...(models.images?.length ? { images: models.images } : {}) }, signal) : {},
83
+ extract.length ? extractValues(models.cloudflare, {
84
+ model: "clairic", state: `${page.title}\n${page.url}\n\n${full.slice(0, MAX_TEXT)}`,
85
+ fields: Object.fromEntries(extract.map(([name, field]) => [name, { type: field.type, instructions: field.instructions, ...(field.unit ? { unit: field.unit } : {}) }])),
86
+ }, signal) : {},
87
+ ]);
88
+ const answers = {};
89
+ for (const [name, field] of entries) {
90
+ if (field.type === "bool" || field.type === "choice") {
91
+ const answer = decided[name];
92
+ if (answer?.type === "bool" && field.type === "bool")
93
+ answers[name] = { value: answer.probability >= 0.5, probability: answer.probability };
94
+ else if (answer?.type === "choice" && field.type === "choice")
95
+ answers[name] = { value: answer.choice, confidence: answer.confidence };
96
+ else
97
+ throw new Error("The decision classifier returned an unexpected answer.");
98
+ }
99
+ else {
100
+ const answer = extracted.safeParse(read[name]);
101
+ if (!answer.success)
102
+ throw new Error("Workers AI returned an unexpected answer.");
103
+ answers[name] = { value: answer.data.value, confidence: answer.data.confidence ?? 0 };
104
+ }
105
+ }
106
+ const truncated = (decide.length > 0 && full.length > decideLimit) || (extract.length > 0 && full.length > MAX_TEXT);
107
+ return { answers, ...(truncated ? { truncated: true } : {}) };
108
+ }
@@ -0,0 +1,100 @@
1
+ import type { CookieParam } from "@browserbasehq/stagehand";
2
+ /**
3
+ * Chromium-based browsers whose cookies can be imported. They share one cookie database format and differ only in
4
+ * their application, data folder under ~/Library/Application Support, and the Keychain item holding the cookie key.
5
+ */
6
+ export declare const BROWSERS: readonly [{
7
+ readonly id: "chrome";
8
+ readonly name: "Google Chrome";
9
+ readonly app: "Google Chrome.app";
10
+ readonly data: "Google/Chrome";
11
+ readonly keychain: "Chrome Safe Storage";
12
+ }, {
13
+ readonly id: "chromium";
14
+ readonly name: "Chromium";
15
+ readonly app: "Chromium.app";
16
+ readonly data: "Chromium";
17
+ readonly keychain: "Chromium Safe Storage";
18
+ }, {
19
+ readonly id: "brave";
20
+ readonly name: "Brave";
21
+ readonly app: "Brave Browser.app";
22
+ readonly data: "BraveSoftware/Brave-Browser";
23
+ readonly keychain: "Brave Safe Storage";
24
+ }, {
25
+ readonly id: "edge";
26
+ readonly name: "Microsoft Edge";
27
+ readonly app: "Microsoft Edge.app";
28
+ readonly data: "Microsoft Edge";
29
+ readonly keychain: "Microsoft Edge Safe Storage";
30
+ }, {
31
+ readonly id: "arc";
32
+ readonly name: "Arc";
33
+ readonly app: "Arc.app";
34
+ readonly data: "Arc/User Data";
35
+ readonly keychain: "Arc Safe Storage";
36
+ }, {
37
+ readonly id: "vivaldi";
38
+ readonly name: "Vivaldi";
39
+ readonly app: "Vivaldi.app";
40
+ readonly data: "Vivaldi";
41
+ readonly keychain: "Vivaldi Safe Storage";
42
+ }, {
43
+ readonly id: "opera";
44
+ readonly name: "Opera";
45
+ readonly app: "Opera.app";
46
+ readonly data: "com.operasoftware.Opera";
47
+ readonly keychain: "Opera Safe Storage";
48
+ }, {
49
+ readonly id: "helium";
50
+ readonly name: "Helium";
51
+ readonly app: "Helium.app";
52
+ readonly data: "net.imput.helium";
53
+ readonly keychain: "Helium Storage Key";
54
+ }];
55
+ export type BrowserId = (typeof BROWSERS)[number]["id"];
56
+ export declare const BROWSER_IDS: [BrowserId, ...BrowserId[]];
57
+ /** One browser's cookie store: the browser, its data folder, and how to read its Keychain key. */
58
+ export interface CookieSource {
59
+ browser: BrowserId;
60
+ name: string;
61
+ root: string;
62
+ keychain: string;
63
+ }
64
+ /** Installed browsers: the app is in /Applications or ~/Applications and its data folder exists. Leftover data of a removed app is ignored. */
65
+ export declare function installedBrowsers(home?: string): Promise<CookieSource[]>;
66
+ export declare function normalizeCookieDomains(domains: string[]): string[];
67
+ export interface BrowserProfile {
68
+ /** Browser identifier: the value cookie_import's browser takes. */
69
+ browser: BrowserId;
70
+ /** Profile folder: the value cookie_import's profile takes. */
71
+ profile: string;
72
+ /** Display name chosen in the browser, such as "Work"; absent when Local State cannot be read. */
73
+ name?: string;
74
+ }
75
+ export declare function listBrowserProfiles(source: CookieSource): Promise<BrowserProfile[]>;
76
+ export interface BrowserCookies {
77
+ browser: BrowserId;
78
+ cookies: CookieParam[];
79
+ domains: string[];
80
+ matched: number;
81
+ skipped: {
82
+ expired: number;
83
+ partitioned: number;
84
+ unsupportedEncryption: number;
85
+ decryptionFailed: number;
86
+ };
87
+ }
88
+ export interface BrowserProfileMatch extends BrowserProfile {
89
+ /** The browser's display name, such as Google Chrome. */
90
+ browserName: string;
91
+ /** Unexpired, unpartitioned cookies for the domains: the ones an import could transfer. */
92
+ cookies: number;
93
+ }
94
+ /** Profiles of the given browsers holding importable cookies for the domains, most first. Decrypts nothing, so it needs no Keychain access. */
95
+ export declare function findBrowserProfiles(domains: string[], signal: AbortSignal, sources: CookieSource[]): Promise<BrowserProfileMatch[]>;
96
+ /** Only selected domains are read. No database copies or decrypted export files are created. */
97
+ export declare function readBrowserCookies(source: CookieSource, profile: string, domains: string[], signal: AbortSignal, options?: {
98
+ readPassword?: (signal: AbortSignal) => Promise<string>;
99
+ cacheKey?: boolean;
100
+ }): Promise<BrowserCookies>;
@@ -0,0 +1,261 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createDecipheriv, createHash, pbkdf2Sync, timingSafeEqual } from "node:crypto";
3
+ import { access, readdir, readFile, stat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { getDomain } from "tldts";
8
+ const executeFile = promisify(execFile);
9
+ const profilePattern = /^(?:Default|Profile [0-9]+)$/;
10
+ const chromiumEpochSeconds = 11_644_473_600;
11
+ /**
12
+ * Chromium-based browsers whose cookies can be imported. They share one cookie database format and differ only in
13
+ * their application, data folder under ~/Library/Application Support, and the Keychain item holding the cookie key.
14
+ */
15
+ export const BROWSERS = [
16
+ { id: "chrome", name: "Google Chrome", app: "Google Chrome.app", data: "Google/Chrome", keychain: "Chrome Safe Storage" },
17
+ { id: "chromium", name: "Chromium", app: "Chromium.app", data: "Chromium", keychain: "Chromium Safe Storage" },
18
+ { id: "brave", name: "Brave", app: "Brave Browser.app", data: "BraveSoftware/Brave-Browser", keychain: "Brave Safe Storage" },
19
+ { id: "edge", name: "Microsoft Edge", app: "Microsoft Edge.app", data: "Microsoft Edge", keychain: "Microsoft Edge Safe Storage" },
20
+ { id: "arc", name: "Arc", app: "Arc.app", data: "Arc/User Data", keychain: "Arc Safe Storage" },
21
+ { id: "vivaldi", name: "Vivaldi", app: "Vivaldi.app", data: "Vivaldi", keychain: "Vivaldi Safe Storage" },
22
+ { id: "opera", name: "Opera", app: "Opera.app", data: "com.operasoftware.Opera", keychain: "Opera Safe Storage" },
23
+ { id: "helium", name: "Helium", app: "Helium.app", data: "net.imput.helium", keychain: "Helium Storage Key" },
24
+ ];
25
+ export const BROWSER_IDS = BROWSERS.map(browser => browser.id);
26
+ /** Installed browsers: the app is in /Applications or ~/Applications and its data folder exists. Leftover data of a removed app is ignored. */
27
+ export async function installedBrowsers(home = homedir()) {
28
+ if (process.platform !== "darwin")
29
+ throw new Error("Browser cookie import currently supports macOS only.");
30
+ const sources = [];
31
+ for (const browser of BROWSERS) {
32
+ const root = join(home, "Library", "Application Support", browser.data);
33
+ const exists = async (path) => access(path).then(() => true, () => false);
34
+ if (await exists(root) && (await exists(join("/Applications", browser.app)) || await exists(join(home, "Applications", browser.app)))) {
35
+ sources.push({ browser: browser.id, name: browser.name, root, keychain: browser.keychain });
36
+ }
37
+ }
38
+ return sources;
39
+ }
40
+ export function normalizeCookieDomains(domains) {
41
+ if (!domains.length || domains.length > 20)
42
+ throw new Error("Specify between 1 and 20 cookie domains.");
43
+ return [...new Set(domains.map(input => {
44
+ const domain = input.trim().toLowerCase().replace(/^\./, "").replace(/\.$/, "");
45
+ if (domain.length > 253 || !/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(domain) ||
46
+ domain.split(".").some(label => label.length > 63 || label.startsWith("-") || label.endsWith("-")) ||
47
+ !getDomain(domain, { allowPrivateDomains: true })) {
48
+ throw new Error("Use specific bare cookie domains, such as github.com. URLs, wildcards, and public suffixes are not allowed.");
49
+ }
50
+ return domain;
51
+ }))];
52
+ }
53
+ /** Cookie database paths for a profile. Opera keeps its only profile directly in the data folder, so Default falls back to it. */
54
+ function databaseCandidates(root, profile) {
55
+ const folders = profile === "Default" ? [join(root, profile), root] : [join(root, profile)];
56
+ return folders.flatMap(folder => [join(folder, "Network", "Cookies"), join(folder, "Cookies")]);
57
+ }
58
+ async function databasePath(source, profile) {
59
+ if (!profilePattern.test(profile))
60
+ throw new Error("Choose Default or a Profile number returned by cookie_profiles.");
61
+ for (const path of databaseCandidates(source.root, profile)) {
62
+ try {
63
+ if ((await stat(path)).isFile())
64
+ return path;
65
+ }
66
+ catch (error) {
67
+ if (error.code !== "ENOENT")
68
+ throw new Error(`Cannot access ${source.name}'s cookie database. Check local file permissions.`);
69
+ }
70
+ }
71
+ throw new Error(`No cookie database found for this ${source.name} profile. Open ${source.name} and check cookie_profiles.`);
72
+ }
73
+ export async function listBrowserProfiles(source) {
74
+ let entries;
75
+ try {
76
+ entries = await readdir(source.root, { withFileTypes: true });
77
+ }
78
+ catch (error) {
79
+ if (error.code === "ENOENT")
80
+ return [];
81
+ throw new Error(`Cannot list ${source.name} profiles. Check local file permissions.`);
82
+ }
83
+ let names = {};
84
+ try {
85
+ names = JSON.parse(await readFile(join(source.root, "Local State"), "utf8"))?.profile?.info_cache ?? {};
86
+ }
87
+ catch { /* Names are a convenience; folders alone identify profiles. */ }
88
+ const folders = entries.filter(entry => entry.isDirectory() && profilePattern.test(entry.name)).map(entry => entry.name);
89
+ // A single-profile browser (Opera) stores its cookies in the data folder itself.
90
+ if (!folders.includes("Default") && entries.some(entry => entry.name === "Cookies" || entry.name === "Network"))
91
+ folders.push("Default");
92
+ return folders.sort().map(profile => {
93
+ const name = names[profile]?.name;
94
+ return typeof name === "string" && name ? { browser: source.browser, profile, name } : { browser: source.browser, profile };
95
+ });
96
+ }
97
+ async function keychainPassword(source, signal) {
98
+ signal.throwIfAborted();
99
+ try {
100
+ // stdout is captured in memory; never include subprocess output in an error.
101
+ const { stdout } = await executeFile("/usr/bin/security", ["find-generic-password", "-w", "-s", source.keychain], { signal, encoding: "utf8", maxBuffer: 16_384 });
102
+ const password = stdout.replace(/\r?\n$/, "");
103
+ if (!password)
104
+ throw new Error("empty");
105
+ return password;
106
+ }
107
+ catch {
108
+ signal.throwIfAborted();
109
+ throw new Error(`Could not unlock ${source.keychain}. Click Allow (not Always Allow) on the macOS Keychain prompt for this import, then retry. Always Allow would let any local process decrypt every ${source.name} cookie and saved password.`);
110
+ }
111
+ }
112
+ /**
113
+ * Bun ships bun:sqlite and no node:sqlite; Node the reverse. Chromium's microsecond timestamps exceed
114
+ * Number.MAX_SAFE_INTEGER, which node:sqlite refuses to return as numbers, so on Node integers are read
115
+ * as BigInt and converted, matching the numbers bun:sqlite returns.
116
+ */
117
+ async function openReadOnly(path) {
118
+ if (process.versions.bun) {
119
+ const { Database } = await import("bun:sqlite");
120
+ const database = new Database(path, { readonly: true });
121
+ return {
122
+ exec: sql => database.exec(sql),
123
+ get: sql => database.query(sql).get() ?? undefined,
124
+ all: (sql, parameters) => database.query(sql).all(...parameters),
125
+ close: () => database.close(),
126
+ };
127
+ }
128
+ const { DatabaseSync } = await import("node:sqlite");
129
+ const database = new DatabaseSync(path, { readOnly: true });
130
+ const statement = (sql) => {
131
+ const prepared = database.prepare(sql);
132
+ prepared.setReadBigInts(true);
133
+ return prepared;
134
+ };
135
+ const numbers = (row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, typeof value === "bigint" ? Number(value) : value]));
136
+ return {
137
+ exec: sql => database.exec(sql),
138
+ get: sql => { const row = statement(sql).get(); return row && numbers(row); },
139
+ all: (sql, parameters) => statement(sql).all(...parameters).map(numbers),
140
+ close: () => database.close(),
141
+ };
142
+ }
143
+ /** Reads the rows for the selected domains in one short read transaction, which includes committed WAL changes without locking the browser. */
144
+ async function selectCookieRows(source, path, selected) {
145
+ let database;
146
+ try {
147
+ database = await openReadOnly(path);
148
+ database.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 1000; BEGIN");
149
+ const version = Number(database.get("SELECT value FROM meta WHERE key = 'version'")?.value);
150
+ if (!Number.isInteger(version) || version < 23 || version > 24)
151
+ throw new Error("unsupported schema");
152
+ const where = selected.map(() => "(host_key = ? OR host_key = ? OR host_key LIKE ?)").join(" OR ");
153
+ // SAFETY: the SELECT names exactly CookieRow's columns, and both drivers return BLOBs as Uint8Array and integers as numbers.
154
+ const rows = database.all(`SELECT host_key, name, value, encrypted_value, path, expires_utc,
155
+ has_expires, is_secure, is_httponly, samesite, top_frame_site_key FROM cookies WHERE ${where}`, selected.flatMap(domain => [domain, `.${domain}`, `%.${domain}`]));
156
+ return { rows, version };
157
+ }
158
+ catch {
159
+ throw new Error(`Could not read ${source.name} cookies. Close ${source.name} and retry; supported cookie database versions are 23 and 24.`);
160
+ }
161
+ finally {
162
+ database?.close();
163
+ }
164
+ }
165
+ const expiresAt = (row) => row.expires_utc / 1_000_000 - chromiumEpochSeconds;
166
+ const expired = (row) => Boolean(row.has_expires) && expiresAt(row) <= Date.now() / 1000;
167
+ /** Profiles of the given browsers holding importable cookies for the domains, most first. Decrypts nothing, so it needs no Keychain access. */
168
+ export async function findBrowserProfiles(domains, signal, sources) {
169
+ const selected = normalizeCookieDomains(domains);
170
+ const matches = [];
171
+ for (const source of sources) {
172
+ for (const profile of await listBrowserProfiles(source)) {
173
+ signal.throwIfAborted();
174
+ let path;
175
+ try {
176
+ path = await databasePath(source, profile.profile);
177
+ }
178
+ catch {
179
+ continue;
180
+ } // A profile the browser never opened has no cookie database yet.
181
+ const cookies = (await selectCookieRows(source, path, selected)).rows.filter(row => !expired(row) && !row.top_frame_site_key).length;
182
+ if (cookies)
183
+ matches.push({ ...profile, browserName: source.name, cookies });
184
+ }
185
+ }
186
+ return matches.sort((a, b) => b.cookies - a.cookies);
187
+ }
188
+ /**
189
+ * Derived cookie keys per browser, kept in this process after the first unlock by callers that pass cacheKey, so later
190
+ * imports skip the Keychain prompt. They never leave memory and are zeroed when the process exits.
191
+ */
192
+ const cachedKeys = new Map();
193
+ process.once("exit", () => { for (const key of cachedKeys.values())
194
+ key.fill(0); });
195
+ /** Only selected domains are read. No database copies or decrypted export files are created. */
196
+ export async function readBrowserCookies(source, profile, domains, signal, options = {}) {
197
+ const selected = normalizeCookieDomains(domains);
198
+ signal.throwIfAborted();
199
+ const { rows, version } = await selectCookieRows(source, await databasePath(source, profile), selected);
200
+ signal.throwIfAborted();
201
+ const result = { browser: source.browser, cookies: [], domains: selected, matched: rows.length,
202
+ skipped: { expired: 0, partitioned: 0, unsupportedEncryption: 0, decryptionFailed: 0 } };
203
+ let key;
204
+ try {
205
+ for (const row of rows) {
206
+ signal.throwIfAborted();
207
+ const expires = expiresAt(row);
208
+ if (expired(row)) {
209
+ result.skipped.expired++;
210
+ continue;
211
+ }
212
+ // Stagehand's cookie API has no partition key. Never widen a partitioned cookie into an ordinary cookie.
213
+ if (row.top_frame_site_key) {
214
+ result.skipped.partitioned++;
215
+ continue;
216
+ }
217
+ let value = row.value;
218
+ if (row.encrypted_value.length) {
219
+ const encrypted = Buffer.from(row.encrypted_value);
220
+ if (encrypted.subarray(0, 3).toString() !== "v10") {
221
+ result.skipped.unsupportedEncryption++;
222
+ continue;
223
+ }
224
+ key ??= (options.cacheKey && cachedKeys.get(source.browser)) ||
225
+ pbkdf2Sync(await (options.readPassword ?? (abort => keychainPassword(source, abort)))(signal), "saltysalt", 1003, 16, "sha1");
226
+ if (options.cacheKey)
227
+ cachedKeys.set(source.browser, key);
228
+ signal.throwIfAborted();
229
+ try {
230
+ const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
231
+ const plaintext = Buffer.concat([decipher.update(encrypted.subarray(3)), decipher.final()]);
232
+ try {
233
+ if (version >= 24) {
234
+ const hash = createHash("sha256").update(row.host_key).digest();
235
+ if (plaintext.length < 32 || !timingSafeEqual(plaintext.subarray(0, 32), hash))
236
+ throw new Error("domain mismatch");
237
+ }
238
+ value = new TextDecoder("utf-8", { fatal: true }).decode(plaintext.subarray(version >= 24 ? 32 : 0));
239
+ }
240
+ finally {
241
+ plaintext.fill(0);
242
+ }
243
+ }
244
+ catch {
245
+ result.skipped.decryptionFailed++;
246
+ continue;
247
+ }
248
+ }
249
+ result.cookies.push({ name: row.name, value, domain: row.host_key, path: row.path,
250
+ secure: Boolean(row.is_secure), httpOnly: Boolean(row.is_httponly),
251
+ ...(row.has_expires ? { expires } : {}),
252
+ ...(row.samesite === 0 ? { sameSite: "None" } : row.samesite === 1 ? { sameSite: "Lax" } : row.samesite === 2 ? { sameSite: "Strict" } : {}),
253
+ });
254
+ }
255
+ return result;
256
+ }
257
+ finally {
258
+ if (key !== cachedKeys.get(source.browser))
259
+ key?.fill(0);
260
+ }
261
+ }
@@ -0,0 +1,14 @@
1
+ /** A loopback DevTools endpoint in front of a browser this extension does not own. */
2
+ export interface GuardedEndpoint {
3
+ /** WebSocket URL to hand to Stagehand instead of the real endpoint. */
4
+ url: string;
5
+ /** The browser-level WebSocket URL as the browser reported it, which the browser itself can usually reach. */
6
+ browserUrl: string;
7
+ close(): Promise<void>;
8
+ }
9
+ /**
10
+ * Stagehand's close() on an attached browser sends Browser.close, which would quit the user's own browser. This proxy
11
+ * forwards every DevTools message unchanged except those commands, which it answers itself with an empty result, so
12
+ * Stagehand's close only ends the connection. It listens only on 127.0.0.1; `headers` authenticate it to the endpoint.
13
+ */
14
+ export declare function guardEndpoint(cdpUrl: string, signal: AbortSignal, headers?: Record<string, string>): Promise<GuardedEndpoint>;