Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(login-fill): find sign-in fields inside open shadow roots
meutexb6ba999fc2d0
diff --git a/server/login-fill.test.ts b/server/login-fill.test.tsindex a4ff6b4ecb..0dba48b6fb 100644--- a/server/login-fill.test.ts+++ b/server/login-fill.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";import { loginMatchesHost, loginPlace, type LoginPlace } from "../shared/logins.ts";import { fillLogin, SECRET_HOLD_MS, type FillCandidate, type FillLoginDeps } from "./login-fill.ts";-import { FakeLoginPage, LOGIN_FORM } from "./testing/fake-login-page.ts";+import { FakeLoginPage, LOGIN_FORM, openShadowRoot } from "./testing/fake-login-page.ts";import { parseTotpKey, totpCode, type TotpKey } from "./totp.ts";// Obvious fakes only.@@ -368,3 +368,44 @@ describe("one-time codes and fields", () => {expect(page.field("input[name=password]").value).toBe("");});});++describe("fill_login reaches fields inside open shadow roots", () => {+ it("fills a username and password that live inside an open shadow root", async () => {+ const { page, fill } = setup("https://accounts.example.com/login",+ `<form action="/session" method="post"><sdf-input id="user"></sdf-input><sdf-input id="pass"></sdf-input><button type="submit">Sign in</button></form>`,+ [{ host: "accounts.example.com", username: "[email protected]" }], { submit: false });+ openShadowRoot(page.window, "#user", `<input id="email" name="email" type="email" autocomplete="username">`);+ openShadowRoot(page.window, "#pass", `<input id="password" name="password" type="password" autocomplete="current-password">`);+ const outcome = await fill();+ expect(outcome).toMatchObject({ ok: true, filled: ["username", "password"] });+ expect(outcome.text).not.toContain("No login fields found");+ expect(page.typed).toEqual(["[email protected]", PASSWORD]);+ expect(page.deepField("input[name=email]").value).toBe("[email protected]");+ expect(page.deepField("input[name=password]").value).toBe(PASSWORD);+ });++ it("recognises and fills a one-time code box named only by its shadow host", async () => {+ const { page, fill, remembered } = setup("https://example.com/2fa",+ `<form><sf-code label="Your Six-Digit Code"></sf-code></form>`,+ [{ host: "example.com", username: "alice", totp: KEY }], { submit: false });+ openShadowRoot(page.window, "sf-code", `<input type="text" inputmode="numeric">`);+ const code = totpCode(KEY, NOW);+ const outcome = await fill();+ expect(outcome).toMatchObject({ ok: true, filled: ["code"] });+ expect(page.typed).toEqual([code]);+ expect(page.deepField('input[inputmode="numeric"]').value).toBe(code);+ expect(remembered).toContainEqual(["code", code]);+ });++ it("does not treat a field inside a hidden shadow host as usable", async () => {+ const { page, fill } = setup("https://example.com/login",+ `<form><sdf-input id="hidden" style="display:none"></sdf-input></form>`,+ [{ host: "example.com", username: "alice" }], { submit: false });+ openShadowRoot(page.window, "#hidden", `<input name="password" type="password" autocomplete="current-password">`);+ const outcome = await fill();+ expect(outcome.ok).toBe(false);+ expect(outcome.text).toContain("No login fields found");+ expect(page.typed).toEqual([]);+ expect(page.deepField("input[name=password]").value).toBe("");+ });+});diff --git a/server/login-fill.ts b/server/login-fill.tsindex d38d7be6e1..566b7a3626 100644--- a/server/login-fill.ts+++ b/server/login-fill.ts@@ -94,15 +94,27 @@ const MARK = "data-omb-login";// Shared by every page script: what a person could see, which fields this fill marked, a site's error line, a CAPTCHA.const PAGE_HELPERS = `const MARK = ${JSON.stringify(MARK)};+ const queryAllDeep = (root, selector) => {+ const found = Array.from(root.querySelectorAll(selector));+ for (const host of root.querySelectorAll("*")) {+ if (host.shadowRoot) found.push(...queryAllDeep(host.shadowRoot, selector));+ }+ return found;+ };+ const all = (selector) => queryAllDeep(document, selector);+ const hostOf = (el) => {+ const root = el.getRootNode ? el.getRootNode() : null;+ return root && root.host ? root.host : null;+ };const visible = (el) => {if (!(el instanceof Element) || !el.isConnected || el.getClientRects().length === 0) return false;- for (let node = el; node instanceof Element; node = node.parentElement) {+ for (let node = el; node; node = node.parentElement || hostOf(node)) {const style = getComputedStyle(node);if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse" || style.opacity === "0") return false;}return true;};- const marked = (prefix) => Array.from(document.querySelectorAll("[" + MARK + "]")).filter((el) => (el.getAttribute(MARK) || "").startsWith(prefix));+ const marked = (prefix) => all("[" + MARK + "]").filter((el) => (el.getAttribute(MARK) || "").startsWith(prefix));const secretField = (el) => /:(?:password|code\\d+)$/.test(el.getAttribute(MARK) || "");const alertText = () => {for (const el of document.querySelectorAll('[role="alert"], [aria-live="assertive"], [aria-live="polite"], .error, .alert, [class*="error" i]')) {@@ -131,13 +143,20 @@ const PAGE_HELPERS = `const FIND_FIELDS = `((nonce, step) => {${PAGE_HELPERS}const key = nonce + ":" + step + ":";- for (const old of document.querySelectorAll("[" + MARK + "]")) {+ for (const old of all("[" + MARK + "]")) {const owner = old.getAttribute(MARK) || "";if (!owner.startsWith(nonce + ":") || owner.startsWith(key)) old.removeAttribute(MARK);}const usable = (el) => el instanceof HTMLInputElement && !el.disabled && !el.readOnly && el.type !== "hidden" && visible(el);const tokens = (el) => (el.getAttribute("autocomplete") || "").toLowerCase().split(/\\s+/);- const hint = (el) => [el.name, el.id, el.getAttribute("aria-label"), el.placeholder, el.getAttribute("autocomplete")].join(" ").toLowerCase();+ const hint = (el) => {+ const host = hostOf(el);+ const labels = el.labels ? Array.from(el.labels).map((label) => label.innerText || label.textContent || "").join(" ") : "";+ return [el.name, el.id, el.getAttribute("aria-label"), el.placeholder, el.getAttribute("autocomplete"),+ host && host.getAttribute("name"), host && host.getAttribute("id"), host && host.getAttribute("label"),+ host && host.getAttribute("aria-label"), host && host.getAttribute("placeholder"), host && host.getAttribute("autocomplete"),+ labels].join(" ").toLowerCase();+ };const plain = (el) => el.type === "text" || el.type === "email" || el.type === "tel";// A strong hint makes even a password-type box a code box; a weak one// ("verify", "code") only a plain one, so a sign-up form's "verify@@ -148,7 +167,7 @@ const FIND_FIELDS = `((nonce, step) => {const isCode = (el) => tokens(el).includes("one-time-code") ||((plain(el) || el.type === "number" || el.type === "password") && STRONG.test(hint(el)) && !NOT_CODE.test(hint(el))) ||((plain(el) || el.type === "number") && WEAK.test(hint(el)) && !NOT_CODE.test(hint(el)));- const inputs = Array.from(document.querySelectorAll("input")).filter(usable);+ const inputs = all("input").filter(usable);const codes = inputs.filter(isCode);const rest = inputs.filter((el) => !codes.includes(el));const passwords = rest.filter((el) => el.type === "password" && !tokens(el).includes("new-password"));@@ -183,7 +202,12 @@ const FIND_FIELDS = `((nonce, step) => {* and listens for the form being sent. */const FOCUS_FIELD = `((nonce, key, mode, keep) => {${PAGE_HELPERS}- const el = document.querySelector("[" + MARK + "=\\"" + key + "\\"]");+ const activeElement = () => {+ let node = document.activeElement;+ while (node && node.shadowRoot && node.shadowRoot.activeElement) node = node.shadowRoot.activeElement;+ return node;+ };+ const el = all("[" + MARK + "=\\"" + key + "\\"]")[0] || null;if (!(el instanceof HTMLInputElement)) return JSON.stringify({ href: location.href, focused: false, same: false });if (mode === "type" && typeof keep === "string" && el.value === keep) return JSON.stringify({ href: location.href, focused: true, same: true });if (mode === "submit" && !window["__ombLogin" + nonce]) {@@ -199,7 +223,7 @@ const FOCUS_FIELD = `((nonce, key, mode, keep) => {el.dispatchEvent(new Event("input", { bubbles: true }));}const busy = mode === "submit" && sending(marked(nonce + ":").filter((field) => field instanceof HTMLInputElement));- return JSON.stringify({ href: location.href, focused: document.activeElement === el, same: false, busy });+ return JSON.stringify({ href: location.href, focused: activeElement() === el, same: false, busy });})`;const CHECK_FIELDS = `((key) => {@@ -214,14 +238,18 @@ const MARK_SUBMIT = `((key) => {${PAGE_HELPERS}const fields = marked(key).filter((el) => el instanceof HTMLInputElement);const field = fields.find((el) => /:password$/.test(el.getAttribute(MARK) || "")) || fields[fields.length - 1];- const label = (el) => (el.innerText || el.value || el.getAttribute("aria-label") || el.title || "").replace(/\\s+/g, " ").trim();+ const label = (el) => {+ const host = hostOf(el);+ return (el.innerText || el.value || el.getAttribute("aria-label") || el.title ||+ (host && (host.innerText || host.textContent || host.getAttribute("aria-label"))) || "").replace(/\\s+/g, " ").trim();+ };const NAMED = /^(?:sign ?in|log ?in|log ?on|sign ?on|continue|next|submit|verify|confirm)$/i;const enabled = (el) => visible(el) && !el.disabled && el.getAttribute("aria-disabled") !== "true";const inForm = field && field.form? Array.from(field.form.querySelectorAll("button, input[type=submit], input[type=image]")).filter((el) => enabled(el) && (el.type === "submit" || el.type === "image")): [];const control = inForm.find((el) => NAMED.test(label(el))) || inForm[0] ||- Array.from(document.querySelectorAll('button, [role="button"], input[type=submit], input[type=button]')).find((el) => enabled(el) && NAMED.test(label(el)));+ all('button, [role="button"], input[type=submit], input[type=button]').find((el) => enabled(el) && NAMED.test(label(el)));if (!control) return JSON.stringify({ found: false });control.setAttribute(MARK, key + "submit");return JSON.stringify({ found: true });diff --git a/server/testing/fake-login-page.ts b/server/testing/fake-login-page.tsindex 2e02b47550..2c197426eb 100644--- a/server/testing/fake-login-page.ts+++ b/server/testing/fake-login-page.ts@@ -1,11 +1,35 @@// A stand-in for the bot's browser in fill_login tests: one happy-dom page answering the engine commands// login-fill sends and taking typed text, keys and clicks like the input relay. It records every engine command, so a// test can prove no secret went through one.-import { Window } from "happy-dom";+import { type Document, type Element, type ShadowRoot, Window } from "happy-dom";/** What the site does with a sent form: show another page (a sign-in that worked, or a next step), or stay and say why. */export type SiteAnswer = { navigate: { url: string; html: string } } | { error: string } | null;+/** The focused element, resolving into open shadow roots: a browser's document.activeElement is the host, not the inner field. */+function activeElement(window: Window): Element | null {+ let node = window.document.activeElement;+ while (node && node.shadowRoot && node.shadowRoot.activeElement) node = node.shadowRoot.activeElement;+ return node;+}++/** querySelectorAll over the light DOM and every open shadow root it reaches. */+function deepQuery(root: Document | ShadowRoot, selector: string): Element[] {+ const found = Array.from(root.querySelectorAll(selector));+ for (const host of Array.from(root.querySelectorAll("*"))) {+ if (host.shadowRoot) found.push(...deepQuery(host.shadowRoot, selector));+ }+ return found;+}++/** Gives the host element an open shadow root holding `inner`; tests build component pages with it. */+export function openShadowRoot(window: Window, selector: string, inner: string): void {+ const host = window.document.querySelector(selector);+ if (!host) throw new Error(`host not found: ${selector}`);+ const root = host.attachShadow({ mode: "open" });+ (root as unknown as { innerHTML: string }).innerHTML = inner;+}+export class FakeLoginPage {window: Window;/** Every engine command, as its argument list. */@@ -64,6 +88,11 @@ export class FakeLoginPage {return this.window.document.querySelector(selector) as unknown as { value: string };}+ /** The first element matching `selector` in the light DOM or an open shadow root. */+ deepField(selector: string): { value: string } {+ return deepQuery(this.window.document, selector)[0] as unknown as { value: string };+ }+/** What the engine answers: its `data`, or null for a stopped browser. */async engine(args: string[]): Promise<Record<string, unknown> | null> {this.engineCalls.push(args);@@ -77,7 +106,7 @@ export class FakeLoginPage {/** `keyboard insertText` over the relay: into the focused field at its caret, with beforeinput and input events. */async insertText(text: string): Promise<void> {this.typed.push(text);- const field = this.window.document.activeElement as unknown as { value: string; dispatchEvent(event: unknown): boolean } | null;+ const field = activeElement(this.window) as unknown as { value: string; dispatchEvent(event: unknown): boolean } | null;if (!field || typeof field.value !== "string") return;const InputEvent = this.window.InputEvent;field.dispatchEvent(new InputEvent("beforeinput", { bubbles: true, data: text, inputType: "insertText" }));@@ -90,7 +119,7 @@ export class FakeLoginPage {async press(key: string): Promise<void> {this.pressed.push(key);this.onKey?.(key);- const field = this.window.document.activeElement as unknown as { form?: unknown } | null;+ const field = activeElement(this.window) as unknown as { form?: unknown } | null;const form = field?.form as unknown as { requestSubmit(): void; querySelectorAll(selector: string): ArrayLike<{ type?: string }> } | null | undefined;if (key !== "Enter" || !form) return;const buttons = Array.from(form.querySelectorAll("button, input[type=submit]")).filter((el) => el.type === "submit");