omowright 0.1.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 (165) hide show
  1. package/README.md +33 -23
  2. package/TOOLS.md +140 -19
  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} +12 -53
  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 +11 -7
  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 +39 -33
  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 +17 -4
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -160
  108. package/src/bridge-schemas.js +0 -44
  109. package/src/bridge-transport.js +0 -57
  110. package/src/browser-process.js +0 -122
  111. package/src/bsk/browser-signals.js +0 -90
  112. package/src/bsk/browsers.js +0 -114
  113. package/src/bsk/connect.js +0 -45
  114. package/src/bsk/daemon-info.js +0 -100
  115. package/src/bsk/external-extension.js +0 -110
  116. package/src/bsk/identify-browser.js +0 -88
  117. package/src/bsk/install-cli.js +0 -81
  118. package/src/bsk/ipc-client.js +0 -236
  119. package/src/bsk/onboard.js +0 -133
  120. package/src/bsk/screenshot.js +0 -49
  121. package/src/bsk/session.js +0 -131
  122. package/src/bsk/snapshot.js +0 -56
  123. package/src/bsk/targets.js +0 -25
  124. package/src/captcha-wait.js +0 -74
  125. package/src/captcha.js +0 -142
  126. package/src/cdp-errors.js +0 -23
  127. package/src/cdp-methods.js +0 -61
  128. package/src/chrome-profile.js +0 -176
  129. package/src/chrome.js +0 -192
  130. package/src/cloak-profile.js +0 -266
  131. package/src/connection.js +0 -135
  132. package/src/cookies.js +0 -29
  133. package/src/core.js +0 -1710
  134. package/src/cua.js +0 -74
  135. package/src/dialog-policy.js +0 -80
  136. package/src/emulate.js +0 -127
  137. package/src/events.js +0 -111
  138. package/src/frames-snapshot.js +0 -138
  139. package/src/har.js +0 -103
  140. package/src/human-handoff.js +0 -122
  141. package/src/injected.js +0 -3
  142. package/src/instance-lock.js +0 -230
  143. package/src/instances.js +0 -493
  144. package/src/internal-capability.js +0 -1
  145. package/src/launch-endpoint.js +0 -185
  146. package/src/layers.js +0 -138
  147. package/src/llm.js +0 -201
  148. package/src/lock-file.js +0 -130
  149. package/src/native-host-win32.js +0 -201
  150. package/src/network-events.js +0 -201
  151. package/src/network-snoop.js +0 -229
  152. package/src/open-shadow-query.js +0 -22
  153. package/src/owner-only.js +0 -109
  154. package/src/page-bundle.js +0 -1397
  155. package/src/page-routes.js +0 -94
  156. package/src/pipe.js +0 -391
  157. package/src/routes.js +0 -256
  158. package/src/running-browser.js +0 -85
  159. package/src/scroll-collect.js +0 -73
  160. package/src/serial-emitter.js +0 -17
  161. package/src/shared-connections.js +0 -278
  162. package/src/snapshot-diff.js +0 -75
  163. package/src/trace.js +0 -183
  164. package/src/url-match.js +0 -148
  165. package/src/viewport.js +0 -12
package/src/layers.js DELETED
@@ -1,138 +0,0 @@
1
- export async function describeLayers(page, { grid = 5 } = {}) {
2
- return page.evaluate(gridSize => {
3
- const width = Math.round(globalThis.visualViewport?.width ?? globalThis.innerWidth ?? 0);
4
- const height = Math.round(globalThis.visualViewport?.height ?? globalThis.innerHeight ?? 0);
5
- const viewport = { width, height };
6
- const total = gridSize * gridSize;
7
- const hits = new Map();
8
-
9
- function pierceTopmost(x, y) {
10
- const stack = document.elementsFromPoint(x, y);
11
- let el = stack[0] ?? null;
12
- const seen = new Set();
13
- while (el?.shadowRoot && typeof el.shadowRoot.elementsFromPoint === "function") {
14
- if (seen.has(el)) break;
15
- seen.add(el);
16
- const inner = el.shadowRoot.elementsFromPoint(x, y) ?? [];
17
- const next = inner.find(node => node && node !== el);
18
- if (!next) break;
19
- el = next;
20
- }
21
- return el;
22
- }
23
-
24
- function parentOf(node) {
25
- if (!node) return null;
26
- if (node.parentElement) return node.parentElement;
27
- const root = node.getRootNode?.();
28
- return root?.host ?? null;
29
- }
30
-
31
- function promote(el) {
32
- const minArea = 0.5 * width * height;
33
- let node = el;
34
- while (node && node.nodeType === 1) {
35
- const position = getComputedStyle(node).position;
36
- if (position === "fixed" || position === "sticky" || position === "absolute") {
37
- const rect = node.getBoundingClientRect();
38
- if (rect.width * rect.height >= minArea) return node;
39
- }
40
- node = parentOf(node);
41
- }
42
- return el;
43
- }
44
-
45
- function labelledByText(el) {
46
- const ids = (el.getAttribute("aria-labelledby") || "").trim();
47
- if (!ids) return "";
48
- return ids.split(/\s+/).map(id => document.getElementById(id)?.textContent?.trim() ?? "").filter(Boolean).join(" ");
49
- }
50
-
51
- function elementName(el) {
52
- const ariaLabel = el.getAttribute("aria-label");
53
- if (ariaLabel) return ariaLabel;
54
- const labelled = labelledByText(el);
55
- if (labelled) return labelled;
56
- const heading = el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();
57
- if (heading) return heading;
58
- return ((el.innerText || el.textContent || "").trim().replace(/\s+/g, " ")).slice(0, 80);
59
- }
60
-
61
- function selectorHint(el) {
62
- if (el.id) return `#${el.id}`;
63
- const classes = [...el.classList].join(".");
64
- return classes ? `${el.tagName.toLowerCase()}.${classes}` : el.tagName.toLowerCase();
65
- }
66
-
67
- function describe(el, coverage) {
68
- return {
69
- tagName: el.tagName,
70
- role: el.getAttribute("role") || "",
71
- name: elementName(el),
72
- coverage,
73
- position: getComputedStyle(el).position,
74
- selectorHint: selectorHint(el),
75
- ariaModal: el.getAttribute("aria-modal") === "true",
76
- };
77
- }
78
-
79
- function isMainContent(el) {
80
- if (el === document.documentElement || el === document.body) return true;
81
- if (el.tagName === "MAIN") return true;
82
- return (el.getAttribute("role") || "").toLowerCase() === "main";
83
- }
84
-
85
- function isBlocking(el, info) {
86
- if (info.coverage < 0.6) return false;
87
- if (getComputedStyle(el).pointerEvents === "none") return false;
88
- const role = (info.role || "").toLowerCase();
89
- if (role === "dialog" || role === "alertdialog") return true;
90
- if (info.ariaModal) return true;
91
- if (isMainContent(el)) return false;
92
- return info.position === "fixed" || info.position === "absolute";
93
- }
94
-
95
- const insetX = width * 0.05;
96
- const insetY = height * 0.05;
97
- const spanX = width * 0.9;
98
- const spanY = height * 0.9;
99
- for (let row = 0; row < gridSize; row++) {
100
- for (let col = 0; col < gridSize; col++) {
101
- const x = insetX + ((col + 0.5) * spanX) / gridSize;
102
- const y = insetY + ((row + 0.5) * spanY) / gridSize;
103
- const top = pierceTopmost(x, y);
104
- if (!top) continue;
105
- const candidate = promote(top);
106
- hits.set(candidate, (hits.get(candidate) ?? 0) + 1);
107
- }
108
- }
109
-
110
- const candidates = [...hits.entries()]
111
- .map(([el, count]) => {
112
- const info = describe(el, total > 0 ? count / total : 0);
113
- return { el, info };
114
- })
115
- .sort((a, b) => b.info.coverage - a.info.coverage);
116
-
117
- const blockingEntry = candidates.find(entry => isBlocking(entry.el, entry.info));
118
- return {
119
- blocking: blockingEntry ? blockingEntry.info : null,
120
- candidates: candidates.map(entry => entry.info),
121
- viewport,
122
- };
123
- }, grid);
124
- }
125
-
126
- export function layersHeader(result) {
127
- const blocking = result?.blocking;
128
- if (!blocking) return "@layers none";
129
- const who = blocking.role || blocking.tagName;
130
- const pct = Math.round(blocking.coverage * 100);
131
- return `@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`;
132
- }
133
-
134
- export async function snapshotWithLayers(page, snapshotOptions) {
135
- const snapshot = await page.snapshot(snapshotOptions);
136
- const layers = await describeLayers(page);
137
- return { ...snapshot, layers, tree: `${layersHeader(layers)}\n${snapshot.tree}` };
138
- }
package/src/llm.js DELETED
@@ -1,201 +0,0 @@
1
- const SNAPSHOT_PARSE_ERROR =
2
- "compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";
3
-
4
- export function compactSnapshot(snapshot) {
5
- const obj = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
6
- if (obj?.full === false && obj.diff) {
7
- const { added, changed, removed, focused } = obj.diff;
8
- const lines = [
9
- ...added.map(node => `+ ${node.tree}`),
10
- ...changed.map(node => `~ ${node.tree}`),
11
- ];
12
- if (removed.length) lines.push(`- ${refRanges(removed)}`);
13
- lines.push(`@focused ${focused ?? "none"}`);
14
- return lines.join("\n");
15
- }
16
- if (!obj || typeof obj.tree !== "string") throw new TypeError(SNAPSHOT_PARSE_ERROR);
17
- return obj.tree;
18
- }
19
-
20
- function refRanges(refs) {
21
- const sorted = refs.map(ref => {
22
- const [, prefix, number] = /^((?:f\d+)?e)(\d+)$/.exec(ref);
23
- return { prefix, number: Number(number) };
24
- }).sort((a, b) => a.prefix.localeCompare(b.prefix) || a.number - b.number);
25
- const ranges = [];
26
- for (let i = 0; i < sorted.length; i++) {
27
- const first = sorted[i];
28
- let last = first;
29
- while (sorted[i + 1]?.prefix === first.prefix && sorted[i + 1].number === last.number + 1) last = sorted[++i];
30
- ranges.push(first === last ? `${first.prefix}${first.number}` : `${first.prefix}${first.number}-${last.prefix}${last.number}`);
31
- }
32
- return ranges.join(", ");
33
- }
34
-
35
- export function snapshotTokens(snapshot) {
36
- const text = typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot);
37
- return { bytes: Buffer.byteLength(text, "utf8"), estTokens: Math.ceil(Buffer.byteLength(text, "utf8") / 4) };
38
- }
39
-
40
- export const toolSchemas = [
41
- {
42
- name: "newTab",
43
- description: "Open a tab and return its page. Waits for interactivity.",
44
- parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
45
- },
46
- {
47
- name: "attachPage",
48
- description: "Attach to an existing tab by targetId from listTargets().",
49
- parameters: { type: "object", properties: { targetId: { type: "string" } }, required: ["targetId"] },
50
- },
51
- {
52
- name: "page.goto",
53
- description: "Navigate the page; resolves when the page looks interactive.",
54
- parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
55
- },
56
- {
57
- name: "page.snapshot",
58
- description: "PRIMARY page read. Snapshot once, act on refs, then use {diff:true} for changes. Full fallbacks carry full:true and a reason. Options: diff, maxDepth, maxChars, interactive, showHidden, selector, ref.",
59
- parameters: { type: "object", properties: { options: { type: "object" } } },
60
- },
61
- {
62
- name: "page.locator",
63
- description: "Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",
64
- parameters: { type: "object", properties: { selectorOrRef: { type: "string" } }, required: ["selectorOrRef"] },
65
- },
66
- {
67
- name: "page.evaluate",
68
- description: "Run JS in the page and return the result.",
69
- parameters: { type: "object", properties: { expression: { type: "string" } }, required: ["expression"] },
70
- },
71
- {
72
- name: "page.screenshot",
73
- description: "Capture page image bytes (path, fullPage, clip, type, quality).",
74
- parameters: { type: "object", properties: { options: { type: "object" } } },
75
- },
76
- {
77
- name: "page.pdf",
78
- description: "Print the page to PDF bytes (path, format, margin, printBackground).",
79
- parameters: { type: "object", properties: { options: { type: "object" } } },
80
- },
81
- {
82
- name: "compactSnapshot",
83
- description: "Compact page.snapshot() before reading: full results become raw trees; diffs use +/~ lines and removed ref ranges. Refs resolve in-page.",
84
- parameters: { type: "object", properties: { snapshot: {} }, required: ["snapshot"] },
85
- },
86
- {
87
- name: "createCua",
88
- description: "Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",
89
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
90
- },
91
- {
92
- name: "createCaptcha",
93
- description: "Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",
94
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
95
- },
96
- {
97
- name: "createChromeApi",
98
- description: "Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",
99
- parameters: { type: "object", properties: { connection: {}, options: { type: "object" } }, required: ["connection"] },
100
- },
101
- {
102
- name: "injectCookies",
103
- description: "Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",
104
- parameters: { type: "object", properties: { page: {}, cookies: { type: "array" } }, required: ["page", "cookies"] },
105
- },
106
- {
107
- name: "createNetworkSnoop",
108
- description: "Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",
109
- parameters: { type: "object", properties: { page: {}, match: {}, bodies: { type: "boolean" }, maxEntries: { type: "number" }, maxBodyBytes: { type: "number" } }, required: ["page"] },
110
- },
111
- {
112
- name: "snoop.waitFor",
113
- description: "Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",
114
- parameters: { type: "object", properties: { match: {}, timeoutMs: { type: "number" } } },
115
- },
116
- {
117
- name: "snoop.popJson",
118
- description: "Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",
119
- parameters: { type: "object", properties: {} },
120
- },
121
- {
122
- name: "snoop.summary",
123
- description: "Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",
124
- parameters: { type: "object", properties: { max: { type: "number" } } },
125
- },
126
- {
127
- name: "collectWhileScrolling",
128
- description: "Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",
129
- parameters: { type: "object", properties: { page: {}, snoop: {}, minItems: { type: "number" }, maxScrolls: { type: "number" }, extract: {}, scroll: { type: "string", enum: ["wheel", "end"] }, settleMs: { type: "number" } }, required: ["page", "snoop"] },
130
- },
131
- {
132
- name: "createTrace",
133
- description: "Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",
134
- parameters: { type: "object", properties: { page: {}, dir: { type: "string" }, screenshots: { type: "boolean" }, network: { type: "boolean" }, console: { type: "boolean" }, maxBodyBytes: { type: "number" }, events: {} }, required: ["page", "dir"] },
135
- },
136
- {
137
- name: "trace.step",
138
- description: "Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",
139
- parameters: { type: "object", properties: { name: { type: "string" }, fn: {} }, required: ["name", "fn"] },
140
- },
141
- {
142
- name: "trace.stop",
143
- description: "Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",
144
- parameters: { type: "object", properties: {} },
145
- },
146
- {
147
- name: "reconcileFrames",
148
- description: "Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",
149
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
150
- },
151
- {
152
- name: "snapshotWithFrames",
153
- description: "Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",
154
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
155
- },
156
- {
157
- name: "connectPipe.dialogPolicy",
158
- description: "Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",
159
- parameters: { type: "object", properties: { accept: { type: "boolean" }, promptText: { type: "string" } } },
160
- },
161
- {
162
- name: "requestHuman",
163
- description: "Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",
164
- parameters: { type: "object", properties: { page: {}, prompt: { type: "string" }, until: {}, timeoutMs: { type: "number" }, pollMs: { type: "number" }, signal: {} }, required: ["page"] },
165
- },
166
- {
167
- name: "describeLayers",
168
- description: "Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",
169
- parameters: { type: "object", properties: { page: {}, grid: { type: "number" } }, required: ["page"] },
170
- },
171
- {
172
- name: "snapshotWithLayers",
173
- description: "Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",
174
- parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
175
- },
176
- {
177
- name: "emulate",
178
- description: "Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",
179
- parameters: { type: "object", properties: { page: {}, preset: {} }, required: ["page", "preset"] },
180
- },
181
- {
182
- name: "createRoutes",
183
- description: "Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",
184
- parameters: { type: "object", properties: { page: {} }, required: ["page"] },
185
- },
186
- {
187
- name: "route.continue",
188
- description: "Continue an intercepted request, optionally overriding url, method, headers, or postData.",
189
- parameters: { type: "object", properties: { url: { type: "string" }, method: { type: "string" }, headers: { type: "object" }, postData: {} } },
190
- },
191
- {
192
- name: "route.fulfill",
193
- description: "Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",
194
- parameters: { type: "object", properties: { status: { type: "number" }, headers: { type: "object" }, contentType: { type: "string" }, body: {} } },
195
- },
196
- {
197
- name: "route.abort",
198
- description: "Abort an intercepted request with a CDP errorReason (defaults to Failed).",
199
- parameters: { type: "object", properties: { reason: { type: "string" } } },
200
- },
201
- ];
package/src/lock-file.js DELETED
@@ -1,130 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import { link, open, readFile, unlink } from "node:fs/promises";
4
- import path from "node:path";
5
- import { promisify } from "node:util";
6
- import { restrictNewFileToOwner } from "./owner-only.js";
7
-
8
- const execFileAsync = promisify(execFile);
9
- const WINDOWS_START_TIME_TIMEOUT_MS = 15_000;
10
- let ownStartTime;
11
-
12
- // When the process holding `pid` started, in a form that only has to compare
13
- // equal to itself on this machine; null when the platform cannot say. A dead
14
- // holder's pid can be reused, and pid plus start time is what stays unique.
15
- export async function processStartTime(pid) {
16
- if (process.platform === "win32") {
17
- if (!Number.isInteger(pid) || pid <= 0) return null;
18
- // Win32_Process.CreationDate is readable for every process, not only the
19
- // caller's own (Get-Process StartTime is not), and a reused pid usually
20
- // belongs to someone else. FILETIME ticks keep the value locale-free.
21
- // PowerShell is spawned by absolute path: a bare name resolves from the cwd
22
- // before PATH, which another user may be able to write.
23
- const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
24
- try {
25
- const { stdout } = await execFileAsync(
26
- path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
27
- [
28
- "-NoLogo",
29
- "-NoProfile",
30
- "-NonInteractive",
31
- "-Command",
32
- `(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`,
33
- ],
34
- { timeout: WINDOWS_START_TIME_TIMEOUT_MS, windowsHide: true },
35
- );
36
- const ticks = String(stdout).trim();
37
- return /^\d+$/.test(ticks) ? ticks : null;
38
- } catch {
39
- return null;
40
- }
41
- }
42
- if (process.platform === "linux") {
43
- try {
44
- const text = await readFile(`/proc/${pid}/stat`, "utf8");
45
- // Field 22 (starttime); the fields after the parenthesised comm start at 3.
46
- return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
47
- } catch {
48
- return null;
49
- }
50
- }
51
- try {
52
- const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], {
53
- env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
54
- });
55
- return stdout.trim() || null;
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- // This process's own start time, looked up once: on Windows each lookup is a
62
- // PowerShell call.
63
- export function ownProcessStartTime() {
64
- ownStartTime ??= processStartTime(process.pid);
65
- return ownStartTime;
66
- }
67
-
68
- // Build the lock out of sight and hard-link it into place, so a lock file is
69
- // never visible half-written: a reader either misses it or reads it whole.
70
- // Returns the inode and token that identify our lock, or null when the path is taken.
71
- export async function createLock(lockPath) {
72
- const ownStart = ownProcessStartTime();
73
- const token = randomUUID();
74
- const tempPath = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
75
- let handle;
76
- try {
77
- handle = await open(tempPath, "wx", 0o600);
78
- await handle.writeFile(
79
- `${JSON.stringify({ pid: process.pid, start: await ownStart, token, acquiredAt: new Date().toISOString() })}\n`,
80
- "utf8",
81
- );
82
- const { ino } = await handle.stat();
83
- await handle.close();
84
- handle = null;
85
- await restrictNewFileToOwner(tempPath);
86
- try {
87
- await link(tempPath, lockPath);
88
- } catch (error) {
89
- if (error?.code === "EEXIST") return null;
90
- throw error;
91
- }
92
- return { ino, token };
93
- } finally {
94
- await handle?.close().catch(() => {});
95
- await unlink(tempPath).catch(() => {});
96
- }
97
- }
98
-
99
- // Content and inode come from one open handle, so the identity we act on is
100
- // bound to the exact file we inspected rather than to the path.
101
- export async function readLockState(lockPath) {
102
- let handle;
103
- try {
104
- handle = await open(lockPath, "r");
105
- } catch (error) {
106
- if (error?.code === "ENOENT") return null;
107
- throw error;
108
- }
109
- try {
110
- const stats = await handle.stat();
111
- const text = await handle.readFile("utf8");
112
- const state = { ino: stats.ino, mtimeMs: stats.mtimeMs, pid: null, start: null, token: null };
113
- try {
114
- const value = JSON.parse(text);
115
- if (Number.isInteger(value?.pid) && value.pid > 0) state.pid = value.pid;
116
- if (typeof value?.start === "string") state.start = value.start;
117
- if (typeof value?.token === "string") state.token = value.token;
118
- } catch {
119
- // No identity: an empty or partial lock is aged out, never reclaimed on
120
- // the spot, because a live contender may have just created it.
121
- }
122
- return state;
123
- } finally {
124
- await handle.close().catch(() => {});
125
- }
126
- }
127
-
128
- export function isSameLock(state, ino, token) {
129
- return state !== null && state.ino === ino && state.token === token;
130
- }
@@ -1,201 +0,0 @@
1
- // Windows half of native-messaging host registration (#90 cluster 3). Chrome on Windows finds a host through the
2
- // per-user registry value HKCU\Software\<vendor>\<browser>\NativeMessagingHosts\<name> (default value = manifest path),
3
- // and file safety lives in the owner SID and ACL, not in uid/mode bits. The policy below is the ACL analogue of the
4
- // POSIX checks in bridge-transport.js: only the user, SYSTEM, Administrators and TrustedInstaller may be able to
5
- // change the host executable, the directory it starts in, the manifest or its directory, or replace any directory on
6
- // the path to them. For a .cmd/.bat host only the wrapper and its directory are covered, not what the script runs.
7
- import { execFile } from "node:child_process";
8
- import { existsSync } from "node:fs";
9
- import { mkdir, rmdir, unlink } from "node:fs/promises";
10
- import path from "node:path";
11
-
12
- const SYSTEM = "S-1-5-18";
13
- const ADMINISTRATORS = "S-1-5-32-544";
14
- const TRUSTED_INSTALLER = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
15
- const OWNER_RIGHTS = "S-1-3-4";
16
- const CREATOR_OWNER = "S-1-3-0";
17
-
18
- // FileSystemRights bits (winnt.h). Directory names in brackets.
19
- const WRITE_DATA = 0x2; // [AddFile]
20
- const APPEND_DATA = 0x4; // [AddSubdirectory]
21
- const WRITE_EA = 0x10;
22
- const DELETE_CHILD = 0x40;
23
- const WRITE_ATTRIBUTES = 0x100;
24
- const DELETE = 0x10000;
25
- const WRITE_DAC = 0x40000;
26
- const WRITE_OWNER = 0x80000;
27
- const GENERIC_ALL = 0x10000000;
28
- const GENERIC_WRITE = 0x40000000;
29
-
30
- // Rights that let a principal change an object's content, metadata, ACL or owner, or delete it.
31
- const MODIFY = WRITE_DATA | APPEND_DATA | WRITE_EA | WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL | GENERIC_WRITE;
32
- // What an untrusted principal must not hold on each kind of path component. "final" is a directory whose content
33
- // matters: the manifest directory, and the host's own directory (Chrome starts the host there, so an .exe loads DLLs
34
- // and a .cmd resolves bare commands from it).
35
- const FORBIDDEN = {
36
- executable: MODIFY,
37
- manifest: MODIFY,
38
- final: MODIFY | DELETE_CHILD,
39
- // An ancestor may let others add entries (default C:\ grants Users AddSubdirectory, the analogue of a sticky root
40
- // /tmp), but nobody untrusted may delete or rename an existing child, delete the ancestor, or take its ACL.
41
- ancestor: DELETE_CHILD | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL,
42
- };
43
-
44
- export const WIN32_REGISTRY_KEYS = Object.freeze({
45
- chrome: "HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",
46
- chromium: "HKCU\\Software\\Chromium\\NativeMessagingHosts",
47
- });
48
-
49
- export const isWin32RegistryKey = (key) => typeof key === "string" && /^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);
50
-
51
- // Returns null when the inspected path is safe as `kind` ("executable", "manifest", "final" or "ancestor"), else the
52
- // reason. `item` is one entry of inspectWin32Paths(); `userSid` is the current user's SID.
53
- export function win32PathRisk(item, kind, userSid) {
54
- const trusted = new Set([userSid, SYSTEM, ADMINISTRATORS, TRUSTED_INSTALLER]);
55
- if (item?.inaccessible) return "could not be inspected";
56
- if (!item?.exists) return "is missing";
57
- if (item.reparse) return "is a symlink, junction or other reparse point";
58
- if (kind === "executable" || kind === "manifest") {
59
- if (item.directory) return "is not a regular file";
60
- if (kind === "executable" && !/\.(exe|cmd|bat|com)$/i.test(item.path)) return "is not a .exe, .cmd, .bat or .com file";
61
- } else if (!item.directory) return "is not a directory";
62
- if (!trusted.has(item.owner)) return `is owned by untrusted ${item.owner}`;
63
- trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER); // OWNER RIGHTS = the (trusted) owner; CREATOR OWNER = whoever creates a child
64
- for (const ace of item.aces ?? []) {
65
- if (!ace.allow || trusted.has(ace.sid)) continue;
66
- // An inherit-only ACE does not apply to this object, but on a final directory an object-inheriting one lands on
67
- // every file created in it (the manifest, a DLL next to the host), so it counts with the file rights.
68
- const mask = !ace.inheritOnly ? FORBIDDEN[kind] : kind === "final" && ace.objectInherit ? MODIFY : 0;
69
- if ((Number(ace.rights) & mask) !== 0) return `grants ${ace.sid} write access`;
70
- }
71
- return null;
72
- }
73
-
74
- const systemBinary = (...segments) => {
75
- const file = path.win32.join(process.env.SystemRoot || "C:\\Windows", "System32", ...segments);
76
- if (!existsSync(file)) throw new Error(`${file} is missing`);
77
- return file;
78
- };
79
-
80
- // Exit code of a finished child; a spawn failure, a timeout or a kill rejects (the caller fails closed).
81
- function run(file, args) {
82
- return new Promise((resolve, reject) => {
83
- execFile(file, args, { timeout: 15_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
84
- if (error && (typeof error.code !== "number" || error.killed)) reject(error);
85
- else resolve({ code: error ? error.code : 0, stdout, stderr });
86
- });
87
- });
88
- }
89
-
90
- // One bounded PowerShell call that reports, for each path in order: whether it exists or could not be read, whether it
91
- // is a directory or a reparse point, its owner SID and its ACEs (SID, allow/deny, rights mask, inherit-only,
92
- // object-inherit); plus the current user SID. Paths travel base64-encoded inside the script and nothing path-shaped
93
- // comes back, so no console code page can garble them. Under Constrained Language Mode the .NET calls fail, and so
94
- // does the whole inspection: the caller fails closed.
95
- const INSPECT = `$ErrorActionPreference = 'Stop'
96
- $paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')))
97
- $sid = [System.Security.Principal.SecurityIdentifier]
98
- $items = @(foreach ($p in $paths) {
99
- try { $i = Get-Item -LiteralPath $p -Force; $acl = Get-Acl -LiteralPath $p }
100
- catch [System.Management.Automation.ItemNotFoundException] { [pscustomobject]@{ exists = $false; inaccessible = $false }; continue }
101
- catch { [pscustomobject]@{ exists = $false; inaccessible = $true }; continue }
102
- $aces = @(foreach ($r in $acl.GetAccessRules($true, $true, $sid)) { [pscustomobject]@{
103
- sid = $r.IdentityReference.Value; allow = ($r.AccessControlType -eq 'Allow'); rights = [int64]$r.FileSystemRights
104
- inheritOnly = (($r.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0)
105
- objectInherit = (($r.InheritanceFlags -band [System.Security.AccessControl.InheritanceFlags]::ObjectInherit) -ne 0) } })
106
- [pscustomobject]@{ exists = $true; inaccessible = $false; directory = [bool]$i.PSIsContainer; owner = $acl.GetOwner($sid).Value
107
- aces = $aces; reparse = (($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) }
108
- })
109
- ConvertTo-Json -Depth 6 -Compress @{ user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; items = $items }`;
110
-
111
- export async function inspectWin32Paths(paths) {
112
- let out;
113
- try {
114
- const script = INSPECT.replace("__PATHS__", Buffer.from(JSON.stringify(paths), "utf8").toString("base64"));
115
- const powershell = systemBinary("WindowsPowerShell", "v1.0", "powershell.exe");
116
- const result = await run(powershell, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")]);
117
- if (result.code !== 0) throw new Error(String(result.stderr).trim() || `exit ${result.code}`);
118
- out = JSON.parse(result.stdout);
119
- } catch (error) {
120
- throw new Error(`native host security could not be verified (the PowerShell ACL inspection failed; Constrained Language Mode or a policy may block it): ${error.message}`);
121
- }
122
- const items = [out.items ?? []].flat();
123
- if (typeof out.user !== "string" || items.length !== paths.length) throw new Error("native host security could not be verified: unexpected ACL report");
124
- return { user: out.user, items: items.map((item, index) => ({ ...item, path: paths[index], aces: [item.aces ?? []].flat() })) };
125
- }
126
-
127
- // Every directory from the drive root down to `dir`, root first. Only local drive-letter paths are accepted: a UNC or
128
- // \\?\ root has an ACL this host does not own and cannot be walked the same way.
129
- export function win32DirectoryChain(dir) {
130
- const absolute = path.win32.resolve(dir);
131
- const { root } = path.win32.parse(absolute);
132
- if (!/^[A-Za-z]:\\$/.test(root) || /^\\\\/.test(dir)) throw new Error(`${dir} is not on a local drive-letter path`);
133
- const chain = [root];
134
- for (const part of absolute.slice(root.length).split("\\").filter(Boolean)) chain.push(path.win32.join(chain.at(-1), part));
135
- return chain;
136
- }
137
-
138
- async function registryDefault(key, view) {
139
- const result = await run(systemBinary("reg.exe"), ["query", key, "/ve", ...(view ? [`/reg:${view}`] : [])]);
140
- if (result.code !== 0) return null;
141
- return /REG_SZ\s+(.*?)\s*$/m.exec(result.stdout)?.[1] ?? "";
142
- }
143
-
144
- // Verifies the host and the manifest directory, writes the manifest through `writeManifest(file)` (the shared atomic
145
- // writer), re-verifies the written file, then points the per-user registry value at it.
146
- export async function installWin32NativeHost({ hostName, hostPath, dir, registryKey, force, writeManifest }) {
147
- const hostChain = win32DirectoryChain(path.win32.dirname(hostPath));
148
- win32DirectoryChain(hostPath);
149
- const dirChain = win32DirectoryChain(dir);
150
- const { user, items } = await inspectWin32Paths([hostPath, ...hostChain, ...dirChain]);
151
- const reject = (prefix, item, kind) => { const risk = win32PathRisk(item, kind, user); if (risk) throw new Error(`${prefix}: ${item.path} ${risk}`); };
152
- const kindAt = (chain, index) => (index === chain.length - 1 ? "final" : "ancestor");
153
- reject("hostPath must be a securely owned executable file", items[0], "executable");
154
- items.slice(1, 1 + hostChain.length).forEach((item, index) => reject("hostPath directory security rejected", item, kindAt(hostChain, index)));
155
- const dirItems = items.slice(1 + hostChain.length);
156
- const firstMissing = dirItems.findIndex((item) => !item.exists && !item.inaccessible);
157
- dirItems.slice(0, firstMissing === -1 ? undefined : firstMissing).forEach((item, index) => reject("nativeMessagingHostDir security rejected", item, kindAt(dirChain, index)));
158
- if (firstMissing === 0) throw new Error(`nativeMessagingHostDir security rejected: ${dirChain[0]} is missing`);
159
- const created = firstMissing > 0 ? dirChain.slice(firstMissing) : [];
160
- const file = path.win32.join(dirChain.at(-1), `${hostName}.json`);
161
- // Only what this call itself created is removed on failure: the directories its own mkdir made (a concurrent install
162
- // may have made them first) and the manifest only after its own write produced it.
163
- const firstMade = created.length ? await mkdir(dirChain.at(-1), { recursive: true }) : undefined;
164
- // mkdir creates a tail of dirChain and reports its first directory, possibly in \\?\ or long-name form, so locate it
165
- // by depth rather than by spelling: C:\a\b has three components and is dirChain[2].
166
- const madeDepth = firstMade === undefined ? 0 : firstMade.replace(/^\\\\\?\\/, "").split(/[\\/]+/).filter(Boolean).length;
167
- const made = madeDepth > 0 && madeDepth <= dirChain.length ? dirChain.slice(madeDepth - 1) : [];
168
- let wroteManifest = false;
169
- try {
170
- if (created.length) {
171
- const again = await inspectWin32Paths(created);
172
- if (again.user !== user) throw new Error("native host security could not be verified: user changed");
173
- again.items.forEach((item, offset) => reject("nativeMessagingHostDir security rejected", item, kindAt(dirChain, firstMissing + offset)));
174
- }
175
- const hostKey = `${registryKey}\\${hostName}`;
176
- // Chromium reads HKLM before HKCU, so a machine-level entry would win; refuse before writing anything.
177
- const machineKey = `HKLM\\${hostKey.slice("HKCU\\".length)}`;
178
- for (const view of ["32", "64"]) {
179
- if (await registryDefault(machineKey, view) !== null) throw new Error(`${hostKey} is shadowed by a machine-level registration at ${machineKey} (/reg:${view})`);
180
- }
181
- const current = await registryDefault(hostKey);
182
- if (current !== null && current.toLowerCase() !== file.toLowerCase() && !force) throw new Error(`${hostKey} already points at ${current}; use force`);
183
- const manifest = await writeManifest(file);
184
- wroteManifest = true;
185
- const written = await inspectWin32Paths([file]);
186
- const manifestRisk = win32PathRisk(written.items[0], "manifest", user);
187
- // On a force reinstall the HKCU value may already name this path; it then points at a missing file, which Chrome
188
- // treats as no host, and nobody untrusted can recreate the file in the verified directory.
189
- if (manifestRisk) { await unlink(file).catch(() => {}); throw new Error(`native messaging manifest security rejected: ${file} ${manifestRisk}`); }
190
- const added = await run(systemBinary("reg.exe"), ["add", hostKey, "/ve", "/t", "REG_SZ", "/d", file, "/f"]);
191
- if (added.code !== 0) throw new Error(`native host registry write failed: ${String(added.stderr).trim()}`);
192
- return { path: file, manifest, registryKey: hostKey };
193
- } catch (error) {
194
- // rmdir (not recursive) leaves a directory alone once another install has put a file in it.
195
- if (made.length) {
196
- if (wroteManifest) await unlink(file).catch(() => {});
197
- for (const entry of [...made].reverse()) await rmdir(entry).catch(() => {});
198
- }
199
- throw error;
200
- }
201
- }