A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

9 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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