omowright 0.2.0 → 0.3.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.
Files changed (174) hide show
  1. package/README.md +24 -22
  2. package/TOOLS.md +6 -6
  3. package/dist/agent-tabs.d.ts +56 -0
  4. package/dist/aria-hidden.d.ts +1 -0
  5. package/dist/aside/cli-binary.d.ts +7 -0
  6. package/dist/aside/cli-contract.d.ts +9 -0
  7. package/dist/aside/errors.d.ts +8 -0
  8. package/dist/aside/line-transport.d.ts +11 -0
  9. package/dist/aside/mcp-transport.d.ts +11 -0
  10. package/dist/aside/onboard.d.ts +76 -0
  11. package/dist/aside/session-types.d.ts +68 -0
  12. package/dist/aside/session.d.ts +20 -0
  13. package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
  14. package/dist/bridge-schemas.d.ts +326 -0
  15. package/dist/bridge-transport.d.ts +144 -0
  16. package/dist/browser-context.d.ts +4024 -0
  17. package/dist/browser-process.d.ts +10 -0
  18. package/dist/bsk/browser-signals.d.ts +23 -0
  19. package/dist/bsk/browsers.d.ts +46 -0
  20. package/dist/bsk/connect.d.ts +23 -0
  21. package/dist/bsk/daemon-info.d.ts +16 -0
  22. package/dist/bsk/external-extension.d.ts +74 -0
  23. package/dist/bsk/identify-browser.d.ts +48 -0
  24. package/dist/bsk/install-cli.d.ts +37 -0
  25. package/dist/bsk/ipc-client.d.ts +45 -0
  26. package/dist/bsk/onboard.d.ts +96 -0
  27. package/dist/bsk/reply-fields.d.ts +3 -0
  28. package/dist/bsk/screenshot.d.ts +24 -0
  29. package/dist/bsk/session.d.ts +142 -0
  30. package/dist/bsk/snapshot.d.ts +16 -0
  31. package/dist/bsk/targets.d.ts +20 -0
  32. package/dist/captcha-wait.d.ts +17 -0
  33. package/dist/captcha.d.ts +46 -0
  34. package/dist/cdp-errors.d.ts +38 -0
  35. package/dist/cdp-methods.d.ts +10 -0
  36. package/dist/cdp-protocol.d.ts +459 -0
  37. package/dist/chrome-profile.d.ts +77 -0
  38. package/dist/chrome.d.ts +130 -0
  39. package/dist/cloak-profile.d.ts +43 -0
  40. package/dist/connection.d.ts +4024 -0
  41. package/dist/console-events.d.ts +22 -0
  42. package/dist/cookies.d.ts +42 -0
  43. package/dist/core.d.ts +10810 -0
  44. package/dist/cua.d.ts +56 -0
  45. package/dist/dialog-policy.d.ts +43 -0
  46. package/dist/ego/bindings.d.ts +68 -0
  47. package/dist/ego/cdp-client.d.ts +28 -0
  48. package/dist/ego/client.d.ts +8 -0
  49. package/dist/ego/errors.d.ts +7 -0
  50. package/dist/emulate.d.ts +62 -0
  51. package/dist/engines.d.ts +59 -0
  52. package/dist/events.d.ts +93 -0
  53. package/dist/frames-snapshot.d.ts +58 -0
  54. package/dist/har.d.ts +88 -0
  55. package/dist/human-handoff.d.ts +30 -0
  56. package/{src/index.js → dist/index.d.ts} +11 -55
  57. package/dist/index.js +39262 -0
  58. package/dist/injected.d.ts +1 -0
  59. package/dist/instance-lock.d.ts +5 -0
  60. package/dist/instances.d.ts +45 -0
  61. package/dist/internal-capability.d.ts +1 -0
  62. package/dist/launch-endpoint.d.ts +34 -0
  63. package/dist/layers.d.ts +31 -0
  64. package/dist/llm.d.ts +1349 -0
  65. package/dist/lock-backend-win32-xbcm60vz.js +57 -0
  66. package/dist/lock-backend-win32.d.ts +3 -0
  67. package/dist/lock-backend.d.ts +6 -0
  68. package/dist/native-host-win32.d.ts +38 -0
  69. package/dist/network-events.d.ts +66 -0
  70. package/dist/network-snoop.d.ts +56 -0
  71. package/dist/nul-frames.d.ts +4 -0
  72. package/dist/open-shadow-query.d.ts +1 -0
  73. package/dist/owner-only.d.ts +15 -0
  74. package/dist/page-bundle.js +1587 -0
  75. package/dist/page-events.d.ts +25 -0
  76. package/dist/page-routes.d.ts +30 -0
  77. package/dist/page-setup.d.ts +55 -0
  78. package/dist/pipe.d.ts +71 -0
  79. package/dist/process-start-time.d.ts +2 -0
  80. package/dist/read-property.d.ts +2 -0
  81. package/dist/routes.d.ts +60 -0
  82. package/dist/running-browser.d.ts +39 -0
  83. package/dist/scroll-collect.d.ts +36 -0
  84. package/dist/serial-emitter.d.ts +5 -0
  85. package/dist/shared-connections.d.ts +11 -0
  86. package/dist/snapshot-diff.d.ts +57 -0
  87. package/dist/text-matching.d.ts +21 -0
  88. package/dist/trace.d.ts +59 -0
  89. package/dist/url-match.d.ts +7 -0
  90. package/dist/viewport.d.ts +26 -0
  91. package/dist/ws.d.ts +62 -0
  92. package/package.json +47 -26
  93. package/presets/agent-events/SKILL.md +1 -1
  94. package/presets/captcha/SKILL.md +1 -3
  95. package/presets/chrome/SKILL.md +2 -2
  96. package/presets/cloak-bridge/SKILL.md +11 -11
  97. package/presets/network/SKILL.md +15 -13
  98. package/presets/visual-browse/SKILL.md +14 -10
  99. package/skills/omowright/SKILL.md +77 -47
  100. package/skills/omowright/references/aside.md +50 -0
  101. package/skills/omowright/references/browserskill.md +29 -32
  102. package/skills/omowright/references/ego.md +24 -0
  103. package/skills/omowright/references/eval-kernel.md +44 -23
  104. package/skills/omowright/references/frames-layers-human.md +16 -7
  105. package/skills/omowright/references/quickstart.md +3 -3
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -179
  108. package/src/aria-hidden.js +0 -47
  109. package/src/bridge-schemas.js +0 -44
  110. package/src/bridge-transport.js +0 -83
  111. package/src/browser-context.js +0 -105
  112. package/src/browser-process.js +0 -127
  113. package/src/bsk/browser-signals.js +0 -90
  114. package/src/bsk/browsers.js +0 -114
  115. package/src/bsk/connect.js +0 -75
  116. package/src/bsk/daemon-info.js +0 -100
  117. package/src/bsk/external-extension.js +0 -110
  118. package/src/bsk/identify-browser.js +0 -88
  119. package/src/bsk/install-cli.js +0 -81
  120. package/src/bsk/ipc-client.js +0 -236
  121. package/src/bsk/onboard.js +0 -140
  122. package/src/bsk/screenshot.js +0 -49
  123. package/src/bsk/session.js +0 -131
  124. package/src/bsk/snapshot.js +0 -56
  125. package/src/bsk/targets.js +0 -25
  126. package/src/captcha-wait.js +0 -79
  127. package/src/captcha.js +0 -142
  128. package/src/cdp-errors.js +0 -23
  129. package/src/cdp-methods.js +0 -69
  130. package/src/chrome-profile.js +0 -176
  131. package/src/chrome.js +0 -194
  132. package/src/cloak-profile.js +0 -266
  133. package/src/connection.js +0 -234
  134. package/src/console-events.js +0 -12
  135. package/src/cookies.js +0 -39
  136. package/src/core.js +0 -1702
  137. package/src/cua.js +0 -74
  138. package/src/dialog-policy.js +0 -80
  139. package/src/emulate.js +0 -127
  140. package/src/events.js +0 -111
  141. package/src/frames-snapshot.js +0 -138
  142. package/src/har.js +0 -103
  143. package/src/human-handoff.js +0 -124
  144. package/src/injected.js +0 -3
  145. package/src/instance-lock.js +0 -74
  146. package/src/instances.js +0 -490
  147. package/src/internal-capability.js +0 -1
  148. package/src/launch-endpoint.js +0 -185
  149. package/src/layers.js +0 -138
  150. package/src/llm.js +0 -201
  151. package/src/lock-backend-win32.js +0 -54
  152. package/src/lock-backend.js +0 -81
  153. package/src/native-host-win32.js +0 -201
  154. package/src/network-events.js +0 -223
  155. package/src/network-snoop.js +0 -229
  156. package/src/nul-frames.js +0 -28
  157. package/src/open-shadow-query.js +0 -101
  158. package/src/owner-only.js +0 -196
  159. package/src/page-bundle.js +0 -1478
  160. package/src/page-events.js +0 -45
  161. package/src/page-routes.js +0 -94
  162. package/src/page-setup.js +0 -239
  163. package/src/pipe.js +0 -418
  164. package/src/process-start-time.js +0 -64
  165. package/src/routes.js +0 -256
  166. package/src/running-browser.js +0 -85
  167. package/src/scroll-collect.js +0 -73
  168. package/src/serial-emitter.js +0 -17
  169. package/src/shared-connections.js +0 -285
  170. package/src/snapshot-diff.js +0 -75
  171. package/src/text-matching.js +0 -101
  172. package/src/trace.js +0 -183
  173. package/src/url-match.js +0 -148
  174. package/src/viewport.js +0 -12
@@ -1,69 +0,0 @@
1
- /**
2
- * Every CDP command the page path sends (`connect()`, the page API, frame snapshots, agent tabs and their viewport
3
- * pin). A scoped endpoint can allow exactly these and refuse the rest. Optional modules send more and need a full
4
- * endpoint: routes, emulation, cookies, `createEvents()` (`Browser.setDownloadBehavior`), the
5
- * bridge and `connectPipe`. `test/scoped-endpoint.test.mjs` runs navigate, snapshot, fill, click, evaluate,
6
- * screenshot and agent tabs through such an endpoint; the other listed methods (PDF, history, reload, dialogs, file
7
- * upload, screencast, lifecycle) are listed from the source, not exercised there. No cookie read is listed: an
8
- * endpoint must refuse `Network.getCookies` rather than answer it without its `urls` filter.
9
- */
10
- export const OMOWRIGHT_PAGE_CDP_METHODS = Object.freeze([
11
- "Browser.getVersion",
12
- "DOM.describeNode",
13
- "DOM.enable",
14
- "DOM.getBoxModel",
15
- "DOM.getContentQuads",
16
- "DOM.getDocument",
17
- "DOM.querySelectorAll",
18
- "DOM.resolveNode",
19
- "DOM.scrollIntoViewIfNeeded",
20
- "DOM.setFileInputFiles",
21
- "Emulation.setDeviceMetricsOverride",
22
- "Emulation.setFocusEmulationEnabled",
23
- "Emulation.setEmulatedMedia",
24
- "Input.dispatchKeyEvent",
25
- "Input.dispatchMouseEvent",
26
- "Input.insertText",
27
- "Inspector.enable",
28
- "Network.disable",
29
- "Network.enable",
30
- "Network.getResponseBody",
31
- "Network.setExtraHTTPHeaders",
32
- "Page.addScriptToEvaluateOnNewDocument",
33
- "Page.captureScreenshot",
34
- "Page.close",
35
- "Page.createIsolatedWorld",
36
- "Page.enable",
37
- "Page.getFrameTree",
38
- "Page.getLayoutMetrics",
39
- "Page.getNavigationHistory",
40
- "Page.handleJavaScriptDialog",
41
- "Page.navigate",
42
- "Page.navigateToHistoryEntry",
43
- "Page.printToPDF",
44
- "Page.reload",
45
- "Page.removeScriptToEvaluateOnNewDocument",
46
- "Page.screencastFrameAck",
47
- "Page.setInterceptFileChooserDialog",
48
- "Page.setWebLifecycleState",
49
- "Page.startScreencast",
50
- "Page.stopScreencast",
51
- "Runtime.callFunctionOn",
52
- "Runtime.addBinding",
53
- "Runtime.disable",
54
- "Runtime.discardConsoleEntries",
55
- "Runtime.enable",
56
- "Runtime.evaluate",
57
- "Runtime.releaseObject",
58
- "Runtime.removeBinding",
59
- "Runtime.runIfWaitingForDebugger",
60
- "Target.activateTarget",
61
- "Target.attachToTarget",
62
- "Target.closeTarget",
63
- "Target.createTarget",
64
- "Target.detachFromTarget",
65
- "Target.getTargetInfo",
66
- "Target.getTargets",
67
- "Target.setAutoAttach",
68
- "Target.setDiscoverTargets",
69
- ]);
@@ -1,176 +0,0 @@
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 DELETED
@@ -1,194 +0,0 @@
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
- // CDP has no window-focus state, and document.hasFocus() is no substitute: OmOWright
9
- // enables focus emulation on every page it attaches to (other automation clients do
10
- // too), so those pages report focus, background agent windows included (#122).
11
- const WINDOW_FOCUS_UNKNOWN = "is unavailable in standalone OmOWright: CDP exposes no window focus state; " +
12
- "track chrome.windows.onFocusChanged through the extension bridge instead";
13
- const DOWNLOAD_TIMEOUT_MS = 30_000;
14
-
15
- function matchUrlPattern(url, pattern) {
16
- const patterns = Array.isArray(pattern) ? pattern : [pattern];
17
- return patterns.some(item => {
18
- if (!item.includes("*")) return url.startsWith(item);
19
- const regex = new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
20
- return regex.test(url);
21
- });
22
- }
23
-
24
- export function createChromeApi(connection, options = {}) {
25
- const profile = createProfileApis(options.profilePath);
26
- const cdp = connection.cdp;
27
-
28
- async function pageTargets() {
29
- return (await connection.listTargets()).filter(target => target.type === "page");
30
- }
31
-
32
- async function toTab(target) {
33
- let windowId = 0;
34
- try {
35
- const win = await cdp.send("Browser.getWindowForTarget", { targetId: target.targetId ?? target.id });
36
- windowId = win.windowId;
37
- } catch {}
38
- return {
39
- id: target.targetId ?? target.id,
40
- url: target.url ?? "",
41
- title: target.title ?? "",
42
- windowId,
43
- active: false,
44
- pinned: false,
45
- audible: false,
46
- discarded: false,
47
- groupId: -1,
48
- index: -1,
49
- };
50
- }
51
-
52
- const tabs = {
53
- async query(queryInfo = {}) {
54
- let targets = await pageTargets();
55
- if (queryInfo.url) targets = targets.filter(t => matchUrlPattern(t.url ?? "", queryInfo.url));
56
- if (queryInfo.title) targets = targets.filter(t => (t.title ?? "").includes(queryInfo.title));
57
- const out = [];
58
- for (const target of targets) {
59
- const tab = await toTab(target);
60
- if (queryInfo.windowId != null && tab.windowId !== queryInfo.windowId) continue;
61
- out.push(tab);
62
- }
63
- return out;
64
- },
65
- async get(tabId) {
66
- const targets = await pageTargets();
67
- const target = targets.find(t => (t.targetId ?? t.id) === tabId);
68
- if (!target) throw new Error(`No tab with id: ${tabId}`);
69
- return toTab(target);
70
- },
71
- };
72
-
73
- async function collectWindows(queryOptions = {}) {
74
- const byWindow = new Map();
75
- for (const target of await pageTargets()) {
76
- const tab = await toTab(target);
77
- const list = byWindow.get(tab.windowId) ?? [];
78
- list.push(tab);
79
- byWindow.set(tab.windowId, list);
80
- }
81
- return [...byWindow.entries()].map(([windowId, windowTabs]) => {
82
- const win = {
83
- id: windowId,
84
- type: "normal",
85
- state: "normal",
86
- alwaysOnTop: false,
87
- incognito: false,
88
- };
89
- if (queryOptions.populate) win.tabs = windowTabs;
90
- return win;
91
- });
92
- }
93
-
94
- const windows = {
95
- async get(windowId, queryOptions = {}) {
96
- const all = await collectWindows(queryOptions);
97
- const win = all.find(item => item.id === windowId);
98
- if (!win) throw new Error(`No window with id: ${windowId}`);
99
- return win;
100
- },
101
- async getCurrent(queryOptions = {}) {
102
- const all = await collectWindows(queryOptions);
103
- if (all.length === 0) throw new Error("No browser window found");
104
- return all[0];
105
- },
106
- async getLastFocused() {
107
- throw new UnsupportedOperationError(`chrome.windows.getLastFocused ${WINDOW_FOCUS_UNKNOWN}`);
108
- },
109
- async getAll(queryOptions = {}) {
110
- return collectWindows(queryOptions);
111
- },
112
- };
113
-
114
- const downloads = {
115
- async search(query = {}) {
116
- return profile.withDb("History", db => {
117
- const rows = db.prepare(
118
- `SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,
119
- (SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url
120
- FROM downloads d ORDER BY d.start_time DESC LIMIT ?`,
121
- ).all(query.limit ?? 100);
122
- return rows
123
- .map(row => ({
124
- id: Number(row.id),
125
- url: row.url ?? "",
126
- filename: row.target_path,
127
- startTime: row.start_time ? new Date(chromeTimeToMs(row.start_time)).toISOString() : null,
128
- bytesReceived: Number(row.received_bytes),
129
- totalBytes: Number(row.total_bytes),
130
- state: Number(row.state) === 1 ? "complete" : Number(row.state) === 2 ? "canceled" : Number(row.state) === 3 ? "interrupted" : "in_progress",
131
- }))
132
- .filter(item => !query.url || item.url.includes(query.url))
133
- .filter(item => !query.filename || item.filename.includes(query.filename));
134
- });
135
- },
136
-
137
- async download(downloadOptions) {
138
- const downloadDir = options.downloadDir ?? path.join(tmpdir(), "omowright-downloads");
139
- mkdirSync(downloadDir, { recursive: true });
140
-
141
- let resolveBegin;
142
- let resolveDone;
143
- let rejectDone;
144
- const began = new Promise(resolve => { resolveBegin = resolve; });
145
- const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
146
- const offBegin = cdp.on("Browser.downloadWillBegin", params => resolveBegin(params));
147
- const offProgress = cdp.on("Browser.downloadProgress", params => {
148
- if (params.state === "completed") resolveDone(params);
149
- else if (params.state === "canceled") rejectDone(new Error("Download was canceled"));
150
- });
151
- const timer = setTimeout(() => rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)), DOWNLOAD_TIMEOUT_MS);
152
-
153
- const page = await connection.newTab("about:blank");
154
- try {
155
- await cdp.send("Browser.setDownloadBehavior", { behavior: "allow", downloadPath: downloadDir, eventsEnabled: true });
156
- await page.evaluate(`(() => {
157
- const a = document.createElement("a");
158
- a.href = ${JSON.stringify(downloadOptions.url)};
159
- document.body.appendChild(a);
160
- a.click();
161
- })()`);
162
- const begin = await Promise.race([began, done.then(() => null)]);
163
- if (!begin) throw new Error("No download started for the given URL");
164
- await done;
165
- const filename = downloadOptions.filename ?? begin.suggestedFilename;
166
- return {
167
- id: begin.guid,
168
- url: begin.url ?? downloadOptions.url,
169
- filename: path.join(downloadDir, filename ?? "download"),
170
- state: "complete",
171
- };
172
- } finally {
173
- clearTimeout(timer);
174
- offBegin();
175
- offProgress();
176
- await page.close().catch(() => {});
177
- }
178
- },
179
-
180
- async pause() { throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED}`); },
181
- async resume() { throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED}`); },
182
- async cancel() { throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED}`); },
183
- async erase() { throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED}`); },
184
- };
185
-
186
- return {
187
- tabs,
188
- windows,
189
- downloads,
190
- bookmarks: profile.bookmarks,
191
- history: profile.history,
192
- topSites: profile.topSites,
193
- };
194
- }
@@ -1,266 +0,0 @@
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
- }