An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(page): detect captchas and walk the agent through solving them
Shahriar36c79de23a31
diff --git a/lib/actions/page/captcha-vendors.ts b/lib/actions/page/captcha-vendors.tsnew file mode 100644index 0000000..f482497--- /dev/null+++ b/lib/actions/page/captcha-vendors.ts@@ -0,0 +1,75 @@+export type CaptchaKind = 'checkbox' | 'interactive' | 'invisible';++export interface CaptchaVendor {+ id: string;+ label: string;+ kind: CaptchaKind;+ hostMarkers: string[];+ frame?: string;+ challengeFrame?: string;+ checkbox?: string;+ solvedInPage?: string;+ solvedInFrame?: string;+}++export const CAPTCHA_VENDORS: readonly CaptchaVendor[] = [+ {+ id: 'turnstile',+ label: 'Cloudflare Turnstile',+ kind: 'checkbox',+ hostMarkers: ['.cf-turnstile', '#cf-turnstile', '#challenge-stage', '#cf-challenge-running', '#challenge-running'],+ frame: 'challenges.cloudflare.com',+ checkbox: 'input[type="checkbox"]',+ solvedInPage: '!!document.querySelector(\'input[name="cf-turnstile-response"]\')?.value',+ },+ {+ id: 'recaptcha-v2',+ label: 'reCAPTCHA v2',+ kind: 'checkbox',+ hostMarkers: ['.g-recaptcha', '#g-recaptcha', 'iframe[src*="recaptcha/api2/anchor"]', 'iframe[src*="recaptcha/enterprise/anchor"]'],+ frame: 'recaptcha/api2/anchor',+ challengeFrame: 'recaptcha/api2/bframe',+ checkbox: '#recaptcha-anchor',+ solvedInFrame: '!!document.querySelector(\'#recaptcha-anchor.recaptcha-checkbox-checked\')',+ solvedInPage: '!!document.querySelector(\'textarea#g-recaptcha-response\')?.value',+ },+ {+ id: 'hcaptcha',+ label: 'hCaptcha',+ kind: 'checkbox',+ hostMarkers: ['.h-captcha', '[data-hcaptcha-widget-id]', 'iframe[src*="hcaptcha.com/captcha"]'],+ frame: 'frame=checkbox',+ challengeFrame: 'frame=challenge',+ checkbox: '#checkbox',+ solvedInPage: '!!document.querySelector(\'textarea[name="h-captcha-response"]\')?.value',+ },+ {+ id: 'geetest',+ label: 'GeeTest',+ kind: 'checkbox',+ hostMarkers: ['.geetest_holder', '.geetest_radar_tip', '.geetest_btn'],+ checkbox: '.geetest_radar_tip',+ solvedInPage: '!!document.querySelector(\'.geetest_success_radar_tip\')',+ },+ {+ id: 'arkose',+ label: 'Arkose FunCaptcha',+ kind: 'interactive',+ hostMarkers: ['#funcaptcha', '#arkose', '[data-pkey]', 'iframe[src*="arkoselabs.com"]'],+ frame: 'arkoselabs.com',+ },+ {+ id: 'aws-waf',+ label: 'AWS WAF Captcha',+ kind: 'interactive',+ hostMarkers: ['#captcha-container', 'script[src*="captcha.awswaf.com"]', 'iframe[src*="awswaf.com"]'],+ frame: 'awswaf.com',+ },+ {+ id: 'recaptcha-v3',+ label: 'reCAPTCHA v3',+ kind: 'invisible',+ hostMarkers: ['script[src*="recaptcha/api.js?render="]', 'script[src*="recaptcha/enterprise.js?render="]'],+ solvedInPage: '!!document.querySelector(\'textarea#g-recaptcha-response\')?.value',+ },+] as const;diff --git a/lib/actions/page/find-captcha.ts b/lib/actions/page/find-captcha.tsnew file mode 100644index 0000000..23a0b04--- /dev/null+++ b/lib/actions/page/find-captcha.ts@@ -0,0 +1,12 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';++export const findCaptcha = defineAction({+ name: 'page.findCaptcha',+ description:+ 'Look for a captcha on the page and report what it is, without touching it. Ordinary selectors cannot see one: vendors build the widget inside a closed shadow root holding a cross-origin iframe holding another shadow root, so page.getPageInfo shows nothing where the captcha visibly is. This reads through all of that with Chrome’s debugger and reports the vendor (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, GeeTest, Arkose, AWS WAF), the widget’s on-screen bounds, whether it is already satisfied, and a viewport point for its checkbox when it has one. Read-only — it never clicks. Call it when a page stalls on “verifying you are human”, refuses a form for no visible reason, or shows a checkbox no selector can find. Chrome only, and it briefly shows the “Browsentic is debugging this browser” bar.',+ input: z.object({}),+ execute() {+ throw new ActionError('page.findCaptcha is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');+ },+});diff --git a/lib/actions/page/solve-captcha.ts b/lib/actions/page/solve-captcha.tsnew file mode 100644index 0000000..e910546--- /dev/null+++ b/lib/actions/page/solve-captcha.ts@@ -0,0 +1,27 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';++export const solveCaptcha = defineAction({+ name: 'page.solveCaptcha',+ description:+ 'Tick a captcha’s “I am a human” checkbox with a real browser-level click and wait for the widget to settle. Works where an ordinary click cannot reach: the checkbox lives inside a closed shadow root inside a cross-origin iframe, and it only responds to genuine pointer input. Returns state "solved" when the widget accepted it. When the vendor escalates to a challenge a person has to answer — an image grid, Arkose, AWS WAF — it returns state "needsHuman" with the widget bounds and does not attempt the challenge; screenshot that region, tell the user it needs them, and poll page.findCaptcha until they are done. State "invisible" means a scoring captcha with nothing to click. Chrome only, shows the debugger bar while it runs, and it is gated for approval because it acts on another site’s security control.',+ input: z.object({+ waitMs: z+ .number()+ .int()+ .min(0)+ .max(120_000)+ .default(20_000)+ .describe('How long to wait after clicking for the widget to report a verdict.'),+ timeoutMs: z+ .number()+ .int()+ .min(1000)+ .max(180_000)+ .default(60_000)+ .describe('Overall budget for the whole attempt, including finding the widget.'),+ }),+ execute() {+ throw new ActionError('page.solveCaptcha is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');+ },+});diff --git a/lib/bridge/captcha.ts b/lib/bridge/captcha.tsnew file mode 100644index 0000000..80a9ea5--- /dev/null+++ b/lib/bridge/captcha.ts@@ -0,0 +1,284 @@+import { z } from 'zod';+import { CAPTCHA_VENDORS, type CaptchaVendor } from '@/lib/actions/page/captcha-vendors';+import { solveCaptcha } from '@/lib/actions/page/solve-captcha';+import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { frameSessions, send, settle, withDebugger, type DebuggerSession, type FrameSession } from './cdp';+import { dispatchClick, type ClickPlan, type Point } from './trusted-input';++type CaptchaState = 'idle' | 'pending' | 'solved' | 'needsHuman' | 'invisible';++interface Rect {+ x: number;+ y: number;+ width: number;+ height: number;+}++interface Sighting {+ vendor: CaptchaVendor;+ frames: FrameSession[];+ state: CaptchaState;+ hasToken: boolean;+ bounds?: Rect;+ point?: Point;+ note?: string;+}++const FIREFOX_HINT =+ 'Reading a captcha needs Chrome’s debugger, which Firefox does not expose — solve the captcha in the page yourself.';++const POLL_INTERVAL_MS = 500;++const CLICK_STYLE = {+ button: 'left' as const,+ clickCount: 1,+ modifiers: [] as string[],+ moveSteps: 14,+ hoverMs: 120,+ holdMs: 70,+};++export function findCaptchaInTab(tabId: number): Promise<ActionResult> {+ return withDebugger(tabId, FIREFOX_HINT, async (session) => {+ const seen = await scan(session);+ return success(seen ? report(seen) : { found: false });+ });+}++export function solveCaptchaInTab(tabId: number, input: unknown): Promise<ActionResult> {+ const parsed = solveCaptcha.input.safeParse(input ?? {});+ if (!parsed.success) return Promise.resolve(failure('INVALID_INPUT', z.prettifyError(parsed.error)));+ const { waitMs, timeoutMs } = parsed.data;++ return withDebugger(tabId, FIREFOX_HINT, async (session) => {+ const deadline = Date.now() + timeoutMs;+ const found = await scan(session);+ if (!found) {+ return failure(+ 'CAPTCHA_NOT_FOUND',+ 'No captcha widget on this page. If the page is still blocked, take a fresh page.getPageInfo — the block may be something else.',+ );+ }+ if (!found.point || found.state !== 'idle') return success({ ...report(found), clicked: false });++ await dispatchClick(session, clickPlanFor(found.point));+ const settled = await awaitVerdict(session, found, Math.min(waitMs, deadline - Date.now()));+ return success({ ...report(settled), clicked: true });+ });+}++function clickPlanFor(point: Point): ClickPlan {+ return {+ point,+ from: { x: Math.max(point.x - 140, 0), y: Math.max(point.y - 90, 0) },+ ...CLICK_STYLE,+ };+}++function report(seen: Sighting) {+ return {+ found: true,+ vendor: seen.vendor.id,+ label: seen.vendor.label,+ kind: seen.vendor.kind,+ state: seen.state,+ solved: seen.state === 'solved',+ hasToken: seen.hasToken,+ bounds: seen.bounds,+ point: seen.point,+ note: seen.note,+ };+}++async function scan(session: DebuggerSession): Promise<Sighting | null> {+ await readDocument(session);+ for (const vendor of CAPTCHA_VENDORS) {+ if (await present(session, vendor)) return inspect(session, vendor);+ }+ return null;+}++async function present(session: DebuggerSession, vendor: CaptchaVendor): Promise<boolean> {+ for (const marker of vendor.hostMarkers) {+ if ((await findNodes(session, marker)).length) return true;+ }+ return false;+}++async function inspect(session: DebuggerSession, vendor: CaptchaVendor): Promise<Sighting> {+ const frames = vendor.frame ? await frameSessions(session) : [];+ const hasToken = vendor.solvedInPage ? await truthy(session, vendor.solvedInPage) : false;++ if (hasToken || (await checkedInFrame(session, vendor, frames))) {+ return { vendor, frames, state: 'solved', hasToken };+ }+ if (vendor.kind === 'invisible') {+ return { vendor, frames, state: 'invisible', hasToken, note: `${vendor.label} scores in the background — there is nothing to click.` };+ }+ if (vendor.challengeFrame && (await truthy(session, visibleFrame(vendor.challengeFrame)))) {+ return {+ vendor,+ frames,+ state: 'needsHuman',+ hasToken,+ bounds: await frameBounds(session, vendor.challengeFrame),+ note: `${vendor.label} has escalated to a challenge only a person can answer.`,+ };+ }+ if (vendor.kind === 'interactive') {+ return {+ vendor,+ frames,+ state: 'needsHuman',+ hasToken,+ bounds: vendor.frame ? await frameBounds(session, vendor.frame) : undefined,+ note: `${vendor.label} asks for a puzzle rather than a checkbox.`,+ };+ }++ const located = await locateCheckbox(session, vendor, frames);+ return {+ vendor,+ frames,+ state: located.point ? 'idle' : 'needsHuman',+ hasToken,+ bounds: located.bounds,+ point: located.point,+ note: located.note,+ };+}++async function awaitVerdict(session: DebuggerSession, seen: Sighting, budgetMs: number): Promise<Sighting> {+ const { vendor, frames } = seen;+ const until = Date.now() + Math.max(0, budgetMs);++ while (Date.now() < until) {+ await settle(POLL_INTERVAL_MS);+ const hasToken = vendor.solvedInPage ? await truthy(session, vendor.solvedInPage) : false;+ if (hasToken || (await checkedInFrame(session, vendor, frames))) {+ return { ...seen, state: 'solved', hasToken };+ }+ if (vendor.challengeFrame && (await truthy(session, visibleFrame(vendor.challengeFrame)))) {+ return {+ ...seen,+ state: 'needsHuman',+ hasToken,+ bounds: (await frameBounds(session, vendor.challengeFrame)) ?? seen.bounds,+ note: `${vendor.label} answered the checkbox with a challenge only a person can answer.`,+ };+ }+ }+ return {+ ...seen,+ state: 'pending',+ note: `${vendor.label} accepted the click but had not settled within the wait — call page.findCaptcha again to re-check.`,+ };+}++async function locateCheckbox(+ session: DebuggerSession,+ vendor: CaptchaVendor,+ frames: FrameSession[],+): Promise<{ bounds?: Rect; point?: Point; note?: string }> {+ if (!vendor.checkbox) return { note: `${vendor.label} exposes no checkbox to click.` };++ if (!vendor.frame) {+ const [nodeId] = await findNodes(session, vendor.checkbox);+ const bounds = nodeId ? await boxOf(session, nodeId) : null;+ return bounds+ ? { bounds, point: centreOf(bounds) }+ : { note: `${vendor.label}’s checkbox is in the page but has no box on screen — scroll it into view, then retry.` };+ }++ const [frameNode] = await findNodes(session, `iframe[src*="${vendor.frame}"]`);+ const bounds = frameNode ? await boxOf(session, frameNode) : null;+ if (!bounds) return { note: `${vendor.label}’s widget iframe is not painted — scroll it into view, then retry.` };++ const child = frames.find((frame) => frame.url.includes(vendor.frame!));+ if (!child) return { bounds, note: `Chrome did not expose ${vendor.label}’s widget frame, so its checkbox cannot be located.` };++ const inner: DebuggerSession = { tabId: session.tabId, sessionId: child.sessionId };+ await readDocument(inner).catch(() => {});+ const [checkboxNode] = await findNodes(inner, vendor.checkbox);+ const box = checkboxNode ? await boxOf(inner, checkboxNode) : null;+ if (!box) return { bounds, note: `${vendor.label}’s widget is open but its checkbox could not be located inside the frame.` };++ const point = { x: Math.round(bounds.x + box.x + box.width / 2), y: Math.round(bounds.y + box.y + box.height / 2) };+ return contains(bounds, point)+ ? { bounds, point }+ : { bounds, note: `${vendor.label}’s checkbox resolved outside its own frame — refusing to click a guessed point.` };+}++async function checkedInFrame(+ session: DebuggerSession,+ vendor: CaptchaVendor,+ frames: FrameSession[],+): Promise<boolean> {+ if (!vendor.solvedInFrame || !vendor.frame) return false;+ const child = frames.find((frame) => frame.url.includes(vendor.frame!));+ if (!child) return false;+ return truthy({ tabId: session.tabId, sessionId: child.sessionId }, vendor.solvedInFrame);+}++async function frameBounds(session: DebuggerSession, fragment: string): Promise<Rect | undefined> {+ const [nodeId] = await findNodes(session, `iframe[src*="${fragment}"]`);+ return (nodeId ? await boxOf(session, nodeId) : null) ?? undefined;+}++const visibleFrame = (fragment: string) =>+ `[...document.querySelectorAll('iframe')].some((f) => f.src.includes(${JSON.stringify(fragment)}) && f.getBoundingClientRect().height > 40 && getComputedStyle(f).visibility !== 'hidden' && getComputedStyle(f.parentElement || f).visibility !== 'hidden')`;++const centreOf = (box: Rect): Point => ({+ x: Math.round(box.x + box.width / 2),+ y: Math.round(box.y + box.height / 2),+});++const contains = (box: Rect, point: Point) =>+ point.x >= box.x && point.x <= box.x + box.width && point.y >= box.y && point.y <= box.y + box.height;++async function readDocument(session: DebuggerSession): Promise<void> {+ await send(session, 'DOM.enable');+ await send(session, 'DOM.getDocument', { depth: -1, pierce: true });+}++async function findNodes(session: DebuggerSession, selector: string): Promise<number[]> {+ const search = await send<{ searchId?: string; resultCount?: number }>(session, 'DOM.performSearch', {+ query: selector,+ includeUserAgentShadowDOM: false,+ }).catch(() => null);+ if (!search?.searchId) return [];++ const found = search.resultCount+ ? await send<{ nodeIds?: number[] }>(session, 'DOM.getSearchResults', {+ searchId: search.searchId,+ fromIndex: 0,+ toIndex: search.resultCount,+ }).catch(() => null)+ : null;+ await send(session, 'DOM.discardSearchResults', { searchId: search.searchId }).catch(() => {});+ return found?.nodeIds ?? [];+}++async function boxOf(session: DebuggerSession, nodeId: number): Promise<Rect | null> {+ const box = await send<{ model?: { content?: number[] } }>(session, 'DOM.getBoxModel', { nodeId }).catch(() => null);+ const quad = box?.model?.content;+ if (!quad || quad.length < 8) return null;++ const xs = [quad[0], quad[2], quad[4], quad[6]];+ const ys = [quad[1], quad[3], quad[5], quad[7]];+ const x = Math.min(...xs);+ const y = Math.min(...ys);+ const width = Math.max(...xs) - x;+ const height = Math.max(...ys) - y;+ return width > 0 && height > 0+ ? { x: Math.round(x), y: Math.round(y), width: Math.round(width), height: Math.round(height) }+ : null;+}++async function truthy(session: DebuggerSession, expression: string): Promise<boolean> {+ const evaluated = await send<{ result?: { value?: unknown } }>(session, 'Runtime.evaluate', {+ expression,+ returnByValue: true,+ }).catch(() => null);+ return evaluated?.result?.value === true;+}diff --git a/mcp/skills/captcha.md b/mcp/skills/captcha.mdnew file mode 100644index 0000000..926c5a4--- /dev/null+++ b/mcp/skills/captcha.md@@ -0,0 +1,47 @@+---+name: captcha+description: Get past a “verify you are human” block — read what the widget is, tick its checkbox, hand a real challenge to the user.+triggers: [captcha, recaptcha, hcaptcha, turnstile, cloudflare, verify you are human, prove you are human, i am not a robot, checking your browser, just a moment, are you a robot, human verification, challenge, bot check, blocked by, security check]+---++A captcha is the one thing on a page that ordinary targeting cannot see. Vendors build the widget as a closed shadow root holding a cross-origin iframe holding another shadow root, so `page_getPageInfo` reports nothing where the checkbox visibly is, and `page_clickElement` has no element to aim at. Two tools read through that; nothing else on the page changes how you work.++## 1. Notice you are blocked++The signs are a page that never finishes ("Checking your browser", "Just a moment…"), a form that refuses without saying why, a visible checkbox no snapshot lists, or a `TARGET_NOT_FOUND` for something you can plainly see in a screenshot. Any of those, stop guessing selectors and call `page_findCaptcha {}`.++Do not call it speculatively on every page. It attaches Chrome's debugger for a moment, which flashes the "Browsentic is debugging this browser" bar at the user, so it earns its place only once something is actually stuck.++## 2. Read it before you touch it++`page_findCaptcha` never clicks. It reports `vendor` and `label` (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, GeeTest, Arkose, AWS WAF), the widget's on-screen `bounds`, a viewport `point` for its checkbox when it has one, and a `state`:++- **`solved`** — already satisfied. The block is something else; re-snapshot and carry on.+- **`idle`** — a checkbox is waiting. This is the case §3 handles.+- **`invisible`** — a scoring captcha like reCAPTCHA v3. **There is nothing to click and nothing to wait for.** If the page still refuses you, the site has judged the session, and no amount of retrying changes that — say so and stop.+- **`needsHuman`** — a challenge a person has to answer. Go to §4.+- **`found: false`** — no captcha here at all, so whatever is blocking you is a different problem.++## 3. Tick the checkbox++`page_solveCaptcha {}` finds the widget, clicks its checkbox with a real browser-level mouse event, and waits for the verdict. A synthetic click cannot do this: the checkbox only reacts to genuine pointer input, which is the whole point of it.++It is gated for approval, because ticking a site's human check is the user's call rather than yours. **If it comes back `DECLINED`, that is an answer — say so and stop, do not look for another way through.**++Read `state` on the result the same way as in §2. `pending` means the widget took the click but had not settled inside the wait; call `page_findCaptcha {}` again a few seconds later rather than clicking twice. Raise `waitMs` when a site is habitually slow.++## 4. When it needs the user, hand it over++`needsHuman` means the vendor escalated to an image grid, a puzzle, or a slider — Arkose and AWS WAF do this every time, reCAPTCHA and hCaptcha do it when they are suspicious. **Do not attempt the challenge.** It is a test that a person is present, you are not one, and answering it is not a capability you have.++What to do instead, in order: `page_screenshot {}` so you can see the challenge and describe it, then tell the user plainly that this one needs them and that they can solve it in the browser window already in front of them. Do not pass `save: true` — they are looking at the real thing, and a file of it helps nobody. Then wait: poll `page_findCaptcha {}` every several seconds until `state` becomes `solved`, and continue the task from there. If they do not solve it within a reasonable spell, report that you are still waiting rather than looping forever in silence.++The user is sitting at this browser. Handing them ten seconds of clicking is a normal step in a task, not a failure to report apologetically.++## 5. When the tools cannot run++`DEBUGGER_UNAVAILABLE` means Chrome's debugger could not attach — almost always DevTools being open on that tab. Tell the user to close DevTools and retry; there is no fallback, because reading a closed shadow root is exactly what the debugger is for.++`UNSUPPORTED` means Firefox, which does not expose a debugger to extensions. Neither tool works there. Say so and ask the user to deal with the captcha themselves.++Both are terminal conditions. Report them and move on to whatever else the task needs.