askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
control.ts · 31.1 KB · 648 lines
| 1 | /** |
| 2 | * Automation API — drive the real browser from scripts, tests and agents. |
| 3 | * |
| 4 | * Why this exists instead of "just use Playwright/CDP": |
| 5 | * - It is the SAME window a human is looking at: tabs, payment inspector and all. |
| 6 | * - Payments are first-class: read every quote/decision/receipt, assert on spend, and |
| 7 | * set an approval policy (ask | auto up to $N | deny) — no native dialog to dodge. |
| 8 | * - Logins use the vault: `login` fills + submits saved credentials without the script |
| 9 | * ever holding the password. |
| 10 | * - Input is real (trusted mouse/keyboard/text events), so sites that ignore |
| 11 | * synthetic `.click()` behave exactly as they do for a person. |
| 12 | * |
| 13 | * Security model (this is remote control of a browser that holds a wallet and a vault): |
| 14 | * - OFF unless DBB_CONTROL=1. Binds 127.0.0.1 only. |
| 15 | * - Every request needs `Authorization: Bearer <token>`; the token is random per launch |
| 16 | * (or DBB_CONTROL_TOKEN) and written 0600 to ~/.dbbasic/control.json. |
| 17 | * - Requests carrying an `Origin` header are refused (a web page can't drive it), and |
| 18 | * the Host header must be loopback (DNS-rebinding guard). |
| 19 | * - The toolbar shows a visible 🤖 chip whenever it is on. |
| 20 | */ |
| 21 | |
| 22 | import { FIND_JS, FORMS_JS, elementExpr, pointOf } from "./page-tools"; |
| 23 | import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; |
| 24 | import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; |
| 25 | import { homedir } from "node:os"; |
| 26 | import { dirname, join } from "node:path"; |
| 27 | import { randomBytes } from "node:crypto"; |
| 28 | import { webContents, type WebContents } from "electron"; |
| 29 | import { safeEqual } from "@dbbasic/vault"; |
| 30 | import type { VaultService } from "./vault-service.js"; |
| 31 | import type { SettleContext } from "./settle-service.js"; |
| 32 | import type { ExtensionRegistry } from "./extensions.js"; |
| 33 | import type { ChatService } from "./chat-service.js"; |
| 34 | import type { McpService } from "./mcp-service.js"; |
| 35 | import type { BookmarksService } from "./bookmarks-service.js"; |
| 36 | |
| 37 | export interface TabInfo { |
| 38 | id: number; |
| 39 | wcId: number | null; |
| 40 | url: string; |
| 41 | title: string; |
| 42 | active: boolean; |
| 43 | loading: boolean; |
| 44 | /** What the tab is doing: connecting|waiting|slow|receiving|redirecting|challenge|pay-pending|pay-paying|pay-settled|summarizing|failed|offline, or null when idle. */ |
| 45 | state: string | null; |
| 46 | } |
| 47 | |
| 48 | export interface ApprovalPolicy { |
| 49 | mode: "ask" | "auto" | "deny"; |
| 50 | /** Auto-approve prompts up to this many USD (only used in "auto"). Policy hard caps still apply. */ |
| 51 | maxUsd: number; |
| 52 | } |
| 53 | |
| 54 | export interface ControlDeps { |
| 55 | /** Ask the chrome UI to do a tab operation and wait for its answer. */ |
| 56 | askChrome(op: string, args: Record<string, unknown>): Promise<unknown>; |
| 57 | /** True in background mode (DBB_BACKGROUND=1): the window is never raised or focused. */ |
| 58 | background: boolean; |
| 59 | /** Bring the browser window to the front and give it keyboard focus (real input needs it). */ |
| 60 | focusWindow(): void; |
| 61 | vault: VaultService; |
| 62 | eventsSince(n: number): { events: unknown[]; next: number }; |
| 63 | /** The right-click menu shown (or, in background mode, recorded) last, and picking one of its items. */ |
| 64 | contextMenu: { last(): { wcId: number; items: unknown[] } | null; pick(id: string): boolean }; |
| 65 | /** Browsing history on the askrobots account (see history.ts). */ |
| 66 | history: { |
| 67 | state(): unknown; |
| 68 | flush(): Promise<unknown>; |
| 69 | pause(on: boolean): Promise<unknown>; |
| 70 | forget(scope: "url" | "last_hour" | "site", target?: string): Promise<unknown>; |
| 71 | never(host: string): Promise<unknown>; |
| 72 | /** Bring the address bar's copy of history up to date now (otherwise it happens on its own). */ |
| 73 | syncCopy(): Promise<unknown>; |
| 74 | }; |
| 75 | getApproval(): ApprovalPolicy; |
| 76 | setApproval(p: ApprovalPolicy): void; |
| 77 | spent(): string; |
| 78 | /** AI Reader: open the reader view for a tab (and, only with `acknowledge`, summarize it). */ |
| 79 | reader(p: Record<string, unknown>): Promise<unknown>; |
| 80 | aiStatus(): unknown; |
| 81 | /** The in-browser chat (see chat-service.ts). */ |
| 82 | chat: ChatService; |
| 83 | /** MCP connections (see mcp-service.ts). */ |
| 84 | mcp: McpService; |
| 85 | /** What the browser is using: memory and CPU per tab, cache and disk. */ |
| 86 | resources: { state(): Promise<unknown>; clearCache(): Promise<unknown> }; |
| 87 | /** Bookmarks: saved links on askrobots (see bookmarks-service.ts). */ |
| 88 | bookmarks: BookmarksService; |
| 89 | /** Keep: copies of pages, so their tabs can be closed (see keep-store.ts). */ |
| 90 | keep: { tab(o: Record<string, unknown>): Promise<unknown>; list(q: string): Promise<unknown>; get(id: string): Promise<unknown>; remove(id: string): Promise<boolean> }; |
| 91 | downloads(): unknown; |
| 92 | getNetPolicy(): { blockWebSockets: boolean }; |
| 93 | /** Methods added by local extensions (see extensions.ts), reached as ext.<name>. */ |
| 94 | extensions: ExtensionRegistry<WebContents>; |
| 95 | /** Throws "caller-network-on" while the caller network is on. */ |
| 96 | assertNotCallerNet(what: string): void; |
| 97 | callerNet: { |
| 98 | state(): unknown; |
| 99 | configure(p: { enabled?: unknown; userAgent?: unknown; answerTimeoutMs?: unknown; cookies?: unknown; limits?: unknown }): void; |
| 100 | pending(afterId: number, waitMs: number): Promise<unknown>; |
| 101 | answer(id: number, a: Record<string, unknown>): void; |
| 102 | fail(id: number, kind: unknown, detail?: unknown): void; |
| 103 | registerDocument(doc: Record<string, unknown>): void; |
| 104 | freshVisit(wcId: number): Promise<void>; |
| 105 | noteKnownDocument(wcId: number, url: string, redirects: Array<{ status?: number; to: string }>): void; |
| 106 | }; |
| 107 | setNetPolicy(p: { websockets?: boolean }): void; |
| 108 | /** Wait until a page has finished loading and say why (see settle.ts). */ |
| 109 | settle(ctx: SettleContext, opts: unknown): Promise<unknown>; |
| 110 | setAiProvider(p: unknown): boolean; |
| 111 | receipts(): unknown; |
| 112 | } |
| 113 | |
| 114 | /** Run a caller-network operation, turning its validation errors into API errors. */ |
| 115 | function provider<T>(fn: () => T): T { |
| 116 | try { |
| 117 | return fn(); |
| 118 | } catch (e) { |
| 119 | const code = (e as { code?: unknown }).code; |
| 120 | if (e instanceof Error && typeof code === "string") throw new RpcError(code, e.message); |
| 121 | throw e; |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | class RpcError extends Error { |
| 126 | code: string; |
| 127 | constructor(code: string, message: string) { |
| 128 | super(message); |
| 129 | this.code = code; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | let tabs: TabInfo[] = []; |
| 134 | export const setTabs = (t: TabInfo[]) => void (tabs = t); |
| 135 | export const getTabs = (): TabInfo[] => tabs; |
| 136 | |
| 137 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); |
| 138 | const str = (v: unknown, name: string): string => { |
| 139 | if (typeof v !== "string" || !v) throw new RpcError("bad-params", `"${name}" (string) is required`); |
| 140 | return v; |
| 141 | }; |
| 142 | |
| 143 | function resolveTab(p: Record<string, unknown>): TabInfo { |
| 144 | const t = p.tab == null ? tabs.find((x) => x.active) : tabs.find((x) => x.id === Number(p.tab)); |
| 145 | if (!t) throw new RpcError("no-tab", p.tab == null ? "no active tab" : `no tab ${String(p.tab)}`); |
| 146 | return t; |
| 147 | } |
| 148 | /** |
| 149 | * A tab can be listed a moment before its page exists (the id is published at dom-ready). Wait briefly for it |
| 150 | * instead of failing, so a script that starts right after launch or right after opening a tab just works. |
| 151 | */ |
| 152 | async function addressable(t: TabInfo): Promise<number> { |
| 153 | for (let i = 0; i < 250; i++) { |
| 154 | const cur = tabs.find((x) => x.id === t.id); |
| 155 | if (cur?.wcId != null) return cur.wcId; |
| 156 | await sleep(20); |
| 157 | } |
| 158 | throw new RpcError("tab-not-ready", `tab ${t.id} is not ready yet`); |
| 159 | } |
| 160 | |
| 161 | function guest(t: TabInfo): WebContents { |
| 162 | const wc = t.wcId == null ? undefined : webContents.fromId(t.wcId); |
| 163 | if (!wc || wc.isDestroyed()) throw new RpcError("tab-not-ready", `tab ${t.id} is not ready yet`); |
| 164 | return wc; |
| 165 | } |
| 166 | |
| 167 | async function evalIn(wc: WebContents, js: string): Promise<unknown> { |
| 168 | try { |
| 169 | return await wc.executeJavaScript(js, true); |
| 170 | } catch (e) { |
| 171 | throw new RpcError("eval-error", e instanceof Error ? e.message : String(e)); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /** |
| 176 | * "Has this page finished loading?" Returns a verdict: whether it settled, which rule ended the wait, what |
| 177 | * actually happened (ok, error status, blank, failed and why, bot check, payment, download…), and facts about |
| 178 | * the load. The two-frame test needs a visible page, so (like a screenshot) it brings the tab forward. |
| 179 | */ |
| 180 | /** In caller-network mode, a new visit starts with a clean slate (only then; it needs the page to be addressable). */ |
| 181 | async function freshVisit(d: ControlDeps, t: TabInfo): Promise<void> { |
| 182 | if ((d.callerNet.state() as { enabled?: boolean }).enabled) await d.callerNet.freshVisit(await addressable(t)); |
| 183 | } |
| 184 | |
| 185 | async function settleTab(d: ControlDeps, t: TabInfo, opts: unknown): Promise<unknown> { |
| 186 | const wcId = await addressable(t); |
| 187 | const o = (opts && typeof opts === "object" ? opts : {}) as Record<string, unknown>; |
| 188 | if (o.frames !== false) await front(d, t); |
| 189 | return d.settle({ tabId: t.id, wcId, askChrome: d.askChrome.bind(d) }, o); |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Real input needs a visible, focused page — bring the tab AND the window to the front first. Without the window |
| 194 | * part, anything else that grabbed focus (a person clicking elsewhere, another app) makes key events land nowhere. |
| 195 | */ |
| 196 | async function front(d: ControlDeps, t: TabInfo): Promise<WebContents> { |
| 197 | if (!t.active) { |
| 198 | await d.askChrome("tab.activate", { id: t.id }); |
| 199 | await sleep(80); |
| 200 | } |
| 201 | d.focusWindow(); |
| 202 | const wc = guest(t); |
| 203 | // Focusing a page focuses (and, on macOS, raises) its window, so background mode never does it. |
| 204 | if (!d.background) wc.focus(); |
| 205 | return wc; |
| 206 | } |
| 207 | |
| 208 | /** Which element a call names: a ref (from page.forms / page.find) or a CSS selector. */ |
| 209 | function targetOf(p: Record<string, unknown>): { ref?: string; selector?: string } { |
| 210 | if (p.ref != null) return { ref: str(typeof p.ref === "number" ? String(p.ref) : p.ref, "ref") }; |
| 211 | return { selector: str(p.selector, "selector") }; |
| 212 | } |
| 213 | function noElement(p: Record<string, unknown>): RpcError { |
| 214 | return p.ref != null |
| 215 | ? new RpcError("no-element", `ref ${String(p.ref)} is not on the page any more (ask page.forms or page.find again)`) |
| 216 | : new RpcError("no-element", `nothing matches ${String(p.selector)}`); |
| 217 | } |
| 218 | |
| 219 | const KEYS: Record<string, string> = { Enter: "Enter", Tab: "Tab", Escape: "Escape", Backspace: "Backspace", Delete: "Delete", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right", Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", " ": "Space" }; |
| 220 | |
| 221 | export async function handle(d: ControlDeps, method: string, p: Record<string, unknown>): Promise<unknown> { |
| 222 | switch (method) { |
| 223 | // ---- meta / tabs -------------------------------------------------------- |
| 224 | case "status": |
| 225 | return { version: 1, extensions: d.extensions.loadedNames(), tabs, approval: d.getApproval(), spent: d.spent(), vault: await d.vault.state() }; |
| 226 | case "tabs.list": |
| 227 | return tabs; |
| 228 | case "tabs.new": |
| 229 | return d.askChrome("tab.new", { url: p.url ?? null, activate: p.activate !== false, wait: p.wait !== false }); |
| 230 | case "tabs.close": |
| 231 | return d.askChrome("tab.close", { id: resolveTab(p).id }); |
| 232 | case "tabs.activate": |
| 233 | return d.askChrome("tab.activate", { id: resolveTab(p).id }); |
| 234 | |
| 235 | // ---- navigation --------------------------------------------------------- |
| 236 | case "page.goto": { |
| 237 | const t = resolveTab(p); |
| 238 | await freshVisit(d, t); |
| 239 | if (!p.settle) return d.askChrome("tab.goto", { id: t.id, url: str(p.url, "url"), wait: p.wait !== false }); |
| 240 | // `settle: true` (or an options object) waits until the page is REALLY finished and says why. It starts once |
| 241 | // the navigation has begun, so it never judges the page being left; the verdict replaces the plain load wait. |
| 242 | const loaded = (await d.askChrome("tab.goto", { id: t.id, url: str(p.url, "url"), wait: "start" })) as Record<string, unknown>; |
| 243 | return { ...loaded, settle: await settleTab(d, t, p.settle === true ? {} : p.settle) }; |
| 244 | } |
| 245 | case "page.settle": |
| 246 | return settleTab(d, resolveTab(p), p); |
| 247 | case "page.back": |
| 248 | case "page.forward": |
| 249 | case "page.reload": |
| 250 | return d.askChrome("tab." + method.slice(5), { id: resolveTab(p).id, wait: p.wait !== false }); |
| 251 | |
| 252 | // ---- reading ------------------------------------------------------------ |
| 253 | case "page.eval": |
| 254 | return { value: await evalIn(guest(resolveTab(p)), str(p.js, "js")) }; |
| 255 | case "page.text": { |
| 256 | const sel = p.selector == null ? null : str(p.selector, "selector"); |
| 257 | return { text: await evalIn(guest(resolveTab(p)), `(() => { const e = ${sel ? `document.querySelector(${JSON.stringify(sel)})` : "document.body"}; return e ? e.innerText : null; })()`) }; |
| 258 | } |
| 259 | case "page.html": |
| 260 | return { html: await evalIn(guest(resolveTab(p)), "document.documentElement.outerHTML") }; |
| 261 | case "page.forms": { |
| 262 | // The fields and buttons of the page, with refs that click/hover/type accept. Sensitive values are never returned. |
| 263 | const r = await evalIn(guest(resolveTab(p)), FORMS_JS({ includeHidden: p.includeHidden === true, limit: Number(p.limit) || 200 })); |
| 264 | return r; |
| 265 | } |
| 266 | case "page.find": { |
| 267 | const text = p.text == null ? undefined : str(p.text, "text"); |
| 268 | const label = p.label == null ? undefined : str(p.label, "label"); |
| 269 | const role = p.role == null ? undefined : str(p.role, "role"); |
| 270 | if (text == null && label == null && role == null) throw new RpcError("bad-params", 'pass at least one of "text", "label", "role"'); |
| 271 | return evalIn(guest(resolveTab(p)), FIND_JS({ text, label, role, includeHidden: p.includeHidden === true, limit: Number(p.limit) || 20 })); |
| 272 | } |
| 273 | case "page.screenshot": { |
| 274 | const t = resolveTab(p); |
| 275 | const wc = await front(d, t); |
| 276 | const img = await wc.capturePage(); |
| 277 | return { png: img.toPNG().toString("base64"), width: img.getSize().width, height: img.getSize().height }; |
| 278 | } |
| 279 | |
| 280 | // ---- acting (real, trusted input) ---------------------------------------- |
| 281 | case "page.click": { |
| 282 | const t = resolveTab(p); |
| 283 | const wc = await front(d, t); |
| 284 | let x = Number(p.x), y = Number(p.y); |
| 285 | if (p.ref != null || p.selector != null) { |
| 286 | const pt = (await evalIn(wc, pointOf(targetOf(p)))) as { x: number; y: number } | null; |
| 287 | if (!pt) throw noElement(p); |
| 288 | ({ x, y } = pt); |
| 289 | await sleep(50); // let scroll settle |
| 290 | } else if (!Number.isFinite(x) || !Number.isFinite(y)) throw new RpcError("bad-params", 'pass "ref", "selector" or both "x" and "y"'); |
| 291 | wc.sendInputEvent({ type: "mouseMove", x, y }); |
| 292 | wc.sendInputEvent({ type: "mouseDown", x, y, button: "left", clickCount: 1 }); |
| 293 | wc.sendInputEvent({ type: "mouseUp", x, y, button: "left", clickCount: 1 }); |
| 294 | return { clicked: { x, y } }; |
| 295 | } |
| 296 | case "page.hover": { |
| 297 | // Move the real pointer over an element (or to x,y) without clicking: shows hover states and link addresses. |
| 298 | const t = resolveTab(p); |
| 299 | const wc = await front(d, t); |
| 300 | let x = Number(p.x), y = Number(p.y); |
| 301 | if (p.ref != null || p.selector != null) { |
| 302 | const pt = (await evalIn(wc, pointOf(targetOf(p)))) as { x: number; y: number } | null; |
| 303 | if (!pt) throw noElement(p); |
| 304 | ({ x, y } = pt); |
| 305 | await sleep(50); |
| 306 | } else if (!Number.isFinite(x) || !Number.isFinite(y)) throw new RpcError("bad-params", 'pass "ref", "selector" or both "x" and "y"'); |
| 307 | wc.sendInputEvent({ type: "mouseMove", x, y }); |
| 308 | return { hovered: { x, y } }; |
| 309 | } |
| 310 | case "page.type": { |
| 311 | const t = resolveTab(p); |
| 312 | const wc = await front(d, t); |
| 313 | const text = typeof p.text === "string" ? p.text : str(p.text, "text"); |
| 314 | if (p.ref != null || p.selector != null) { |
| 315 | const ok = await evalIn(wc, `(() => { const e = ${elementExpr(targetOf(p))}; if (!e) return false; e.scrollIntoView({block:"center"}); e.focus(); ${p.clear !== false ? "if (e.select) e.select();" : ""} return true; })()`); |
| 316 | if (!ok) throw noElement(p); |
| 317 | } |
| 318 | await wc.insertText(text); // replaces the selection when clear (default), else appends |
| 319 | return { typed: text.length }; |
| 320 | } |
| 321 | case "page.press": { |
| 322 | const t = resolveTab(p); |
| 323 | const wc = await front(d, t); |
| 324 | const key = str(p.key, "key"); |
| 325 | const keyCode = KEYS[key] ?? key; |
| 326 | wc.sendInputEvent({ type: "keyDown", keyCode }); |
| 327 | if (key === "Enter") wc.sendInputEvent({ type: "char", keyCode: "\r" }); |
| 328 | else if (key.length === 1) wc.sendInputEvent({ type: "char", keyCode: key }); |
| 329 | wc.sendInputEvent({ type: "keyUp", keyCode }); |
| 330 | return { pressed: key }; |
| 331 | } |
| 332 | case "page.waitFor": { |
| 333 | const t = resolveTab(p); |
| 334 | const timeout = Math.min(Number(p.timeoutMs) || 10_000, 120_000); |
| 335 | const conds = { |
| 336 | selector: p.selector == null ? null : str(p.selector, "selector"), |
| 337 | text: p.text == null ? null : str(p.text, "text"), |
| 338 | url: p.url == null ? null : str(p.url, "url"), |
| 339 | }; |
| 340 | if (!conds.selector && !conds.text && !conds.url) throw new RpcError("bad-params", 'pass at least one of "selector", "text", "url"'); |
| 341 | const js = `(() => (${conds.selector ? `!!document.querySelector(${JSON.stringify(conds.selector)})` : "true"}) && (${conds.text ? `(document.body?.innerText||"").includes(${JSON.stringify(conds.text)})` : "true"}) && (${conds.url ? `location.href.includes(${JSON.stringify(conds.url)})` : "true"}))()`; |
| 342 | const end = Date.now() + timeout; |
| 343 | for (;;) { |
| 344 | try { |
| 345 | if (await guest(t).executeJavaScript(js)) return { matched: true }; |
| 346 | } catch { |
| 347 | /* page mid-navigation — keep polling */ |
| 348 | } |
| 349 | if (Date.now() > end) throw new RpcError("timeout", `waitFor timed out after ${timeout}ms`); |
| 350 | await sleep(100); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | // ---- chat ------------------------------------------------------------------ |
| 355 | case "chat.state": |
| 356 | return d.chat.state(); |
| 357 | case "chat.send": { |
| 358 | // Sends one message and waits for the assistant to finish (wait:false returns at once; poll chat.events). |
| 359 | const text = str(p.text, "text"); |
| 360 | if (p.mode != null) d.chat.setMode(p.mode); |
| 361 | const run = d.chat.send(text); |
| 362 | if (p.wait === false) return { started: true }; |
| 363 | return run; |
| 364 | } |
| 365 | case "chat.events": |
| 366 | return d.chat.eventsSince(Number(p.since) || 0); |
| 367 | case "chat.confirm": |
| 368 | return { settled: d.chat.confirm(str(p.id, "id"), p.ok === true) }; |
| 369 | case "chat.stop": |
| 370 | d.chat.stop(); |
| 371 | return { stopped: true }; |
| 372 | case "chat.clear": |
| 373 | d.chat.clear(); |
| 374 | return { cleared: true }; |
| 375 | case "chat.mode": |
| 376 | return { mode: d.chat.setMode(p.mode) }; |
| 377 | case "chat.model": |
| 378 | // Pick the assistant's model: one of chat.state's `models` ids ("provider/model"). Remembered across restarts. |
| 379 | return d.chat.setModel(str(p.model, "model")); |
| 380 | |
| 381 | // ---- keep ----------------------------------------------------------------------- |
| 382 | case "keep.tab": |
| 383 | return d.keep.tab({ ...(typeof p.tab === "number" ? { tab: p.tab } : {}), ...(typeof p.reason === "string" ? { reason: p.reason } : {}), close: p.close !== false, bookmark: p.bookmark !== false }); |
| 384 | case "keep.list": |
| 385 | return d.keep.list(typeof p.q === "string" ? p.q : ""); |
| 386 | case "keep.get": |
| 387 | return d.keep.get(str(p.id, "id")); |
| 388 | case "keep.remove": |
| 389 | return { removed: await d.keep.remove(str(p.id, "id")) }; |
| 390 | |
| 391 | // ---- bookmarks ------------------------------------------------------------------ |
| 392 | case "bookmarks.list": |
| 393 | if (p.refresh === true) { |
| 394 | d.assertNotCallerNet("bookmarks"); |
| 395 | return d.bookmarks.refresh(); |
| 396 | } |
| 397 | return d.bookmarks.state(); |
| 398 | case "bookmarks.add": |
| 399 | d.assertNotCallerNet("bookmarks"); |
| 400 | return d.bookmarks.add(str(p.url, "url"), typeof p.title === "string" ? p.title : ""); |
| 401 | case "bookmarks.search": |
| 402 | d.assertNotCallerNet("bookmarks"); |
| 403 | return d.bookmarks.search(str(p.q, "q")); |
| 404 | case "bookmarks.check": |
| 405 | d.assertNotCallerNet("bookmarks"); |
| 406 | return d.bookmarks.checkPage(str(p.url, "url")); |
| 407 | case "bookmarks.setCheck": |
| 408 | return d.bookmarks.setCheckPages(p.on === true); |
| 409 | case "bookmarks.has": |
| 410 | return { saved: d.bookmarks.has(str(p.url, "url")) }; |
| 411 | |
| 412 | // ---- resources ------------------------------------------------------------------ |
| 413 | case "resources.state": |
| 414 | return d.resources.state(); |
| 415 | case "resources.clearCache": |
| 416 | return d.resources.clearCache(); |
| 417 | |
| 418 | // ---- MCP connections ---------------------------------------------------------- |
| 419 | case "mcp.state": |
| 420 | return d.mcp.state(); |
| 421 | case "mcp.connect": { |
| 422 | // By default the consent page opens in a tab of this browser (the redirect back is caught inside it). open:false returns the |
| 423 | // consent address instead and listens on 127.0.0.1, so a script can do what the person's browser would; via:"system" opens the person's own browser. |
| 424 | const via = p.via === "tab" || p.via === "system" || p.via === "none" ? p.via : undefined; |
| 425 | const r = await d.mcp.connect(str(p.id, "id"), { open: p.open !== false, ...(via ? { via } : {}) }); |
| 426 | if (p.wait === true) await r.done; |
| 427 | return { authorizeUrl: r.authorizeUrl }; |
| 428 | } |
| 429 | case "mcp.cancel": |
| 430 | d.mcp.cancelConnect(str(p.id, "id")); |
| 431 | return { cancelled: true }; |
| 432 | case "mcp.disconnect": |
| 433 | return d.mcp.disconnect(str(p.id, "id")); |
| 434 | case "mcp.refresh": |
| 435 | return d.mcp.refreshNow(str(p.id, "id")); |
| 436 | case "mcp.tools": |
| 437 | return (await d.mcp.toolDefs()).map((t) => ({ name: t.name, risk: t.risk, description: t.description })); |
| 438 | |
| 439 | // ---- vault --------------------------------------------------------------- |
| 440 | case "vault.state": |
| 441 | return d.vault.state(); |
| 442 | case "vault.unlock": { |
| 443 | const r = await d.vault.unlock(str(p.master, "master")); |
| 444 | if (!r.ok) throw new RpcError(r.code, r.message); |
| 445 | return r.data; |
| 446 | } |
| 447 | case "login": { |
| 448 | // Fill (and by default submit) the saved login for this tab's exact origin. |
| 449 | provider(() => d.assertNotCallerNet("login")); |
| 450 | const t = resolveTab(p); |
| 451 | await front(d, t); |
| 452 | const r = await d.vault.fill(guest(t).id, typeof p.id === "string" ? p.id : undefined, p.submit !== false); |
| 453 | if (!r.ok) throw new RpcError(r.code, r.message); |
| 454 | if (p.submit !== false && p.wait !== false) await d.askChrome("tab.waitLoad", { id: t.id, ms: 15_000 }); |
| 455 | return r.data; // username + origin only — never the password |
| 456 | } |
| 457 | |
| 458 | // ---- a network layer the caller supplies --------------------------------- |
| 459 | case "net.provider": { |
| 460 | // {enabled?, userAgent?, answerTimeoutMs?, cookies?: "off" | "visit", limits?: {requests?, bytes?}}: while on, the browser makes NO request of its own; each one is handed to the |
| 461 | // caller (net.pending) to answer (net.answer) or refuse (net.fail). userAgent is required when turning it on. |
| 462 | if (p.enabled !== undefined || p.answerTimeoutMs !== undefined || p.userAgent !== undefined || p.cookies !== undefined || p.limits !== undefined) provider(() => d.callerNet.configure(p)); |
| 463 | return d.callerNet.state(); |
| 464 | } |
| 465 | case "net.pending": { |
| 466 | const after = p.afterId === undefined ? 0 : Number(p.afterId); |
| 467 | const wait = p.waitMs === undefined ? 0 : Number(p.waitMs); |
| 468 | if (!Number.isFinite(after) || !Number.isFinite(wait)) throw new RpcError("bad-params", "afterId and waitMs must be numbers"); |
| 469 | return { requests: await d.callerNet.pending(after, wait) }; |
| 470 | } |
| 471 | case "net.answer": { |
| 472 | const { id, ...answer } = p; |
| 473 | provider(() => d.callerNet.answer(Number(id), answer)); |
| 474 | return { answered: Number(id) }; |
| 475 | } |
| 476 | case "net.fail": |
| 477 | provider(() => d.callerNet.fail(Number(p.id), p.kind, p.detail)); |
| 478 | return { failed: Number(p.id) }; |
| 479 | case "page.load": { |
| 480 | // Load a main document the caller ALREADY fetched, as it is: {url (its final address), status, headers, bodyBase64|bodyText, |
| 481 | // redirects?: [{status,to}], settle?}. Relative links resolve against url; the facts list the redirects. |
| 482 | const t = resolveTab(p); |
| 483 | const url = str(p.url, "url"); |
| 484 | const { settle: settleOpt, ...doc } = p; |
| 485 | const redirects = Array.isArray(p.redirects) ? (p.redirects as Array<{ status?: number; to: string }>) : []; |
| 486 | provider(() => d.callerNet.registerDocument({ ...doc, url })); |
| 487 | await freshVisit(d, t); |
| 488 | d.callerNet.noteKnownDocument(await addressable(t), url, redirects); |
| 489 | const loaded = (await d.askChrome("tab.goto", { id: t.id, url, wait: settleOpt ? "start" : true })) as Record<string, unknown>; |
| 490 | return settleOpt ? { ...loaded, settle: await settleTab(d, t, settleOpt === true ? {} : settleOpt) } : loaded; |
| 491 | } |
| 492 | |
| 493 | // ---- network policy ------------------------------------------------------ |
| 494 | case "net.policy": { |
| 495 | // {blockWebSockets?: boolean}: refuse WebSockets before any connection is opened (they bypass the network layer). |
| 496 | if (p.blockWebSockets !== undefined) { |
| 497 | if (typeof p.blockWebSockets !== "boolean") throw new RpcError("bad-params", "blockWebSockets must be true or false"); |
| 498 | d.setNetPolicy({ websockets: p.blockWebSockets }); |
| 499 | } |
| 500 | return d.getNetPolicy(); |
| 501 | } |
| 502 | |
| 503 | // ---- downloads ----------------------------------------------------------- |
| 504 | case "downloads.list": |
| 505 | return d.downloads(); |
| 506 | |
| 507 | // ---- AI Reader ----------------------------------------------------------- |
| 508 | case "ai.status": |
| 509 | return d.aiStatus(); |
| 510 | case "ai.provider": { |
| 511 | if (!d.setAiProvider(p.provider)) throw new RpcError("bad-params", 'provider must be "anthropic" or "openai" and have a key'); |
| 512 | return d.aiStatus(); |
| 513 | } |
| 514 | case "reader.open": { |
| 515 | provider(() => d.assertNotCallerNet("the reader")); |
| 516 | // Opens the reader view. Page text is sent to an AI provider ONLY when `acknowledge: true` is passed |
| 517 | // (a human would have been asked); without it the reader opens with no summary. |
| 518 | const t = resolveTab(p); |
| 519 | if (t.wcId == null) throw new RpcError("tab-not-ready", `tab ${t.id} is not ready yet`); |
| 520 | return d.reader({ ...p, wcId: t.wcId }); |
| 521 | } |
| 522 | |
| 523 | // ---- x402 ---------------------------------------------------------------- |
| 524 | case "x402.spent": |
| 525 | return { spent: d.spent() }; |
| 526 | case "x402.receipts": |
| 527 | return d.receipts(); |
| 528 | case "x402.events": |
| 529 | return d.eventsSince(Number(p.since) || 0); |
| 530 | |
| 531 | // ---- the right-click menu -------------------------------------------------- |
| 532 | case "menu.last": |
| 533 | return { menu: d.contextMenu.last() }; |
| 534 | // ---- history ---------------------------------------------------------------------- |
| 535 | case "history.state": |
| 536 | return d.history.state(); |
| 537 | case "history.flush": |
| 538 | // Send what is waiting now (otherwise it goes every 30 seconds), and say how it stands. |
| 539 | return d.history.flush(); |
| 540 | case "history.pause": |
| 541 | return d.history.pause(p.paused === true); |
| 542 | case "history.forget": { |
| 543 | const scope = str(p.scope, "scope"); |
| 544 | if (!["url", "last_hour", "site"].includes(scope)) throw new RpcError("bad-params", 'scope is "url", "last_hour" or "site" (forgetting everything is done on askrobots.com)'); |
| 545 | return d.history.forget(scope as "url" | "last_hour" | "site", typeof p.target === "string" ? p.target : undefined); |
| 546 | } |
| 547 | case "history.never": |
| 548 | return d.history.never(str(p.host, "host")); |
| 549 | case "history.syncCopy": |
| 550 | return d.history.syncCopy(); |
| 551 | |
| 552 | case "menu.pick": { |
| 553 | if (typeof p.id !== "string" || !p.id) throw new RpcError("bad-params", "id is required (an item id from menu.last)"); |
| 554 | return { ok: d.contextMenu.pick(p.id) }; |
| 555 | } |
| 556 | case "x402.approval": { |
| 557 | if (p.mode != null) { |
| 558 | if (p.mode !== "ask" && p.mode !== "auto" && p.mode !== "deny") throw new RpcError("bad-params", 'mode must be "ask", "auto" or "deny"'); |
| 559 | const maxUsd = p.maxUsd == null ? d.getApproval().maxUsd : Number(p.maxUsd); |
| 560 | if (!Number.isFinite(maxUsd) || maxUsd < 0) throw new RpcError("bad-params", "maxUsd must be a non-negative number"); |
| 561 | d.setApproval({ mode: p.mode, maxUsd }); |
| 562 | } |
| 563 | return d.getApproval(); |
| 564 | } |
| 565 | default: |
| 566 | if (d.extensions.has(method)) { |
| 567 | try { |
| 568 | return await d.extensions.call(method, p, { |
| 569 | // The page of the tab the request names. The tab is made the visible one, but the window is NOT raised or focused. |
| 570 | webContents: async (params) => { |
| 571 | const t = resolveTab(params); |
| 572 | if (!t.active) { |
| 573 | await d.askChrome("tab.activate", { id: t.id }); |
| 574 | await sleep(80); |
| 575 | } |
| 576 | await addressable(t); |
| 577 | return guest(t); |
| 578 | }, |
| 579 | }); |
| 580 | } catch (e) { |
| 581 | if (e instanceof RpcError) throw e; |
| 582 | throw new RpcError("extension-error", e instanceof Error ? e.message : String(e)); |
| 583 | } |
| 584 | } |
| 585 | throw new RpcError("no-method", `unknown method "${method}"`); |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | export interface ControlHandle { |
| 590 | port: number; |
| 591 | token: string; |
| 592 | file: string; |
| 593 | close(): void; |
| 594 | } |
| 595 | |
| 596 | export async function startControl(d: ControlDeps, opts: { port: number; token?: string }): Promise<ControlHandle> { |
| 597 | const token = opts.token || randomBytes(24).toString("hex"); |
| 598 | const hostOk = (h: string | undefined) => h === `127.0.0.1:${opts.port}` || h === `localhost:${opts.port}`; |
| 599 | |
| 600 | const reply = (res: ServerResponse, status: number, body: unknown) => { |
| 601 | res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }); |
| 602 | res.end(JSON.stringify(body)); |
| 603 | }; |
| 604 | const readBody = async (req: IncomingMessage): Promise<string> => { |
| 605 | // Collect bytes and decode once: decoding each chunk would corrupt a multi-byte character that spans two of them. |
| 606 | const chunks: Buffer[] = []; |
| 607 | let n = 0; |
| 608 | for await (const c of req) { |
| 609 | const buf = Buffer.isBuffer(c) ? c : Buffer.from(c); |
| 610 | n += buf.byteLength; |
| 611 | if (n > 64 * 1024 * 1024) throw new RpcError("too-large", "request body too large"); // an answer may carry up to 32 MB, as base64 |
| 612 | chunks.push(buf); |
| 613 | } |
| 614 | return Buffer.concat(chunks).toString("utf8"); |
| 615 | }; |
| 616 | |
| 617 | const server = createServer(async (req, res) => { |
| 618 | if (!hostOk(req.headers.host)) return reply(res, 403, { ok: false, error: { code: "bad-host", message: "loopback only" } }); |
| 619 | if (req.headers.origin) return reply(res, 403, { ok: false, error: { code: "bad-origin", message: "browser-originated requests are refused" } }); |
| 620 | const auth = req.headers.authorization ?? ""; |
| 621 | if (!safeEqual(auth, `Bearer ${token}`)) return reply(res, 401, { ok: false, error: { code: "unauthorized", message: "missing or wrong bearer token" } }); |
| 622 | if (req.method !== "POST" || req.url !== "/rpc") return reply(res, 404, { ok: false, error: { code: "not-found", message: "POST /rpc" } }); |
| 623 | |
| 624 | let id: unknown = null; |
| 625 | try { |
| 626 | const msg = JSON.parse(await readBody(req)) as { id?: unknown; method?: string; params?: Record<string, unknown> }; |
| 627 | id = msg.id ?? null; |
| 628 | const result = await handle(d, str(msg.method, "method"), msg.params ?? {}); |
| 629 | reply(res, 200, { id, ok: true, result }); |
| 630 | } catch (e) { |
| 631 | const err = e instanceof RpcError ? e : new RpcError("error", e instanceof Error ? e.message : String(e)); |
| 632 | reply(res, 200, { id, ok: false, error: { code: err.code, message: err.message } }); |
| 633 | } |
| 634 | }); |
| 635 | |
| 636 | await new Promise<void>((resolve, reject) => { |
| 637 | server.once("error", reject); |
| 638 | server.listen(opts.port, "127.0.0.1", resolve); |
| 639 | }); |
| 640 | |
| 641 | // DBB_CONTROL_FILE lets a test harness keep its own token file instead of clobbering the real one. |
| 642 | const dir = join(homedir(), ".dbbasic"); |
| 643 | const file = process.env.DBB_CONTROL_FILE || join(dir, "control.json"); |
| 644 | mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); |
| 645 | writeFileSync(file, JSON.stringify({ url: `http://127.0.0.1:${opts.port}/rpc`, token, pid: process.pid }), { mode: 0o600 }); |
| 646 | chmodSync(file, 0o600); |
| 647 | return { port: opts.port, token, file, close: () => server.close() }; |
| 648 | } |