codex-browser-use 0.0.0-stage → 4.8.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/LICENSE +21 -0
- package/README.md +312 -2
- package/bin/browser-use.js +200 -0
- package/bin/chrome-native-host.js +29 -0
- package/extension/background.js +1384 -0
- package/extension/content-script.js +3 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +33 -0
- package/package.json +44 -4
- package/rules/browser_use.md +26 -0
- package/skill/SKILL.md +72 -0
- package/skill/references/cookbook.md +281 -0
- package/skill/references/tools.md +18 -0
- package/src/ax-tree.js +889 -0
- package/src/backend-discovery.js +123 -0
- package/src/backend-native-driver.js +223 -0
- package/src/backend-page-commands.js +91 -0
- package/src/backend-tabs.js +490 -0
- package/src/backend-transport.js +165 -0
- package/src/bridge-browser.js +3787 -0
- package/src/bridge-client.js +181 -0
- package/src/config.js +166 -0
- package/src/content-extractor.js +576 -0
- package/src/engine-discovery.js +90 -0
- package/src/extension.js +26 -0
- package/src/frame-reader.js +160 -0
- package/src/install.js +303 -0
- package/src/locators.js +1497 -0
- package/src/official-runtime.js +359 -0
- package/src/portable-server.js +231 -0
- package/src/read-only.js +333 -0
- package/src/repl-session.js +180 -0
- package/src/repl-worker.js +190 -0
- package/src/script-runner.js +1546 -0
- package/src/server.js +1121 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { lstat, mkdir, open, link, rename, unlink } from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
/** @returns {string} */
|
|
9
|
+
export function defaultBridgeFile() {
|
|
10
|
+
return path.join(homedir(), ".local", "share", "browser-use", "chrome-host", "bridge.json");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** @param {string} file @param {boolean} create @returns {Promise<void>} */
|
|
14
|
+
async function privateDirectory(file, create) {
|
|
15
|
+
if (!path.isAbsolute(file)) throw new Error("Browser bridge descriptor must be an absolute path");
|
|
16
|
+
const directory = path.dirname(file);
|
|
17
|
+
if (create) await mkdir(directory, {recursive: true, mode: 0o700});
|
|
18
|
+
const info = await lstat(directory);
|
|
19
|
+
if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0) {
|
|
20
|
+
throw new Error("Browser bridge descriptor requires an owner-only directory");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param {string} socketPath @returns {Promise<boolean>} */
|
|
25
|
+
function isSocketAlive(socketPath) {
|
|
26
|
+
return new Promise((resolve) => {
|
|
27
|
+
let settled = false;
|
|
28
|
+
const socket = net.createConnection({path: socketPath});
|
|
29
|
+
const finish = (alive) => {
|
|
30
|
+
if (settled) return;
|
|
31
|
+
settled = true;
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
socket.destroy();
|
|
34
|
+
resolve(alive);
|
|
35
|
+
};
|
|
36
|
+
const timer = setTimeout(() => finish(false), 300);
|
|
37
|
+
timer.unref?.();
|
|
38
|
+
socket.once("connect", () => finish(true));
|
|
39
|
+
socket.once("error", () => finish(false));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param {string} file @returns {Promise<boolean>} */
|
|
44
|
+
async function isDescriptorLive(file) {
|
|
45
|
+
let info;
|
|
46
|
+
try {
|
|
47
|
+
info = await lstat(file);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error?.code === "ENOENT") return false;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
if (!info.isFile() || info.uid !== process.getuid?.()) {
|
|
53
|
+
throw new Error("Refusing to replace non-regular or foreign browser bridge descriptor");
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const existingSocket = await readBackend(file);
|
|
57
|
+
return await isSocketAlive(existingSocket);
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @param {string} file @param {string} socketPath @returns {Promise<()=>Promise<void>>} */
|
|
64
|
+
export async function publishBackend(file, socketPath) {
|
|
65
|
+
await privateDirectory(file, true);
|
|
66
|
+
const temporary = path.join(path.dirname(file), `.bridge-${randomUUID()}`);
|
|
67
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
68
|
+
let publishedIno;
|
|
69
|
+
let renamed = false;
|
|
70
|
+
try {
|
|
71
|
+
await handle.writeFile(JSON.stringify({version: 1, socketPath}));
|
|
72
|
+
publishedIno = (await handle.stat()).ino;
|
|
73
|
+
try {
|
|
74
|
+
await link(temporary, file);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error?.code !== "EEXIST") throw error;
|
|
77
|
+
let live = await isDescriptorLive(file);
|
|
78
|
+
for (let attempt = 0; attempt < 4 && live; attempt += 1) {
|
|
79
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
80
|
+
live = await isDescriptorLive(file);
|
|
81
|
+
}
|
|
82
|
+
if (live) {
|
|
83
|
+
throw new Error("Another live browser bridge host is already active");
|
|
84
|
+
}
|
|
85
|
+
await rename(temporary, file);
|
|
86
|
+
renamed = true;
|
|
87
|
+
}
|
|
88
|
+
} finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
if (!renamed) await unlink(temporary).catch(() => {});
|
|
91
|
+
}
|
|
92
|
+
return async () => {
|
|
93
|
+
try {
|
|
94
|
+
const current = await lstat(file);
|
|
95
|
+
if (current.ino === publishedIno) await unlink(file);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error?.code !== "ENOENT") throw error;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {string} file @returns {Promise<string>} */
|
|
103
|
+
export async function readBackend(file) {
|
|
104
|
+
await privateDirectory(file, false);
|
|
105
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
106
|
+
try {
|
|
107
|
+
const info = await handle.stat();
|
|
108
|
+
if (!info.isFile() || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0 || info.size > 4096) {
|
|
109
|
+
throw new Error("Invalid browser bridge descriptor");
|
|
110
|
+
}
|
|
111
|
+
const descriptor = JSON.parse(await handle.readFile("utf8"));
|
|
112
|
+
const socketPath = descriptor?.socketPath;
|
|
113
|
+
if (descriptor?.version !== 1 || typeof socketPath !== "string" || !path.isAbsolute(socketPath) || socketPath.includes(":")) {
|
|
114
|
+
throw new Error("Invalid browser bridge socket path");
|
|
115
|
+
}
|
|
116
|
+
await privateDirectory(socketPath, false);
|
|
117
|
+
const socket = await lstat(socketPath);
|
|
118
|
+
if (!socket.isSocket() || socket.uid !== process.getuid?.()) throw new Error("Browser bridge socket is unavailable");
|
|
119
|
+
return socketPath;
|
|
120
|
+
} finally {
|
|
121
|
+
await handle.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { endianness } from "node:os";
|
|
2
|
+
import { FrameReader, encodeFrame } from "./frame-reader.js";
|
|
3
|
+
|
|
4
|
+
const littleEndian = endianness() === "LE";
|
|
5
|
+
const maxMessage = 2 * 1024 * 1024;
|
|
6
|
+
const maxChunkChars = 512 * 1024;
|
|
7
|
+
const maxUnacknowledged = 128;
|
|
8
|
+
/** @typedef {{id:number,title?:string,url?:string,active?:boolean}} BrowserTab */
|
|
9
|
+
/** @typedef {Record<string,unknown>} Params */
|
|
10
|
+
/** @typedef {(method:string, id:number, params:Params)=>void} EventListener */
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Speak Chrome native messaging over a dedicated input and output pair.
|
|
14
|
+
* @param {import("node:stream").Readable} input
|
|
15
|
+
* @param {import("node:stream").Writable} output
|
|
16
|
+
* @param {{timeoutMs?:number}} [options]
|
|
17
|
+
* @returns {{createBlankTab:()=>Promise<BrowserTab>,readTab:(id:number)=>Promise<BrowserTab|null>,closeTab:(id:number)=>Promise<void>,releaseTab?:(id:number)=>Promise<void>,markTab?:(id:number,status:string,markOptions?:{focus?:boolean})=>Promise<void>,attach:(id:number)=>Promise<void>,detach:(id:number)=>Promise<void>,execute:(id:number,method:string,params:Params,childSession?:string)=>Promise<unknown>,navigate:(id:number,url:string)=>Promise<void>,watchDownloads:(id:number)=>Promise<void>,unwatchDownloads:(id:number)=>Promise<void>,groupTabs:(tabIds:number[],groupOptions?:{title?:string,color?:string,groupId?:number|null,sessionId?:string,collapsed?:boolean})=>Promise<{groupId:number|null,supported?:boolean}>,ungroupTabs?:(tabIds:number[])=>Promise<{ok?:boolean,ungrouped?:number,supported?:boolean}>,listTabGroups?:()=>Promise<Array<Record<string,unknown>>>,cleanupGroups?:(cleanupOptions?:{ungroupFinished?:boolean,closeDuplicateDeliverables?:boolean,keepTabIds?:number[]})=>Promise<Record<string,unknown>>,onEvent:(listener:EventListener)=>void,closed:Promise<Error>,close:()=>void}}
|
|
18
|
+
*/
|
|
19
|
+
export function createNativeTabDriver(input, output, options = {}) {
|
|
20
|
+
/** @type {Map<number,{resolve:(result:unknown)=>void,reject:(error:Error)=>void,timer:ReturnType<typeof setTimeout>,parts:string[]}>} */
|
|
21
|
+
const pending = new Map();
|
|
22
|
+
/** @type {Map<number,number>} */
|
|
23
|
+
const expiredCommands = new Map();
|
|
24
|
+
/** @type {Map<number,number>} */
|
|
25
|
+
const expiredCountsByTab = new Map();
|
|
26
|
+
/** @type {EventListener | undefined} */
|
|
27
|
+
let onEvent;
|
|
28
|
+
const closed = Promise.withResolvers();
|
|
29
|
+
let nextId = 0;
|
|
30
|
+
const reader = new FrameReader({
|
|
31
|
+
littleEndian,
|
|
32
|
+
maxFrameBytes: maxMessage,
|
|
33
|
+
maxBufferedBytes: 4 * maxMessage,
|
|
34
|
+
overflowError: "Invalid Chrome native message size",
|
|
35
|
+
lengthError: "Invalid Chrome native message size",
|
|
36
|
+
});
|
|
37
|
+
/** @type {Error | undefined} */
|
|
38
|
+
let failure;
|
|
39
|
+
|
|
40
|
+
/** @param {Error} error @returns {void} */
|
|
41
|
+
function fail(error) {
|
|
42
|
+
if (failure) return;
|
|
43
|
+
failure = error;
|
|
44
|
+
for (const item of pending.values()) {
|
|
45
|
+
clearTimeout(item.timer);
|
|
46
|
+
item.reject(error);
|
|
47
|
+
}
|
|
48
|
+
pending.clear();
|
|
49
|
+
expiredCommands.clear();
|
|
50
|
+
expiredCountsByTab.clear();
|
|
51
|
+
closed.resolve(error);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
input.on("data", (chunk) => {
|
|
55
|
+
if (failure) return;
|
|
56
|
+
try {
|
|
57
|
+
reader.push(chunk);
|
|
58
|
+
let raw;
|
|
59
|
+
while ((raw = reader.nextFrame()) !== null) {
|
|
60
|
+
const reply = JSON.parse(raw.toString("utf8"));
|
|
61
|
+
if (["onCDPEvent", "onCDPDetach", "onTabCreated"].includes(reply?.event) && Number.isSafeInteger(reply.tabId)) {
|
|
62
|
+
onEvent?.(reply.event, reply.tabId, reply.params);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const item = pending.get(reply?.id);
|
|
66
|
+
const expiredTab = expiredCommands.get(reply?.id);
|
|
67
|
+
if (expiredTab !== undefined) {
|
|
68
|
+
if (typeof reply?.ok === "boolean" || reply?.final === true) {
|
|
69
|
+
expiredCommands.delete(reply.id);
|
|
70
|
+
const remaining = expiredCountsByTab.get(expiredTab) - 1;
|
|
71
|
+
if (remaining === 0) expiredCountsByTab.delete(expiredTab);
|
|
72
|
+
else expiredCountsByTab.set(expiredTab, remaining);
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!item) throw new Error("Invalid Chrome native response ID");
|
|
77
|
+
if (typeof reply.chunk === "string") {
|
|
78
|
+
if (reply.index !== item.parts.length || item.parts.length >= 64 || reply.chunk.length > maxChunkChars ||
|
|
79
|
+
typeof reply.final !== "boolean") throw new Error("Invalid Chrome native chunk");
|
|
80
|
+
item.parts.push(reply.chunk);
|
|
81
|
+
if (!reply.final) continue;
|
|
82
|
+
reply.value = JSON.parse(item.parts.join(""));
|
|
83
|
+
reply.ok = true;
|
|
84
|
+
}
|
|
85
|
+
if (typeof reply.ok !== "boolean") throw new Error("Invalid Chrome native response");
|
|
86
|
+
pending.delete(reply.id);
|
|
87
|
+
clearTimeout(item.timer);
|
|
88
|
+
if (reply.ok) item.resolve(reply.value);
|
|
89
|
+
else item.reject(new Error(typeof reply.error === "string" ? reply.error : "Chrome tab operation failed"));
|
|
90
|
+
}
|
|
91
|
+
} catch (error) {
|
|
92
|
+
fail(error);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
input.once("end", () => fail(new Error("Chrome disconnected from the native host")));
|
|
96
|
+
input.once("close", () => fail(new Error("Chrome native input closed")));
|
|
97
|
+
input.on("error", fail);
|
|
98
|
+
output.on("error", fail);
|
|
99
|
+
|
|
100
|
+
/** @param {string} method @param {number} [tabId] @param {Params} [details] @returns {Promise<unknown>} */
|
|
101
|
+
async function request(method, tabId, details) {
|
|
102
|
+
if (failure) throw failure;
|
|
103
|
+
const isolateTimeout = method === "execute" && tabId !== undefined;
|
|
104
|
+
if (isolateTimeout) {
|
|
105
|
+
if (expiredCountsByTab.has(tabId)) {
|
|
106
|
+
throw new Error("A timed-out Chrome command is still in flight for this tab");
|
|
107
|
+
}
|
|
108
|
+
if (pending.size + expiredCommands.size >= maxUnacknowledged) {
|
|
109
|
+
throw new Error("Too many Chrome commands are awaiting acknowledgement");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const id = ++nextId;
|
|
113
|
+
const packet = encodeFrame({ id, method, tabId, details }, {
|
|
114
|
+
littleEndian,
|
|
115
|
+
maxFrameBytes: maxMessage,
|
|
116
|
+
overflowError: "Invalid Chrome native message size",
|
|
117
|
+
});
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const timer = setTimeout(() => {
|
|
120
|
+
const operation = typeof details?.method === "string" ? details.method : method;
|
|
121
|
+
if (!isolateTimeout) {
|
|
122
|
+
fail(new Error(`Chrome native operation timed out: ${operation}`));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
pending.delete(id);
|
|
126
|
+
expiredCommands.set(id, tabId);
|
|
127
|
+
expiredCountsByTab.set(tabId, (expiredCountsByTab.get(tabId) ?? 0) + 1);
|
|
128
|
+
reject(new Error(`Chrome native operation timed out: ${operation}. Chrome may still complete it.`));
|
|
129
|
+
}, options.timeoutMs ?? 10000);
|
|
130
|
+
pending.set(id, { resolve, reject, timer, parts: [] });
|
|
131
|
+
output.write(packet, (error) => {
|
|
132
|
+
if (error) fail(error);
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @param {unknown} value @param {number} [expectedId] @returns {BrowserTab} */
|
|
138
|
+
function tab(value, expectedId) {
|
|
139
|
+
if (!value || typeof value !== "object" || !Number.isSafeInteger(value.id) ||
|
|
140
|
+
value.id < 0 || (expectedId !== undefined && value.id !== expectedId)) {
|
|
141
|
+
throw new Error("Chrome native driver returned an invalid tab");
|
|
142
|
+
}
|
|
143
|
+
return value;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
async createBlankTab() { return tab(await request("createBlankTab")); },
|
|
148
|
+
/** @returns {Promise<BrowserTab[]>} */
|
|
149
|
+
async listTabs() {
|
|
150
|
+
const value = await request("listTabs");
|
|
151
|
+
return Array.isArray(value)
|
|
152
|
+
? value.filter((entry) => entry && Number.isSafeInteger(entry.id) && entry.id >= 0)
|
|
153
|
+
: [];
|
|
154
|
+
},
|
|
155
|
+
/** @param {number} id @returns {Promise<BrowserTab>} */
|
|
156
|
+
async claimTab(id) { return tab(await request("claimTab", id), id); },
|
|
157
|
+
/** @param {number} id @returns {Promise<BrowserTab|null>} */
|
|
158
|
+
async readTab(id) {
|
|
159
|
+
const value = await request("readTab", id);
|
|
160
|
+
return value === null ? null : tab(value, id);
|
|
161
|
+
},
|
|
162
|
+
/** @param {number} id @param {{format?:string,maxChars?:number}} [options] @returns {Promise<unknown>} */
|
|
163
|
+
async readTabContext(id, options = {}) {
|
|
164
|
+
return await request("readTabContext", id, options);
|
|
165
|
+
},
|
|
166
|
+
/** @param {{cursorMode?:string}} [config] @returns {Promise<unknown>} */
|
|
167
|
+
async setConfig(config = {}) {
|
|
168
|
+
return await request("setConfig", undefined, config);
|
|
169
|
+
},
|
|
170
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
171
|
+
async closeTab(id) { await request("closeTab", id); },
|
|
172
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
173
|
+
async releaseTab(id) { await request("releaseTab", id); },
|
|
174
|
+
/** @param {number} id @param {string} status @param {{focus?:boolean}} [markOptions] @returns {Promise<void>} */
|
|
175
|
+
async markTab(id, status, markOptions = {}) {
|
|
176
|
+
await request("markTab", id, {status, ...(markOptions?.focus === true ? {focus: true} : {})});
|
|
177
|
+
},
|
|
178
|
+
/** @param {number} id @param {number} x @param {number} y @param {boolean} [waitForArrival] @returns {Promise<void>} */
|
|
179
|
+
async moveCursor(id, x, y, waitForArrival = true) {
|
|
180
|
+
await request("moveCursor", id, {x, y, waitForArrival});
|
|
181
|
+
},
|
|
182
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
183
|
+
async attach(id) { await request("attach", id); },
|
|
184
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
185
|
+
async detach(id) { await request("detach", id); },
|
|
186
|
+
/** @param {number} id @param {string} method @param {Params} params @param {string} [childSession] @returns {Promise<unknown>} */
|
|
187
|
+
async execute(id, method, params, childSession) { return await request("execute", id, {method, params, childSession}); },
|
|
188
|
+
/** @param {number} id @param {string} url @returns {Promise<void>} */
|
|
189
|
+
async navigate(id, url) { await request("navigate", id, {url}); },
|
|
190
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
191
|
+
async watchDownloads(id) { await request("watchDownloads", id); },
|
|
192
|
+
/** @param {number} id @returns {Promise<void>} */
|
|
193
|
+
async unwatchDownloads(id) { await request("unwatchDownloads", id); },
|
|
194
|
+
/** @param {number[]} tabIds @param {{title?:string,color?:string,groupId?:number|null,sessionId?:string,collapsed?:boolean}} [groupOptions] @returns {Promise<{groupId:number|null,supported?:boolean}>} */
|
|
195
|
+
async groupTabs(tabIds, groupOptions = {}) {
|
|
196
|
+
return await request("groupTabs", undefined, {
|
|
197
|
+
tabIds,
|
|
198
|
+
title: groupOptions.title,
|
|
199
|
+
color: groupOptions.color,
|
|
200
|
+
groupId: groupOptions.groupId ?? null,
|
|
201
|
+
...(typeof groupOptions.sessionId === "string" ? {sessionId: groupOptions.sessionId} : {}),
|
|
202
|
+
...(typeof groupOptions.collapsed === "boolean" ? {collapsed: groupOptions.collapsed} : {}),
|
|
203
|
+
});
|
|
204
|
+
},
|
|
205
|
+
/** @param {number[]} tabIds @returns {Promise<{ok?:boolean,ungrouped?:number,supported?:boolean}>} */
|
|
206
|
+
async ungroupTabs(tabIds) {
|
|
207
|
+
return await request("ungroupTabs", undefined, {tabIds});
|
|
208
|
+
},
|
|
209
|
+
/** @returns {Promise<Array<Record<string,unknown>>>} */
|
|
210
|
+
async listTabGroups() {
|
|
211
|
+
const value = await request("listTabGroups");
|
|
212
|
+
return Array.isArray(value) ? value : [];
|
|
213
|
+
},
|
|
214
|
+
/** @param {{ungroupFinished?:boolean,closeDuplicateDeliverables?:boolean,keepTabIds?:number[]}} [cleanupOptions] @returns {Promise<Record<string,unknown>>} */
|
|
215
|
+
async cleanupGroups(cleanupOptions = {}) {
|
|
216
|
+
return await request("cleanupGroups", undefined, cleanupOptions);
|
|
217
|
+
},
|
|
218
|
+
/** @param {EventListener} listener @returns {void} */
|
|
219
|
+
onEvent(listener) { onEvent = listener; },
|
|
220
|
+
closed: closed.promise,
|
|
221
|
+
close() { fail(new Error("Chrome native tab driver closed")); },
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
const pageCommands = new Set([
|
|
4
|
+
"Accessibility.enable", "Accessibility.getFullAXTree", "Accessibility.getPartialAXTree",
|
|
5
|
+
"DOM.describeNode", "DOM.enable", "DOM.focus", "DOM.getBoxModel", "DOM.getContentQuads", "DOM.getDocument",
|
|
6
|
+
"DOM.getFrameOwner", "DOM.getNodeForLocation", "DOM.querySelector", "DOM.resolveNode",
|
|
7
|
+
"DOM.scrollIntoViewIfNeeded", "DOM.setFileInputFiles",
|
|
8
|
+
"DOMSnapshot.captureSnapshot",
|
|
9
|
+
"Emulation.clearDeviceMetricsOverride", "Emulation.setDeviceMetricsOverride",
|
|
10
|
+
"Emulation.setFocusEmulationEnabled",
|
|
11
|
+
"Input.dispatchKeyEvent", "Input.dispatchMouseEvent", "Input.dispatchTouchEvent",
|
|
12
|
+
"Input.insertText", "Input.synthesizeScrollGesture",
|
|
13
|
+
"Network.disable", "Network.enable", "Network.getResponseBody",
|
|
14
|
+
"Page.addScriptToEvaluateOnNewDocument", "Page.removeScriptToEvaluateOnNewDocument",
|
|
15
|
+
"Page.bringToFront", "Page.captureScreenshot", "Page.createIsolatedWorld", "Page.enable", "Page.getFrameTree",
|
|
16
|
+
"Page.getLayoutMetrics", "Page.getNavigationHistory", "Page.handleJavaScriptDialog",
|
|
17
|
+
"Page.navigate", "Page.navigateToHistoryEntry", "Page.reload",
|
|
18
|
+
"Page.setInterceptFileChooserDialog", "Page.setLifecycleEventsEnabled",
|
|
19
|
+
"Runtime.addBinding", "Runtime.callFunctionOn", "Runtime.enable", "Runtime.evaluate",
|
|
20
|
+
"Runtime.releaseObject", "Runtime.releaseObjectGroup", "Runtime.removeBinding",
|
|
21
|
+
"Target.setAutoAttach",
|
|
22
|
+
]);
|
|
23
|
+
const clipboardBinding = /^__browserUseClipboard_[a-f0-9]{32}$/u;
|
|
24
|
+
|
|
25
|
+
/** @param {unknown} method @param {unknown} params @returns {void} */
|
|
26
|
+
export function validatePageCommand(method, params) {
|
|
27
|
+
if (!pageCommands.has(method)) throw new Error(`Unsupported portable browser command: ${String(method)}`);
|
|
28
|
+
if (params === null || typeof params !== "object" || Array.isArray(params)) {
|
|
29
|
+
throw new Error("Invalid portable browser command parameters");
|
|
30
|
+
}
|
|
31
|
+
if (method === "Target.setAutoAttach" &&
|
|
32
|
+
(params.autoAttach !== true || params.flatten !== true || params.waitForDebuggerOnStart !== false ||
|
|
33
|
+
!Array.isArray(params.filter) || params.filter.length !== 1 ||
|
|
34
|
+
params.filter[0]?.type !== "iframe" || params.filter[0]?.exclude !== false)) {
|
|
35
|
+
throw new Error("Portable browser auto-attach is limited to child iframe targets");
|
|
36
|
+
}
|
|
37
|
+
if ((method === "Runtime.addBinding" || method === "Runtime.removeBinding") &&
|
|
38
|
+
(typeof params.name !== "string" || !clipboardBinding.test(params.name))) {
|
|
39
|
+
throw new Error("Portable browser bindings are limited to the engine clipboard");
|
|
40
|
+
}
|
|
41
|
+
if (method === "Page.addScriptToEvaluateOnNewDocument" &&
|
|
42
|
+
(typeof params.source !== "string" || !/\binstallPageClipboardBridge\("__browserUseClipboard_[a-f0-9]{32}"\)/u.test(params.source))) {
|
|
43
|
+
throw new Error("Portable browser document injection is limited to the engine clipboard");
|
|
44
|
+
}
|
|
45
|
+
if (method === "Page.handleJavaScriptDialog" &&
|
|
46
|
+
(typeof params.accept !== "boolean" ||
|
|
47
|
+
(params.promptText !== undefined && typeof params.promptText !== "string"))) {
|
|
48
|
+
throw new Error("Invalid browser dialog response parameters");
|
|
49
|
+
}
|
|
50
|
+
if (method === "Page.setInterceptFileChooserDialog" && typeof params.enabled !== "boolean") {
|
|
51
|
+
throw new Error("Page.setInterceptFileChooserDialog requires a boolean enabled flag");
|
|
52
|
+
}
|
|
53
|
+
if (method === "Network.getResponseBody" &&
|
|
54
|
+
(typeof params.requestId !== "string" || params.requestId.length === 0 || params.requestId.length > 256)) {
|
|
55
|
+
throw new Error("Network.getResponseBody requires a non-empty requestId");
|
|
56
|
+
}
|
|
57
|
+
if (method === "Emulation.setDeviceMetricsOverride") {
|
|
58
|
+
const validSize = (value) => Number.isSafeInteger(value) && value >= 100 && value <= 4096;
|
|
59
|
+
if (!validSize(params.width) || !validSize(params.height) ||
|
|
60
|
+
typeof params.deviceScaleFactor !== "number" || !Number.isFinite(params.deviceScaleFactor) ||
|
|
61
|
+
params.deviceScaleFactor < 0 || params.deviceScaleFactor > 8 ||
|
|
62
|
+
typeof params.mobile !== "boolean") {
|
|
63
|
+
throw new Error("Invalid Emulation.setDeviceMetricsOverride viewport parameters");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (method === "DOM.setFileInputFiles") {
|
|
67
|
+
if (!Array.isArray(params.files) || params.files.length === 0 ||
|
|
68
|
+
params.files.some((file) => typeof file !== "string" || file.length === 0 || !path.isAbsolute(file))) {
|
|
69
|
+
throw new Error("DOM.setFileInputFiles requires non-empty absolute file paths");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (method === "Page.navigate") {
|
|
73
|
+
if (typeof params.url === "string" && params.url.startsWith("about:blank")) return;
|
|
74
|
+
if (typeof params.url !== "string") throw new Error("Browser navigation requires a URL");
|
|
75
|
+
const url = new URL(params.url);
|
|
76
|
+
if (!["http:", "https:", "file:", "data:"].includes(url.protocol) || url.username || url.password) {
|
|
77
|
+
throw new Error("Browser navigation requires an HTTP(S), file, or data URL without credentials");
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** @param {unknown} policy @returns {void} */
|
|
83
|
+
export function validateNetworkPolicy(policy) {
|
|
84
|
+
if (policy === undefined) return;
|
|
85
|
+
if (!Array.isArray(policy?.constraints) || !policy.constraints.every(
|
|
86
|
+
(entry) => ["domains", "origins"].includes(entry?.kind) && entry.mode === "denylist" &&
|
|
87
|
+
Array.isArray(entry.patterns) && entry.patterns.length === 0,
|
|
88
|
+
)) {
|
|
89
|
+
throw new Error("The portable browser backend cannot enforce this browser network policy");
|
|
90
|
+
}
|
|
91
|
+
}
|