omowright 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
@@ -0,0 +1,123 @@
1
+ # Frames, layers, human handoff, device emulation
2
+
3
+ Four modules for the moments when the plain snapshot-and-click loop stalls.
4
+ All come from the package entrypoint:
5
+
6
+ ```js
7
+ const { reconcileFrames, snapshotWithFrames, describeLayers, layersHeader, snapshotWithLayers,
8
+ requestHuman, DEVICE_PRESETS, emulate, compactSnapshot } = await import("omowright");
9
+ ```
10
+
11
+ ## Out-of-process iframes and shadow DOM
12
+
13
+ Cross-origin iframes (payment widgets, embedded editors, CAPTCHA frames) run in
14
+ their own process. The snapshot stitches each one in as a child tree under the
15
+ owning `- iframe [ref=eK]:` line, and child refs carry a frame prefix:
16
+
17
+ ```
18
+ - iframe [ref=e12]:
19
+ - textbox "Card number" [ref=f1e3]
20
+ - button "Pay" [ref=f1e4]
21
+ ```
22
+
23
+ Refs stay page-level. `page.locator("f1e3").fill("4242...")` routes to the
24
+ right frame session; there is no frame handle to fetch and no `FrameLocator`
25
+ to build by hand. Plain `page.snapshot()` sees frames that existed before
26
+ `attachPage()`, so this is the normal path, not a special one.
27
+
28
+ Two shapes worth recognising:
29
+
30
+ - An `iframe` line with no children means the child tree wasn't reachable. Run
31
+ `reconcileFrames(page)` (returns the frames it re-linked) and snapshot again,
32
+ or call `snapshotWithFrames(page)`, which does the repair first and adds a
33
+ `missingFrames` list only when a frame still couldn't be entered.
34
+ - A closed shadow root hides the host link, so the frame inside it shows up as
35
+ an orphan `- iframe:` block at the end of the tree. Its `f<N>e<M>` refs work
36
+ the same way.
37
+
38
+ Rough edge: the first click into a freshly adopted OOPIF can land on the
39
+ embedder instead of the frame. Take a fresh snapshot and click the ref again;
40
+ the second attempt lands.
41
+
42
+ ```js
43
+ const snap = await snapshotWithFrames(page, { interactive: true });
44
+ if (snap.missingFrames) console.log("unreachable frames:", snap.missingFrames);
45
+ await page.locator("f1e3").fill("4242 4242 4242 4242");
46
+ ```
47
+
48
+ ## Layers: why did the same click miss twice?
49
+
50
+ A cookie banner, a modal, or a full-page loader sitting above the target
51
+ swallows clicks while the a11y tree still lists the element you aimed at. After
52
+ two identical misses, ask what's on top before switching to coordinates:
53
+
54
+ ```js
55
+ const layers = await describeLayers(page);
56
+ console.log(layersHeader(layers));
57
+ // @layers blocking=dialog "Cookie preferences" coverage=100% hint=#onetrust-banner-sdk
58
+ if (layers.blocking) {
59
+ // Dismiss through a fresh ref: snapshot the overlay by its hint, click its button.
60
+ const tree = compactSnapshot(await page.snapshot({ selector: layers.blocking.selectorHint, interactive: true }));
61
+ await page.locator(/\[ref=(e\d+)\]/.exec(tree)[1]).click(); // first interactive ref inside the overlay
62
+ }
63
+ ```
64
+
65
+ `selectorHint` is `#id` when the overlay has one and a bare tag or
66
+ `tag.class` otherwise; a bare tag is too broad for a CSS click, which is why
67
+ the recipe scopes a snapshot to it instead of clicking through it.
68
+
69
+ `describeLayers` hit-tests a 5x5 grid over the viewport (pass `{ grid }` to
70
+ change it), pierces open shadow roots, and reports the topmost element that
71
+ covers at least 60% of the points as `blocking`, with `role`, `name`,
72
+ `coverage`, `position`, `ariaModal`, and a `selectorHint`. `candidates` lists
73
+ the runners-up. `@layers none` means nothing is covering the page and the miss
74
+ has another cause (stale ref, off-screen target, disabled control).
75
+
76
+ `snapshotWithLayers(page, opts)` folds this into the read you were already
77
+ doing: the header becomes the first line of `tree`, and the raw result sits in
78
+ `snapshot.layers`. Use it as the default read on sites known for overlays.
79
+
80
+ ## Human handoff: login, OTP, CAPTCHA you can't solve
81
+
82
+ When every rung fails on a login wall, a one-time code, or a challenge the
83
+ captcha preset can't clear, hand the tab to the person and wait for a signal:
84
+
85
+ ```js
86
+ const result = await requestHuman(page, {
87
+ prompt: "Sign in with your account, then click Done.",
88
+ until: { url: /\/dashboard/ }, // or { selector: "nav.account" } or async page => boolean
89
+ timeoutMs: 300000,
90
+ });
91
+ // { outcome: "continued" | "timed_out" | "cancelled", elapsedMs, reason: "until" | "done-button" | "timed_out" | "signal" }
92
+ if (result.outcome !== "continued") throw new Error(`handoff ${result.outcome}`);
93
+ ```
94
+
95
+ The call brings the window to the front, injects a shadow-DOM banner with your
96
+ prompt and a Done button, then polls every `pollMs` for `until` or the button.
97
+ Pass an `AbortSignal` as `signal` to cancel from your side. The banner is
98
+ removed on every exit path, so the next snapshot is clean.
99
+
100
+ The cookie rule from `stealth.md` (next to this file) still holds here: the handoff is
101
+ the way to get into Google or 1Password, since injecting their cookies gets the
102
+ user logged out server-side. Let the human sign in inside the automated
103
+ browser and continue from that session.
104
+
105
+ ## Device emulation for responsive QA
106
+
107
+ `emulate` sets viewport metrics, touch, and user agent in one call:
108
+
109
+ ```js
110
+ await emulate(page, "iphone-14"); // 390x844 @3x, touch, iOS Safari UA
111
+ await page.goto("https://example.com");
112
+ await page.screenshot({ path: "/tmp/home-iphone.png" });
113
+ await emulate(page, "desktop-1440"); // 1440x900, mouse
114
+ await emulate(page, null); // clear the override, restore the original UA
115
+ ```
116
+
117
+ Presets in `DEVICE_PRESETS`: `iphone-14` (390x844), `pixel-7` (412x915),
118
+ `ipad-air` (820x1180), `desktop-1440` (1440x900). Pass an object with the same
119
+ fields (`width, height, deviceScaleFactor, mobile, hasTouch, userAgent,
120
+ platform`) for a custom device. The original UA is captured on the first call
121
+ per page, so `null` always returns to where you started. Re-snapshot after
122
+ switching: layout changes move refs, and a mobile layout often swaps a nav bar
123
+ for a menu button.
@@ -0,0 +1,109 @@
1
+ # Quickstart — connections, pages, snapshots
2
+
3
+ ## Runtime
4
+
5
+ Bun >= 1.4 recommended (`bun test` runs the suite as-is); Node >= 22 supported
6
+ (`node --test`). Same source, no build step.
7
+
8
+ ## Two transports
9
+
10
+ ```js
11
+ const { connect, connectPipe } = await import("omowright");
12
+ ```
13
+
14
+ - `connectPipe({ browserPath, browserArgs, storageRoot })` — launches a browser
15
+ over `--remote-debugging-pipe`. Zero TCP listeners (verified with `lsof`),
16
+ nothing for other processes to hijack. Default choice. Returns an object with
17
+ `newTab(url)`.
18
+ - `connect("http://127.0.0.1:9222")` — attaches to a running Chromium started
19
+ with `--remote-debugging-port`, or a user's own Chrome with remote debugging
20
+ enabled from `chrome://inspect/#remote-debugging` (its `DevToolsActivePort`
21
+ names the port and the `ws://127.0.0.1:<port>/devtools/browser/<id>` URL;
22
+ `connect()` takes either). Use for a real user browser (its
23
+ profile, cookies, logins); pair with `createChromeApi` for bookmarks/history.
24
+ Returns a `BrowserConnection` with `newTab(url)`.
25
+ - `connectRunningBrowser({ browser })` — finds that port for you: it reads
26
+ `DevToolsActivePort` in each known browser profile, keeps the one whose port
27
+ answers (a TCP check, so no prompt), and connects to its exact WebSocket URL.
28
+ It never edits the profile. Two live browsers throw `choose_browser`; none
29
+ throws `not_found`, which means the user has not allowed remote debugging yet.
30
+ It works where an extension-based attach is blocked, for example a page that
31
+ holds another extension's iframe.
32
+
33
+ **Every NEW connection to a user's own Chrome shows them an "Allow remote
34
+ debugging?" prompt.** `connect()` calls in one process share one connection
35
+ per browser, and `close()` releases your handle (the last release disconnects).
36
+ So keep ONE handle for the whole job: across eval cells, store it on
37
+ `globalThis` and reuse it instead of connecting (and closing) in every cell.
38
+
39
+ ```js
40
+ globalThis.userBrowser ??= await connect("http://127.0.0.1:9222"); // one prompt
41
+ const page = await userBrowser.newTab("https://example.com");
42
+ // ... work, in this cell and later ones ...
43
+ await page.close();
44
+ // at the very end of the job:
45
+ await userBrowser.close();
46
+ ```
47
+
48
+ Always launch with a dedicated `--user-data-dir` (a `mkdtemp` dir) and delete it
49
+ after `browser.close()`. Under Node, `node:sqlite` loads lazily with a
50
+ `bun:sqlite` fallback under Bun (see Runtime above).
51
+
52
+ ## Page essentials
53
+
54
+ ```js
55
+ const page = await browser.newTab(url); // waits for interactivity
56
+ await page.goto(url); // content-probe readiness
57
+ await page.goto(url, { waitUntil: "commit" }); // escape hatch for tiny pages
58
+ await page.title(); page.url();
59
+ await page.evaluate("document.readyState");
60
+ await page.screenshot({ path, fullPage?, clip?, type?, quality? });
61
+ await page.pdf({ path, format?, margin? });
62
+ await page.locator("e1").click(); // ref or CSS
63
+ await page.locator("input[name=q]").fill("text");
64
+ await page.keyboard.press("Enter"); await page.mouse.wheel(0, 400);
65
+ await page.close();
66
+ ```
67
+
68
+ ## Snapshot discipline
69
+
70
+ ```js
71
+ const snap = await page.snapshot(); // { tree, refs } or JSON string
72
+ const tree = compactSnapshot(snap); // raw tree, ~57% smaller
73
+ await page.snapshot({ interactive: true }); // controls, headings, landmarks and state feedback
74
+ await page.snapshot({ maxDepth: 20, maxChars: 4000, selector: "main" });
75
+ ```
76
+
77
+ Tree lines look like `- link "Learn more" [ref=e1]` — feed `e1` to
78
+ `page.locator("e1")`. **EVERY NEW SNAPSHOT INVALIDATES EARLIER REFS**: re-snapshot
79
+ after each state change, never act on a stale ref. Start with
80
+ `interactive: true`; escalate to a full snapshot when a target or needed text is
81
+ missing or truncated. Interactive reads keep capped text for clickable nodes,
82
+ scrollable containers and live regions: roles alert, alertdialog, status, log,
83
+ timer and marquee, and any `aria-live="polite"` or `"assertive"` element such as
84
+ a toast. A clickable or scrollable node keeps up to 100 characters of its own
85
+ text. Every other piece of text inside a live region counts toward that region's
86
+ 100 characters in total, however many items it holds, so two toasts each keep
87
+ their own text and a long log keeps only its start. A live region nested inside
88
+ a clickable or scrollable node, such as a toast in a scrollable pane, keeps its
89
+ own 100 characters beside the node's. Clickable or scrollable nodes inside or
90
+ around a live region keep their own 100 on top, so a scrollable `role="log"`
91
+ keeps up to 100 characters of its own text plus 100 for entries that are kept
92
+ nodes (`aria-live="off"` text is dropped; an invalid `aria-live` value counts
93
+ as unset). Other free-standing body prose is omitted.
94
+
95
+ ## Readiness and dialogs
96
+
97
+ Both are transport-level contracts documented once, in
98
+ `TOOLS.md` at the package root (sections "Readiness
99
+ probe" and "Dialogs"). Short form: `goto` waits for meaningful content, not
100
+ `readyState`, and times out after 30s on near-empty pages (`waitUntil: "commit"`
101
+ is the escape hatch); every JavaScript dialog is auto-accepted unless a dialog
102
+ policy says otherwise, and observable via `page.on("dialog")`, where a listener
103
+ can also answer it (`dialog.accept(text)` / `dialog.dismiss()`) instead of the policy.
104
+
105
+ ## Errors worth knowing
106
+
107
+ - `RefStaleError` — the element vanished after your snapshot; re-snapshot.
108
+ - `UnsupportedOperationError` — extension-bridge feature (password managers,
109
+ `OmO.*` extension commands, MV3 write methods). Not available standalone.
@@ -0,0 +1,174 @@
1
+ # Stealth — CloakBrowser through OmOWright
2
+
3
+ CloakBrowser is a stealth Chromium with source-level fingerprint patches (passes
4
+ Cloudflare Turnstile, FingerprintJS, BrowserScan). OmOWright drives its binary
5
+ over the pipe transport — no CDP port, no agent-browser CLI.
6
+
7
+ ## Binary discovery
8
+
9
+ ```bash
10
+ python3 -c "import cloakbrowser, json; print(cloakbrowser.binary_info()['binary_path'])"
11
+ # -> ~/.cloakbrowser/chromium-<ver>/Chromium.app/Contents/MacOS/Chromium
12
+ ```
13
+
14
+ Not installed: `uv pip install "cloakbrowser==0.5.7"` in a venv, then
15
+ `python -c "import cloakbrowser; cloakbrowser.ensure_binary()"`.
16
+
17
+ ## Single-instance rule
18
+
19
+ CloakBrowser enforces **ONE RUNNING INSTANCE** (Chromium SingletonLock, possibly
20
+ strengthened by source patches). If one is already running, `connectPipe` HANGS
21
+ during early init — the `Browser.getVersion` handshake never answers and
22
+ OmOWright times out.
23
+
24
+ Use `connectNamed(name, options)` — attach-or-launch under one name, no probe
25
+ ritual. A healthy registered instance is attached over its endpoint; a stale
26
+ record is cleaned up and the browser relaunched; a live pid whose recorded port
27
+ refuses connections, or answers as a different browser, is a reused pid (treated
28
+ as stale), while an endpoint that hangs or answers wrongly fails fast with an
29
+ `unresponsive holder` error naming the holder (name, pid, endpoint). The record
30
+ stores the browser's `webSocketDebuggerUrl` (it carries the browser GUID), and
31
+ an attach happens only when the endpoint still answers with that exact URL. The
32
+ returned `BrowserConnection` supports `newTab()` on both the launch and the
33
+ attach path.
34
+
35
+ **A named instance is not private.** Naming one replaces the pipe transport with
36
+ a TCP endpoint (`--remote-debugging-address=127.0.0.1 --remote-debugging-port=0`).
37
+ Loopback keeps it off the network, but nothing authenticates it: any process or
38
+ user on this machine can read the registry record (or scan the port) and drive
39
+ the browser — cookies, logged-in sessions, local file reads through CDP.
40
+ Name-less launches keep the pipe and expose no port at all, so use a name only
41
+ on a machine you trust and only when the instance is meant to be shared.
42
+
43
+ ```js
44
+ const { connectNamed, listInstances } = await import("omowright");
45
+ const browser = await connectNamed("cloak-main", {
46
+ browserPath, // required only when a launch is needed (connectCloakProfile resolves it)
47
+ browserArgs,
48
+ profileDir, // recorded with the instance; used for endpoint discovery
49
+ registryRoot, // defaults to ~/.local/share/omowright/instances
50
+ });
51
+ const page = await browser.newTab("https://target.com");
52
+ await listInstances();
53
+ // [{ name, pid, endpoint, webSocketDebuggerUrl, profileDir, browserPath,
54
+ // startedAt, alive, responsive }]
55
+ ```
56
+
57
+ `close()` on the launcher terminates the browser and removes its record; on an
58
+ attached client it only detaches — the instance keeps running for the next
59
+ `connectNamed`. Attaches in one process share one CDP connection per browser
60
+ (Chrome asks to allow remote debugging once per connection): `close()`
61
+ releases your handle and the last release disconnects, so keep one handle
62
+ open across actions instead of attaching per action.
63
+ `connectCloakProfile({ name })` and `omowright-cloak --name <name>` go through
64
+ the same registry: same name, same instance. Without `name` both keep the
65
+ zero-port pipe and never touch the registry.
66
+
67
+ **Fallback — a nameless CloakBrowser is already running** (launched outside
68
+ OmOWright): probe the legacy endpoint, then attach — do NOT spawn another.
69
+
70
+ ```bash
71
+ curl -s -m 2 http://127.0.0.1:9242/json/version # Browser info -> an instance is alive
72
+ ```
73
+
74
+ ```js
75
+ const browser = await connect("http://127.0.0.1:9242");
76
+ const page = await browser.newTab("https://target.com");
77
+ // ... work ...
78
+ await page.close(); // close only YOUR tab
79
+ ```
80
+
81
+ ## Launch
82
+
83
+ ```js
84
+ const { connectCloakProfile } = await import("omowright");
85
+ const browser = await connectCloakProfile({
86
+ profileDir: `${process.env.HOME}/.local/share/omowright-cloak`,
87
+ fingerprintSeed: 63498, // first use pins it; later runs reuse it and reject a mismatch
88
+ });
89
+ ```
90
+
91
+ CLI equivalent:
92
+ `omowright-cloak --profile "$HOME/.local/share/omowright-cloak" --url https://target.example --once --snapshot`
93
+
94
+ - Omit `--headless` when the WAF is aggressive — headed mode carries stronger
95
+ trust signals. The patches apply in both modes.
96
+ - Do NOT pass an init-script for `navigator.webdriver` — CloakBrowser patches it
97
+ at C++ source. `--user-agent` is the only override worth passing.
98
+ - The seed lives in `.omowright-cloak.json` (mode `0600`) and is passed as the
99
+ same `--fingerprint=<seed>` on every launch. Do not pass `--user-data-dir`,
100
+ `--fingerprint`, or `--fingerprint-platform` through `browserArgs`; conflicting
101
+ identity overrides are rejected.
102
+ - The helper uses `connectPipe()` — `connectNamed()` when you pass `name` — so
103
+ an anonymous launch still has no listening CDP TCP port. One process per
104
+ profile.
105
+
106
+ Verify: `await page.evaluate("navigator.webdriver")` must be `false`. For a full
107
+ check load `https://bot.sannysoft.com` or `https://browserscan.net` and read the
108
+ result panel with a snapshot.
109
+
110
+ ## Persistent profiles and cookies
111
+
112
+ Reuse a stable `--user-data-dir` (not a temp dir) to keep logins across runs —
113
+ WAF trust builds with profile age. To import cookies from a real browser profile,
114
+ extract them to JSON and inject with the package helper:
115
+
116
+ ```js
117
+ import { injectCookies } from "omowright";
118
+ const cookies = JSON.parse(await fs.promises.readFile(cookieFile, "utf8"));
119
+ await injectCookies(page, cookies); // sanitize + Network.setCookies
120
+ await page.goto(url); // cookies apply on navigation
121
+ ```
122
+
123
+ `injectCookies` drops `expires <= 0`, forces `secure` + root path + url-scoping
124
+ for `__Host-` cookies, drops `SameSite=None` when not secure, and dedupes by
125
+ name+domain — raw exports fail CDP validation without this. Cookie files are
126
+ live secrets: `0600`, never committed, never printed.
127
+
128
+ ## NEVER extract and reuse cookies for Google or 1Password
129
+
130
+ **HARD RULE, LEARNED BY KILLING THE USER'S REAL SESSIONS ON 2026-08-23. VIOLATING
131
+ IT LOGS THE USER OUT OF THEIR OWN BROWSER.**
132
+
133
+ - **Google (any property: youtube.com, google.com, accounts.google.com, mail,
134
+ drive, ...)** — Google's risk engine detects reuse from a new device
135
+ fingerprint and **invalidates the session server-side; the source browser is
136
+ logged out too.** One run succeeds, then the account is signed out everywhere
137
+ the cookies came from. Not a rotation you can race — a kill. To act as the
138
+ user on Google, drive the user's own logged-in browser.
139
+ - **1Password web (1password.com)** — sessions are bound to full app state
140
+ (IndexedDB device keys, SRP session derivation), not cookies. Injection always
141
+ lands on the sign-in page, from any machine including the same one. There is
142
+ no cookie-only path in.
143
+ - 1Password direct login does not persist across tabs either: a new tab to
144
+ my.1password.com asks for the password again. The original logged-in tab stays
145
+ valid — keep it open and reuse it.
146
+ - 1Password auto-lock extends to 8 hours max (Settings > Security > Auto-lock >
147
+ 8 hours), but closing the browser ALWAYS locks it — hardcoded. Keep the browser
148
+ running and the tab open.
149
+
150
+ Cookie extraction + injection stays fine for sites with ordinary session cookies
151
+ (Grafana, internal tools, most SaaS).
152
+
153
+ ## Session reuse doctrine (ordinary cookie sessions)
154
+
155
+ Do everything in ONE browser session: inject, navigate, read, screenshot, one
156
+ run. Cross-run reuse dies — Grafana rotates its session token per request, so a
157
+ reused cookie works once and re-extracting yields the same dead token. Recovery
158
+ is a fresh login in the source browser, then extract + use immediately.
159
+
160
+ ## Chromium cookie decryption notes (macOS)
161
+
162
+ - Keychain `*- Safe Storage` password -> PBKDF2(`saltysalt`, 1003) ->
163
+ AES-128-CBC with a 16-space IV; strip the `v10` prefix AND the 32-byte SHA256
164
+ domain hash prepended to the plaintext.
165
+ - Read from a GUI login session (for example a LaunchAgent), NOT plain SSH — the keychain
166
+ denies secret reads (`-w`) from non-GUI sessions.
167
+ - A cookie DB in rollback-journal mode (empty `-journal`) needs only the main
168
+ `Cookies` file copied; a WAL-mode DB needs its `-wal` file copied alongside.
169
+
170
+ ## When stealth is NOT needed
171
+
172
+ A plain headless shell is faster and sufficient for most sites. Reach for
173
+ CloakBrowser when the plain path returns a challenge page (Cloudflare "Verify
174
+ you are human", DataDome, PerimeterX) or empty content.
@@ -0,0 +1,179 @@
1
+ import { DEFAULT_AGENT_VIEWPORT, repinViewport } from "./viewport.js";
2
+ import { targetCreationCapability } from "./internal-capability.js";
3
+
4
+ const managers = new WeakMap();
5
+ const CAPABILITY = targetCreationCapability;
6
+
7
+ function optionsKey(options = {}) {
8
+ return JSON.stringify({
9
+ viewport: { ...DEFAULT_AGENT_VIEWPORT, ...(options.viewport ?? {}) },
10
+ closeTimeoutMs: options.closeTimeoutMs ?? 5_000,
11
+ });
12
+ }
13
+
14
+ export class AgentTabManager {
15
+ #connection;
16
+ #owned = new Map();
17
+ #unsubscribers = [];
18
+ #disposed = false;
19
+ #closing = new Map();
20
+ viewport;
21
+ closeTimeoutMs;
22
+ ready;
23
+
24
+ constructor(connection, options = {}) {
25
+ if (!connection?.cdp) throw new TypeError("createAgentTabs requires a browser connection");
26
+ this.#connection = connection;
27
+ this.viewport = Object.freeze({ ...DEFAULT_AGENT_VIEWPORT, ...(options.viewport ?? {}) });
28
+ this.closeTimeoutMs = options.closeTimeoutMs ?? 5_000;
29
+ this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed", info => this.#destroyed(info?.targetId)));
30
+ this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed", info => this.#destroyed(info?.targetId)));
31
+ this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected", () => {
32
+ for (const id of [...this.#owned.keys()]) this.#destroyed(id, Error("Browser transport disconnected"));
33
+ }));
34
+ this.ready = Promise.resolve(connection.cdp.ensureConnected?.());
35
+ }
36
+
37
+ async create(url = "about:blank", options = {}) {
38
+ if (this.#disposed) throw Error("Agent tab manager is disposed");
39
+ await this.ready;
40
+ const viewport = { ...this.viewport, ...(options.viewport ?? {}) };
41
+ // A headed browser keeps a background tab in a shared window hidden: it never
42
+ // paints (Page.captureScreenshot hangs) and requestAnimationFrame never fires.
43
+ // Its own window doesn't take focus from the user's tab, and the tab renders
44
+ // (verified headed on Linux and macOS).
45
+ const result = await this.#connection.cdp.send("Target.createTarget", {
46
+ url: "about:blank", background: true, newWindow: true,
47
+ ...(options.browserContextId ? { browserContextId: options.browserContextId } : {}),
48
+ }, undefined, { capability: CAPABILITY });
49
+ const targetId = result.targetId;
50
+ // CloakBrowser headless defers renderer startup for background targets until
51
+ // activation; activating before attach avoids Page.enable timing out.
52
+ if (await this.#isHeadless()) await this.#connection.cdp.send("Target.activateTarget", { targetId });
53
+ // Finish session/domain setup on a stable document before starting a
54
+ // navigation that can replace the renderer or its execution contexts.
55
+ const tab = await this.adopt(targetId, { viewport });
56
+ if (url !== "about:blank") await tab.page.goto(url);
57
+ return tab;
58
+ }
59
+
60
+ async adopt(targetId, options = {}) {
61
+ if (this.#disposed) throw Error("Agent tab manager is disposed");
62
+ const existing = this.#owned.get(targetId);
63
+ if (existing) return this.#public(existing);
64
+ const viewport = { ...this.viewport, ...(options.viewport ?? {}) };
65
+ const record = { targetId, page: null, viewport: Object.freeze({ ...viewport }), repinQueue: Promise.resolve() };
66
+ this.#owned.set(targetId, record);
67
+ try {
68
+ record.page = await this.#connection.attachPage(targetId);
69
+ await repinViewport(record.page, record.viewport);
70
+ record.navigationOff = record.page.on?.("framenavigated", event => {
71
+ if (!event.parentFrameId) this.#repin(record);
72
+ });
73
+ return this.#public(record);
74
+ } catch (error) {
75
+ await this.#connection.cdp.send("Target.closeTarget", { targetId }).catch(() => {});
76
+ throw error;
77
+ }
78
+ }
79
+
80
+ #public(record) {
81
+ return Object.freeze({ targetId: record.targetId, page: record.page, viewport: { ...record.viewport }, close: options => this.close(record.targetId, options) });
82
+ }
83
+ get(targetId) { const record = this.#owned.get(targetId); return record ? this.#public(record) : null; }
84
+ list() { return [...this.#owned.values()].map(record => this.#public(record)); }
85
+ async #isHeadless() {
86
+ if (typeof this.#connection.cdp.isHeadless === "boolean") return this.#connection.cdp.isHeadless;
87
+ const version = await this.#connection.cdp.send("Browser.getVersion").catch(() => null);
88
+ return /Headless/i.test(version?.product ?? "");
89
+ }
90
+ #queueRepin(record, viewport, reportErrors = false) {
91
+ const size = { ...viewport };
92
+ const operation = record.repinQueue.then(async () => {
93
+ try { await repinViewport(record.page, size); }
94
+ catch (error) { if (reportErrors) console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`, error); else throw error; }
95
+ record.viewport = Object.freeze(size);
96
+ return { ...size };
97
+ });
98
+ record.repinQueue = operation.catch(() => {});
99
+ return operation;
100
+ }
101
+ async #repin(record) { await this.#queueRepin(record, record.viewport, true); }
102
+ async repin(tabOrTargetId, viewport = this.viewport) {
103
+ const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
104
+ const record = this.#owned.get(id);
105
+ if (!record) throw Error(`Target ${id} is not owned by this manager`);
106
+ return this.#queueRepin(record, viewport);
107
+ }
108
+
109
+ async close(tabOrTargetId, options = {}) {
110
+ const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
111
+ const record = this.#owned.get(id);
112
+ if (!record) throw Error(`Target ${id} is not owned by this manager`);
113
+ const existing = this.#closing.get(id);
114
+ if (existing) return existing.promise;
115
+ let resolveOperation, rejectOperation;
116
+ const promise = new Promise((resolve, reject) => { resolveOperation = resolve; rejectOperation = reject; });
117
+ const entry = { promise, reject: rejectOperation };
118
+ this.#closing.set(id, entry);
119
+ this.#close(record, options).then(resolveOperation, rejectOperation).finally(() => {
120
+ if (this.#closing.get(id) === entry) this.#closing.delete(id);
121
+ });
122
+ return promise;
123
+ }
124
+
125
+ async #close(record, options) {
126
+ let resolveDestroy, rejectDestroy;
127
+ const destroyed = new Promise((resolve, reject) => { resolveDestroy = resolve; rejectDestroy = reject; });
128
+ const timeout = setTimeout(() => rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)), options.timeoutMs ?? this.closeTimeoutMs);
129
+ const off = this.#connection.cdp.on("Target.targetDestroyed", info => { if (info?.targetId === record.targetId) resolveDestroy(); });
130
+ const offDisconnect = this.#connection.cdp.transportEvents?.on?.("disconnected", () => rejectDestroy(Error("Browser transport disconnected")));
131
+ try {
132
+ if (options.runBeforeUnload && record.page) await record.page.cdp.send("Page.close", undefined, await record.page.resolveSessionId()).catch(() => this.#connection.cdp.send("Target.closeTarget", { targetId: record.targetId }));
133
+ else await this.#connection.cdp.send("Target.closeTarget", { targetId: record.targetId });
134
+ if (this.#owned.has(record.targetId)) await destroyed;
135
+ } finally {
136
+ clearTimeout(timeout); off(); offDisconnect?.();
137
+ // Ownership is removed only by Target.targetDestroyed (or transport loss).
138
+ if (!this.#owned.has(record.targetId)) record.navigationOff?.();
139
+ }
140
+ }
141
+
142
+ #destroyed(id, error) {
143
+ const record = this.#owned.get(id);
144
+ if (!record) return;
145
+ record.navigationOff?.();
146
+ this.#owned.delete(id);
147
+ if (error) this.#closing.get(id)?.reject(error);
148
+ }
149
+ async closeAll(options = {}) {
150
+ const results = await Promise.allSettled([...this.#owned.keys()].map(id => this.close(id, options)));
151
+ const failures = results.filter(result => result.status === "rejected").map(result => result.reason);
152
+ if (failures.length) throw new AggregateError(failures, "Failed to close one or more agent tabs");
153
+ }
154
+ async dispose(options = { closeOwned: true }) {
155
+ if (this.#disposed) return;
156
+ let failure;
157
+ if (options.closeOwned !== false) try { await this.closeAll(options); } catch (error) { failure = error; }
158
+ this.#disposed = true;
159
+ for (const off of this.#unsubscribers) off();
160
+ this.#unsubscribers = [];
161
+ if (failure) throw failure;
162
+ }
163
+ }
164
+
165
+ export function getAgentTabs(connection) {
166
+ return managers.get(connection);
167
+ }
168
+
169
+ export function createAgentTabs(connection, options = {}) {
170
+ const current = managers.get(connection);
171
+ if (current) {
172
+ if (current._optionsKey !== optionsKey(options)) throw new TypeError("Conflicting AgentTabManager options");
173
+ return current;
174
+ }
175
+ const manager = new AgentTabManager(connection, options);
176
+ Object.defineProperty(manager, "_optionsKey", { value: optionsKey(options) });
177
+ managers.set(connection, manager);
178
+ return manager;
179
+ }
@@ -0,0 +1,47 @@
1
+ // Self-contained because role locator queries serialize this into the frame's isolated world.
2
+ // Port of Playwright's isElementHiddenForAria (packages/injected/src/roleUtils.ts): getByRole skips the elements it
3
+ // reports unless includeHidden is set. `cache` memoizes the ancestor walk for one query.
4
+ export function isElementHiddenForAria(element, cache) {
5
+ const getStyle = node => node.ownerDocument?.defaultView?.getComputedStyle(node);
6
+ const isVisibleTextNode = text => {
7
+ const range = text.ownerDocument.createRange();
8
+ range.selectNode(text);
9
+ const rect = range.getBoundingClientRect();
10
+ return rect.width > 0 && rect.height > 0;
11
+ };
12
+ const belongsToDisplayNoneOrAriaHiddenOrNonSlotted = node => {
13
+ let hidden = cache.get(node);
14
+ if (hidden === undefined) {
15
+ // Light-DOM children of a shadow host render only when a slot takes them.
16
+ hidden = !!(node.parentElement && node.parentElement.shadowRoot && !node.assignedSlot);
17
+ if (!hidden) {
18
+ const style = getStyle(node);
19
+ hidden = !style || style.display === "none" || node.getAttribute("aria-hidden")?.toLowerCase() === "true";
20
+ }
21
+ if (!hidden) {
22
+ const parent = node.parentElement ?? (node.parentNode?.nodeType === 11 ? node.parentNode.host : null);
23
+ if (parent) hidden = belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent);
24
+ }
25
+ cache.set(node, hidden);
26
+ }
27
+ return hidden;
28
+ };
29
+ // A form's named controls can shadow its tagName.
30
+ const tagName = typeof element.tagName === "string" ? element.tagName.toUpperCase() : "FORM";
31
+ if (["STYLE", "SCRIPT", "NOSCRIPT", "TEMPLATE"].includes(tagName)) return true;
32
+ const style = getStyle(element);
33
+ const isSlot = element.nodeName === "SLOT";
34
+ if (style?.display === "contents" && !isSlot) {
35
+ // display:contents is not rendered itself, but its child nodes are.
36
+ for (let child = element.firstChild; child; child = child.nextSibling) {
37
+ if (child.nodeType === 1 && !isElementHiddenForAria(child, cache)) return false;
38
+ if (child.nodeType === 3 && isVisibleTextNode(child)) return false;
39
+ }
40
+ return true;
41
+ }
42
+ // <option> inside <select> and <slot> ignore visibility and content-visibility; checkVisibility() covers
43
+ // content-visibility and closed <details> up the flat tree.
44
+ const isOptionInsideSelect = element.nodeName === "OPTION" && !!element.closest("select");
45
+ if (!isOptionInsideSelect && !isSlot && style && (!element.checkVisibility() || style.visibility !== "visible")) return true;
46
+ return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);
47
+ }