omowright 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +282 -2
- package/TOOLS.md +366 -0
- package/bin/omowright-cloak.mjs +112 -0
- package/package.json +61 -4
- package/presets/agent-events/SKILL.md +75 -0
- package/presets/captcha/SKILL.md +129 -0
- package/presets/chrome/SKILL.md +84 -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 +186 -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 +96 -0
- package/skills/omowright/references/stealth.md +174 -0
- package/src/agent-tabs.js +160 -0
- package/src/bridge-schemas.js +44 -0
- package/src/bridge-transport.js +57 -0
- package/src/browser-process.js +122 -0
- package/src/bsk/browser-signals.js +90 -0
- package/src/bsk/browsers.js +114 -0
- package/src/bsk/connect.js +45 -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 +133 -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 +74 -0
- package/src/captcha.js +142 -0
- package/src/cdp-errors.js +23 -0
- package/src/cdp-methods.js +61 -0
- package/src/chrome-profile.js +176 -0
- package/src/chrome.js +192 -0
- package/src/cloak-profile.js +266 -0
- package/src/connection.js +135 -0
- package/src/cookies.js +29 -0
- package/src/core.js +1710 -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 +122 -0
- package/src/index.js +86 -0
- package/src/injected.js +3 -0
- package/src/instance-lock.js +230 -0
- package/src/instances.js +493 -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-file.js +130 -0
- package/src/native-host-win32.js +201 -0
- package/src/network-events.js +201 -0
- package/src/network-snoop.js +229 -0
- package/src/open-shadow-query.js +22 -0
- package/src/owner-only.js +109 -0
- package/src/page-bundle.js +1397 -0
- package/src/page-routes.js +94 -0
- package/src/pipe.js +391 -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 +278 -0
- package/src/snapshot-diff.js +75 -0
- package/src/trace.js +183 -0
- package/src/url-match.js +148 -0
- package/src/viewport.js +12 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { UnsupportedOperationError } from "./core.js";
|
|
4
|
+
|
|
5
|
+
let DatabaseCtor;
|
|
6
|
+
async function loadSqlite() {
|
|
7
|
+
if (DatabaseCtor) return DatabaseCtor;
|
|
8
|
+
try {
|
|
9
|
+
const mod = await import("node:sqlite");
|
|
10
|
+
DatabaseCtor = file => new mod.DatabaseSync(file, { readOnly: true, readBigInts: true });
|
|
11
|
+
} catch {
|
|
12
|
+
const mod = await import("bun:sqlite");
|
|
13
|
+
DatabaseCtor = file => new mod.Database(file, { readonly: true });
|
|
14
|
+
}
|
|
15
|
+
return DatabaseCtor;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const CHROME_EPOCH_OFFSET_MS = 11_644_473_600_000;
|
|
19
|
+
const chromeTimeToMs = time => Number(BigInt(time) / 1000n) - CHROME_EPOCH_OFFSET_MS;
|
|
20
|
+
const msToChromeTime = ms => BigInt(Math.floor((ms + CHROME_EPOCH_OFFSET_MS) * 1000));
|
|
21
|
+
|
|
22
|
+
export { chromeTimeToMs };
|
|
23
|
+
|
|
24
|
+
const EXTENSION_BRIDGE_REQUIRED = "requires the extension bridge in standalone OmOWright";
|
|
25
|
+
|
|
26
|
+
export function createProfileApis(profilePath) {
|
|
27
|
+
function profileDir() {
|
|
28
|
+
if (!profilePath) {
|
|
29
|
+
throw new UnsupportedOperationError(
|
|
30
|
+
"chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return path.join(profilePath, "Default");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function openDb(fileName) {
|
|
37
|
+
const file = path.join(profileDir(), fileName);
|
|
38
|
+
if (!existsSync(file)) return null;
|
|
39
|
+
const ctor = await loadSqlite();
|
|
40
|
+
return ctor(file);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function withDb(fileName, fn) {
|
|
44
|
+
const db = await openDb(fileName);
|
|
45
|
+
if (!db) return [];
|
|
46
|
+
try {
|
|
47
|
+
return fn(db);
|
|
48
|
+
} finally {
|
|
49
|
+
db.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function bookmarkRoots() {
|
|
54
|
+
const file = path.join(profileDir(), "Bookmarks");
|
|
55
|
+
if (!existsSync(file)) return [];
|
|
56
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
57
|
+
return Object.values(parsed.roots ?? {}).filter(node => node && typeof node === "object" && node.id);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function walkBookmarks(nodes, visit, acc = []) {
|
|
61
|
+
for (const node of nodes) {
|
|
62
|
+
visit(node, acc);
|
|
63
|
+
if (Array.isArray(node.children)) walkBookmarks(node.children, visit, acc);
|
|
64
|
+
}
|
|
65
|
+
return acc;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function findBookmark(id) {
|
|
69
|
+
for (const root of bookmarkRoots()) {
|
|
70
|
+
const found = walkBookmarks([root], (node, acc) => {
|
|
71
|
+
if (node.id === String(id)) acc.push(node);
|
|
72
|
+
});
|
|
73
|
+
if (found.length > 0) return found[0];
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function toBookmark(node) {
|
|
79
|
+
const out = { id: node.id, title: node.name ?? "", type: node.type };
|
|
80
|
+
if (node.url) out.url = node.url;
|
|
81
|
+
if (node.date_added) out.dateAdded = chromeTimeToMs(node.date_added);
|
|
82
|
+
if (node.children) out.children = node.children.map(toBookmark);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const bookmarks = {
|
|
87
|
+
async get(idOrIdList) {
|
|
88
|
+
const ids = Array.isArray(idOrIdList) ? idOrIdList : [idOrIdList];
|
|
89
|
+
return ids.map(findBookmark).filter(Boolean).map(toBookmark);
|
|
90
|
+
},
|
|
91
|
+
async getChildren(id) {
|
|
92
|
+
const node = findBookmark(id);
|
|
93
|
+
return (node?.children ?? []).map(toBookmark);
|
|
94
|
+
},
|
|
95
|
+
async getRecent(numberOfItems) {
|
|
96
|
+
const urls = walkBookmarks(bookmarkRoots(), (node, acc) => {
|
|
97
|
+
if (node.type === "url") acc.push(node);
|
|
98
|
+
});
|
|
99
|
+
return urls
|
|
100
|
+
.sort((a, b) => Number(b.date_added ?? 0) - Number(a.date_added ?? 0))
|
|
101
|
+
.slice(0, numberOfItems)
|
|
102
|
+
.map(toBookmark);
|
|
103
|
+
},
|
|
104
|
+
async getSubTree(id) {
|
|
105
|
+
const node = findBookmark(id);
|
|
106
|
+
return node ? [toBookmark(node)] : [];
|
|
107
|
+
},
|
|
108
|
+
async getTree() {
|
|
109
|
+
return bookmarkRoots().map(toBookmark);
|
|
110
|
+
},
|
|
111
|
+
async search(query) {
|
|
112
|
+
const needle = typeof query === "string" ? query.toLowerCase() : (query.query ?? "").toLowerCase();
|
|
113
|
+
const url = typeof query === "object" ? query.url?.toLowerCase() : undefined;
|
|
114
|
+
const title = typeof query === "object" ? query.title?.toLowerCase() : undefined;
|
|
115
|
+
return walkBookmarks(bookmarkRoots(), (node, acc) => {
|
|
116
|
+
if (node.type !== "url") return;
|
|
117
|
+
const name = (node.name ?? "").toLowerCase();
|
|
118
|
+
const href = (node.url ?? "").toLowerCase();
|
|
119
|
+
const ok = (needle && (name.includes(needle) || href.includes(needle)))
|
|
120
|
+
|| (url && href.includes(url))
|
|
121
|
+
|| (title && name.includes(title));
|
|
122
|
+
if (ok) acc.push(node);
|
|
123
|
+
}).map(toBookmark);
|
|
124
|
+
},
|
|
125
|
+
async create() { throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
126
|
+
async update() { throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
127
|
+
async move() { throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
128
|
+
async remove() { throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
129
|
+
async removeTree() { throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const history = {
|
|
133
|
+
async search(query) {
|
|
134
|
+
const text = `%${query.text ?? ""}%`;
|
|
135
|
+
const start = query.startTime != null ? msToChromeTime(query.startTime) : 0n;
|
|
136
|
+
const end = query.endTime != null ? msToChromeTime(query.endTime) : 99999999999999999n;
|
|
137
|
+
const max = query.maxResults ?? 100;
|
|
138
|
+
return (await withDb("History", db => db.prepare(
|
|
139
|
+
`SELECT id, url, title, visit_count, last_visit_time FROM urls
|
|
140
|
+
WHERE (url LIKE ? OR title LIKE ?) AND last_visit_time BETWEEN ? AND ?
|
|
141
|
+
ORDER BY last_visit_time DESC LIMIT ?`,
|
|
142
|
+
).all(text, text, start, end, max).map(row => ({
|
|
143
|
+
id: String(row.id),
|
|
144
|
+
url: row.url,
|
|
145
|
+
title: row.title ?? "",
|
|
146
|
+
visitCount: Number(row.visit_count),
|
|
147
|
+
lastVisitTime: chromeTimeToMs(row.last_visit_time),
|
|
148
|
+
}))));
|
|
149
|
+
},
|
|
150
|
+
async getVisits(details) {
|
|
151
|
+
return (await withDb("History", db => db.prepare(
|
|
152
|
+
`SELECT v.id, v.visit_time, v.transition FROM visits v
|
|
153
|
+
JOIN urls u ON u.id = v.url WHERE u.url = ?
|
|
154
|
+
ORDER BY v.visit_time DESC`,
|
|
155
|
+
).all(details.url).map(row => ({
|
|
156
|
+
id: String(row.id),
|
|
157
|
+
url: details.url,
|
|
158
|
+
visitTime: chromeTimeToMs(row.visit_time),
|
|
159
|
+
transition: Number(row.transition),
|
|
160
|
+
}))));
|
|
161
|
+
},
|
|
162
|
+
async addUrl() { throw new UnsupportedOperationError(`chrome.history.addUrl ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
163
|
+
async deleteUrl() { throw new UnsupportedOperationError(`chrome.history.deleteUrl ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
164
|
+
async deleteRange() { throw new UnsupportedOperationError(`chrome.history.deleteRange ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const topSites = {
|
|
168
|
+
async get() {
|
|
169
|
+
return (await withDb("Top Sites", db => db.prepare(
|
|
170
|
+
`SELECT url, title, url_rank FROM top_sites ORDER BY url_rank ASC LIMIT 50`,
|
|
171
|
+
).all())).map(row => ({ url: row.url, title: row.title ?? "" }));
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
return { bookmarks, history, topSites, withDb };
|
|
176
|
+
}
|
package/src/chrome.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { UnsupportedOperationError } from "./core.js";
|
|
5
|
+
import { createProfileApis, chromeTimeToMs } from "./chrome-profile.js";
|
|
6
|
+
|
|
7
|
+
const EXTENSION_BRIDGE_REQUIRED = "requires the extension bridge in standalone OmOWright";
|
|
8
|
+
const DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
9
|
+
|
|
10
|
+
function matchUrlPattern(url, pattern) {
|
|
11
|
+
const patterns = Array.isArray(pattern) ? pattern : [pattern];
|
|
12
|
+
return patterns.some(item => {
|
|
13
|
+
if (!item.includes("*")) return url.startsWith(item);
|
|
14
|
+
const regex = new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
|
|
15
|
+
return regex.test(url);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createChromeApi(connection, options = {}) {
|
|
20
|
+
const profile = createProfileApis(options.profilePath);
|
|
21
|
+
const cdp = connection.cdp;
|
|
22
|
+
|
|
23
|
+
async function pageTargets() {
|
|
24
|
+
return (await connection.listTargets()).filter(target => target.type === "page");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function toTab(target) {
|
|
28
|
+
let windowId = 0;
|
|
29
|
+
try {
|
|
30
|
+
const win = await cdp.send("Browser.getWindowForTarget", { targetId: target.targetId ?? target.id });
|
|
31
|
+
windowId = win.windowId;
|
|
32
|
+
} catch {}
|
|
33
|
+
return {
|
|
34
|
+
id: target.targetId ?? target.id,
|
|
35
|
+
url: target.url ?? "",
|
|
36
|
+
title: target.title ?? "",
|
|
37
|
+
windowId,
|
|
38
|
+
active: false,
|
|
39
|
+
pinned: false,
|
|
40
|
+
audible: false,
|
|
41
|
+
discarded: false,
|
|
42
|
+
groupId: -1,
|
|
43
|
+
index: -1,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const tabs = {
|
|
48
|
+
async query(queryInfo = {}) {
|
|
49
|
+
let targets = await pageTargets();
|
|
50
|
+
if (queryInfo.url) targets = targets.filter(t => matchUrlPattern(t.url ?? "", queryInfo.url));
|
|
51
|
+
if (queryInfo.title) targets = targets.filter(t => (t.title ?? "").includes(queryInfo.title));
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const target of targets) {
|
|
54
|
+
const tab = await toTab(target);
|
|
55
|
+
if (queryInfo.windowId != null && tab.windowId !== queryInfo.windowId) continue;
|
|
56
|
+
out.push(tab);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
},
|
|
60
|
+
async get(tabId) {
|
|
61
|
+
const targets = await pageTargets();
|
|
62
|
+
const target = targets.find(t => (t.targetId ?? t.id) === tabId);
|
|
63
|
+
if (!target) throw new Error(`No tab with id: ${tabId}`);
|
|
64
|
+
return toTab(target);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
async function collectWindows(queryOptions = {}) {
|
|
69
|
+
const byWindow = new Map();
|
|
70
|
+
for (const target of await pageTargets()) {
|
|
71
|
+
const tab = await toTab(target);
|
|
72
|
+
const list = byWindow.get(tab.windowId) ?? [];
|
|
73
|
+
list.push(tab);
|
|
74
|
+
byWindow.set(tab.windowId, list);
|
|
75
|
+
}
|
|
76
|
+
return [...byWindow.entries()].map(([windowId, windowTabs], index) => {
|
|
77
|
+
const win = {
|
|
78
|
+
id: windowId,
|
|
79
|
+
focused: index === 0,
|
|
80
|
+
type: "normal",
|
|
81
|
+
state: "normal",
|
|
82
|
+
alwaysOnTop: false,
|
|
83
|
+
incognito: false,
|
|
84
|
+
};
|
|
85
|
+
if (queryOptions.populate) win.tabs = windowTabs;
|
|
86
|
+
return win;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const windows = {
|
|
91
|
+
async get(windowId, queryOptions = {}) {
|
|
92
|
+
const all = await collectWindows(queryOptions);
|
|
93
|
+
const win = all.find(item => item.id === windowId);
|
|
94
|
+
if (!win) throw new Error(`No window with id: ${windowId}`);
|
|
95
|
+
return win;
|
|
96
|
+
},
|
|
97
|
+
async getCurrent(queryOptions = {}) {
|
|
98
|
+
const all = await collectWindows(queryOptions);
|
|
99
|
+
if (all.length === 0) throw new Error("No browser window found");
|
|
100
|
+
return all[0];
|
|
101
|
+
},
|
|
102
|
+
async getLastFocused(queryOptions = {}) {
|
|
103
|
+
const all = await collectWindows(queryOptions);
|
|
104
|
+
if (all.length === 0) throw new Error("No browser window found");
|
|
105
|
+
return all[0];
|
|
106
|
+
},
|
|
107
|
+
async getAll(queryOptions = {}) {
|
|
108
|
+
return collectWindows(queryOptions);
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const downloads = {
|
|
113
|
+
async search(query = {}) {
|
|
114
|
+
return profile.withDb("History", db => {
|
|
115
|
+
const rows = db.prepare(
|
|
116
|
+
`SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,
|
|
117
|
+
(SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url
|
|
118
|
+
FROM downloads d ORDER BY d.start_time DESC LIMIT ?`,
|
|
119
|
+
).all(query.limit ?? 100);
|
|
120
|
+
return rows
|
|
121
|
+
.map(row => ({
|
|
122
|
+
id: Number(row.id),
|
|
123
|
+
url: row.url ?? "",
|
|
124
|
+
filename: row.target_path,
|
|
125
|
+
startTime: row.start_time ? new Date(chromeTimeToMs(row.start_time)).toISOString() : null,
|
|
126
|
+
bytesReceived: Number(row.received_bytes),
|
|
127
|
+
totalBytes: Number(row.total_bytes),
|
|
128
|
+
state: Number(row.state) === 1 ? "complete" : Number(row.state) === 2 ? "canceled" : Number(row.state) === 3 ? "interrupted" : "in_progress",
|
|
129
|
+
}))
|
|
130
|
+
.filter(item => !query.url || item.url.includes(query.url))
|
|
131
|
+
.filter(item => !query.filename || item.filename.includes(query.filename));
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
async download(downloadOptions) {
|
|
136
|
+
const downloadDir = options.downloadDir ?? path.join(tmpdir(), "omowright-downloads");
|
|
137
|
+
mkdirSync(downloadDir, { recursive: true });
|
|
138
|
+
|
|
139
|
+
let resolveBegin;
|
|
140
|
+
let resolveDone;
|
|
141
|
+
let rejectDone;
|
|
142
|
+
const began = new Promise(resolve => { resolveBegin = resolve; });
|
|
143
|
+
const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
|
|
144
|
+
const offBegin = cdp.on("Browser.downloadWillBegin", params => resolveBegin(params));
|
|
145
|
+
const offProgress = cdp.on("Browser.downloadProgress", params => {
|
|
146
|
+
if (params.state === "completed") resolveDone(params);
|
|
147
|
+
else if (params.state === "canceled") rejectDone(new Error("Download was canceled"));
|
|
148
|
+
});
|
|
149
|
+
const timer = setTimeout(() => rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)), DOWNLOAD_TIMEOUT_MS);
|
|
150
|
+
|
|
151
|
+
const page = await connection.newTab("about:blank");
|
|
152
|
+
try {
|
|
153
|
+
await cdp.send("Browser.setDownloadBehavior", { behavior: "allow", downloadPath: downloadDir, eventsEnabled: true });
|
|
154
|
+
await page.evaluate(`(() => {
|
|
155
|
+
const a = document.createElement("a");
|
|
156
|
+
a.href = ${JSON.stringify(downloadOptions.url)};
|
|
157
|
+
document.body.appendChild(a);
|
|
158
|
+
a.click();
|
|
159
|
+
})()`);
|
|
160
|
+
const begin = await Promise.race([began, done.then(() => null)]);
|
|
161
|
+
if (!begin) throw new Error("No download started for the given URL");
|
|
162
|
+
await done;
|
|
163
|
+
const filename = downloadOptions.filename ?? begin.suggestedFilename;
|
|
164
|
+
return {
|
|
165
|
+
id: begin.guid,
|
|
166
|
+
url: begin.url ?? downloadOptions.url,
|
|
167
|
+
filename: path.join(downloadDir, filename ?? "download"),
|
|
168
|
+
state: "complete",
|
|
169
|
+
};
|
|
170
|
+
} finally {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
offBegin();
|
|
173
|
+
offProgress();
|
|
174
|
+
await page.close().catch(() => {});
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
async pause() { throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
179
|
+
async resume() { throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
180
|
+
async cancel() { throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
181
|
+
async erase() { throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED}`); },
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
tabs,
|
|
186
|
+
windows,
|
|
187
|
+
downloads,
|
|
188
|
+
bookmarks: profile.bookmarks,
|
|
189
|
+
history: profile.history,
|
|
190
|
+
topSites: profile.topSites,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
@@ -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
|
+
}
|