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,266 @@
|
|
|
1
|
+
import { randomInt } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
mkdir,
|
|
4
|
+
open,
|
|
5
|
+
readFile,
|
|
6
|
+
unlink,
|
|
7
|
+
} from "node:fs/promises";
|
|
8
|
+
import { globSync } from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { connectNamed, listInstances, withEngineLock } from "./instances.js";
|
|
12
|
+
import { restrictToOwner } from "./owner-only.js";
|
|
13
|
+
import { connectPipe } from "./pipe.js";
|
|
14
|
+
|
|
15
|
+
const LEGACY_PROBE_TIMEOUT_MS = 1500;
|
|
16
|
+
|
|
17
|
+
const MIN_FINGERPRINT_SEED = 10_000;
|
|
18
|
+
const MAX_FINGERPRINT_SEED = 99_999;
|
|
19
|
+
const METADATA_FILE = ".omowright-cloak.json";
|
|
20
|
+
const DEFAULT_PROFILE_DIR = path.join(
|
|
21
|
+
os.homedir(),
|
|
22
|
+
".local",
|
|
23
|
+
"share",
|
|
24
|
+
"omowright-cloak",
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
function normalizeFingerprintSeed(value) {
|
|
28
|
+
const seed = typeof value === "string" && value.trim() !== ""
|
|
29
|
+
? Number(value)
|
|
30
|
+
: value;
|
|
31
|
+
if (
|
|
32
|
+
!Number.isInteger(seed) ||
|
|
33
|
+
seed < MIN_FINGERPRINT_SEED ||
|
|
34
|
+
seed > MAX_FINGERPRINT_SEED
|
|
35
|
+
) {
|
|
36
|
+
throw new RangeError(
|
|
37
|
+
`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return seed;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function platformFingerprint() {
|
|
44
|
+
return process.platform === "darwin" ? "macos" : "windows";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function identityFlag(value) {
|
|
48
|
+
return /^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function buildCloakBrowserArgs({
|
|
52
|
+
profileDir,
|
|
53
|
+
fingerprintSeed,
|
|
54
|
+
extraArgs = [],
|
|
55
|
+
} = {}) {
|
|
56
|
+
const profile = path.resolve(profileDir ?? DEFAULT_PROFILE_DIR);
|
|
57
|
+
const seed = normalizeFingerprintSeed(fingerprintSeed);
|
|
58
|
+
const conflicting = extraArgs.filter(identityFlag);
|
|
59
|
+
if (conflicting.length > 0) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return [
|
|
65
|
+
"--no-first-run",
|
|
66
|
+
"--no-default-browser-check",
|
|
67
|
+
"--disable-session-crashed-bubble",
|
|
68
|
+
`--user-data-dir=${profile}`,
|
|
69
|
+
`--fingerprint=${seed}`,
|
|
70
|
+
`--fingerprint-platform=${platformFingerprint()}`,
|
|
71
|
+
...extraArgs,
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function readMetadata(metadataPath) {
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(await readFile(metadataPath, "utf8"));
|
|
78
|
+
return normalizeFingerprintSeed(parsed.fingerprintSeed);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error?.code === "ENOENT") return null;
|
|
81
|
+
if (error instanceof SyntaxError) {
|
|
82
|
+
throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`);
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function writeMetadata(metadataPath, fingerprintSeed) {
|
|
89
|
+
const handle = await open(metadataPath, "wx", 0o600);
|
|
90
|
+
try {
|
|
91
|
+
await handle.writeFile(
|
|
92
|
+
`${JSON.stringify({ fingerprintSeed }, null, 2)}\n`,
|
|
93
|
+
"utf8",
|
|
94
|
+
);
|
|
95
|
+
} finally {
|
|
96
|
+
await handle.close();
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
await restrictToOwner(metadataPath, "file");
|
|
100
|
+
} catch (error) {
|
|
101
|
+
// Fail closed: never leave a fresh seed file under the inherited ACL.
|
|
102
|
+
await unlink(metadataPath).catch(() => {});
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function resolveCloakProfile({
|
|
108
|
+
profileDir = DEFAULT_PROFILE_DIR,
|
|
109
|
+
fingerprintSeed,
|
|
110
|
+
randomSeed = () => randomInt(MIN_FINGERPRINT_SEED, MAX_FINGERPRINT_SEED + 1),
|
|
111
|
+
} = {}) {
|
|
112
|
+
const resolvedProfile = path.resolve(profileDir);
|
|
113
|
+
const metadataPath = path.join(resolvedProfile, METADATA_FILE);
|
|
114
|
+
await mkdir(resolvedProfile, { recursive: true, mode: 0o700 });
|
|
115
|
+
await restrictToOwner(resolvedProfile, "directory");
|
|
116
|
+
|
|
117
|
+
const requested = fingerprintSeed === undefined
|
|
118
|
+
? null
|
|
119
|
+
: normalizeFingerprintSeed(fingerprintSeed);
|
|
120
|
+
let stored = await readMetadata(metadataPath);
|
|
121
|
+
|
|
122
|
+
if (stored === null) {
|
|
123
|
+
const candidate = requested ?? normalizeFingerprintSeed(randomSeed());
|
|
124
|
+
try {
|
|
125
|
+
await writeMetadata(metadataPath, candidate);
|
|
126
|
+
stored = candidate;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error?.code !== "EEXIST") throw error;
|
|
129
|
+
stored = await readMetadata(metadataPath);
|
|
130
|
+
if (stored === null) {
|
|
131
|
+
throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (requested !== null && requested !== stored) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
await restrictToOwner(metadataPath, "file");
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
profileDir: resolvedProfile,
|
|
146
|
+
metadataPath,
|
|
147
|
+
fingerprintSeed: stored,
|
|
148
|
+
browserArgs: buildCloakBrowserArgs({
|
|
149
|
+
profileDir: resolvedProfile,
|
|
150
|
+
fingerprintSeed: stored,
|
|
151
|
+
}),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function findCloakBrowserPath({
|
|
156
|
+
browserRoot = path.join(os.homedir(), ".cloakbrowser"),
|
|
157
|
+
} = {}) {
|
|
158
|
+
const candidates = globSync(
|
|
159
|
+
path.join(
|
|
160
|
+
path.resolve(browserRoot),
|
|
161
|
+
"chromium-*",
|
|
162
|
+
"Chromium.app",
|
|
163
|
+
"Contents",
|
|
164
|
+
"MacOS",
|
|
165
|
+
"Chromium",
|
|
166
|
+
),
|
|
167
|
+
).sort();
|
|
168
|
+
const browserPath = candidates.at(-1);
|
|
169
|
+
if (!browserPath) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`CloakBrowser binary not found under ${path.resolve(browserRoot)}; set CLOAKBROWSER_BIN`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return browserPath;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function assertCloakLaunchClear({
|
|
178
|
+
browserPath,
|
|
179
|
+
profileDir,
|
|
180
|
+
registryRoot,
|
|
181
|
+
legacyProbeUrl,
|
|
182
|
+
probeTimeoutMs,
|
|
183
|
+
}) {
|
|
184
|
+
const records = await listInstances({ registryRoot, probeTimeoutMs });
|
|
185
|
+
for (const record of records) {
|
|
186
|
+
if (!record.alive || !record.responsive) continue;
|
|
187
|
+
if (!record.profileDir) continue;
|
|
188
|
+
if (path.resolve(record.profileDir) === path.resolve(profileDir)) continue;
|
|
189
|
+
// Records store a resolved path; the caller's may be relative or spelled
|
|
190
|
+
// differently, and an unresolved compare would skip the guard.
|
|
191
|
+
if (path.resolve(record.browserPath) !== path.resolve(browserPath)) continue;
|
|
192
|
+
throw new Error(
|
|
193
|
+
`CloakBrowser allows one instance: "${record.name}" (pid ${record.pid}, profile ${record.profileDir}) is live — connectNamed("${record.name}") to reuse it or close it first`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Nothing dials a local port its caller did not name (#80): the legacy
|
|
198
|
+
// probe runs only against an endpoint passed as legacyProbeUrl.
|
|
199
|
+
if (legacyProbeUrl === undefined) return;
|
|
200
|
+
// A registered holder may legitimately answer on the legacy port; only an
|
|
201
|
+
// unregistered engine there blocks a launch.
|
|
202
|
+
const legacyHost = new URL(legacyProbeUrl).host;
|
|
203
|
+
const explainedByRecord = records.some(
|
|
204
|
+
(record) =>
|
|
205
|
+
record.alive && record.responsive && new URL(record.endpoint).host === legacyHost,
|
|
206
|
+
);
|
|
207
|
+
if (explainedByRecord) return;
|
|
208
|
+
try {
|
|
209
|
+
const response = await fetch(new URL("/json/version", legacyProbeUrl), {
|
|
210
|
+
signal: AbortSignal.timeout(probeTimeoutMs ?? LEGACY_PROBE_TIMEOUT_MS),
|
|
211
|
+
});
|
|
212
|
+
if (response.ok) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
`an unregistered CloakBrowser is answering on ${legacyProbeUrl} — attach with connect("${legacyProbeUrl}") or close it before launching`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
} catch (error) {
|
|
218
|
+
const unreachable =
|
|
219
|
+
error instanceof TypeError ||
|
|
220
|
+
error?.name === "TimeoutError" ||
|
|
221
|
+
error?.name === "AbortError";
|
|
222
|
+
if (!unreachable) throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function connectCloakProfile({
|
|
227
|
+
browserPath = process.env.CLOAKBROWSER_BIN ?? findCloakBrowserPath(),
|
|
228
|
+
profileDir = process.env.CLOAK_PROFILE_DIR ?? DEFAULT_PROFILE_DIR,
|
|
229
|
+
fingerprintSeed = process.env.CLOAK_FINGERPRINT_SEED,
|
|
230
|
+
browserArgs = [],
|
|
231
|
+
storageRoot,
|
|
232
|
+
name,
|
|
233
|
+
...options
|
|
234
|
+
} = {}) {
|
|
235
|
+
const profile = await resolveCloakProfile({ profileDir, fingerprintSeed });
|
|
236
|
+
const resolvedBrowserArgs = buildCloakBrowserArgs({
|
|
237
|
+
profileDir: profile.profileDir,
|
|
238
|
+
fingerprintSeed: profile.fingerprintSeed,
|
|
239
|
+
extraArgs: browserArgs,
|
|
240
|
+
});
|
|
241
|
+
if (name === undefined) {
|
|
242
|
+
return connectPipe({
|
|
243
|
+
browserPath,
|
|
244
|
+
browserArgs: resolvedBrowserArgs,
|
|
245
|
+
storageRoot: storageRoot ?? profile.profileDir,
|
|
246
|
+
...options,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const { legacyProbeUrl, ...connectOptions } = options;
|
|
250
|
+
return withEngineLock(connectOptions.registryRoot, browserPath, async () => {
|
|
251
|
+
await assertCloakLaunchClear({
|
|
252
|
+
browserPath,
|
|
253
|
+
profileDir: profile.profileDir,
|
|
254
|
+
registryRoot: connectOptions.registryRoot,
|
|
255
|
+
legacyProbeUrl,
|
|
256
|
+
probeTimeoutMs: connectOptions.probeTimeoutMs,
|
|
257
|
+
});
|
|
258
|
+
return connectNamed(name, {
|
|
259
|
+
browserPath,
|
|
260
|
+
browserArgs: resolvedBrowserArgs,
|
|
261
|
+
profileDir: profile.profileDir,
|
|
262
|
+
storageRoot: storageRoot ?? profile.profileDir,
|
|
263
|
+
...connectOptions,
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import {
|
|
4
|
+
CdpClient,
|
|
5
|
+
FrameManager,
|
|
6
|
+
OmOPage,
|
|
7
|
+
SessionManager,
|
|
8
|
+
} from "./core.js";
|
|
9
|
+
import { acquireSharedConnection, canShareConnection } from "./shared-connections.js";
|
|
10
|
+
import { createAgentTabs, getAgentTabs } from "./agent-tabs.js";
|
|
11
|
+
import { repinViewport } from "./viewport.js";
|
|
12
|
+
import { BrowserContext } from "./browser-context.js";
|
|
13
|
+
|
|
14
|
+
export class TabRepository {
|
|
15
|
+
#client;
|
|
16
|
+
constructor(client) { this.#client = client; }
|
|
17
|
+
async listTargets() { return this.#client.discoverTargets(); }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class BrowserConnection {
|
|
21
|
+
#client;
|
|
22
|
+
#sessions;
|
|
23
|
+
#pages = new Map();
|
|
24
|
+
#contexts = new Map();
|
|
25
|
+
#storageRoot;
|
|
26
|
+
#popups = new Map();
|
|
27
|
+
#popupTargets = new Map();
|
|
28
|
+
#attachingPopups = new Map();
|
|
29
|
+
#ownedPopups = new Set();
|
|
30
|
+
#popupOff = [];
|
|
31
|
+
|
|
32
|
+
constructor(client, options = {}) {
|
|
33
|
+
this.#client = client;
|
|
34
|
+
this.#sessions = new SessionManager(client);
|
|
35
|
+
this.tabs = new TabRepository(client);
|
|
36
|
+
this.#storageRoot = path.resolve(options.storageRoot ?? process.cwd());
|
|
37
|
+
this.#popupOff.push(client.on("Target.targetCreated", ({ targetInfo }) => {
|
|
38
|
+
if (targetInfo?.type !== "page" || !this.#acceptsPopup(targetInfo.openerId)) return;
|
|
39
|
+
// Target discovery and Page.windowOpen are independently dispatched. Keep
|
|
40
|
+
// the target's opener identity even when discovery wins that race.
|
|
41
|
+
const targets = this.#popupTargets.get(targetInfo.openerId) ?? [];
|
|
42
|
+
targets.push({ targetId: targetInfo.targetId });
|
|
43
|
+
this.#popupTargets.set(targetInfo.openerId, targets);
|
|
44
|
+
this.#matchPopups(targetInfo.openerId);
|
|
45
|
+
}));
|
|
46
|
+
this.#popupOff.push(client.on("Target.targetDestroyed", ({ targetId }) => {
|
|
47
|
+
this.#ownedPopups.delete(targetId);
|
|
48
|
+
const error = Error("Popup closed before attachment completed");
|
|
49
|
+
this.#attachingPopups.get(targetId)?.reject(error);
|
|
50
|
+
for (const targets of this.#popupTargets.values()) {
|
|
51
|
+
const target = targets.find(target => target.targetId === targetId);
|
|
52
|
+
if (target) target.error = error;
|
|
53
|
+
}
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async initialize() {
|
|
58
|
+
await this.#client.ensureConnected();
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get cdp() { return this.#client; }
|
|
63
|
+
|
|
64
|
+
setDialogPolicy(policy) {
|
|
65
|
+
if (typeof this.#client.setDialogPolicy !== "function") {
|
|
66
|
+
throw new Error("dialog policy is not supported by this transport");
|
|
67
|
+
}
|
|
68
|
+
this.#client.setDialogPolicy(policy);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async listTargets() { return this.tabs.listTargets(); }
|
|
72
|
+
|
|
73
|
+
async newTab(url = "about:blank") {
|
|
74
|
+
return (await (getAgentTabs(this) ?? createAgentTabs(this)).create(url)).page;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
#acceptsPopup(openerId) {
|
|
78
|
+
return !!getAgentTabs(this)?.get(openerId) &&
|
|
79
|
+
this.#pages.get(openerId)?.page.events.listenerCount("popup") > 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
#matchPopups(openerId) {
|
|
83
|
+
const targets = this.#popupTargets.get(openerId);
|
|
84
|
+
const queue = this.#popups.get(openerId);
|
|
85
|
+
while (targets?.length && queue?.length) {
|
|
86
|
+
const target = targets.shift();
|
|
87
|
+
const pending = queue.shift();
|
|
88
|
+
if (target.error) pending.reject(target.error);
|
|
89
|
+
else {
|
|
90
|
+
this.#attachingPopups.set(target.targetId, pending);
|
|
91
|
+
this.#ownedPopups.add(target.targetId);
|
|
92
|
+
pending.operation = this.#attachPopup(target.targetId, pending).catch(pending.reject).finally(() => {
|
|
93
|
+
this.#attachingPopups.delete(target.targetId);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (!targets?.length) this.#popupTargets.delete(openerId);
|
|
98
|
+
if (!queue?.length) this.#popups.delete(openerId);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async #attachPopup(targetId, pending) {
|
|
102
|
+
const tabs = getAgentTabs(this) ?? createAgentTabs(this);
|
|
103
|
+
const { page } = await tabs.adopt(targetId);
|
|
104
|
+
page.popupMetadata = Object.freeze(pending.metadata);
|
|
105
|
+
await page.waitForLoadState("interactive");
|
|
106
|
+
pending.resolve(page);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async attachPage(targetId) {
|
|
110
|
+
if (this.#pages.has(targetId)) return this.#pages.get(targetId).page;
|
|
111
|
+
const sessionId = await this.#sessions.resolvePageSession(targetId);
|
|
112
|
+
const frames = new FrameManager(this.#client, targetId, sessionId);
|
|
113
|
+
await frames.initialize();
|
|
114
|
+
|
|
115
|
+
const entry = { frames, page: null };
|
|
116
|
+
const host = this.#createPageHost(targetId, entry);
|
|
117
|
+
const page = new OmOPage(this.#client, frames, targetId, sessionId, host);
|
|
118
|
+
const { targetInfo } = await this.#client.send("Target.getTargetInfo", { targetId });
|
|
119
|
+
const contextId = targetInfo.browserContextId;
|
|
120
|
+
if (!this.#contexts.has(contextId)) this.#contexts.set(contextId, new BrowserContext(this, contextId));
|
|
121
|
+
const context = this.#contexts.get(contextId);
|
|
122
|
+
page.context = () => context;
|
|
123
|
+
for (const frame of frames.frames.values()) context.trackOrigin(frame.url);
|
|
124
|
+
page.on("framenavigated", frame => context.trackOrigin(frame.url));
|
|
125
|
+
entry.page = page;
|
|
126
|
+
this.#pages.set(targetId, entry);
|
|
127
|
+
return page;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
#createPageHost(targetId, entry) {
|
|
131
|
+
return {
|
|
132
|
+
daemonSession: { accountId: 0, id: "standalone" },
|
|
133
|
+
extensionBridgeRoute: {},
|
|
134
|
+
page: null,
|
|
135
|
+
resolvePageSession: (id, preferred) => this.#sessions.resolvePageSession(id, preferred),
|
|
136
|
+
setViewportSize: async size => {
|
|
137
|
+
const tabs = getAgentTabs(this);
|
|
138
|
+
if (tabs?.get(targetId)) await tabs.repin(targetId, size);
|
|
139
|
+
else await repinViewport(entry.page, size);
|
|
140
|
+
},
|
|
141
|
+
resolvePath: value => path.resolve(this.#storageRoot, value),
|
|
142
|
+
ensurePath: async value => {
|
|
143
|
+
const resolved = path.resolve(this.#storageRoot, value);
|
|
144
|
+
await mkdir(path.dirname(resolved), { recursive: true });
|
|
145
|
+
return resolved;
|
|
146
|
+
},
|
|
147
|
+
registerReadableDownload: value => value,
|
|
148
|
+
isReadableDownload: () => false,
|
|
149
|
+
resolvePopup: async metadata => {
|
|
150
|
+
if (!this.#acceptsPopup(targetId)) return;
|
|
151
|
+
const queue = this.#popups.get(targetId) ?? [];
|
|
152
|
+
const promise = new Promise((resolve, reject) => queue.push({
|
|
153
|
+
resolve, reject, metadata: { url: metadata.url, windowName: metadata.windowName },
|
|
154
|
+
}));
|
|
155
|
+
this.#popups.set(targetId, queue);
|
|
156
|
+
this.#matchPopups(targetId);
|
|
157
|
+
return promise;
|
|
158
|
+
},
|
|
159
|
+
openPopupTab: async () => { throw Error("Popup tab control requires the extension bridge"); },
|
|
160
|
+
closeTab: async (_page, options = {}) => {
|
|
161
|
+
if (options.runBeforeUnload) {
|
|
162
|
+
await this.#client.send("Page.close", undefined, await this.#sessions.resolvePageSession(targetId));
|
|
163
|
+
} else {
|
|
164
|
+
await this.#client.send("Target.closeTarget", { targetId });
|
|
165
|
+
}
|
|
166
|
+
await entry.page?.dispose();
|
|
167
|
+
await entry.frames.dispose();
|
|
168
|
+
this.#pages.delete(targetId);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async close() {
|
|
174
|
+
for (const off of this.#popupOff) off();
|
|
175
|
+
for (const queue of this.#popups.values()) {
|
|
176
|
+
for (const pending of queue) pending.reject(Error("Browser connection closed"));
|
|
177
|
+
}
|
|
178
|
+
this.#popups.clear();
|
|
179
|
+
this.#popupTargets.clear();
|
|
180
|
+
for (const pending of this.#attachingPopups.values()) pending.reject(Error("Browser connection closed"));
|
|
181
|
+
await Promise.all([...this.#attachingPopups.values()].map(pending => pending.operation));
|
|
182
|
+
const tabs = getAgentTabs(this);
|
|
183
|
+
if (tabs) {
|
|
184
|
+
await Promise.all([...this.#ownedPopups].filter(id => tabs.get(id)).map(id => tabs.close(id)));
|
|
185
|
+
await tabs.dispose({ closeOwned: false });
|
|
186
|
+
}
|
|
187
|
+
for (const [targetId, entry] of [...this.#pages]) {
|
|
188
|
+
await entry.page.dispose().catch(() => {});
|
|
189
|
+
await entry.frames.dispose().catch(() => {});
|
|
190
|
+
this.#pages.delete(targetId);
|
|
191
|
+
}
|
|
192
|
+
await this.#sessions.dispose();
|
|
193
|
+
await this.#client.close();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// `await using browser = await connect(...)` closes the connection when the
|
|
197
|
+
// scope ends, also on a throw, so an agent script exits on its own (#244).
|
|
198
|
+
async [Symbol.asyncDispose]() {
|
|
199
|
+
await this.close();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// The browser's WebSocket URL carries its GUID: a ws:// URL is one already, an
|
|
204
|
+
// HTTP endpoint answers it on /json/version (no WebSocket, so no consent prompt).
|
|
205
|
+
async function browserKey(client, cdpUrl) {
|
|
206
|
+
if (/^wss?:\/\//.test(cdpUrl)) return cdpUrl;
|
|
207
|
+
return (await client.discoverVersion()).webSocketDebuggerUrl;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Attaches in one process share one connection per browser (#76): each new
|
|
211
|
+
// connection to a user's Chrome is a new "Allow remote debugging?" prompt.
|
|
212
|
+
function createClient(cdpHttpUrl, options) {
|
|
213
|
+
if (typeof cdpHttpUrl !== "string" || cdpHttpUrl.length === 0) {
|
|
214
|
+
throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL");
|
|
215
|
+
}
|
|
216
|
+
return new CdpClient({ cdpUrl: cdpHttpUrl, ...options.client, dialogPolicy: options.dialogPolicy ?? options.client?.dialogPolicy });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// A connection of its own, never shared: for callers that lease or own the
|
|
220
|
+
// connection themselves (the named-instance registry).
|
|
221
|
+
export async function openConnection(cdpHttpUrl, options = {}) {
|
|
222
|
+
return new BrowserConnection(createClient(cdpHttpUrl, options), options).initialize();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export async function connect(cdpHttpUrl, options = {}) {
|
|
226
|
+
const client = createClient(cdpHttpUrl, options);
|
|
227
|
+
if (!canShareConnection(options)) return new BrowserConnection(client, options).initialize();
|
|
228
|
+
const key = await browserKey(client, cdpHttpUrl);
|
|
229
|
+
// Opened on the resolved GUID URL, never the port: a reconnect then reaches
|
|
230
|
+
// only this browser, and fails once it is gone (#79 review).
|
|
231
|
+
return acquireSharedConnection(key, options, {
|
|
232
|
+
open: (snapshot) => openConnection(key, snapshot),
|
|
233
|
+
});
|
|
234
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function subscribeConsoleEvents(page) {
|
|
2
|
+
return page.cdp.on("Runtime.consoleAPICalled", (event, metadata) => {
|
|
3
|
+
if (!metadata.sessionId || !page.frameManager.hasSession(metadata.sessionId)) return;
|
|
4
|
+
const text = (event.args ?? []).map(arg => {
|
|
5
|
+
if (arg.unserializableValue !== undefined) return arg.unserializableValue;
|
|
6
|
+
if (arg.value !== undefined) return typeof arg.value === "string" ? arg.value : String(arg.value);
|
|
7
|
+
return arg.description ?? arg.type;
|
|
8
|
+
}).join(" ");
|
|
9
|
+
page.events.emit("console", { type: () => event.type, text: () => text })
|
|
10
|
+
.catch(error => console.warn("[console] page event listener failed", error));
|
|
11
|
+
});
|
|
12
|
+
}
|
package/src/cookies.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function cookieToCdp(cookie) {
|
|
2
|
+
const { name, value, url, domain, path, httpOnly, secure, sameSite } = cookie;
|
|
3
|
+
const out = { name, value, url, domain, path, httpOnly, secure, sameSite };
|
|
4
|
+
if (cookie.expires !== undefined && cookie.expires !== -1) out.expires = cookie.expires;
|
|
5
|
+
if (cookie.partitionKey !== undefined) {
|
|
6
|
+
out.partitionKey = { topLevelSite: cookie.partitionKey, hasCrossSiteAncestor: true };
|
|
7
|
+
}
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function sanitizeCookies(cookies) {
|
|
12
|
+
const byKey = new Map();
|
|
13
|
+
for (const cookie of cookies) {
|
|
14
|
+
const out = {
|
|
15
|
+
name: cookie.name,
|
|
16
|
+
value: cookie.value,
|
|
17
|
+
path: cookie.path || "/",
|
|
18
|
+
secure: Boolean(cookie.secure),
|
|
19
|
+
httpOnly: Boolean(cookie.httpOnly),
|
|
20
|
+
};
|
|
21
|
+
if (cookie.name.startsWith("__Host-")) {
|
|
22
|
+
out.secure = true;
|
|
23
|
+
out.path = "/";
|
|
24
|
+
out.url = `https://${cookie.domain.replace(/^\./, "")}`;
|
|
25
|
+
} else {
|
|
26
|
+
out.domain = cookie.domain;
|
|
27
|
+
}
|
|
28
|
+
if (cookie.expires && cookie.expires > 0) out.expires = cookie.expires;
|
|
29
|
+
if (cookie.sameSite && (cookie.sameSite !== "None" || out.secure)) out.sameSite = cookie.sameSite;
|
|
30
|
+
const key = `${out.name}|${out.domain ?? out.url}`;
|
|
31
|
+
const prev = byKey.get(key);
|
|
32
|
+
if (!prev || (out.expires ?? 0) > (prev.expires ?? 0)) byKey.set(key, out);
|
|
33
|
+
}
|
|
34
|
+
return [...byKey.values()];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function injectCookies(page, cookies) {
|
|
38
|
+
await page._sendToTarget("Network.setCookies", { cookies: sanitizeCookies(cookies).map(cookieToCdp) });
|
|
39
|
+
}
|