Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(login): guard code entry and submission after turn cancellation
Afloat95cdff863751
diff --git a/server/host/fill-login-turn.test.ts b/server/host/fill-login-turn.test.tsindex 3e37a24f61..3b7be8340c 100644--- a/server/host/fill-login-turn.test.ts+++ b/server/host/fill-login-turn.test.ts@@ -91,6 +91,17 @@ describe("fill_login outside the bot's own browser", () => {});describe("fill_login in the bot's own browser", () => {+ it("passes turn cancellation through to the login action before browser input starts", async () => {+ const engine = vi.fn(async () => ({ url: "https://bank.test/sign-in" }));+ const { fill } = harness({+ at: "browser", turnActive: () => false,+ target: async () => ({ session: "bot-b1", spec: { command: "agent-browser", env: {} }, env: {} }),+ loginInput: () => ({ engine, insertText: async () => {}, press: async () => {}, click: async () => {} }),+ });+ expect(await fill(bot, turn, undefined, undefined)).toEqual({ ok: false, text: "Stopped filling this login because the turn ended." });+ expect(engine).not.toHaveBeenCalled();+ });+it("fills there and never asks to move", async () => {const { fill, moveToBrowser, target } = harness({ at: "browser" });const answer = await fill(bot, turn, undefined, undefined);diff --git a/server/host/fill-login-turn.ts b/server/host/fill-login-turn.tsindex 733da5c337..304db33e0f 100644--- a/server/host/fill-login-turn.ts+++ b/server/host/fill-login-turn.ts@@ -98,6 +98,7 @@ export function createFillLoginTurn(deps: FillLoginTurnDeps) {}, {...deps.loginInput(session, spec, env),remember: deps.remember,+ turnActive: () => deps.turnActive?.(capability) !== false,...(deps.mailCodes ? { emailCode: (ask) => deps.mailCodes!.find(current, capability, ask, () => deps.turnActive?.(capability) !== false) } : {}),}), deps.stepContext(current, capability));if (outcome.ok && outcome.loginId) deps.logins.markUsed(outcome.loginId);diff --git a/server/login-email-code.test.ts b/server/login-email-code.test.tsindex bc47eabc0c..9a69e4a7ad 100644--- a/server/login-email-code.test.ts+++ b/server/login-email-code.test.ts@@ -16,8 +16,8 @@ const HOME = { url: "https://acme.test/home", html: "<title>Home</title><h1>Welclet page: FakeLoginPage | null = null;afterEach(() => { page?.close(); page = null; });-function setup(url: string, html: string, answer: (ask: EmailCodeAsk) => EmailCodeAnswer | Promise<EmailCodeAnswer>, over: Partial<FillLoginInput> & { onSleep?: (clock: number) => void } = {}) {- const { onSleep, ...inputOver } = over;+function setup(url: string, html: string, answer: (ask: EmailCodeAsk) => EmailCodeAnswer | Promise<EmailCodeAnswer>, over: Partial<FillLoginInput> & { onSleep?: (clock: number) => void; active?: () => boolean } = {}) {+ const { onSleep, active, ...inputOver } = over;page = new FakeLoginPage(url, html);const remembered: Array<[string, string]> = [];const asks: EmailCodeAsk[] = [];@@ -27,6 +27,7 @@ function setup(url: string, html: string, answer: (ask: EmailCodeAsk) => EmailCoengine: (args) => page!.engine(args), insertText: (text) => page!.insertText(text), press: (key) => page!.press(key), click: (selector) => page!.click(selector),remember: (value, kind) => { remembered.push([kind, value]); },now: () => clock, sleep: async (ms) => { clock += ms; onSleep?.(clock); },+ turnActive: active,emailCode: async (ask) => {asks.push(ask);const result = await answer(ask);@@ -40,6 +41,66 @@ function setup(url: string, html: string, answer: (ask: EmailCodeAsk) => EmailCoconst code = (): EmailCodeAnswer => ({ kind: "code", code: CODE, typed: () => {} });const saved = (over: Partial<FillCandidate> = {}): FillCandidate => ({ ...loginPlace("acme.test"), id: "l1", username: "[email protected]", source: "settings", secrets: async () => ({ password: "fake-S3cret!pass", totp: null }), ...over });+describe("a code is entered only while its requesting turn remains active", () => {+ it("discards a code returned after the turn ended", async () => {+ let active = true;+ const { page: current, run, typedCount } = setup("https://acme.test/verify", CODE_PAGE, () => { active = false; return code(); }, { active: () => active });+ expect((await run()).ok).toBe(false);+ expect(current.typed).toEqual([]);+ expect(current.pressed).toEqual([]);+ expect(typedCount()).toBe(0);+ });++ it("does not type a code when the turn ends during field focus", async () => {+ let active = true;+ const { page: current, run, typedCount } = setup("https://acme.test/verify", CODE_PAGE, code, { active: () => active });+ current.window.document.querySelector("input")!.addEventListener("focus", () => { active = false; });+ expect((await run()).ok).toBe(false);+ expect(current.typed).toEqual([]);+ expect(current.pressed).toEqual([]);+ expect(typedCount()).toBe(0);+ });++ it("clears a partial code and stops between separate digit boxes", async () => {+ let active = true;+ const { page: current, run, typedCount } = setup("https://acme.test/verify", SIX_BOXES, code, { active: () => active });+ current.window.document.querySelector("input")!.addEventListener("input", () => { active = false; });+ expect((await run()).ok).toBe(false);+ expect(current.typed).toEqual([CODE[0]]);+ expect([...current.window.document.querySelectorAll("input")].every((input) => input.value === "")).toBe(true);+ expect(current.pressed).toEqual([]);+ expect(typedCount()).toBe(0);+ });++ it("does not press Enter when the turn ends while refocusing to submit", async () => {+ let active = true;+ const { page: current, run } = setup("https://acme.test/verify", CODE_PAGE, code, { active: () => active });+ const engine = current.engine.bind(current);+ current.engine = async (args) => {+ const result = await engine(args);+ if (args[1]?.endsWith(', "submit", null)')) active = false;+ return result;+ };+ expect((await run()).ok).toBe(false);+ expect(current.typed).toEqual([CODE]);+ expect(current.pressed).toEqual([]);+ expect(current.clicked).toEqual([]);+ expect(current.window.document.querySelector("input")!.value).toBe("");+ });++ it("does not click the fallback submit button after the turn ends", async () => {+ let active = true;+ const buttonPage = '<p>We sent a code to your email.</p><input name="otp" autocomplete="one-time-code"><button type="button">Verify</button>';+ const { page: current, run } = setup("https://acme.test/verify", buttonPage, code, {+ active: () => active, onSleep: () => { active = false; },+ });+ expect((await run()).ok).toBe(false);+ expect(current.pressed).toEqual(["Enter"]);+ expect(current.clicked).toEqual([]);+ expect(current.window.document.querySelector("input")!.value).toBe("");+ });+});+describe("an emailed code inside fill_login", () => {it("fills the code as real input and tells the bot only that it did", async () => {const { page: current, remembered, asks, typedCount, run } = setup("https://acme.test/verify", CODE_PAGE, code);diff --git a/server/login-fill.ts b/server/login-fill.tsindex 05c3965b3d..d38d7be6e1 100644--- a/server/login-fill.ts+++ b/server/login-fill.ts@@ -26,6 +26,7 @@ export interface FillLoginDeps {remember(value: string, kind: "password" | "code"): void;now?: () => number;sleep?: (ms: number) => Promise<void>;+ turnActive?(): boolean;/** Looks in the person's connected mailbox for a code the page asks for. Absent: no mailbox can be read in this turn. */emailCode?(ask: EmailCodeAsk): Promise<EmailCodeAnswer>;}@@ -84,6 +85,9 @@ const NEXT_STEP_WAIT_MS = 10_000;const FILL_BUDGET_MS = 25_000;const POLL_MS = 250;const MAX_STEPS = 3;+const TURN_ENDED = "Stopped filling this login because the turn ended.";++class LoginTurnEnded extends Error {}const MARK = "data-omb-login";@@ -316,6 +320,7 @@ function pageState(value: Record<string, unknown> | null): PageState | null {}export async function fillLogin(input: FillLoginInput, deps: FillLoginDeps): Promise<FillLoginOutcome> {+ if (deps.turnActive?.() === false) return { ok: false, text: TURN_ENDED };const now = deps.now ?? Date.now;const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));const page = await deps.engine(["get", "url"]);@@ -428,6 +433,10 @@ class LoginRun {return loginOriginCheck(href, this.login).ok;}+ private checkActive(): void {+ if (this.deps.turnActive?.() === false) throw new LoginTurnEnded(TURN_ENDED);+ }+private async page(script: string, ...args: unknown[]): Promise<Record<string, unknown> | null> {try { return evaluated(await this.deps.engine(["eval", call(script, ...args)])); } catch { return null; }}@@ -483,9 +492,11 @@ class LoginRun {async run(): Promise<FillLoginOutcome> {try {+ this.checkActive();return await this.steps();} catch (error) {await this.clear();+ if (error instanceof LoginTurnEnded) return this.outcome(false, TURN_ENDED);throw error;}}@@ -542,7 +553,8 @@ class LoginRun {let sent: Submitted;try {sent = await this.submitStep(step, typed.last, fields.alert);- } catch {+ } catch (error) {+ if (error instanceof LoginTurnEnded) throw error;return this.failed(`Filled ${this.filledWords()} for ${this.who()} on ${this.host}, but the browser did not take the Enter key or the click to submit it.`);}if (sent.kind === "no-control") return this.leave(`It was not submitted: Enter did nothing and the page has no sign-in button to press. Press the page's own sign-in button now.${codeNote}`);@@ -577,15 +589,19 @@ class LoginRun {}private async type(key: string, text: string, keep?: string): Promise<"typed" | "kept" | "missed" | "moved"> {+ this.checkActive();const focus = await this.page(FOCUS_FIELD, this.nonce, key, "type", keep ?? null);+ this.checkActive();if (!focus || typeof focus.href !== "string" || !this.stillHere(focus.href)) return "moved";if (focus.same === true) return "kept";if (focus.focused !== true) return "missed";await this.deps.insertText(text);+ this.checkActive();return "typed";}private async fillStep(step: number, fields: Found): Promise<{ kind: "typed"; last: string } | { kind: "none" } | { kind: "moved" }> {+ this.checkActive();const key = `${this.nonce}:${step}:`;const typed: Array<[FilledField, string]> = [];let moved = false;@@ -605,6 +621,7 @@ class LoginRun {if (fields.username && this.login.username && await fill("username", this.login.username, this.login.username)) typed.push(["username", "username"]);if (!moved && (fields.password || fields.code > 0)) {this.secrets ??= await this.login.secrets();+ this.checkActive();this.deps.remember(this.secrets.password, "password");if (this.secrets.totp) this.deps.remember(this.secrets.totp.secret, "password");}@@ -643,6 +660,7 @@ class LoginRun {if (!this.deps.emailCode || site === null) return null;const waitStarted = this.now();const answer = await this.deps.emailCode({ site, boxes: fields.code, askedAt: this.submittedAt, via: fields.via, now: this.now, sleep: this.sleep });+ this.checkActive();this.deadline += this.now() - waitStarted;if (answer.kind === "miss") this.codeHelp = `${CODE_MISS[answer.why]} ${CODE_FROM_INBOX}`;if (answer.kind === "no-mailbox") {@@ -654,8 +672,10 @@ class LoginRun {/** Enter in the step's last field; when that sends nothing within two seconds, the form's sign-in button. */private async submitStep(step: number, last: string, alertBefore: string): Promise<Submitted> {+ this.checkActive();const key = `${this.nonce}:${step}:`;const focus = await this.page(FOCUS_FIELD, this.nonce, key + last, "submit", null);+ this.checkActive();const before = typeof focus?.href === "string" ? focus.href : "";const busyBefore = focus?.busy === true;const sending = (state: PageState) => state.submitted || (state.busy && !busyBefore);@@ -667,7 +687,9 @@ class LoginRun {const until = Math.min(this.deadline, this.now() + ms);for (;;) {await this.sleep(POLL_MS);+ this.checkActive();const state = pageState(await this.page(PAGE_STATE, this.nonce));+ this.checkActive();if (state && (settled(state) || (untilSent && sending(state)))) return state;if (this.now() >= until) return state ?? "silent";}@@ -677,6 +699,7 @@ class LoginRun {let state = await watch(ENTER_WAIT_MS, true);if (!settled(state) && !(state !== "silent" && sending(state))) {const control = await this.page(MARK_SUBMIT, key);+ this.checkActive();if (control?.found !== true) return { kind: "no-control" };await this.deps.click(`[${MARK}="${key}submit"]`);}