omowright 0.0.0 → 0.2.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 +21 -0
- package/README.md +290 -2
- package/TOOLS.md +487 -0
- package/bin/omowright-cloak.mjs +112 -0
- package/package.json +57 -4
- package/presets/agent-events/SKILL.md +75 -0
- package/presets/captcha/SKILL.md +129 -0
- package/presets/chrome/SKILL.md +88 -0
- package/presets/cloak-bridge/SKILL.md +43 -0
- package/presets/network/SKILL.md +126 -0
- package/presets/visual-browse/SKILL.md +103 -0
- package/skills/omowright/SKILL.md +193 -0
- package/skills/omowright/references/1password.md +118 -0
- package/skills/omowright/references/browserskill.md +195 -0
- package/skills/omowright/references/eval-kernel.md +100 -0
- package/skills/omowright/references/frames-layers-human.md +123 -0
- package/skills/omowright/references/quickstart.md +109 -0
- package/skills/omowright/references/stealth.md +174 -0
- package/src/agent-tabs.js +179 -0
- package/src/aria-hidden.js +47 -0
- package/src/bridge-schemas.js +44 -0
- package/src/bridge-transport.js +83 -0
- package/src/browser-context.js +105 -0
- package/src/browser-process.js +127 -0
- package/src/bsk/browser-signals.js +90 -0
- package/src/bsk/browsers.js +114 -0
- package/src/bsk/connect.js +75 -0
- package/src/bsk/daemon-info.js +100 -0
- package/src/bsk/external-extension.js +110 -0
- package/src/bsk/identify-browser.js +88 -0
- package/src/bsk/install-cli.js +81 -0
- package/src/bsk/ipc-client.js +236 -0
- package/src/bsk/onboard.js +140 -0
- package/src/bsk/screenshot.js +49 -0
- package/src/bsk/session.js +131 -0
- package/src/bsk/snapshot.js +56 -0
- package/src/bsk/targets.js +25 -0
- package/src/captcha-wait.js +79 -0
- package/src/captcha.js +142 -0
- package/src/cdp-errors.js +23 -0
- package/src/cdp-methods.js +69 -0
- package/src/chrome-profile.js +176 -0
- package/src/chrome.js +194 -0
- package/src/cloak-profile.js +266 -0
- package/src/connection.js +234 -0
- package/src/console-events.js +12 -0
- package/src/cookies.js +39 -0
- package/src/core.js +1702 -0
- package/src/cua.js +74 -0
- package/src/dialog-policy.js +80 -0
- package/src/emulate.js +127 -0
- package/src/events.js +111 -0
- package/src/frames-snapshot.js +138 -0
- package/src/har.js +103 -0
- package/src/human-handoff.js +124 -0
- package/src/index.js +89 -0
- package/src/injected.js +3 -0
- package/src/instance-lock.js +74 -0
- package/src/instances.js +490 -0
- package/src/internal-capability.js +1 -0
- package/src/launch-endpoint.js +185 -0
- package/src/layers.js +138 -0
- package/src/llm.js +201 -0
- package/src/lock-backend-win32.js +54 -0
- package/src/lock-backend.js +81 -0
- package/src/native-host-win32.js +201 -0
- package/src/network-events.js +223 -0
- package/src/network-snoop.js +229 -0
- package/src/nul-frames.js +28 -0
- package/src/open-shadow-query.js +101 -0
- package/src/owner-only.js +196 -0
- package/src/page-bundle.js +1478 -0
- package/src/page-events.js +45 -0
- package/src/page-routes.js +94 -0
- package/src/page-setup.js +239 -0
- package/src/pipe.js +418 -0
- package/src/process-start-time.js +64 -0
- package/src/routes.js +256 -0
- package/src/running-browser.js +85 -0
- package/src/scroll-collect.js +73 -0
- package/src/serial-emitter.js +17 -0
- package/src/shared-connections.js +285 -0
- package/src/snapshot-diff.js +75 -0
- package/src/text-matching.js +101 -0
- package/src/trace.js +183 -0
- package/src/url-match.js +148 -0
- package/src/viewport.js +12 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Windows half of native-messaging host registration (#90 cluster 3). Chrome on Windows finds a host through the
|
|
2
|
+
// per-user registry value HKCU\Software\<vendor>\<browser>\NativeMessagingHosts\<name> (default value = manifest path),
|
|
3
|
+
// and file safety lives in the owner SID and ACL, not in uid/mode bits. The policy below is the ACL analogue of the
|
|
4
|
+
// POSIX checks in bridge-transport.js: only the user, SYSTEM, Administrators and TrustedInstaller may be able to
|
|
5
|
+
// change the host executable, the directory it starts in, the manifest or its directory, or replace any directory on
|
|
6
|
+
// the path to them. For a .cmd/.bat host only the wrapper and its directory are covered, not what the script runs.
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { mkdir, rmdir, unlink } from "node:fs/promises";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
const SYSTEM = "S-1-5-18";
|
|
13
|
+
const ADMINISTRATORS = "S-1-5-32-544";
|
|
14
|
+
const TRUSTED_INSTALLER = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
|
|
15
|
+
const OWNER_RIGHTS = "S-1-3-4";
|
|
16
|
+
const CREATOR_OWNER = "S-1-3-0";
|
|
17
|
+
|
|
18
|
+
// FileSystemRights bits (winnt.h). Directory names in brackets.
|
|
19
|
+
const WRITE_DATA = 0x2; // [AddFile]
|
|
20
|
+
const APPEND_DATA = 0x4; // [AddSubdirectory]
|
|
21
|
+
const WRITE_EA = 0x10;
|
|
22
|
+
const DELETE_CHILD = 0x40;
|
|
23
|
+
const WRITE_ATTRIBUTES = 0x100;
|
|
24
|
+
const DELETE = 0x10000;
|
|
25
|
+
const WRITE_DAC = 0x40000;
|
|
26
|
+
const WRITE_OWNER = 0x80000;
|
|
27
|
+
const GENERIC_ALL = 0x10000000;
|
|
28
|
+
const GENERIC_WRITE = 0x40000000;
|
|
29
|
+
|
|
30
|
+
// Rights that let a principal change an object's content, metadata, ACL or owner, or delete it.
|
|
31
|
+
const MODIFY = WRITE_DATA | APPEND_DATA | WRITE_EA | WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL | GENERIC_WRITE;
|
|
32
|
+
// What an untrusted principal must not hold on each kind of path component. "final" is a directory whose content
|
|
33
|
+
// matters: the manifest directory, and the host's own directory (Chrome starts the host there, so an .exe loads DLLs
|
|
34
|
+
// and a .cmd resolves bare commands from it).
|
|
35
|
+
const FORBIDDEN = {
|
|
36
|
+
executable: MODIFY,
|
|
37
|
+
manifest: MODIFY,
|
|
38
|
+
final: MODIFY | DELETE_CHILD,
|
|
39
|
+
// An ancestor may let others add entries (default C:\ grants Users AddSubdirectory, the analogue of a sticky root
|
|
40
|
+
// /tmp), but nobody untrusted may delete or rename an existing child, delete the ancestor, or take its ACL.
|
|
41
|
+
ancestor: DELETE_CHILD | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const WIN32_REGISTRY_KEYS = Object.freeze({
|
|
45
|
+
chrome: "HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",
|
|
46
|
+
chromium: "HKCU\\Software\\Chromium\\NativeMessagingHosts",
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export const isWin32RegistryKey = (key) => typeof key === "string" && /^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);
|
|
50
|
+
|
|
51
|
+
// Returns null when the inspected path is safe as `kind` ("executable", "manifest", "final" or "ancestor"), else the
|
|
52
|
+
// reason. `item` is one entry of inspectWin32Paths(); `userSid` is the current user's SID.
|
|
53
|
+
export function win32PathRisk(item, kind, userSid) {
|
|
54
|
+
const trusted = new Set([userSid, SYSTEM, ADMINISTRATORS, TRUSTED_INSTALLER]);
|
|
55
|
+
if (item?.inaccessible) return "could not be inspected";
|
|
56
|
+
if (!item?.exists) return "is missing";
|
|
57
|
+
if (item.reparse) return "is a symlink, junction or other reparse point";
|
|
58
|
+
if (kind === "executable" || kind === "manifest") {
|
|
59
|
+
if (item.directory) return "is not a regular file";
|
|
60
|
+
if (kind === "executable" && !/\.(exe|cmd|bat|com)$/i.test(item.path)) return "is not a .exe, .cmd, .bat or .com file";
|
|
61
|
+
} else if (!item.directory) return "is not a directory";
|
|
62
|
+
if (!trusted.has(item.owner)) return `is owned by untrusted ${item.owner}`;
|
|
63
|
+
trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER); // OWNER RIGHTS = the (trusted) owner; CREATOR OWNER = whoever creates a child
|
|
64
|
+
for (const ace of item.aces ?? []) {
|
|
65
|
+
if (!ace.allow || trusted.has(ace.sid)) continue;
|
|
66
|
+
// An inherit-only ACE does not apply to this object, but on a final directory an object-inheriting one lands on
|
|
67
|
+
// every file created in it (the manifest, a DLL next to the host), so it counts with the file rights.
|
|
68
|
+
const mask = !ace.inheritOnly ? FORBIDDEN[kind] : kind === "final" && ace.objectInherit ? MODIFY : 0;
|
|
69
|
+
if ((Number(ace.rights) & mask) !== 0) return `grants ${ace.sid} write access`;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const systemBinary = (...segments) => {
|
|
75
|
+
const file = path.win32.join(process.env.SystemRoot || "C:\\Windows", "System32", ...segments);
|
|
76
|
+
if (!existsSync(file)) throw new Error(`${file} is missing`);
|
|
77
|
+
return file;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// Exit code of a finished child; a spawn failure, a timeout or a kill rejects (the caller fails closed).
|
|
81
|
+
function run(file, args) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
execFile(file, args, { timeout: 15_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
|
|
84
|
+
if (error && (typeof error.code !== "number" || error.killed)) reject(error);
|
|
85
|
+
else resolve({ code: error ? error.code : 0, stdout, stderr });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// One bounded PowerShell call that reports, for each path in order: whether it exists or could not be read, whether it
|
|
91
|
+
// is a directory or a reparse point, its owner SID and its ACEs (SID, allow/deny, rights mask, inherit-only,
|
|
92
|
+
// object-inherit); plus the current user SID. Paths travel base64-encoded inside the script and nothing path-shaped
|
|
93
|
+
// comes back, so no console code page can garble them. Under Constrained Language Mode the .NET calls fail, and so
|
|
94
|
+
// does the whole inspection: the caller fails closed.
|
|
95
|
+
const INSPECT = `$ErrorActionPreference = 'Stop'
|
|
96
|
+
$paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')))
|
|
97
|
+
$sid = [System.Security.Principal.SecurityIdentifier]
|
|
98
|
+
$items = @(foreach ($p in $paths) {
|
|
99
|
+
try { $i = Get-Item -LiteralPath $p -Force; $acl = Get-Acl -LiteralPath $p }
|
|
100
|
+
catch [System.Management.Automation.ItemNotFoundException] { [pscustomobject]@{ exists = $false; inaccessible = $false }; continue }
|
|
101
|
+
catch { [pscustomobject]@{ exists = $false; inaccessible = $true }; continue }
|
|
102
|
+
$aces = @(foreach ($r in $acl.GetAccessRules($true, $true, $sid)) { [pscustomobject]@{
|
|
103
|
+
sid = $r.IdentityReference.Value; allow = ($r.AccessControlType -eq 'Allow'); rights = [int64]$r.FileSystemRights
|
|
104
|
+
inheritOnly = (($r.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0)
|
|
105
|
+
objectInherit = (($r.InheritanceFlags -band [System.Security.AccessControl.InheritanceFlags]::ObjectInherit) -ne 0) } })
|
|
106
|
+
[pscustomobject]@{ exists = $true; inaccessible = $false; directory = [bool]$i.PSIsContainer; owner = $acl.GetOwner($sid).Value
|
|
107
|
+
aces = $aces; reparse = (($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) }
|
|
108
|
+
})
|
|
109
|
+
ConvertTo-Json -Depth 6 -Compress @{ user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; items = $items }`;
|
|
110
|
+
|
|
111
|
+
export async function inspectWin32Paths(paths) {
|
|
112
|
+
let out;
|
|
113
|
+
try {
|
|
114
|
+
const script = INSPECT.replace("__PATHS__", Buffer.from(JSON.stringify(paths), "utf8").toString("base64"));
|
|
115
|
+
const powershell = systemBinary("WindowsPowerShell", "v1.0", "powershell.exe");
|
|
116
|
+
const result = await run(powershell, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")]);
|
|
117
|
+
if (result.code !== 0) throw new Error(String(result.stderr).trim() || `exit ${result.code}`);
|
|
118
|
+
out = JSON.parse(result.stdout);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
throw new Error(`native host security could not be verified (the PowerShell ACL inspection failed; Constrained Language Mode or a policy may block it): ${error.message}`);
|
|
121
|
+
}
|
|
122
|
+
const items = [out.items ?? []].flat();
|
|
123
|
+
if (typeof out.user !== "string" || items.length !== paths.length) throw new Error("native host security could not be verified: unexpected ACL report");
|
|
124
|
+
return { user: out.user, items: items.map((item, index) => ({ ...item, path: paths[index], aces: [item.aces ?? []].flat() })) };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Every directory from the drive root down to `dir`, root first. Only local drive-letter paths are accepted: a UNC or
|
|
128
|
+
// \\?\ root has an ACL this host does not own and cannot be walked the same way.
|
|
129
|
+
export function win32DirectoryChain(dir) {
|
|
130
|
+
const absolute = path.win32.resolve(dir);
|
|
131
|
+
const { root } = path.win32.parse(absolute);
|
|
132
|
+
if (!/^[A-Za-z]:\\$/.test(root) || /^\\\\/.test(dir)) throw new Error(`${dir} is not on a local drive-letter path`);
|
|
133
|
+
const chain = [root];
|
|
134
|
+
for (const part of absolute.slice(root.length).split("\\").filter(Boolean)) chain.push(path.win32.join(chain.at(-1), part));
|
|
135
|
+
return chain;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function registryDefault(key, view) {
|
|
139
|
+
const result = await run(systemBinary("reg.exe"), ["query", key, "/ve", ...(view ? [`/reg:${view}`] : [])]);
|
|
140
|
+
if (result.code !== 0) return null;
|
|
141
|
+
return /REG_SZ\s+(.*?)\s*$/m.exec(result.stdout)?.[1] ?? "";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Verifies the host and the manifest directory, writes the manifest through `writeManifest(file)` (the shared atomic
|
|
145
|
+
// writer), re-verifies the written file, then points the per-user registry value at it.
|
|
146
|
+
export async function installWin32NativeHost({ hostName, hostPath, dir, registryKey, force, writeManifest }) {
|
|
147
|
+
const hostChain = win32DirectoryChain(path.win32.dirname(hostPath));
|
|
148
|
+
win32DirectoryChain(hostPath);
|
|
149
|
+
const dirChain = win32DirectoryChain(dir);
|
|
150
|
+
const { user, items } = await inspectWin32Paths([hostPath, ...hostChain, ...dirChain]);
|
|
151
|
+
const reject = (prefix, item, kind) => { const risk = win32PathRisk(item, kind, user); if (risk) throw new Error(`${prefix}: ${item.path} ${risk}`); };
|
|
152
|
+
const kindAt = (chain, index) => (index === chain.length - 1 ? "final" : "ancestor");
|
|
153
|
+
reject("hostPath must be a securely owned executable file", items[0], "executable");
|
|
154
|
+
items.slice(1, 1 + hostChain.length).forEach((item, index) => reject("hostPath directory security rejected", item, kindAt(hostChain, index)));
|
|
155
|
+
const dirItems = items.slice(1 + hostChain.length);
|
|
156
|
+
const firstMissing = dirItems.findIndex((item) => !item.exists && !item.inaccessible);
|
|
157
|
+
dirItems.slice(0, firstMissing === -1 ? undefined : firstMissing).forEach((item, index) => reject("nativeMessagingHostDir security rejected", item, kindAt(dirChain, index)));
|
|
158
|
+
if (firstMissing === 0) throw new Error(`nativeMessagingHostDir security rejected: ${dirChain[0]} is missing`);
|
|
159
|
+
const created = firstMissing > 0 ? dirChain.slice(firstMissing) : [];
|
|
160
|
+
const file = path.win32.join(dirChain.at(-1), `${hostName}.json`);
|
|
161
|
+
// Only what this call itself created is removed on failure: the directories its own mkdir made (a concurrent install
|
|
162
|
+
// may have made them first) and the manifest only after its own write produced it.
|
|
163
|
+
const firstMade = created.length ? await mkdir(dirChain.at(-1), { recursive: true }) : undefined;
|
|
164
|
+
// mkdir creates a tail of dirChain and reports its first directory, possibly in \\?\ or long-name form, so locate it
|
|
165
|
+
// by depth rather than by spelling: C:\a\b has three components and is dirChain[2].
|
|
166
|
+
const madeDepth = firstMade === undefined ? 0 : firstMade.replace(/^\\\\\?\\/, "").split(/[\\/]+/).filter(Boolean).length;
|
|
167
|
+
const made = madeDepth > 0 && madeDepth <= dirChain.length ? dirChain.slice(madeDepth - 1) : [];
|
|
168
|
+
let wroteManifest = false;
|
|
169
|
+
try {
|
|
170
|
+
if (created.length) {
|
|
171
|
+
const again = await inspectWin32Paths(created);
|
|
172
|
+
if (again.user !== user) throw new Error("native host security could not be verified: user changed");
|
|
173
|
+
again.items.forEach((item, offset) => reject("nativeMessagingHostDir security rejected", item, kindAt(dirChain, firstMissing + offset)));
|
|
174
|
+
}
|
|
175
|
+
const hostKey = `${registryKey}\\${hostName}`;
|
|
176
|
+
// Chromium reads HKLM before HKCU, so a machine-level entry would win; refuse before writing anything.
|
|
177
|
+
const machineKey = `HKLM\\${hostKey.slice("HKCU\\".length)}`;
|
|
178
|
+
for (const view of ["32", "64"]) {
|
|
179
|
+
if (await registryDefault(machineKey, view) !== null) throw new Error(`${hostKey} is shadowed by a machine-level registration at ${machineKey} (/reg:${view})`);
|
|
180
|
+
}
|
|
181
|
+
const current = await registryDefault(hostKey);
|
|
182
|
+
if (current !== null && current.toLowerCase() !== file.toLowerCase() && !force) throw new Error(`${hostKey} already points at ${current}; use force`);
|
|
183
|
+
const manifest = await writeManifest(file);
|
|
184
|
+
wroteManifest = true;
|
|
185
|
+
const written = await inspectWin32Paths([file]);
|
|
186
|
+
const manifestRisk = win32PathRisk(written.items[0], "manifest", user);
|
|
187
|
+
// On a force reinstall the HKCU value may already name this path; it then points at a missing file, which Chrome
|
|
188
|
+
// treats as no host, and nobody untrusted can recreate the file in the verified directory.
|
|
189
|
+
if (manifestRisk) { await unlink(file).catch(() => {}); throw new Error(`native messaging manifest security rejected: ${file} ${manifestRisk}`); }
|
|
190
|
+
const added = await run(systemBinary("reg.exe"), ["add", hostKey, "/ve", "/t", "REG_SZ", "/d", file, "/f"]);
|
|
191
|
+
if (added.code !== 0) throw new Error(`native host registry write failed: ${String(added.stderr).trim()}`);
|
|
192
|
+
return { path: file, manifest, registryKey: hostKey };
|
|
193
|
+
} catch (error) {
|
|
194
|
+
// rmdir (not recursive) leaves a directory alone once another install has put a file in it.
|
|
195
|
+
if (made.length) {
|
|
196
|
+
if (wroteManifest) await unlink(file).catch(() => {});
|
|
197
|
+
for (const entry of [...made].reverse()) await rmdir(entry).catch(() => {});
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { urlMatches } from "./url-match.js";
|
|
2
|
+
|
|
3
|
+
const sessions = new WeakMap();
|
|
4
|
+
const streams = new WeakMap();
|
|
5
|
+
const METHODS = [
|
|
6
|
+
"Network.requestWillBeSent", "Network.responseReceived",
|
|
7
|
+
"Network.loadingFinished", "Network.loadingFailed",
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
// Readiness tracking and user-facing capture share ownership of the domain.
|
|
11
|
+
// A refused enable is not a page-setup failure (embedded transports may refuse it).
|
|
12
|
+
export function acquireNetwork(cdp, sessionId) {
|
|
13
|
+
let active = sessions.get(cdp);
|
|
14
|
+
if (!active) sessions.set(cdp, active = new Map());
|
|
15
|
+
let state = active.get(sessionId);
|
|
16
|
+
if (!state) {
|
|
17
|
+
state = { users: 0 };
|
|
18
|
+
active.set(sessionId, state);
|
|
19
|
+
state.ready = cdp.send("Network.enable", undefined, sessionId).catch(() => {});
|
|
20
|
+
}
|
|
21
|
+
state.users++;
|
|
22
|
+
let released = false;
|
|
23
|
+
const release = () => {
|
|
24
|
+
if (released) return;
|
|
25
|
+
released = true;
|
|
26
|
+
if (--state.users) return;
|
|
27
|
+
active.delete(sessionId);
|
|
28
|
+
// Order disable before a subsequent acquire's enable, even if the first
|
|
29
|
+
// enable has not completed yet.
|
|
30
|
+
cdp.send("Network.disable", undefined, sessionId).catch(() => {});
|
|
31
|
+
};
|
|
32
|
+
release.ready = state.ready;
|
|
33
|
+
return release;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class NetworkBodyUnavailableError extends Error {
|
|
37
|
+
constructor(message, cause) {
|
|
38
|
+
super(message, { cause });
|
|
39
|
+
this.name = "NetworkBodyUnavailableError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function headers(values = {}) {
|
|
44
|
+
return Object.fromEntries(Object.entries(values).map(([key, value]) => [key.toLowerCase(), String(value)]));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function bodyReaders(body) {
|
|
48
|
+
return {
|
|
49
|
+
body,
|
|
50
|
+
async text() { return (await body()).toString("utf8"); },
|
|
51
|
+
async json() { return JSON.parse(await this.text()); },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function recordFor(cdp, sessionId, params) {
|
|
56
|
+
const request = params.request ?? {};
|
|
57
|
+
const finished = Promise.withResolvers();
|
|
58
|
+
let rawBody;
|
|
59
|
+
const record = {
|
|
60
|
+
exposed: false,
|
|
61
|
+
finish: finished.resolve,
|
|
62
|
+
rawBody() {
|
|
63
|
+
return rawBody ??= finished.promise.then(async failure => {
|
|
64
|
+
try {
|
|
65
|
+
if (failure) throw failure;
|
|
66
|
+
return await cdp.send("Network.getResponseBody", { requestId: params.requestId }, sessionId);
|
|
67
|
+
} catch (cause) {
|
|
68
|
+
throw new NetworkBodyUnavailableError(`Response body is unavailable for ${request.url}`, cause);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
record.request = {
|
|
74
|
+
url: () => request.url ?? params.documentURL ?? "",
|
|
75
|
+
method: () => request.method ?? "GET",
|
|
76
|
+
headers: () => headers(request.headers),
|
|
77
|
+
...bodyReaders(async () => Buffer.from(request.postData ?? "", "utf8")),
|
|
78
|
+
};
|
|
79
|
+
record.setResponse = response => {
|
|
80
|
+
record.response = {
|
|
81
|
+
url: () => response.url ?? record.request.url(),
|
|
82
|
+
method: record.request.method,
|
|
83
|
+
headers: () => headers(response.headers),
|
|
84
|
+
status: () => response.status,
|
|
85
|
+
ok: () => response.status >= 200 && response.status <= 299,
|
|
86
|
+
...bodyReaders(async () => {
|
|
87
|
+
const result = await record.rawBody();
|
|
88
|
+
return Buffer.from(result.body ?? "", result.base64Encoded ? "base64" : "utf8");
|
|
89
|
+
}),
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
return record;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// One CDP event path per page, shared by page events, snoops and traces.
|
|
96
|
+
// Network.enable itself is shared per session with the readiness tracker.
|
|
97
|
+
export function subscribeNetwork(page, handlers) {
|
|
98
|
+
let stream = streams.get(page);
|
|
99
|
+
if (!stream) {
|
|
100
|
+
const observers = new Set();
|
|
101
|
+
const inflight = new Map();
|
|
102
|
+
const unsubscribers = [];
|
|
103
|
+
let sessionId;
|
|
104
|
+
let release;
|
|
105
|
+
let closed = false;
|
|
106
|
+
const ready = Promise.resolve(page.resolveSessionId()).then(async id => {
|
|
107
|
+
sessionId = id;
|
|
108
|
+
if (!closed) {
|
|
109
|
+
release = acquireNetwork(page.cdp, id);
|
|
110
|
+
await release.ready;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
ready.catch(() => {});
|
|
114
|
+
const close = (force = false) => {
|
|
115
|
+
if (closed || (!force && (observers.size || inflight.size))) return;
|
|
116
|
+
closed = true;
|
|
117
|
+
for (const record of inflight.values()) record.finish(Error("Page network capture disposed"));
|
|
118
|
+
inflight.clear();
|
|
119
|
+
observers.clear();
|
|
120
|
+
for (const off of unsubscribers) off();
|
|
121
|
+
release?.();
|
|
122
|
+
streams.delete(page);
|
|
123
|
+
};
|
|
124
|
+
const dispatch = (method, params) => {
|
|
125
|
+
let record = inflight.get(params.requestId);
|
|
126
|
+
if (method === "Network.requestWillBeSent") {
|
|
127
|
+
// Redirects reuse request ids; the previous hop has no readable body.
|
|
128
|
+
record?.finish(Error("Request redirected"));
|
|
129
|
+
record = recordFor(page.cdp, sessionId, params);
|
|
130
|
+
inflight.set(params.requestId, record);
|
|
131
|
+
} else if (method === "Network.responseReceived") {
|
|
132
|
+
record?.setResponse(params.response ?? {});
|
|
133
|
+
} else {
|
|
134
|
+
record?.finish(method === "Network.loadingFailed" ? Error(params.errorText ?? "Request failed") : null);
|
|
135
|
+
}
|
|
136
|
+
for (const observer of observers) observer[method]?.(params, record);
|
|
137
|
+
if (method === "Network.loadingFinished" || method === "Network.loadingFailed") {
|
|
138
|
+
// Preserve bodies for returned response objects before the last
|
|
139
|
+
// listener releases the domain (disable clears the browser cache).
|
|
140
|
+
const done = record?.exposed && record.response
|
|
141
|
+
? record.rawBody().catch(() => {}) : Promise.resolve();
|
|
142
|
+
done.finally(() => {
|
|
143
|
+
if (inflight.get(params.requestId) === record) inflight.delete(params.requestId);
|
|
144
|
+
close();
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
for (const method of METHODS) {
|
|
149
|
+
unsubscribers.push(page.cdp.on(method, (params, meta) => {
|
|
150
|
+
if (closed) return;
|
|
151
|
+
if (sessionId === undefined) {
|
|
152
|
+
ready.then(() => {
|
|
153
|
+
if (!closed && meta?.sessionId === sessionId) dispatch(method, params);
|
|
154
|
+
}).catch(() => {});
|
|
155
|
+
} else if (meta?.sessionId === sessionId) dispatch(method, params);
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
stream = { observers, close, inflight, ready };
|
|
159
|
+
streams.set(page, stream);
|
|
160
|
+
}
|
|
161
|
+
stream.observers.add(handlers);
|
|
162
|
+
return () => {
|
|
163
|
+
stream.observers.delete(handlers);
|
|
164
|
+
// Unobserved requests without a returned response need no further work.
|
|
165
|
+
for (const [id, record] of stream.inflight) {
|
|
166
|
+
if (!record.exposed && !stream.observers.size) {
|
|
167
|
+
record.finish(Error("Network capture disposed"));
|
|
168
|
+
stream.inflight.delete(id);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
stream.close();
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Holds the shared stream for one navigation call. A frame's document records
|
|
176
|
+
// are exposed so bodies stay readable after the domain is released.
|
|
177
|
+
export function trackDocumentResponses(page, frameId) {
|
|
178
|
+
const documents = new Map();
|
|
179
|
+
const dispose = subscribeNetwork(page, {
|
|
180
|
+
"Network.requestWillBeSent": (params, record) => {
|
|
181
|
+
if (params.type !== "Document" || params.frameId !== frameId) return;
|
|
182
|
+
record.exposed = true;
|
|
183
|
+
// Redirect hops share the loader id; the last hop carries the final response.
|
|
184
|
+
documents.set(params.loaderId, record);
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
return {
|
|
188
|
+
ready: networkReady(page),
|
|
189
|
+
response: loaderId => documents.get(loaderId)?.response ?? null,
|
|
190
|
+
dispose,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function disposeNetwork(page) {
|
|
195
|
+
streams.get(page)?.close(true);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function networkReady(page) {
|
|
199
|
+
return streams.get(page)?.ready;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function subscribePageNetworkEvents(page) {
|
|
203
|
+
const emit = (name, value) => page.events.emit(name, value)
|
|
204
|
+
.catch(error => console.warn("[network] page event listener failed", error));
|
|
205
|
+
return subscribeNetwork(page, {
|
|
206
|
+
"Network.requestWillBeSent": (_params, record) => emit("request", record.request),
|
|
207
|
+
"Network.responseReceived": (_params, record) => {
|
|
208
|
+
if (!record) return;
|
|
209
|
+
record.exposed = true;
|
|
210
|
+
emit("response", record.response);
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function networkPredicate(match) {
|
|
216
|
+
if (typeof match === "function") return match;
|
|
217
|
+
if (match instanceof RegExp) return value => {
|
|
218
|
+
match.lastIndex = 0;
|
|
219
|
+
return match.test(value.url());
|
|
220
|
+
};
|
|
221
|
+
if (typeof match === "string") return value => urlMatches(value.url(), match);
|
|
222
|
+
throw new TypeError("urlOrPredicate must be a URL string, RegExp or predicate");
|
|
223
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { subscribeNetwork } from "./network-events.js";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
4
|
+
const JSON_MIME = /^application\/json\s*(;|$)|\+json\s*(;|$)/i;
|
|
5
|
+
|
|
6
|
+
function matchesText(value, pattern) {
|
|
7
|
+
if (pattern === undefined) return true;
|
|
8
|
+
if (value === null || value === undefined) return false;
|
|
9
|
+
if (pattern instanceof RegExp) return pattern.test(String(value));
|
|
10
|
+
return String(value).includes(String(pattern));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function matchesToken(value, expected) {
|
|
14
|
+
if (expected === undefined) return true;
|
|
15
|
+
if (value === null || value === undefined) return false;
|
|
16
|
+
return String(value).toLowerCase() === String(expected).toLowerCase();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function toPredicate(match) {
|
|
20
|
+
if (match === undefined || match === null) return () => true;
|
|
21
|
+
if (typeof match === "function") return match;
|
|
22
|
+
if (typeof match !== "object") throw new TypeError("match must be a predicate function or a descriptor object");
|
|
23
|
+
return entry => matchesText(entry.url, match.url)
|
|
24
|
+
&& matchesToken(entry.method, match.method)
|
|
25
|
+
&& matchesText(entry.mimeType, match.mimeType)
|
|
26
|
+
&& matchesToken(entry.resourceType, match.resourceType);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function startedAtOf(params) {
|
|
30
|
+
const wallTime = Number(params?.wallTime);
|
|
31
|
+
return Number.isFinite(wallTime) && wallTime > 0 ? Math.round(wallTime * 1000) : Date.now();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function decodeBody(entry) {
|
|
35
|
+
if (typeof entry.body !== "string") return null;
|
|
36
|
+
return entry.base64Encoded ? Buffer.from(entry.body, "base64").toString("utf8") : entry.body;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Buffers CDP network traffic for a single page session.
|
|
41
|
+
*
|
|
42
|
+
* Entries are tracked while in flight and committed to the buffer once they finish
|
|
43
|
+
* (or fail), so filters may depend on response-only fields such as status or mimeType.
|
|
44
|
+
*/
|
|
45
|
+
export function createNetworkSnoop(page, options = {}) {
|
|
46
|
+
if (!page?.cdp || typeof page.resolveSessionId !== "function") {
|
|
47
|
+
throw new TypeError("createNetworkSnoop requires a page with cdp and resolveSessionId");
|
|
48
|
+
}
|
|
49
|
+
const { match, bodies = true, maxEntries = 500, maxBodyBytes = 5_000_000 } = options;
|
|
50
|
+
const wanted = toPredicate(match);
|
|
51
|
+
|
|
52
|
+
const inflight = new Map();
|
|
53
|
+
const buffer = [];
|
|
54
|
+
const waiters = new Set();
|
|
55
|
+
const handlers = {};
|
|
56
|
+
let disposed = false;
|
|
57
|
+
let queue = Promise.resolve();
|
|
58
|
+
|
|
59
|
+
function subscribe(method, handler) {
|
|
60
|
+
handlers[method] = handler;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function enqueue(task) {
|
|
64
|
+
queue = queue.then(task).catch(error => console.warn("[network-snoop] entry processing failed", error));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function loadBody(entry, record) {
|
|
68
|
+
if (entry.encodedDataLength > maxBodyBytes) {
|
|
69
|
+
entry.bodySkipped = true;
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const result = await record.rawBody();
|
|
74
|
+
entry.body = result?.body ?? null;
|
|
75
|
+
entry.base64Encoded = Boolean(result?.base64Encoded);
|
|
76
|
+
} catch {
|
|
77
|
+
// Bodies expire with the network cache; keep the entry, drop the body.
|
|
78
|
+
entry.body = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function commit(entry) {
|
|
83
|
+
buffer.push(entry);
|
|
84
|
+
while (buffer.length > maxEntries) buffer.shift();
|
|
85
|
+
for (const waiter of [...waiters]) if (waiter.test(entry)) waiter.resolve(entry);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
subscribe("Network.requestWillBeSent", params => {
|
|
89
|
+
const requestId = params?.requestId;
|
|
90
|
+
if (!requestId) return;
|
|
91
|
+
inflight.set(requestId, {
|
|
92
|
+
requestId,
|
|
93
|
+
url: params.request?.url ?? params.documentURL ?? "",
|
|
94
|
+
method: params.request?.method ?? "GET",
|
|
95
|
+
resourceType: params.type ?? null,
|
|
96
|
+
status: null,
|
|
97
|
+
statusText: null,
|
|
98
|
+
mimeType: null,
|
|
99
|
+
requestHeaders: params.request?.headers ?? {},
|
|
100
|
+
responseHeaders: null,
|
|
101
|
+
remoteIPAddress: null,
|
|
102
|
+
postData: params.request?.postData ?? null,
|
|
103
|
+
encodedDataLength: 0,
|
|
104
|
+
body: null,
|
|
105
|
+
base64Encoded: false,
|
|
106
|
+
bodySkipped: false,
|
|
107
|
+
failed: false,
|
|
108
|
+
errorText: null,
|
|
109
|
+
startedAt: startedAtOf(params),
|
|
110
|
+
finishedAt: null,
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
subscribe("Network.responseReceived", params => {
|
|
115
|
+
const entry = inflight.get(params?.requestId);
|
|
116
|
+
if (!entry) return;
|
|
117
|
+
const response = params.response ?? {};
|
|
118
|
+
entry.status = response.status ?? null;
|
|
119
|
+
entry.statusText = response.statusText ?? "";
|
|
120
|
+
entry.mimeType = response.mimeType ?? null;
|
|
121
|
+
entry.responseHeaders = response.headers ?? {};
|
|
122
|
+
entry.remoteIPAddress = response.remoteIPAddress ?? null;
|
|
123
|
+
if (params.type) entry.resourceType = params.type;
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
subscribe("Network.loadingFinished", (params, record) => {
|
|
127
|
+
const entry = inflight.get(params?.requestId);
|
|
128
|
+
if (!entry) return;
|
|
129
|
+
inflight.delete(entry.requestId);
|
|
130
|
+
entry.encodedDataLength = Number(params.encodedDataLength ?? 0);
|
|
131
|
+
entry.finishedAt = Date.now();
|
|
132
|
+
enqueue(async () => {
|
|
133
|
+
if (!wanted(entry)) return;
|
|
134
|
+
if (bodies) await loadBody(entry, record);
|
|
135
|
+
commit(entry);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
subscribe("Network.loadingFailed", params => {
|
|
140
|
+
const entry = inflight.get(params?.requestId);
|
|
141
|
+
if (!entry) return;
|
|
142
|
+
inflight.delete(entry.requestId);
|
|
143
|
+
entry.failed = true;
|
|
144
|
+
entry.errorText = params.errorText ?? "";
|
|
145
|
+
entry.encodedDataLength = Number(params.encodedDataLength ?? entry.encodedDataLength);
|
|
146
|
+
entry.finishedAt = Date.now();
|
|
147
|
+
enqueue(async () => { if (wanted(entry)) commit(entry); });
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
function pop() {
|
|
151
|
+
return buffer.splice(0, buffer.length);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function peek() {
|
|
155
|
+
return [...buffer];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function popJson() {
|
|
159
|
+
const values = [];
|
|
160
|
+
for (const entry of pop()) {
|
|
161
|
+
if (!JSON_MIME.test(String(entry.mimeType ?? ""))) continue;
|
|
162
|
+
const text = decodeBody(entry);
|
|
163
|
+
if (text === null) continue;
|
|
164
|
+
try {
|
|
165
|
+
values.push(JSON.parse(text));
|
|
166
|
+
} catch {
|
|
167
|
+
// Truncated or non-JSON payload on a JSON content type: drop it silently.
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return values;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function waitFor(match, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
174
|
+
if (disposed) return Promise.reject(Error("Network snoop is disposed"));
|
|
175
|
+
const predicate = toPredicate(match);
|
|
176
|
+
return new Promise((resolve, reject) => {
|
|
177
|
+
let settled = false;
|
|
178
|
+
const waiter = {};
|
|
179
|
+
const finish = callback => value => {
|
|
180
|
+
if (settled) return;
|
|
181
|
+
settled = true;
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
waiters.delete(waiter);
|
|
184
|
+
callback(value);
|
|
185
|
+
};
|
|
186
|
+
waiter.resolve = finish(resolve);
|
|
187
|
+
waiter.reject = finish(reject);
|
|
188
|
+
waiter.test = entry => {
|
|
189
|
+
try {
|
|
190
|
+
return Boolean(predicate(entry));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
waiter.reject(error instanceof Error ? error : Error(String(error)));
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const timer = setTimeout(
|
|
197
|
+
() => waiter.reject(Error(`Timed out waiting for network response after ${timeoutMs}ms`)),
|
|
198
|
+
timeoutMs,
|
|
199
|
+
);
|
|
200
|
+
waiters.add(waiter);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function summary({ max = 50 } = {}) {
|
|
205
|
+
const shown = buffer.slice(0, max);
|
|
206
|
+
const lines = shown.map(entry => [
|
|
207
|
+
entry.method,
|
|
208
|
+
entry.status ?? (entry.failed ? "FAILED" : "-"),
|
|
209
|
+
entry.mimeType ?? "-",
|
|
210
|
+
`${entry.encodedDataLength}B`,
|
|
211
|
+
entry.url,
|
|
212
|
+
].join(" "));
|
|
213
|
+
const hidden = buffer.length - shown.length;
|
|
214
|
+
if (hidden > 0) lines.push(`... +${hidden} more`);
|
|
215
|
+
return lines.join("\n");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function dispose() {
|
|
219
|
+
if (disposed) return;
|
|
220
|
+
disposed = true;
|
|
221
|
+
unsubscribe();
|
|
222
|
+
for (const waiter of [...waiters]) waiter.reject(Error("Network snoop disposed"));
|
|
223
|
+
waiters.clear();
|
|
224
|
+
inflight.clear();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const unsubscribe = subscribeNetwork(page, handlers);
|
|
228
|
+
return { pop, peek, popJson, waitFor, summary, dispose };
|
|
229
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Reassembles NUL-delimited frames (the CDP pipe's framing) from stream chunks.
|
|
2
|
+
// Only the newly arrived chunk is scanned for the delimiter, and a frame that
|
|
3
|
+
// spans chunks is joined once, when its delimiter arrives, so receiving costs
|
|
4
|
+
// one copy of each byte. Re-copying the pending bytes on every chunk made a
|
|
5
|
+
// large reply quadratic in its size (#237).
|
|
6
|
+
export class NulFrameReader {
|
|
7
|
+
#parts = [];
|
|
8
|
+
|
|
9
|
+
// Returns the frames that chunk completes, decoded as UTF-8, empty ones included.
|
|
10
|
+
push(chunk) {
|
|
11
|
+
const frames = [];
|
|
12
|
+
let start = 0;
|
|
13
|
+
let end;
|
|
14
|
+
while ((end = chunk.indexOf(0, start)) !== -1) {
|
|
15
|
+
const tail = chunk.subarray(start, end);
|
|
16
|
+
let frame = tail;
|
|
17
|
+
if (this.#parts.length > 0) {
|
|
18
|
+
this.#parts.push(tail);
|
|
19
|
+
frame = Buffer.concat(this.#parts);
|
|
20
|
+
this.#parts = [];
|
|
21
|
+
}
|
|
22
|
+
frames.push(frame.toString("utf8"));
|
|
23
|
+
start = end + 1;
|
|
24
|
+
}
|
|
25
|
+
if (start < chunk.length) this.#parts.push(chunk.subarray(start));
|
|
26
|
+
return frames;
|
|
27
|
+
}
|
|
28
|
+
}
|