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
main.ts · 88.6 KB · 1626 lines
| 1 | /** |
| 2 | * Electron main process for dbbasic-browser. |
| 3 | * |
| 4 | * This is the thin shell around the engine. All payment logic lives in |
| 5 | * @dbbasic/x402-engine; here we only: |
| 6 | * - own the https network stack via protocol.handle (the primitive an extension lacks), |
| 7 | * - feed the engine a network fetch that won't recurse into our own handler, |
| 8 | * - surface the approve prompt as a native dialog that shows the price BEFORE paying, |
| 9 | * - stream payment events to the chrome UI for the live spend meter. |
| 10 | */ |
| 11 | |
| 12 | import { execFile } from "node:child_process"; |
| 13 | import { randomUUID } from "node:crypto"; |
| 14 | import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 15 | import { fileURLToPath, pathToFileURL } from "node:url"; |
| 16 | import { basename, dirname, extname, join } from "node:path"; |
| 17 | import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeImage, protocol, safeStorage, session, shell, webContents, type MenuItemConstructorOptions, type WebContents } from "electron"; |
| 18 | import { createPublicClient, http as viemHttp } from "viem"; |
| 19 | import { baseSepolia } from "viem/chains"; |
| 20 | import { privateKeyToAccount } from "viem/accounts"; |
| 21 | import { PolicyEngine, Ledger, X402Engine, formatUsd, signExactEvm } from "@dbbasic/x402-engine"; |
| 22 | import { createPaymentHandler, type RawFetch } from "./intercept.js"; |
| 23 | import { brandedUserAgent } from "./compat.js"; |
| 24 | import { emitNet, netEvents, netRequestFetch, nextNetId, setClientHints, type NetEvent } from "./transport.js"; |
| 25 | import { ExtensionRegistry, loadExtensions, parseExtensionPaths } from "./extensions.js"; |
| 26 | import { CallerNetwork, ProviderError, clampAnswerTimeout, type Answer, type CookieJar, type Document } from "./provider.js"; |
| 27 | import { safeExternalUrl } from "./urls.js"; |
| 28 | import { describeAi, loadAiEnv, resolveAi, type AiConfig, type Provider } from "./ai-config.js"; |
| 29 | import { createReader } from "./reader-service.js"; |
| 30 | import { noteDownload, runSettle, trackLifecycle, noteKnownDocument } from "./settle-service.js"; |
| 31 | import { EXPIRED_HTML, READER_SCHEME, ReaderPages, readerIdFromUrl } from "./reader-pages.js"; |
| 32 | import { READER_CSP } from "./reader.js"; |
| 33 | import { registerVault } from "./vault-service.js"; |
| 34 | import { handle as handleControl, getTabs, setTabs, startControl, type ApprovalPolicy, type ControlDeps, type ControlHandle, type TabInfo } from "./control.js"; |
| 35 | import { parseSavedChoice } from "./chat-model-choice.js"; |
| 36 | import { HistoryCopy } from "./history-copy.js"; |
| 37 | import { forgetMatch, HistoryService, onNeverList } from "./history.js"; |
| 38 | import { FaviconStore, hostOf, type Fetched } from "./favicons.js"; |
| 39 | import { ChatService } from "./chat-service.js"; |
| 40 | import { McpService, createStore, loadServerConfigs } from "./mcp-service.js"; |
| 41 | import { BookmarksService } from "./bookmarks-service.js"; |
| 42 | import { KEPT_SCHEME, KeepStore, keptFilename, keptPageHtml, keptUrl, parseKeptUrl, type KeptRecord } from "./keep-store.js"; |
| 43 | import { diskUsage, type DiskUsage } from "./disk-usage.js"; |
| 44 | import { reservedShortcut } from "./shortcuts.js"; |
| 45 | import { contextMenuItems, type MenuItem } from "./context-menu.js"; |
| 46 | import { commandArgs, commandRows, describeResult, parseCommand, parseSuggestions, remoteAllowed, suggest, toCommand, type OmniTab } from "./omnibox.js"; |
| 47 | import { macFootprints } from "./process-memory.js"; |
| 48 | |
| 49 | const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 50 | |
| 51 | // Branding. (On macOS the Dock label/icon come from the .app bundle — scripts/launch.mjs |
| 52 | // brands the dev bundle; these cover the in-app name, the Dock icon at runtime, and |
| 53 | // the Windows/Linux window + taskbar icon.) |
| 54 | // NOTE: the app name also decides the userData folder (cookies, the default vault.json). |
| 55 | app.setName("dbbasic-browser"); |
| 56 | const ICON_PATH = join(__dirname, "icon.png"); |
| 57 | |
| 58 | // Reader views are served from dbb-reader://<id>/ (see reader-pages.ts). The scheme must be registered before ready. |
| 59 | protocol.registerSchemesAsPrivileged([ |
| 60 | { scheme: READER_SCHEME, privileges: { standard: true, secure: true } }, |
| 61 | { scheme: KEPT_SCHEME, privileges: { standard: true, secure: true } }, |
| 62 | ]); |
| 63 | const readerPages = new ReaderPages(); |
| 64 | |
| 65 | // Who we say we are to web servers: a Chromium-compatible UA with our own product token and a |
| 66 | // link back to dbbasic.com (see compat.ts for why, and why not "Firefox"). DBB_USER_AGENT |
| 67 | // overrides it entirely — handy for debugging a site that misbehaves. |
| 68 | const PRODUCT_VERSION = (() => { |
| 69 | try { |
| 70 | return (JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8")) as { version: string }).version; |
| 71 | } catch { |
| 72 | return "0.0.0"; |
| 73 | } |
| 74 | })(); |
| 75 | const USER_AGENT = |
| 76 | process.env.DBB_USER_AGENT || brandedUserAgent(app.userAgentFallback, { name: "dbbasic-browser", version: PRODUCT_VERSION, url: "https://dbbasic.com" }); |
| 77 | app.userAgentFallback = USER_AGENT; // must be set before the app is ready |
| 78 | |
| 79 | |
| 80 | // Load .env (the local hot-wallet key) so the browser signs with — and shows the |
| 81 | // balance of — the funded wallet, not the placeholder. Never overrides an existing env. |
| 82 | for (const p of [join(__dirname, "..", "..", "..", ".env"), join(process.cwd(), ".env")]) { |
| 83 | try { |
| 84 | for (const line of readFileSync(p, "utf8").split("\n")) { |
| 85 | const m = /^([A-Z0-9_]+)=(.*)$/.exec(line.trim()); |
| 86 | // Only the wallet's own settings. A .env in whatever folder the browser was started from must never be able to switch on |
| 87 | // the automation API, name an extension to load, or set anything else that changes what the browser does. |
| 88 | if (m && m[1] && /^X402_/.test(m[1]) && process.env[m[1]] === undefined) process.env[m[1]] = m[2]; |
| 89 | } |
| 90 | break; |
| 91 | } catch { |
| 92 | /* no .env here — fine */ |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // Falls back to the well-known public Anvil key (never fund THAT one) when no .env. |
| 97 | const TEST_KEY = (process.env.X402_PRIVATE_KEY ?? |
| 98 | "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") as `0x${string}`; |
| 99 | |
| 100 | // Base Sepolia USDC — read the wallet's on-chain balance (a free query, no gas, no key). |
| 101 | const USDC_SEPOLIA = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; |
| 102 | const BALANCE_ABI = [ |
| 103 | { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "a", type: "address" }], outputs: [{ type: "uint256" }] }, |
| 104 | ] as const; |
| 105 | const publicClient = createPublicClient({ |
| 106 | chain: baseSepolia, |
| 107 | transport: viemHttp(process.env.X402_RPC_URL || "https://sepolia.base.org"), |
| 108 | }); |
| 109 | |
| 110 | let mainWindow: BrowserWindow | null = null; |
| 111 | const account = privateKeyToAccount(TEST_KEY); // the wallet: signs payments AND is what we show the balance of |
| 112 | |
| 113 | const MERCHANT_ADDRESS = process.env.X402_MERCHANT_ADDRESS as `0x${string}` | undefined; |
| 114 | const MERCHANT_KEY = process.env.X402_MERCHANT_KEY as `0x${string}` | undefined; |
| 115 | const FACILITATOR = process.env.X402_FACILITATOR || "https://x402.org/facilitator"; |
| 116 | |
| 117 | /** |
| 118 | * Refund: the merchant wallet signs an EIP-3009 transfer of its whole balance back to |
| 119 | * the buyer and settles it through the facilitator. This closes the loop so testnet |
| 120 | * funds circulate instead of draining — pay, watch the merchant balance rise, refund, |
| 121 | * back to start. Uses global fetch (main-process; does NOT go through protocol.handle). |
| 122 | */ |
| 123 | async function refundMerchant(): Promise<{ tx?: string; error?: string }> { |
| 124 | if (callerNet.enabled) return { error: "switched off while the caller network is on" }; |
| 125 | if (!MERCHANT_KEY) return { error: "no merchant wallet configured" }; |
| 126 | const merchant = privateKeyToAccount(MERCHANT_KEY); |
| 127 | const balAtomic = (await publicClient.readContract({ address: USDC_SEPOLIA, abi: BALANCE_ABI, functionName: "balanceOf", args: [merchant.address] })) as bigint; |
| 128 | if (balAtomic <= 0n) return { error: "merchant balance is 0" }; |
| 129 | |
| 130 | const requirements = { |
| 131 | scheme: "exact", |
| 132 | network: "eip155:84532", |
| 133 | amount: balAtomic.toString(), |
| 134 | asset: USDC_SEPOLIA, |
| 135 | payTo: account.address, // back to the buyer |
| 136 | maxTimeoutSeconds: 120, |
| 137 | extra: { assetTransferMethod: "eip3009", name: "USDC", version: "2" }, |
| 138 | }; |
| 139 | const payload = await signExactEvm(merchant, { requirements, priceUsdMicro: balAtomic, assetSymbol: "USDC" }, { maxAuthorizationLifetimeSeconds: 120 }); |
| 140 | const res = await fetch(`${FACILITATOR}/settle`, { |
| 141 | method: "POST", |
| 142 | headers: { "content-type": "application/json" }, |
| 143 | body: JSON.stringify({ x402Version: 2, paymentPayload: payload, paymentRequirements: requirements }), |
| 144 | }); |
| 145 | const settle = (await res.json()) as { success?: boolean; transaction?: string; errorReason?: string }; |
| 146 | if (!settle.success) return { error: settle.errorReason || "settlement failed" }; |
| 147 | bumpBalance(); |
| 148 | return { tx: settle.transaction }; |
| 149 | } |
| 150 | |
| 151 | /** Format atomic USDC (6dp) showing at least 2 and up to 6 decimals — so $0.001 |
| 152 | * payments are visible instead of rounding to $0.00. */ |
| 153 | function fmtUsdc(atomic: bigint): string { |
| 154 | return (Number(atomic) / 1e6).toFixed(6).replace(/(\.\d{2}\d*?)0+$/, "$1"); |
| 155 | } |
| 156 | |
| 157 | async function usdcBalance(addr: `0x${string}`): Promise<string> { |
| 158 | const bal = (await publicClient.readContract({ address: USDC_SEPOLIA, abi: BALANCE_ABI, functionName: "balanceOf", args: [addr] })) as bigint; |
| 159 | return fmtUsdc(bal); |
| 160 | } |
| 161 | |
| 162 | /** Refresh now and again shortly after — on-chain balances settle a few seconds after |
| 163 | * a payment/refund, so a single immediate read often misses the change. */ |
| 164 | function bumpBalance(): void { |
| 165 | void refreshBalance(); |
| 166 | setTimeout(() => void refreshBalance(), 2500); |
| 167 | setTimeout(() => void refreshBalance(), 5500); |
| 168 | } |
| 169 | |
| 170 | /** Push both wallet balances (buyer + merchant) to the toolbar. A free RPC query. */ |
| 171 | async function refreshBalance(): Promise<void> { |
| 172 | // In caller-network mode the browser makes no request of its own, and this is one (an RPC query), so it is skipped. |
| 173 | if (callerNet.enabled) { |
| 174 | mainWindow?.webContents.send("x402:balance", { usdc: null, address: account.address, merchantUsdc: null, merchantAddress: MERCHANT_ADDRESS ?? null }); |
| 175 | return; |
| 176 | } |
| 177 | try { |
| 178 | const usdc = await usdcBalance(account.address); |
| 179 | const merchantUsdc = MERCHANT_ADDRESS ? await usdcBalance(MERCHANT_ADDRESS) : null; |
| 180 | mainWindow?.webContents.send("x402:balance", { usdc, address: account.address, merchantUsdc, merchantAddress: MERCHANT_ADDRESS ?? null }); |
| 181 | } catch { |
| 182 | mainWindow?.webContents.send("x402:balance", { usdc: null, address: account.address, merchantUsdc: null, merchantAddress: MERCHANT_ADDRESS ?? null }); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Every x402 event goes to the UI AND into a ring buffer the automation API can read, so |
| 188 | * a test can assert on exactly what the human-visible inspector shows. |
| 189 | */ |
| 190 | const eventLog: Array<Record<string, unknown>> = []; |
| 191 | let eventSeq = 0; |
| 192 | function emit(payload: Record<string, unknown>): void { |
| 193 | mainWindow?.webContents.send("x402:event", payload); |
| 194 | eventLog.push({ seq: ++eventSeq, at: Date.now(), ...payload }); |
| 195 | if (eventLog.length > 1000) eventLog.shift(); |
| 196 | } |
| 197 | |
| 198 | /** Who answers payment prompts. Default "ask" (native dialog); automation may relax it. */ |
| 199 | let approval: ApprovalPolicy = { mode: "ask", maxUsd: 0 }; |
| 200 | |
| 201 | // Main → chrome UI requests (tab operations only the UI can do), answered over IPC. |
| 202 | const chromeReqs = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>(); |
| 203 | let chromeReqSeq = 0; |
| 204 | function askChrome(op: string, args: Record<string, unknown>): Promise<unknown> { |
| 205 | return new Promise((resolve, reject) => { |
| 206 | if (!mainWindow) return reject(new Error("no window")); |
| 207 | const id = String(++chromeReqSeq); |
| 208 | const timer = setTimeout(() => { |
| 209 | chromeReqs.delete(id); |
| 210 | reject(new Error(`browser UI did not answer "${op}" in time`)); |
| 211 | }, 45_000); |
| 212 | chromeReqs.set(id, { resolve, reject, timer }); |
| 213 | mainWindow.webContents.send("ctl:req", { id, op, args }); |
| 214 | }); |
| 215 | } |
| 216 | |
| 217 | let control: ControlHandle | null = null; |
| 218 | /** Set once the MCP service exists: answers the redirect of a sign-in that is waiting for it inside this browser. */ |
| 219 | let mcpCapture: (url: string) => { status: number; html: string } | null = () => null; |
| 220 | /** Browsing history on the askrobots account (see history.ts); set once the connection exists. Tabs report to it. */ |
| 221 | let history: HistoryService | null = null; |
| 222 | /** The copy of that history kept here for the address bar (see history-copy.ts). */ |
| 223 | let historyCopy: HistoryCopy | null = null; |
| 224 | let favicons: FaviconStore | null = null; |
| 225 | /** The page's visible text and whether a password field shows, read in an isolated world the page cannot reach. */ |
| 226 | async function readForHistory(wc: Electron.WebContents): Promise<void> { |
| 227 | if (!history || wc.isDestroyed()) return; |
| 228 | const s = history.state(); |
| 229 | if (!s.on || s.paused) return; |
| 230 | const r = (await wc |
| 231 | .executeJavaScriptInIsolatedWorld(1009, [{ code: "({ u: location.href, t: document.body ? document.body.innerText : '', pw: [...document.querySelectorAll('input[type=password]')].some((e) => e.offsetParent !== null) })" }]) |
| 232 | .catch(() => null)) as { u?: string; t?: string; pw?: boolean } | null; |
| 233 | if (r && typeof r.u === "string") history.text(wc.id, r.u, String(r.t ?? ""), r.pw === true); |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Network policy that is not about a single request. WebSockets bypass our network layer (Chromium opens them |
| 238 | * itself), so the only way to keep a session to "no connection but the ones we decided on" is to refuse them |
| 239 | * before any connection is made. Off by default; DBB_BLOCK_WEBSOCKETS=1 or the automation API turns it on. |
| 240 | */ |
| 241 | const netPolicy = { blockWebSockets: process.env.DBB_BLOCK_WEBSOCKETS === "1" }; |
| 242 | /** A network layer the caller supplies (see provider.ts). Off until an automation caller turns it on. */ |
| 243 | const callerNet = new CallerNetwork(emitNet, nextNetId); |
| 244 | let desktopUserAgent = ""; |
| 245 | /** |
| 246 | * This mode clears stored data at every visit, so it must only ever run on a profile of its own: starting the app with an |
| 247 | * explicit --user-data-dir. Never the normal one, whose logins it would wipe. |
| 248 | */ |
| 249 | export const dedicatedProfile = (argv: readonly string[] = process.argv): boolean => argv.some((a) => a === "--user-data-dir" || a.startsWith("--user-data-dir=")); |
| 250 | /** Things the browser would do on its own that this mode must not: refuse them with a reason. */ |
| 251 | const refuseWhileCallerNet = (what: string): void => { |
| 252 | if (callerNet.enabled) throw new ProviderError("caller-network-on", `${what} is switched off while the caller network is on (the browser makes no request of its own and signs nothing)`); |
| 253 | }; |
| 254 | /** The per-visit cookie jar, kept in Chromium's own cookie store (see provider.ts). Off unless asked for. */ |
| 255 | let cookiesPerVisit = false; |
| 256 | const visitJar: CookieJar = { |
| 257 | on: () => cookiesPerVisit, |
| 258 | header: async (url) => (await session.defaultSession.cookies.get({ url })).map((c) => `${c.name}=${c.value}`).join("; "), |
| 259 | store: async (url, c) => { |
| 260 | try { |
| 261 | await session.defaultSession.cookies.set({ url, name: c.name, value: c.value, ...(c.domain ? { domain: c.domain } : {}), path: c.path, secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite, ...(c.expirationDate !== undefined ? { expirationDate: c.expirationDate } : {}) }); |
| 262 | } catch (e) { |
| 263 | console.error(`[cookies] refused ${c.name}: ${(e as Error).message}`); // a refusal by the cookie store (prefix, Secure on http, bad domain…) |
| 264 | throw e; |
| 265 | } |
| 266 | }, |
| 267 | }; |
| 268 | function configureCallerNet(p: { enabled?: unknown; userAgent?: unknown; answerTimeoutMs?: unknown; cookies?: unknown; limits?: unknown }): void { |
| 269 | if (p.limits !== undefined) { |
| 270 | const l = p.limits as { requests?: unknown; bytes?: unknown } | null; |
| 271 | const whole = (v: unknown, max: number, what: string) => { |
| 272 | if (v === undefined) return 0; |
| 273 | const n = Number(v); |
| 274 | if (!Number.isInteger(n) || n < 0 || n > max) throw new ProviderError("bad-params", `limits.${what} must be a whole number from 0 (no limit) to ${max}`); |
| 275 | return n; |
| 276 | }; |
| 277 | if (!l || typeof l !== "object") throw new ProviderError("bad-params", "limits must be an object: {requests?, bytes?}"); |
| 278 | callerNet.limits = { requests: whole(l.requests, 100_000, "requests"), bytes: whole(l.bytes, 2 ** 31, "bytes") }; |
| 279 | } |
| 280 | if (p.cookies !== undefined) { |
| 281 | if (p.cookies !== "off" && p.cookies !== "visit") throw new ProviderError("bad-params", 'cookies must be "off" (the default: none stored, none sent) or "visit" (kept for one visit only)'); |
| 282 | cookiesPerVisit = p.cookies === "visit"; |
| 283 | callerNet.jar = cookiesPerVisit ? visitJar : null; |
| 284 | } |
| 285 | if (p.answerTimeoutMs !== undefined) callerNet.answerTimeoutMs = clampAnswerTimeout(p.answerTimeoutMs); |
| 286 | if (p.enabled === true) { |
| 287 | // The caller's identity, always spelled out by the caller. The desktop browser's own identity is never lent to it. |
| 288 | const ua = String(p.userAgent ?? callerNet.userAgent).trim(); |
| 289 | if (!ua) throw new ProviderError("bad-params", "userAgent is required: this mode takes its identity from the caller"); |
| 290 | if (!dedicatedProfile()) throw new ProviderError("needs-dedicated-profile", "start the browser with --user-data-dir=<a folder of its own>: this mode clears stored data at every visit and must never run on your normal profile"); |
| 291 | if (process.env.DBB_NATIVE_NETWORK === "1") throw new ProviderError("native-network", "DBB_NATIVE_NETWORK=1 turns request interception off, so the caller would not see the requests; unset it"); |
| 292 | if (ua.length > 300 || !/^[ -~]+$/.test(ua)) throw new ProviderError("bad-params", "userAgent must be printable ASCII, at most 300 characters"); |
| 293 | if (/dbbasic-browser/i.test(ua)) throw new ProviderError("bad-params", "userAgent must be the caller's own, not the desktop browser's"); |
| 294 | if (!callerNet.enabled) desktopUserAgent = session.defaultSession.getUserAgent(); |
| 295 | callerNet.userAgent = ua; |
| 296 | callerNet.enabled = true; |
| 297 | session.defaultSession.setUserAgent(ua); |
| 298 | for (const wc of webContents.getAllWebContents()) { |
| 299 | if (wc.getType() !== "webview") continue; |
| 300 | wc.setUserAgent(ua); // pages that already exist keep the old one otherwise |
| 301 | wc.setWebRTCIPHandlingPolicy("disable_non_proxied_udp"); // WebRTC opens UDP connections the caller would never see |
| 302 | } |
| 303 | } else if (p.enabled === false && callerNet.enabled) { |
| 304 | callerNet.enabled = false; |
| 305 | callerNet.failAll("other", "the caller network was turned off"); |
| 306 | callerNet.limits = { requests: 0, bytes: 0 }; |
| 307 | cookiesPerVisit = false; |
| 308 | callerNet.jar = null; |
| 309 | void session.defaultSession.clearStorageData(); // leave nothing a caller-supplied page stored (the profile is a dedicated one) |
| 310 | if (desktopUserAgent) { |
| 311 | session.defaultSession.setUserAgent(desktopUserAgent); |
| 312 | for (const wc of webContents.getAllWebContents()) if (wc.getType() === "webview") { wc.setUserAgent(desktopUserAgent); wc.setWebRTCIPHandlingPolicy("default"); } |
| 313 | } |
| 314 | } else if (p.enabled !== undefined && typeof p.enabled !== "boolean") throw new ProviderError("bad-params", "enabled must be true or false"); |
| 315 | emit({ kind: "net-provider-changed", enabled: callerNet.enabled, answerTimeoutMs: callerNet.answerTimeoutMs }); |
| 316 | } |
| 317 | |
| 318 | // A site's icon, fetched by Chromium's own loader without cookies. It skips the browser's request handler on purpose: an |
| 319 | // icon never pays, never opens a sign-in, and is not one of the page's requests in the inspector. |
| 320 | async function fetchIcon(url: string): Promise<Fetched | null> { |
| 321 | const LIMIT = 512 * 1024; |
| 322 | const ac = new AbortController(); |
| 323 | const timer = setTimeout(() => ac.abort(), 8000); |
| 324 | try { |
| 325 | const r = await session.defaultSession.fetch(url, { signal: ac.signal, credentials: "omit", bypassCustomProtocolHandlers: true } as RequestInit); |
| 326 | if (!r.ok || Number(r.headers.get("content-length") || 0) > LIMIT) return null; |
| 327 | const bytes = new Uint8Array(await r.arrayBuffer()); |
| 328 | return bytes.length > LIMIT ? null : { bytes, type: r.headers.get("content-type") || "" }; |
| 329 | } catch { |
| 330 | return null; |
| 331 | } finally { |
| 332 | clearTimeout(timer); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | function setupNetPolicy(): void { |
| 337 | // Permission prompts (camera, location, notifications, …): refused while the caller network is on; otherwise unchanged (granted, as before). |
| 338 | session.defaultSession.setPermissionRequestHandler((_wc, permission, callback) => { |
| 339 | if (callerNet.enabled) emit({ kind: "permission-refused", permission }); |
| 340 | callback(!callerNet.enabled); |
| 341 | }); |
| 342 | session.defaultSession.setPermissionCheckHandler(() => !callerNet.enabled); |
| 343 | session.defaultSession.webRequest.onBeforeRequest({ urls: ["ws://*/*", "wss://*/*"] }, (details, callback) => { |
| 344 | // Always refused while the caller network is on: a WebSocket is a connection the caller never sees. |
| 345 | const refuse = netPolicy.blockWebSockets || callerNet.enabled; |
| 346 | if (refuse) emit({ kind: "websocket-refused", url: details.url }); |
| 347 | callback({ cancel: refuse }); // cancelled before any connection is opened |
| 348 | }); |
| 349 | } |
| 350 | |
| 351 | // ---- downloads ----------------------------------------------------------------------------------- |
| 352 | // Chromium already neutralizes hostile filenames and shows the native Save dialog; what was missing was |
| 353 | // any sign of progress, completion or failure. This tracks each download, announces it to the UI and the |
| 354 | // automation event log, and links paid downloads to the x402 payment that unlocked them. |
| 355 | // DBB_DOWNLOAD_DIR skips the dialog and saves there (scripted runs and tests, so nothing blocks). |
| 356 | interface DownloadRecord { |
| 357 | id: number; |
| 358 | name: string; |
| 359 | host: string; |
| 360 | total: number; |
| 361 | received: number; |
| 362 | state: "progressing" | "paused" | "completed" | "cancelled" | "interrupted"; |
| 363 | path: string; |
| 364 | /** The x402 amount paid for this URL just before the download started, e.g. "$0.001". */ |
| 365 | paid?: string; |
| 366 | /** macOS: whether the file was marked as downloaded from the internet (so Gatekeeper vets it). */ |
| 367 | quarantined?: boolean; |
| 368 | startedAt: number; |
| 369 | } |
| 370 | const downloads = new Map<number, DownloadRecord>(); |
| 371 | let downloadSeq = 0; |
| 372 | |
| 373 | /** A file name that is safe to create: no directories, no control or reserved characters, no leading dots. */ |
| 374 | export function cleanFileName(name: string): string { |
| 375 | const n = basename(String(name).replace(/\\/g, "/")) |
| 376 | .replace(/[\u0000-\u001f<>:"|?*]/g, "_") |
| 377 | .replace(/^\.+/, "_") |
| 378 | .trim() |
| 379 | .slice(0, 180); |
| 380 | return n || "download"; |
| 381 | } |
| 382 | |
| 383 | function uniquePath(dir: string, name: string): string { |
| 384 | const ext = extname(name); |
| 385 | const stem = name.slice(0, name.length - ext.length); |
| 386 | let candidate = join(dir, name); |
| 387 | for (let i = 1; existsSync(candidate) && i < 1000; i++) candidate = join(dir, `${stem} (${i})${ext}`); |
| 388 | return candidate; |
| 389 | } |
| 390 | |
| 391 | /** |
| 392 | * Mark a downloaded file as coming from the internet. Electron does not do this for us, and without |
| 393 | * `com.apple.quarantine` macOS Gatekeeper never vets a downloaded app, installer or script — every mainstream |
| 394 | * browser sets it. Format: flags;timestamp-hex;agent;event-uuid (0083 = a web download, like Chrome's). |
| 395 | */ |
| 396 | function quarantine(path: string): Promise<boolean> { |
| 397 | if (process.platform !== "darwin") return Promise.resolve(false); |
| 398 | const value = `0083;${Math.floor(Date.now() / 1000).toString(16)};dbbasic-browser;${randomUUID().toUpperCase()}`; |
| 399 | return new Promise((resolve) => execFile("/usr/bin/xattr", ["-w", "com.apple.quarantine", value, path], (err) => resolve(!err))); |
| 400 | } |
| 401 | |
| 402 | function paidFor(url: string): string | undefined { |
| 403 | const bare = url.split("#")[0]; |
| 404 | for (let i = eventLog.length - 1; i >= 0 && i > eventLog.length - 300; i--) { |
| 405 | const e = eventLog[i]!; |
| 406 | if (e.kind === "paid" && Date.now() - (e.at as number) < 120_000 && (e.resource === bare || e.requested === bare)) return String(e.amount); |
| 407 | } |
| 408 | return undefined; |
| 409 | } |
| 410 | |
| 411 | // ---- the right-click menu (which items: context-menu.ts) ---------------------------------------------- |
| 412 | /** The menu shown last, so the automation API can read it and pick an item (in background mode it is not shown at all). */ |
| 413 | let lastMenu: { wcId: number; items: MenuItem[]; run: (id: string) => boolean } | null = null; |
| 414 | |
| 415 | function showContextMenu(wc: WebContents, p: Electron.ContextMenuParams, page: boolean): void { |
| 416 | const items = contextMenuItems(p, { |
| 417 | page, |
| 418 | canGoBack: wc.navigationHistory.canGoBack(), |
| 419 | canGoForward: wc.navigationHistory.canGoForward(), |
| 420 | newTabs: !callerNet.enabled, |
| 421 | }); |
| 422 | if (!items.length) return; |
| 423 | const offered = new Set(items.flatMap((it) => ("id" in it && it.enabled !== false ? [it.id] : []))); |
| 424 | const run = (id: string) => { |
| 425 | if (!offered.has(id)) return false; |
| 426 | runMenuItem(wc, p, id); |
| 427 | return true; |
| 428 | }; |
| 429 | lastMenu = { wcId: wc.id, items, run }; |
| 430 | // A scripted run in the background must not put a menu on someone's screen: it is recorded instead (as it is for the |
| 431 | // end-to-end suite, DBB_RECORD_MENUS=1, which picks items through the automation API). |
| 432 | if (background || process.env.DBB_RECORD_MENUS === "1") { |
| 433 | emit({ kind: "context-menu", wcId: wc.id, items: [...offered] }); |
| 434 | return; |
| 435 | } |
| 436 | Menu.buildFromTemplate(items.map((it): MenuItemConstructorOptions => ("id" in it ? { label: it.label, enabled: it.enabled !== false, click: () => run(it.id) } : { type: "separator" }))) |
| 437 | .popup({ window: mainWindow ?? undefined }); |
| 438 | } |
| 439 | |
| 440 | function runMenuItem(wc: WebContents, p: Electron.ContextMenuParams, id: string): void { |
| 441 | if (wc.isDestroyed()) return; |
| 442 | const web = (u: string) => /^https?:\/\//i.test(u); |
| 443 | const newTab = (url: string) => { if (web(url) && !callerNet.enabled) mainWindow?.webContents.send("tab:open", url, { background: true }); }; |
| 444 | const text = (p.selectionText || "").trim(); |
| 445 | if (id.startsWith("spell:")) { |
| 446 | const w = p.dictionarySuggestions?.[Number(id.slice(6))]; |
| 447 | if (w) wc.replaceMisspelling(w); |
| 448 | return; |
| 449 | } |
| 450 | switch (id) { |
| 451 | case "open-link-tab": return newTab(p.linkURL); |
| 452 | case "copy-link": return void clipboard.writeText(p.linkURL); |
| 453 | case "open-image-tab": return newTab(p.srcURL); |
| 454 | case "copy-image": return wc.copyImageAt(p.x, p.y); |
| 455 | case "copy-image-address": return void clipboard.writeText(p.srcURL); |
| 456 | case "save-image": return web(p.srcURL) ? wc.downloadURL(p.srcURL) : undefined; |
| 457 | case "undo": return wc.undo(); |
| 458 | case "redo": return wc.redo(); |
| 459 | case "cut": return wc.cut(); |
| 460 | case "copy": return wc.copy(); |
| 461 | case "paste": return wc.paste(); |
| 462 | case "select-all": return wc.selectAll(); |
| 463 | // The chrome knows the search address and owns the chat: it does these two. |
| 464 | case "search-selection": |
| 465 | case "ask-selection": return void mainWindow?.webContents.send("ctx:action", { id, text }); |
| 466 | case "back": return wc.navigationHistory.goBack(); |
| 467 | case "forward": return wc.navigationHistory.goForward(); |
| 468 | case "reload": return wc.reload(); |
| 469 | case "inspect": return wc.inspectElement(p.x, p.y); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | function setupDownloads(): void { |
| 474 | session.defaultSession.on("will-download", (_event, item, sourceContents) => { |
| 475 | if (sourceContents) noteDownload(sourceContents.id, item.getFilename()); |
| 476 | // In caller-network mode nothing is written to disk: a download is refused, and the verdict still says the address was a download. |
| 477 | if (callerNet.enabled) { |
| 478 | item.cancel(); |
| 479 | emit({ kind: "download-refused", name: cleanFileName(item.getFilename()) }); |
| 480 | return; |
| 481 | } |
| 482 | const id = ++downloadSeq; |
| 483 | let host = ""; |
| 484 | try { |
| 485 | host = new URL(item.getURL()).host; |
| 486 | } catch { |
| 487 | /* data: or blob: URL */ |
| 488 | } |
| 489 | const rec: DownloadRecord = { id, name: cleanFileName(item.getFilename()), host, total: item.getTotalBytes(), received: 0, state: "progressing", path: "", startedAt: Date.now() }; |
| 490 | const paid = paidFor(item.getURL()); |
| 491 | if (paid) rec.paid = paid; |
| 492 | const dir = process.env.DBB_DOWNLOAD_DIR; |
| 493 | if (dir) { |
| 494 | mkdirSync(dir, { recursive: true }); |
| 495 | rec.path = uniquePath(dir, rec.name); |
| 496 | item.setSavePath(rec.path); |
| 497 | } |
| 498 | downloads.set(id, rec); |
| 499 | const announce = () => emit({ kind: "download", ...rec }); |
| 500 | announce(); |
| 501 | let last = 0; |
| 502 | item.on("updated", (_e, state) => { |
| 503 | rec.received = item.getReceivedBytes(); |
| 504 | rec.total = item.getTotalBytes(); |
| 505 | rec.state = state === "interrupted" ? "interrupted" : item.isPaused() ? "paused" : "progressing"; |
| 506 | const now = Date.now(); |
| 507 | if (now - last > 150 || state === "interrupted") { |
| 508 | last = now; |
| 509 | announce(); |
| 510 | } |
| 511 | }); |
| 512 | item.once("done", (_e, state) => { |
| 513 | rec.received = item.getReceivedBytes(); |
| 514 | rec.total = item.getTotalBytes() || rec.received; |
| 515 | rec.path = item.getSavePath() || rec.path; // the path the user chose in the Save dialog |
| 516 | if (state === "completed" && rec.path) { |
| 517 | // The download only counts as completed once it is quarantined, and the state and the announcement change |
| 518 | // together — so nothing (UI, automation, a person) is told "done" before the file is marked. |
| 519 | void quarantine(rec.path).then((ok) => { |
| 520 | rec.quarantined = ok; |
| 521 | rec.state = "completed"; |
| 522 | announce(); |
| 523 | }); |
| 524 | } else { |
| 525 | rec.state = state === "interrupted" ? "interrupted" : "cancelled"; |
| 526 | announce(); |
| 527 | } |
| 528 | }); |
| 529 | }); |
| 530 | } |
| 531 | |
| 532 | function showLastDownload(): void { |
| 533 | const done = [...downloads.values()].filter((d) => d.state === "completed" && d.path).pop(); |
| 534 | if (done) shell.showItemInFolder(done.path); |
| 535 | else void shell.openPath(app.getPath("downloads")); |
| 536 | } |
| 537 | |
| 538 | function buildEngine(): X402Engine { |
| 539 | const policy = new PolicyEngine(); |
| 540 | const ledger = new Ledger(); |
| 541 | |
| 542 | // The engine's network calls go through netRequestFetch (see transport.ts): it never follows |
| 543 | // redirects itself — it returns 3xx to the renderer so URL/origin stay truthful — and, being |
| 544 | // net.request, it is not routed back into our own protocol.handle handler. |
| 545 | const nativeFetch = netRequestFetch(); |
| 546 | // In "caller network" mode (provider.ts) the browser makes no request of its own: the caller answers each one. |
| 547 | const rawFetch: RawFetch = (req) => (callerNet.enabled || callerNet.hasDocumentFor(req.url) ? callerNet.fetch(req) : nativeFetch(req)); |
| 548 | |
| 549 | return new X402Engine({ |
| 550 | account, |
| 551 | policy, |
| 552 | ledger, |
| 553 | fetchImpl: rawFetch as typeof fetch, |
| 554 | approve: async ({ quote, resourceUrl, reason }) => { |
| 555 | // A payment is a signature from the wallet; in caller-network mode the only party that asked is a caller's answer. |
| 556 | if (callerNet.enabled) { |
| 557 | emit({ kind: "auto-decision", resource: resourceUrl, approved: false, price: formatUsd(quote.priceUsdMicro), mode: "caller-network", cap: 0 }); |
| 558 | return false; |
| 559 | } |
| 560 | // Automation may pre-decide — but never silently: every such decision is an event |
| 561 | // (toast + inspector + the API's event log), and policy hard caps still apply |
| 562 | // because we are only ever asked about payments the policy already allowed to prompt. |
| 563 | if (approval.mode !== "ask") { |
| 564 | const usd = Number(quote.priceUsdMicro) / 1e6; |
| 565 | const yes = approval.mode === "auto" && usd <= approval.maxUsd; |
| 566 | emit({ kind: "auto-decision", resource: resourceUrl, approved: yes, price: formatUsd(quote.priceUsdMicro), mode: approval.mode, cap: approval.maxUsd }); |
| 567 | return yes; |
| 568 | } |
| 569 | // Native modal — the price is shown to the user before a signature is produced. |
| 570 | const { response } = await dialog.showMessageBox(mainWindow ?? undefined!, { |
| 571 | type: "question", |
| 572 | buttons: ["Pay", "Cancel"], |
| 573 | defaultId: 0, |
| 574 | cancelId: 1, |
| 575 | title: "Payment required", |
| 576 | message: `Pay ${formatUsd(quote.priceUsdMicro)} ${quote.assetSymbol}?`, |
| 577 | detail: `${resourceUrl}\n\n${reason}`, |
| 578 | }); |
| 579 | return response === 0; |
| 580 | }, |
| 581 | onEvent: (e) => { |
| 582 | // One structured event stream drives both the toolbar (meter/toasts) and the |
| 583 | // per-tab inspector. All bigints are pre-formatted so IPC stays plain JSON. |
| 584 | const send = emit; |
| 585 | |
| 586 | if (e.type === "quoted") { |
| 587 | // Price-before-paying: the 402 is free, so we can report cost before paying. |
| 588 | send({ |
| 589 | kind: "quoted", |
| 590 | resource: e.resourceUrl, |
| 591 | quotes: e.quotes.map((q) => ({ |
| 592 | scheme: q.requirements.scheme, |
| 593 | network: q.requirements.network, |
| 594 | asset: q.assetSymbol, |
| 595 | assetAddress: q.requirements.asset, |
| 596 | amountAtomic: q.requirements.amount, |
| 597 | price: formatUsd(q.priceUsdMicro), |
| 598 | payTo: q.requirements.payTo, |
| 599 | maxTimeoutSeconds: q.requirements.maxTimeoutSeconds, |
| 600 | })), |
| 601 | rejected: e.rejected, |
| 602 | }); |
| 603 | } else if (e.type === "decided") { |
| 604 | send({ |
| 605 | kind: "decided", |
| 606 | resource: e.resourceUrl, |
| 607 | action: e.verdict.action, // allow | prompt | deny |
| 608 | reason: e.verdict.reason, |
| 609 | price: formatUsd(e.quote.priceUsdMicro), |
| 610 | asset: e.quote.assetSymbol, |
| 611 | }); |
| 612 | } else if (e.type === "paid") { |
| 613 | const r = e.receipt; |
| 614 | send({ |
| 615 | kind: "paid", |
| 616 | resource: r.resourceUrl, |
| 617 | requested: r.requestedUrl, |
| 618 | amount: formatUsd(r.priceUsdMicro), |
| 619 | asset: r.assetSymbol, |
| 620 | dest: r.destOrigin, |
| 621 | network: r.network, |
| 622 | payTo: r.payTo, |
| 623 | nonce: r.nonce, |
| 624 | validBefore: r.validBefore, |
| 625 | auth: r.authorization |
| 626 | ? { |
| 627 | from: r.authorization.from, |
| 628 | to: r.authorization.to, |
| 629 | value: r.authorization.value, |
| 630 | validAfter: r.authorization.validAfter, |
| 631 | validBefore: r.authorization.validBefore, |
| 632 | } |
| 633 | : null, |
| 634 | signature: r.signature ?? null, |
| 635 | status: r.status, |
| 636 | tx: r.txHash ?? null, |
| 637 | totalSpent: formatUsd(policy.spentUsdMicro()), |
| 638 | }); |
| 639 | bumpBalance(); // a real (live-route) payment changes the on-chain balances |
| 640 | } else if (e.type === "skipped") { |
| 641 | send({ kind: "skipped", resource: e.resourceUrl, reason: e.reason }); |
| 642 | } |
| 643 | }, |
| 644 | }); |
| 645 | } |
| 646 | |
| 647 | /** Open the built-in help page (optionally at an anchor) in a new tab. */ |
| 648 | function openHelp(anchor: string): void { |
| 649 | const url = pathToFileURL(join(__dirname, "help.html")).href + (anchor ? `#${anchor}` : ""); |
| 650 | mainWindow?.webContents.send("tab:open", url); |
| 651 | } |
| 652 | |
| 653 | /** Loading-animation preference. The chrome UI owns it (localStorage); we only mirror it for the menu's radio check. */ |
| 654 | let motionPref: "always" | "system" | "never" = "system"; |
| 655 | |
| 656 | /** |
| 657 | * AI Reader provider/model. Keys come from the environment or a private file outside the repo |
| 658 | * (see ai-config.ts); they never leave this process. Anthropic is the default provider. |
| 659 | */ |
| 660 | const aiLoaded = loadAiEnv(); |
| 661 | let aiCfg: AiConfig | null = resolveAi(aiLoaded); |
| 662 | function setAiProvider(p: Provider): boolean { |
| 663 | if (!aiCfg?.available.includes(p)) return false; |
| 664 | aiCfg = resolveAi({ ...aiLoaded, values: { ...aiLoaded.values, DBB_AI_PROVIDER: p } }); |
| 665 | buildMenu(); |
| 666 | emit({ kind: "ai-provider", provider: aiCfg?.provider, model: aiCfg?.model }); |
| 667 | return true; |
| 668 | } |
| 669 | |
| 670 | /** Tell the chrome UI to do a tab action (new/close/focus-url/next/prev/reload). */ |
| 671 | const tabCmd = (cmd: string) => () => mainWindow?.webContents.send("tab:cmd", cmd); |
| 672 | |
| 673 | /** |
| 674 | * App menu. Tab shortcuts live here as accelerators rather than keydown handlers in the |
| 675 | * chrome document: once a page has focus, its <webview> swallows key events, but menu |
| 676 | * accelerators still fire. Reload targets the active TAB — Electron's default View►Reload |
| 677 | * would reload the chrome itself and wipe every open tab. |
| 678 | */ |
| 679 | function buildMenu(): void { |
| 680 | const template: MenuItemConstructorOptions[] = [ |
| 681 | ...(process.platform === "darwin" ? [{ role: "appMenu" } as MenuItemConstructorOptions] : []), |
| 682 | { |
| 683 | label: "File", |
| 684 | submenu: [ |
| 685 | { label: "New Tab", accelerator: "CmdOrCtrl+T", click: tabCmd("new") }, |
| 686 | // There is one window, so ⌘N opens a tab, as people expect from it (a separate window is a task of its own). |
| 687 | { label: "New Tab (⌘N)", accelerator: "CmdOrCtrl+N", click: tabCmd("new"), visible: false }, |
| 688 | { label: "Close Tab", accelerator: "CmdOrCtrl+W", click: tabCmd("close") }, |
| 689 | { label: "Open Location", accelerator: "CmdOrCtrl+L", click: tabCmd("focus-url") }, |
| 690 | // Escape hatch for sites that refuse embedded-Chromium browsers (see Help ▸ How we identify ourselves). |
| 691 | { label: "Open Page in Default Browser", accelerator: "CmdOrCtrl+Shift+O", click: tabCmd("open-external") }, |
| 692 | { type: "separator" }, |
| 693 | { label: "Show Last Download in Finder", click: () => showLastDownload() }, |
| 694 | { label: "Show Downloads Folder", click: () => void shell.openPath(app.getPath("downloads")) }, |
| 695 | { label: "Next Tab (alt)", accelerator: "CmdOrCtrl+Alt+Right", click: tabCmd("next"), visible: false }, |
| 696 | { label: "Previous Tab (alt)", accelerator: "CmdOrCtrl+Alt+Left", click: tabCmd("prev"), visible: false }, |
| 697 | // ⌘⇧] and ⌘⇧[, as in Safari and Chrome. Some keyboard layouts report the shifted key as } and {, so both are listened for. |
| 698 | { label: "Next Tab (⌘⇧])", accelerator: "CmdOrCtrl+Shift+]", click: tabCmd("next"), visible: false }, |
| 699 | { label: "Previous Tab (⌘⇧[)", accelerator: "CmdOrCtrl+Shift+[", click: tabCmd("prev"), visible: false }, |
| 700 | { label: "Next Tab (⌘})", accelerator: "CmdOrCtrl+}", click: tabCmd("next"), visible: false }, |
| 701 | { label: "Previous Tab (⌘{)", accelerator: "CmdOrCtrl+{", click: tabCmd("prev"), visible: false }, |
| 702 | // ⌘1 to ⌘8 go to that tab, ⌘9 to the last one. |
| 703 | ...[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => ({ label: n === 9 ? "Last Tab" : `Tab ${n}`, accelerator: `CmdOrCtrl+${n}`, click: tabCmd(`tab:${n}`), visible: false })), |
| 704 | ], |
| 705 | }, |
| 706 | { |
| 707 | label: "Edit", |
| 708 | submenu: [ |
| 709 | { role: "undo" }, |
| 710 | { role: "redo" }, |
| 711 | { type: "separator" }, |
| 712 | { role: "cut" }, |
| 713 | { role: "copy" }, |
| 714 | { role: "paste" }, |
| 715 | { role: "pasteAndMatchStyle" }, |
| 716 | { role: "delete" }, |
| 717 | { role: "selectAll" }, |
| 718 | { type: "separator" }, |
| 719 | // Find uses the page's own find: nothing leaves the machine. ⌘F goes to the page first, so a site with its own |
| 720 | // find (an editor, a document) keeps it; the menu item always opens the browser's. |
| 721 | { label: "Find…", accelerator: "CmdOrCtrl+F", click: tabCmd("find") }, |
| 722 | { label: "Find Next", accelerator: "CmdOrCtrl+G", click: tabCmd("find-next") }, |
| 723 | { label: "Find Previous", accelerator: "CmdOrCtrl+Shift+G", click: tabCmd("find-prev") }, |
| 724 | ], |
| 725 | }, |
| 726 | { |
| 727 | label: "View", |
| 728 | submenu: [ |
| 729 | { label: "Reload Page", accelerator: "CmdOrCtrl+R", click: tabCmd("reload") }, |
| 730 | { |
| 731 | label: "Loading Animations", |
| 732 | submenu: [ |
| 733 | { label: "Always", type: "radio", checked: motionPref === "always", click: tabCmd("motion:always") }, |
| 734 | { label: "Follow System “Reduce Motion”", type: "radio", checked: motionPref === "system", click: tabCmd("motion:system") }, |
| 735 | { label: "Never", type: "radio", checked: motionPref === "never", click: tabCmd("motion:never") }, |
| 736 | ], |
| 737 | }, |
| 738 | { type: "separator" }, |
| 739 | { label: "AI Reader", accelerator: "CmdOrCtrl+Shift+R", click: tabCmd("reader") }, |
| 740 | { label: "Assistant chat", accelerator: "CmdOrCtrl+J", click: tabCmd("chat") }, |
| 741 | { label: "x402 Inspector", click: tabCmd("click:inspectBtn") }, |
| 742 | { label: "What the Browser Is Using (Memory, CPU, Data)", click: tabCmd("click:resBtn") }, |
| 743 | { |
| 744 | label: "AI Provider", |
| 745 | enabled: !!aiCfg, |
| 746 | submenu: aiCfg |
| 747 | ? [ |
| 748 | ...(["anthropic", "openai"] as const).map((p) => ({ |
| 749 | label: p === "anthropic" ? "Anthropic" : "OpenAI", |
| 750 | type: "radio" as const, |
| 751 | enabled: aiCfg!.available.includes(p), |
| 752 | checked: aiCfg!.provider === p, |
| 753 | click: () => void setAiProvider(p), |
| 754 | })), |
| 755 | { type: "separator" as const }, |
| 756 | { label: `Model: ${aiCfg.model}`, enabled: false }, |
| 757 | ] |
| 758 | : [{ label: "No API key found — see Help ▸ AI Reader", enabled: false }], |
| 759 | }, |
| 760 | { type: "separator" }, |
| 761 | { role: "toggleDevTools" }, |
| 762 | { type: "separator" }, |
| 763 | { role: "togglefullscreen" }, |
| 764 | ], |
| 765 | }, |
| 766 | { |
| 767 | label: "Go", |
| 768 | submenu: [ |
| 769 | { label: "Back", accelerator: "CmdOrCtrl+[", click: tabCmd("back") }, |
| 770 | { label: "Forward", accelerator: "CmdOrCtrl+]", click: tabCmd("forward") }, |
| 771 | { type: "separator" }, |
| 772 | { label: "Next Tab", accelerator: "Ctrl+Tab", click: tabCmd("next") }, |
| 773 | { label: "Previous Tab", accelerator: "Ctrl+Shift+Tab", click: tabCmd("prev") }, |
| 774 | ], |
| 775 | }, |
| 776 | { |
| 777 | label: "Bookmarks", |
| 778 | submenu: [ |
| 779 | { label: "Save This Page to askrobots", accelerator: "CmdOrCtrl+D", click: tabCmd("click:starBtn") }, |
| 780 | { label: "Show Bookmarks", accelerator: "CmdOrCtrl+Shift+B", click: tabCmd("click:bmBtn") }, |
| 781 | { type: "separator" }, |
| 782 | { label: "Keep This Page and Close It", click: tabCmd("click:keepBtn") }, |
| 783 | { label: "Show Kept Copies", click: tabCmd("kept") }, |
| 784 | ], |
| 785 | }, |
| 786 | { |
| 787 | label: "History", |
| 788 | submenu: [ |
| 789 | { label: "Show History (askrobots.com)", accelerator: "CmdOrCtrl+Y", click: tabCmd("history:open") }, |
| 790 | { label: "Pause or Resume Recording", click: tabCmd("history:pause") }, |
| 791 | { type: "separator" }, |
| 792 | { label: "Forget This Page…", click: tabCmd("history:forget-url") }, |
| 793 | { label: "Forget This Site…", click: tabCmd("history:forget-site") }, |
| 794 | { label: "Forget the Last Hour…", click: tabCmd("history:forget-hour") }, |
| 795 | { label: "Never Record This Site", click: tabCmd("history:never") }, |
| 796 | ], |
| 797 | }, |
| 798 | { |
| 799 | label: "Tools", |
| 800 | submenu: [ |
| 801 | { label: "Passwords…", click: tabCmd("click:keyBtn") }, |
| 802 | { label: "Connections (askrobots and other services)…", click: tabCmd("connections") }, |
| 803 | { type: "separator" }, |
| 804 | { label: "Wallet: Copy Address and Get Test Funds", click: tabCmd("click:fundBtn") }, |
| 805 | { type: "separator" }, |
| 806 | { label: "x402 Test Gallery (local)", click: tabCmd("click:galleryBtn") }, |
| 807 | { label: "Tour of the Test Gallery", click: tabCmd("click:tourBtn") }, |
| 808 | ], |
| 809 | }, |
| 810 | { role: "windowMenu" }, |
| 811 | { |
| 812 | role: "help", |
| 813 | submenu: [ |
| 814 | { label: "dbbasic-browser Help", accelerator: "F1", click: () => openHelp("") }, |
| 815 | { label: "Keyboard Shortcuts", click: () => openHelp("shortcuts") }, |
| 816 | { label: "x402 Payments", click: () => openHelp("x402") }, |
| 817 | { label: "x402 Demo Gallery (local)", click: () => mainWindow?.webContents.send("tab:open", "http://127.0.0.1:8899/") }, |
| 818 | { label: "Password Manager", click: () => openHelp("passwords") }, |
| 819 | { label: "Automation API", click: () => openHelp("automation") }, |
| 820 | { type: "separator" }, |
| 821 | { |
| 822 | label: control ? `Automation API: on (127.0.0.1:${control.port})` : "Automation API: off — launch with DBB_CONTROL=1", |
| 823 | enabled: false, |
| 824 | }, |
| 825 | { type: "separator" }, |
| 826 | { label: "Report an Issue…", click: () => void shell.openExternal("https://github.com/askrobots/dbbasic-browser/issues/new") }, |
| 827 | { label: "Project on GitHub", click: () => void shell.openExternal("https://github.com/askrobots/dbbasic-browser") }, |
| 828 | ], |
| 829 | }, |
| 830 | ]; |
| 831 | Menu.setApplicationMenu(Menu.buildFromTemplate(template)); |
| 832 | } |
| 833 | |
| 834 | /** |
| 835 | * DBB_BACKGROUND=1: automation that never takes the screen. The window is created off-screen and shown WITHOUT taking focus |
| 836 | * (an off-screen window is still drawn, unlike a hidden or minimized one, so pages, captures and input keep working), the app |
| 837 | * stays out of the Dock, and nothing raises or focuses it afterwards. Meant for scripted runs on a machine someone is using. |
| 838 | */ |
| 839 | const background = process.env.DBB_BACKGROUND === "1"; |
| 840 | |
| 841 | function createWindow(): void { |
| 842 | mainWindow = new BrowserWindow({ |
| 843 | width: 1280, |
| 844 | height: 860, |
| 845 | ...(background ? { show: false } : {}), |
| 846 | title: "dbbasic-browser", |
| 847 | icon: ICON_PATH, |
| 848 | webPreferences: { |
| 849 | preload: join(__dirname, "preload.cjs"), |
| 850 | webviewTag: true, // the page renders in a <webview>; chrome is the host document |
| 851 | contextIsolation: true, |
| 852 | nodeIntegration: false, |
| 853 | additionalArguments: [ |
| 854 | `--homepage=${process.env.HOMEPAGE ?? "https://askrobots.com/"}`, |
| 855 | `--webview-preload=${pathToFileURL(join(__dirname, "webview-preload.cjs")).href}`, |
| 856 | ], |
| 857 | }, |
| 858 | }); |
| 859 | mainWindow.loadFile(join(__dirname, "chrome.html")); |
| 860 | // The browser's own fields (the address bar, the chat box) get the text items of the right-click menu. |
| 861 | mainWindow.webContents.on("context-menu", (_e, p) => { if (mainWindow) showContextMenu(mainWindow.webContents, p, false); }); |
| 862 | if (background) { |
| 863 | if (process.platform === "darwin") app.dock?.hide(); |
| 864 | // Shown first and moved afterwards: macOS clamps a window back onto the screen when it is created or first shown there, |
| 865 | // but lets a window that is already shown be moved off it. (An off-screen window is still drawn; a hidden one is not.) |
| 866 | mainWindow.once("ready-to-show", () => { |
| 867 | mainWindow?.showInactive(); |
| 868 | mainWindow?.setPosition(-20000, -20000); |
| 869 | // macOS keeps a sliver of the window on screen. Make that invisible and untouchable too; the page is still drawn. |
| 870 | mainWindow?.setOpacity(0); |
| 871 | mainWindow?.setIgnoreMouseEvents(true); |
| 872 | }); |
| 873 | } |
| 874 | mainWindow.on("closed", () => (mainWindow = null)); |
| 875 | } |
| 876 | |
| 877 | app.whenReady().then(async () => { |
| 878 | // Chrome's Accept-Language shape ("en-US,en;q=0.9"), not the bare locale the session defaults to. |
| 879 | const locale = app.getLocale() || "en-US"; |
| 880 | // DBB_CALLER_NETWORK_USER_AGENT=<identity> starts with the caller-supplied network layer already ON, before any page is |
| 881 | // created, so not even the first tab is fetched by the browser itself. (Same rules as net.provider: the identity is the caller's.) |
| 882 | const startWithCaller = process.env.DBB_CALLER_NETWORK_USER_AGENT; |
| 883 | session.defaultSession.setUserAgent(USER_AGENT, locale.includes("-") ? `${locale},${locale.split("-")[0]}` : locale); // Chromium adds the q-values itself |
| 884 | if (startWithCaller) { |
| 885 | try { |
| 886 | configureCallerNet({ enabled: true, userAgent: startWithCaller }); |
| 887 | } catch (e) { |
| 888 | console.error(`[net] DBB_CALLER_NETWORK_USER_AGENT refused: ${(e as Error).message}`); |
| 889 | app.exit(2); |
| 890 | return; |
| 891 | } |
| 892 | } |
| 893 | if (process.platform === "darwin") { |
| 894 | const img = nativeImage.createFromPath(ICON_PATH); |
| 895 | if (!img.isEmpty()) app.dock?.setIcon(img); |
| 896 | } |
| 897 | const engine = buildEngine(); |
| 898 | |
| 899 | // Take over https AND http. From here, every request the browser makes is |
| 900 | // paid-aware. x402 works over plain http too (the spec is transport-agnostic), and |
| 901 | // it's what lets a local http demo exercise the same path as a real https site. |
| 902 | const payHandler = createPaymentHandler(engine); |
| 903 | // DBB_NATIVE_NETWORK=1 turns interception OFF so Chromium's own loader makes every request — |
| 904 | // no x402 payments, but handy for telling "our transport" apart from "the site" when debugging. |
| 905 | if (process.env.DBB_NATIVE_NETWORK === "1") { |
| 906 | console.error("[net] DBB_NATIVE_NETWORK=1 — request interception (and x402 payments) disabled"); |
| 907 | } else { |
| 908 | // A sign-in that is waiting for its redirect inside this browser (see mcp-service.ts) is answered here, without any request. |
| 909 | const withSignInRedirect = (h: (r: Request) => Promise<Response>) => async (request: Request): Promise<Response> => { |
| 910 | const caught = request.method === "GET" ? mcpCapture(request.url) : null; |
| 911 | return caught ? new Response(caught.html, { status: caught.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }) : h(request); |
| 912 | }; |
| 913 | protocol.handle("https", withSignInRedirect(payHandler)); |
| 914 | protocol.handle("http", withSignInRedirect(payHandler)); |
| 915 | } |
| 916 | |
| 917 | ipcMain.handle("x402:receipts", () => engine.ledger.all()); |
| 918 | ipcMain.handle("x402:spent", () => formatUsd(engine.policy.spentUsdMicro())); |
| 919 | ipcMain.handle("x402:wallet", () => ({ address: account.address })); |
| 920 | ipcMain.handle("x402:copy", (_e, text: string) => clipboard.writeText(String(text))); |
| 921 | // Open the funding faucet in the OS browser with the address already on the clipboard. |
| 922 | ipcMain.handle("x402:fund", () => { |
| 923 | if (callerNet.enabled) return; |
| 924 | clipboard.writeText(account.address); |
| 925 | return shell.openExternal("https://faucet.circle.com"); |
| 926 | }); |
| 927 | ipcMain.handle("x402:refund", () => refundMerchant()); |
| 928 | ipcMain.handle("x402:open-external", (_e, url: unknown) => { |
| 929 | const safe = safeExternalUrl(url); |
| 930 | return safe ? shell.openExternal(safe).then(() => true) : false; |
| 931 | }); |
| 932 | |
| 933 | // Pages that ask for a new window (target=_blank, window.open) get a tab instead of a |
| 934 | // stray native window. Only web URLs — never let a page spawn file:/custom schemes. |
| 935 | app.on("web-contents-created", (_e, wc) => { |
| 936 | if (wc.getType() !== "webview") return; |
| 937 | trackLifecycle(wc); |
| 938 | // Tab keys belong to the browser: caught before the page, which could otherwise swallow them (see shortcuts.ts). |
| 939 | wc.on("before-input-event", (event, input) => { |
| 940 | const cmd = reservedShortcut(input, process.platform === "darwin"); |
| 941 | if (!cmd) return; |
| 942 | event.preventDefault(); // the page never sees it, and the menu does not run it a second time |
| 943 | mainWindow?.webContents.send("tab:cmd", cmd); |
| 944 | }); |
| 945 | wc.on("context-menu", (_e, p) => showContextMenu(wc, p, true)); |
| 946 | if (callerNet.enabled) wc.setWebRTCIPHandlingPolicy("disable_non_proxied_udp"); // no UDP for ICE/STUN: it would bypass the caller |
| 947 | wc.setWindowOpenHandler(({ url, disposition }) => { |
| 948 | if (callerNet.enabled) { |
| 949 | emit({ kind: "popup-refused", url }); // no new window or tab in this mode |
| 950 | return { action: "deny" }; |
| 951 | } |
| 952 | // ⌘-click and middle-click ask for a background tab: it opens behind the page you are on, as in other browsers. |
| 953 | if (/^https?:\/\//i.test(url)) mainWindow?.webContents.send("tab:open", url, { background: disposition === "background-tab" }); |
| 954 | return { action: "deny" }; |
| 955 | }); |
| 956 | // A tab is created blank and then navigated, which leaves a hidden about:blank "back" entry: Back walked into |
| 957 | // an empty page. Drop it as soon as the tab's first real page commits, so a new tab has nothing to go back to. |
| 958 | let pruned = false; |
| 959 | wc.on("did-navigate", () => { |
| 960 | if (pruned || wc.isDestroyed()) return; |
| 961 | const h = wc.navigationHistory; |
| 962 | if (h.length() === 2 && h.getEntryAtIndex(0).url === "about:blank") { |
| 963 | h.removeEntryAtIndex(0); |
| 964 | pruned = true; |
| 965 | } else if (wc.getURL() !== "about:blank") pruned = true; |
| 966 | }); |
| 967 | // History: each page the tab shows is a visit, from when it appears until the tab moves on or closes. Its text is read |
| 968 | // once it has loaded (and again a little later, for pages that fill in after loading). |
| 969 | const id = wc.id; |
| 970 | let readTimer: ReturnType<typeof setTimeout> | null = null; |
| 971 | const readSoon = (ms: number) => { |
| 972 | if (readTimer) clearTimeout(readTimer); |
| 973 | readTimer = setTimeout(() => void readForHistory(wc), ms); |
| 974 | }; |
| 975 | wc.on("did-navigate", (_e, url) => history?.shown(id, url, wc.getTitle())); |
| 976 | wc.on("did-navigate-in-page", (_e, url, isMainFrame) => { |
| 977 | if (!isMainFrame) return; |
| 978 | history?.shown(id, url, wc.getTitle()); |
| 979 | readSoon(2500); |
| 980 | }); |
| 981 | wc.on("page-title-updated", (_e, title) => history?.title(id, title)); |
| 982 | // The page named its icon: learn it for the site (see favicons.ts). Not while the caller network is on (no requests of |
| 983 | // the browser's own), and not for a site on the never-record list. |
| 984 | wc.on("page-favicon-updated", (_e, urls) => { |
| 985 | const page = wc.getURL(); |
| 986 | if (!favicons || callerNet.enabled || onNeverList(hostOf(page), history?.state().neverSites ?? [])) return; |
| 987 | void favicons.learn(page, urls).then((icon) => { if (icon) mainWindow?.webContents.send("favicon:update", { host: hostOf(page), icon }); }); |
| 988 | }); |
| 989 | // (Read soon after the document is ready too: pages full of ads may not finish loading for minutes.) |
| 990 | wc.on("dom-ready", () => readSoon(2500)); |
| 991 | wc.on("did-finish-load", () => readSoon(1500)); |
| 992 | wc.on("destroyed", () => { |
| 993 | if (readTimer) clearTimeout(readTimer); |
| 994 | history?.left(id); |
| 995 | }); |
| 996 | }); |
| 997 | buildMenu(); |
| 998 | setupDownloads(); |
| 999 | setupNetPolicy(); |
| 1000 | // Serve reader views from the store. When the summary arrives the stored page is updated, so Back/Forward/reload |
| 1001 | // show the finished view instead of the pending snapshot. An evicted page gets a polite "expired" notice. |
| 1002 | protocol.handle(READER_SCHEME, (request) => { |
| 1003 | const id = readerIdFromUrl(request.url); |
| 1004 | const html = id ? readerPages.get(id) : undefined; |
| 1005 | return new Response(html ?? EXPIRED_HTML, { |
| 1006 | status: html ? 200 : 410, |
| 1007 | headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": READER_CSP, "referrer-policy": "no-referrer", "cache-control": "no-store" }, |
| 1008 | }); |
| 1009 | }); |
| 1010 | const reader = createReader({ getWindow: () => mainWindow, askChrome, emit, getAi: () => aiCfg, pages: readerPages }); |
| 1011 | // From the chrome UI (a human clicked Reader): ask before anything is sent. |
| 1012 | ipcMain.handle("reader:open", async (_e, a: { wcId?: number }) => { |
| 1013 | if (callerNet.enabled) return { ok: false, reason: "caller-network-on", message: "The reader is switched off while the caller network is on." }; |
| 1014 | const r = await reader.open({ wcId: Number(a?.wcId), interactive: true }); |
| 1015 | return { ok: r.ok, reason: r.reason, message: r.message, ai: r.ai }; |
| 1016 | }); |
| 1017 | ipcMain.handle("reader:ai", () => describeAi(aiCfg)); |
| 1018 | ipcMain.handle("reader:provider", (_e, p: unknown) => (p === "anthropic" || p === "openai" ? setAiProvider(p) : false)); |
| 1019 | const vaultSvc = registerVault({ path: process.env.DBB_VAULT || join(app.getPath("userData"), "vault.json"), getWindow: () => mainWindow }); |
| 1020 | |
| 1021 | // Tab list mirror (for the automation API) and the chrome UI's answers to askChrome(). |
| 1022 | ipcMain.on("tabs:sync", (_e, list: TabInfo[]) => setTabs(Array.isArray(list) ? list : [])); |
| 1023 | ipcMain.on("ctl:res", (_e, r: { id: string; result?: unknown; error?: string }) => { |
| 1024 | const p = chromeReqs.get(r.id); |
| 1025 | if (!p) return; |
| 1026 | clearTimeout(p.timer); |
| 1027 | chromeReqs.delete(r.id); |
| 1028 | if (r.error) p.reject(new Error(r.error)); |
| 1029 | else p.resolve(r.result); |
| 1030 | }); |
| 1031 | |
| 1032 | // Local extensions (extra automation methods from code on this machine): only from DBB_EXTENSIONS, announced, and all-or-nothing. |
| 1033 | const extensions = new ExtensionRegistry<WebContents>(); |
| 1034 | try { |
| 1035 | await loadExtensions(parseExtensionPaths(process.env.DBB_EXTENSIONS), extensions, (file) => console.error(`[extensions] loaded ${basename(file)}`)); |
| 1036 | } catch (e) { |
| 1037 | console.error(`[extensions] refused to start: ${(e as Error).message}`); |
| 1038 | app.exit(3); |
| 1039 | return; |
| 1040 | } |
| 1041 | |
| 1042 | createWindow(); |
| 1043 | // Automation API: off unless asked for (see control.ts for the security model). |
| 1044 | // MCP connections (sign in with OAuth, add tools to the chat). Sign-ins are kept only encrypted by the operating system; |
| 1045 | // without that, or with DBB_MCP_STORE=memory, they last until the browser closes. |
| 1046 | const mcpAuthPath = join(app.getPath("userData"), "mcp-auth.bin"); |
| 1047 | const mcpEncryption = process.env.DBB_MCP_STORE === "memory" ? { isEncryptionAvailable: () => false, encryptString: () => Buffer.alloc(0), decryptString: () => "" } : safeStorage; |
| 1048 | const mcpConfig = loadServerConfigs(process.env.DBB_MCP_SERVERS || join(app.getPath("userData"), "mcp-servers.json")); |
| 1049 | for (const problem of mcpConfig.problems) console.error(`[mcp] servers file: ${problem}`); |
| 1050 | const mcp = new McpService({ |
| 1051 | fetch: (url, init) => fetch(url, init as RequestInit), |
| 1052 | store: createStore(mcpAuthPath, mcpEncryption, { |
| 1053 | read: (p) => (existsSync(p) ? readFileSync(p) : null), |
| 1054 | write: (p, b) => (b ? (writeFileSync(p, b, { mode: 0o600 }), chmodSync(p, 0o600)) : rmSync(p, { force: true })), |
| 1055 | }), |
| 1056 | servers: mcpConfig.servers, |
| 1057 | openExternal: (url) => { |
| 1058 | const safe = safeExternalUrl(url); |
| 1059 | if (safe) void shell.openExternal(safe); |
| 1060 | }, |
| 1061 | openTab: async (url) => { |
| 1062 | const r = (await askChrome("tab.new", { url, activate: true, wait: false })) as { id?: number } | undefined; |
| 1063 | return typeof r?.id === "number" ? r.id : null; |
| 1064 | }, |
| 1065 | closeTab: async (id) => { |
| 1066 | await askChrome("tab.close", { id }).catch(() => {}); |
| 1067 | }, |
| 1068 | callerNetworkOn: () => callerNet.enabled, |
| 1069 | announce: (e) => { |
| 1070 | emit(e); |
| 1071 | // A new sign-in brings the bookmarks in at once; signing out shows the local copy again. |
| 1072 | if (e.kind === "mcp-signed-in" && e.server === BOOKMARK_SERVER) void bookmarks.refresh(); |
| 1073 | if (e.kind === "mcp-signed-out" && e.server === BOOKMARK_SERVER) mainWindow?.webContents.send("bookmarks:changed", bookmarks.state()); |
| 1074 | // History: a new sign-in (perhaps someone else) or a sign-out empties what was waiting; a sign-in reads the settings. |
| 1075 | if ((e.kind === "mcp-signed-in" || e.kind === "mcp-signed-out") && e.server === BOOKMARK_SERVER) { |
| 1076 | history?.resetAccount(); |
| 1077 | historyCopy?.clear(); |
| 1078 | if (e.kind === "mcp-signed-in") void history?.loadSettings().then(() => historyCopy?.sync()); |
| 1079 | } |
| 1080 | }, |
| 1081 | }); |
| 1082 | mcpCapture = (url) => mcp.captureRedirect(url); |
| 1083 | |
| 1084 | // Bookmarks: the person's saved links on askrobots, over the same connection, with a local copy (see bookmarks-service.ts). |
| 1085 | const BOOKMARK_SERVER = "askrobots"; |
| 1086 | const bookmarksPath = join(app.getPath("userData"), "bookmarks.json"); |
| 1087 | const bookmarks = new BookmarksService({ |
| 1088 | call: (tool, args, opts) => mcp.callDirect(BOOKMARK_SERVER, tool, args, opts), |
| 1089 | connected: () => mcp.isSignedIn(BOOKMARK_SERVER), |
| 1090 | ready: () => mcp.isLoaded(), |
| 1091 | loadCopy: () => (existsSync(bookmarksPath) ? readFileSync(bookmarksPath, "utf8") : null), |
| 1092 | saveCopy: (text) => { |
| 1093 | writeFileSync(bookmarksPath, text, { mode: 0o600 }); |
| 1094 | chmodSync(bookmarksPath, 0o600); |
| 1095 | }, |
| 1096 | changed: (state) => mainWindow?.webContents.send("bookmarks:changed", state), |
| 1097 | }); |
| 1098 | // History on the askrobots account: recorded only while signed in with the "history" permission (see history.ts). |
| 1099 | const historyOn = () => mcp.isLoaded() && mcp.isSignedIn(BOOKMARK_SERVER) && !mcp.missingScopes(BOOKMARK_SERVER).includes("history"); |
| 1100 | let sentSeen = 0; |
| 1101 | let copyTimer: ReturnType<typeof setTimeout> | null = null; |
| 1102 | history = new HistoryService({ |
| 1103 | call: (tool, args) => mcp.callDirect(BOOKMARK_SERVER, tool, args, { fixed: false }), |
| 1104 | connected: historyOn, |
| 1105 | whyOff: () => |
| 1106 | !mcp.isLoaded() || !mcp.isSignedIn(BOOKMARK_SERVER) ? "not signed in to askrobots" : "connect to askrobots again to allow history", |
| 1107 | callerNetworkOn: () => callerNet.enabled, |
| 1108 | now: () => Date.now(), |
| 1109 | changed: (st) => { |
| 1110 | mainWindow?.webContents.send("history:changed", st); |
| 1111 | if (st.queued >= 20) void history?.flush(); |
| 1112 | // visits just sent: read them back into the copy (with their ids), so the address bar knows them |
| 1113 | if (st.sent !== sentSeen) { |
| 1114 | sentSeen = st.sent; |
| 1115 | if (st.sent > 0) copySoon(); |
| 1116 | } |
| 1117 | }, |
| 1118 | // Tests run their stand-in server on this machine; nobody else's pages on 127.0.0.1 are ever recorded. |
| 1119 | allowPrivateHosts: process.env.DBB_HISTORY_LOCAL_TEST === "1", |
| 1120 | }); |
| 1121 | const historyTimer = setInterval(() => void history?.flush(), 30_000); |
| 1122 | historyTimer.unref(); |
| 1123 | // The copy for the address bar: addresses, titles and times only (never the text), in a file only you can read. It is |
| 1124 | // brought up to date when the browser opens, after visits are sent, after a forget, and every 5 minutes (to see what |
| 1125 | // your other computers added or forgot). Deleted on sign-out. |
| 1126 | // Site icons for the tabs and suggestions: fetched once per site from the pages you open, kept in a file only you can read. |
| 1127 | const faviconsPath = join(app.getPath("userData"), "favicons.json"); |
| 1128 | favicons = new FaviconStore({ |
| 1129 | fetch: fetchIcon, |
| 1130 | shrink: (f) => { |
| 1131 | const img = nativeImage.createFromBuffer(Buffer.from(f.bytes)); |
| 1132 | if (img.isEmpty()) return null; |
| 1133 | const { width } = img.getSize(); |
| 1134 | return (width > 32 ? img.resize({ width: 32, height: 32, quality: "best" }) : img).toDataURL(); |
| 1135 | }, |
| 1136 | load: () => (existsSync(faviconsPath) ? readFileSync(faviconsPath, "utf8") : null), |
| 1137 | save: (text) => { |
| 1138 | if (text === null) return rmSync(faviconsPath, { force: true }); |
| 1139 | writeFileSync(faviconsPath, text, { mode: 0o600 }); |
| 1140 | chmodSync(faviconsPath, 0o600); |
| 1141 | }, |
| 1142 | now: () => Date.now(), |
| 1143 | }); |
| 1144 | ipcMain.handle("favicons:all", () => favicons?.all() ?? {}); |
| 1145 | const forgetIcon = (host: string) => { |
| 1146 | favicons?.forget(host); |
| 1147 | mainWindow?.webContents.send("favicon:update", { host, icon: null }); |
| 1148 | }; |
| 1149 | const historyCopyPath = join(app.getPath("userData"), "history-copy.json"); |
| 1150 | historyCopy = new HistoryCopy({ |
| 1151 | call: (tool, args) => mcp.callDirect(BOOKMARK_SERVER, tool, args, { fixed: false }), |
| 1152 | connected: () => historyOn() && !callerNet.enabled, |
| 1153 | load: () => (existsSync(historyCopyPath) ? readFileSync(historyCopyPath, "utf8") : null), |
| 1154 | save: (text) => { |
| 1155 | if (text === null) return rmSync(historyCopyPath, { force: true }); |
| 1156 | writeFileSync(historyCopyPath, text, { mode: 0o600 }); |
| 1157 | chmodSync(historyCopyPath, 0o600); |
| 1158 | }, |
| 1159 | now: () => Date.now(), |
| 1160 | }); |
| 1161 | function copySoon(): void { |
| 1162 | if (copyTimer) clearTimeout(copyTimer); |
| 1163 | copyTimer = setTimeout(() => void historyCopy?.sync(), 1500); |
| 1164 | } |
| 1165 | setInterval(() => void historyCopy?.sync(), 5 * 60_000).unref(); |
| 1166 | // A forget, here and in the copy (at once, then as the account says). |
| 1167 | const forgetHistory = async (scope: "url" | "last_hour" | "site", target?: string) => { |
| 1168 | if (!history) return { forgotten: 0 }; |
| 1169 | const out = await history.forget(scope, target); |
| 1170 | historyCopy?.remove(forgetMatch(scope, target, Date.now())); |
| 1171 | if (scope === "site" && target) forgetIcon(hostOf(target) || target.toLowerCase()); |
| 1172 | copySoon(); |
| 1173 | return out; |
| 1174 | }; |
| 1175 | // Quitting ends every open visit; the browser waits up to 3 seconds for them to reach the account, then quits anyway |
| 1176 | // (whatever has not gone by then is not kept). |
| 1177 | let historySentOnQuit = false; |
| 1178 | app.on("before-quit", (e) => { |
| 1179 | if (historySentOnQuit || !history) return; |
| 1180 | history.leaveAll(); |
| 1181 | if (!history.state().on || history.state().queued === 0) return; |
| 1182 | e.preventDefault(); |
| 1183 | historySentOnQuit = true; |
| 1184 | void Promise.race([history.flush(), new Promise((r) => setTimeout(r, 3000))]).finally(() => app.quit()); |
| 1185 | }); |
| 1186 | ipcMain.handle("history:state", () => history?.state()); |
| 1187 | ipcMain.handle("history:pause", (_e, on: unknown) => history?.setPaused(on === true)); |
| 1188 | ipcMain.handle("history:open", () => mainWindow?.webContents.send("tab:open", "https://askrobots.com/history/", { background: false })); |
| 1189 | // Forgetting deletes on the account, so the person confirms it here (a page cannot ask for it). |
| 1190 | ipcMain.handle("history:forget", async (_e, scope: unknown, target: unknown) => { |
| 1191 | if (!history || !["url", "last_hour", "site"].includes(String(scope))) return { ok: false }; |
| 1192 | const t = String(target ?? ""); |
| 1193 | let host = ""; |
| 1194 | try { |
| 1195 | host = t ? new URL(t).hostname : ""; |
| 1196 | } catch { |
| 1197 | /* not an address */ |
| 1198 | } |
| 1199 | const what = scope === "url" ? `this page (${t.slice(0, 120)})` : scope === "site" ? `everything from ${host}` : "the pages from the last hour"; |
| 1200 | const opts: Electron.MessageBoxOptions = { type: "warning", buttons: ["Forget", "Cancel"], defaultId: 1, cancelId: 1, message: `Forget ${what}?`, detail: "It is deleted from your history on askrobots.com. To forget everything, use the history page on askrobots.com." }; |
| 1201 | const r = mainWindow ? await dialog.showMessageBox(mainWindow, opts) : await dialog.showMessageBox(opts); |
| 1202 | if (r.response !== 0) return { ok: false, cancelled: true }; |
| 1203 | try { |
| 1204 | const out = await forgetHistory(scope as "url" | "last_hour" | "site", t || undefined); |
| 1205 | return { ok: true, ...out }; |
| 1206 | } catch (e) { |
| 1207 | return { ok: false, message: e instanceof Error ? e.message : String(e) }; |
| 1208 | } |
| 1209 | }); |
| 1210 | ipcMain.handle("history:never", async (_e, target: unknown) => { |
| 1211 | try { |
| 1212 | const host = new URL(String(target ?? "")).hostname; |
| 1213 | const state = await history?.neverRecord(host); |
| 1214 | forgetIcon(host); |
| 1215 | return { ok: true, state }; |
| 1216 | } catch (e) { |
| 1217 | return { ok: false, message: e instanceof Error ? e.message : String(e) }; |
| 1218 | } |
| 1219 | }); |
| 1220 | |
| 1221 | // Loaded once when the browser opens (so ☆ knows which pages are saved from the start), when the person opens the list, and |
| 1222 | // right after saving or signing in. Only for a person at the window with a saved sign-in: reading it can raise the system |
| 1223 | // keychain prompt, which a scripted or background run must never wait behind. |
| 1224 | if (!background && process.env.DBB_CONTROL !== "1" && existsSync(mcpAuthPath)) { |
| 1225 | const loadOnce = () => setTimeout(() => { if (!callerNet.enabled) void bookmarks.refresh().then(() => history?.loadSettings()).then(() => historyCopy?.sync()); }, 1200); |
| 1226 | if (mainWindow?.webContents.isLoading()) mainWindow.webContents.once("did-finish-load", loadOnce); |
| 1227 | else loadOnce(); |
| 1228 | } |
| 1229 | ipcMain.handle("bookmarks:state", () => bookmarks.state()); |
| 1230 | ipcMain.handle("bookmarks:refresh", () => (callerNet.enabled ? bookmarks.state() : bookmarks.refresh())); |
| 1231 | ipcMain.handle("bookmarks:search", (_e, q: unknown) => (callerNet.enabled ? { items: [], error: "switched off while the caller network is on" } : bookmarks.search(String(q ?? "")))); |
| 1232 | ipcMain.handle("bookmarks:check", (_e, url: unknown) => (callerNet.enabled ? { checked: false, saved: false } : bookmarks.checkPage(String(url ?? "")))); |
| 1233 | ipcMain.handle("bookmarks:set-check", (_e, on: unknown) => bookmarks.setCheckPages(on === true)); |
| 1234 | ipcMain.handle("bookmarks:add", (_e, url: unknown, title: unknown) => bookmarks.add(String(url ?? ""), String(title ?? ""))); |
| 1235 | ipcMain.handle("mcp:state", () => mcp.state()); |
| 1236 | ipcMain.handle("mcp:connect", async (_e, id: unknown) => { |
| 1237 | try { |
| 1238 | const r = await mcp.connect(String(id)); |
| 1239 | await r.done; |
| 1240 | return { ok: true }; |
| 1241 | } catch (e) { |
| 1242 | return { ok: false, message: e instanceof Error ? e.message : String(e) }; |
| 1243 | } |
| 1244 | }); |
| 1245 | ipcMain.handle("mcp:cancel", (_e, id: unknown) => (mcp.cancelConnect(String(id)), true)); |
| 1246 | ipcMain.handle("mcp:disconnect", (_e, id: unknown) => mcp.disconnect(String(id)).then(() => ({ ok: true }), (e) => ({ ok: false, message: String(e?.message ?? e) }))); |
| 1247 | |
| 1248 | // What the browser is using, so something that hogs the machine has a name: memory and CPU per tab (from the operating system's |
| 1249 | // numbers for each page's own process), the data folder's size and what it is made of, and the cache. |
| 1250 | let diskCache: { at: number; usage: DiskUsage } | null = null; |
| 1251 | let footprintCache: { at: number; bytes: Map<number, number> } | null = null; |
| 1252 | const resources = { |
| 1253 | async state() { |
| 1254 | const metrics = app.getAppMetrics(); |
| 1255 | const byPid = new Map(metrics.map((x) => [x.pid, x])); |
| 1256 | const mb = (kb: number) => Math.round((kb / 1024) * 10) / 10; |
| 1257 | // What a process really costs the machine: on macOS the physical footprint (it counts memory the system has compressed, |
| 1258 | // which resident size hides); elsewhere the figure Electron gives (private bytes on Windows, resident size on Linux). |
| 1259 | if (!footprintCache || Date.now() - footprintCache.at > 2000) footprintCache = { at: Date.now(), bytes: await macFootprints(metrics.map((x) => x.pid)) }; |
| 1260 | const costKB = (x: Electron.ProcessMetric): number => { |
| 1261 | const f = footprintCache?.bytes.get(x.pid); |
| 1262 | if (f != null) return f / 1024; |
| 1263 | return process.platform === "win32" && x.memory.privateBytes != null ? x.memory.privateBytes : x.memory.workingSetSize; |
| 1264 | }; |
| 1265 | const tabsNow = getTabs().map((t) => { |
| 1266 | const wc = t.wcId != null ? webContents.fromId(t.wcId) : undefined; |
| 1267 | const pid = wc && !wc.isDestroyed() ? wc.getOSProcessId() : null; |
| 1268 | const x = pid != null ? byPid.get(pid) : undefined; |
| 1269 | return { id: t.id, title: t.title, url: t.url, active: t.active, pid, memoryMB: x ? mb(costKB(x)) : null, residentMB: x ? mb(x.memory.workingSetSize) : null, cpu: x ? Math.round(x.cpu.percentCPUUsage * 10) / 10 : null }; |
| 1270 | }); |
| 1271 | // Tabs on the same site can share one process: say so, so the same number is not counted twice. |
| 1272 | const pidCount = new Map<number, number>(); |
| 1273 | for (const t of tabsNow) if (t.pid != null) pidCount.set(t.pid, (pidCount.get(t.pid) ?? 0) + 1); |
| 1274 | const byType: Record<string, { processes: number; memoryMB: number; cpu: number }> = {}; |
| 1275 | for (const x of metrics) { |
| 1276 | const k = x.type === "Tab" ? "pages" : x.type === "Browser" ? "browser" : x.type === "GPU" ? "graphics" : "other"; |
| 1277 | const e = (byType[k] ??= { processes: 0, memoryMB: 0, cpu: 0 }); |
| 1278 | e.processes++; |
| 1279 | e.memoryMB = Math.round((e.memoryMB + mb(costKB(x))) * 10) / 10; |
| 1280 | e.cpu = Math.round((e.cpu + x.cpu.percentCPUUsage) * 10) / 10; |
| 1281 | } |
| 1282 | const cacheBytes = await session.defaultSession.getCacheSize().catch(() => null); |
| 1283 | if (!diskCache || Date.now() - diskCache.at > 30_000) diskCache = { at: Date.now(), usage: await diskUsage(app.getPath("userData")) }; |
| 1284 | return { |
| 1285 | totalMemoryMB: Math.round(Object.values(byType).reduce((s, e) => s + e.memoryMB, 0) * 10) / 10, |
| 1286 | totalCpu: Math.round(Object.values(byType).reduce((s, e) => s + e.cpu, 0) * 10) / 10, |
| 1287 | byType, |
| 1288 | tabs: tabsNow.map((t) => ({ ...t, sharedProcess: t.pid != null && (pidCount.get(t.pid) ?? 0) > 1 })), |
| 1289 | cacheBytes, |
| 1290 | disk: diskCache.usage, |
| 1291 | }; |
| 1292 | }, |
| 1293 | async clearCache() { |
| 1294 | const before = await session.defaultSession.getCacheSize().catch(() => 0); |
| 1295 | await session.defaultSession.clearCache(); |
| 1296 | diskCache = null; |
| 1297 | return { freedBytes: before }; |
| 1298 | }, |
| 1299 | }; |
| 1300 | ipcMain.handle("resources:state", () => resources.state()); |
| 1301 | ipcMain.handle("resources:clear-cache", () => resources.clearCache()); |
| 1302 | |
| 1303 | // Keep: a copy of a page (what was on screen, and its text) so its tab can be closed without losing it (see keep-store.ts). |
| 1304 | const keep = new KeepStore(process.env.DBB_KEEP_DIR || join(app.getPath("userData"), "kept")); |
| 1305 | protocol.handle(KEPT_SCHEME, async (request) => { |
| 1306 | const p = parseKeptUrl(request.url); |
| 1307 | if (!p) return new Response("not found", { status: 404 }); |
| 1308 | if (p.file === "page.png") { |
| 1309 | const img = await keep.image(p.id); |
| 1310 | return img ? new Response(new Uint8Array(img), { headers: { "content-type": "image/png", "cache-control": "no-store" } }) : new Response("not found", { status: 404 }); |
| 1311 | } |
| 1312 | const g = await keep.get(p.id); |
| 1313 | return g ? new Response(keptPageHtml(g.record, g.text), { headers: { "content-type": "text/html; charset=utf-8" } }) : new Response("This kept copy was removed.", { status: 404 }); |
| 1314 | }); |
| 1315 | const keepTab = async (o: { tab?: number; reason?: string; close?: boolean; bookmark?: boolean } = {}) => { |
| 1316 | if (callerNet.enabled) return { ok: false, reason: "caller-network-on", message: "Keep is switched off while the caller network is on." }; |
| 1317 | const all = getTabs(); |
| 1318 | const t = typeof o.tab === "number" ? all.find((x) => x.id === o.tab) : all.find((x) => x.active); |
| 1319 | if (!t) return { ok: false, reason: "no-tab", message: "There is no such tab." }; |
| 1320 | if (!/^https?:\/\//i.test(t.url)) return { ok: false, reason: "not-web", message: "Only web pages can be kept." }; |
| 1321 | const wc = t.wcId != null ? webContents.fromId(t.wcId) : undefined; |
| 1322 | if (!wc || wc.isDestroyed()) return { ok: false, reason: "no-tab", message: "That tab is not ready." }; |
| 1323 | // Never keep a copy of a page with a sign-in form showing (it may hold what someone typed). |
| 1324 | const login = await wc.executeJavaScript("[...document.querySelectorAll('input[type=password]')].some((e) => e.offsetParent !== null)").catch(() => false); |
| 1325 | if (login) return { ok: false, reason: "login", message: "Pages with a sign-in form are not kept." }; |
| 1326 | if (!t.active) { |
| 1327 | await askChrome("tab.activate", { id: t.id }); |
| 1328 | await new Promise((r) => setTimeout(r, 200)); // let it be drawn before taking the picture |
| 1329 | } |
| 1330 | const img = await wc.capturePage().catch(() => null); |
| 1331 | const png = img && !img.isEmpty() ? img.toPNG() : null; |
| 1332 | const text = String((await wc.executeJavaScript("document.body ? document.body.innerText : ''").catch(() => "")) ?? ""); |
| 1333 | let record: KeptRecord = await keep.add({ url: t.url, title: t.title, text, png, ...(o.reason ? { reason: o.reason } : {}) }); |
| 1334 | // Also a bookmark on askrobots, and the picture and text in its Files, when connected (a page kept is a page worth finding |
| 1335 | // again, from anywhere). Private, with readable names; the local copy stays either way. |
| 1336 | let bookmarked = false; |
| 1337 | if (o.bookmark !== false && mcp.isLoaded() && mcp.isSignedIn(BOOKMARK_SERVER)) { |
| 1338 | bookmarked = (await bookmarks.add(t.url, t.title)).ok; |
| 1339 | const when = new Date(record.keptAt).toISOString().slice(0, 16).replace("T", " "); |
| 1340 | const description = `Kept from ${record.url} on ${when} UTC: ${record.title}${record.reason ? ` (why: ${record.reason})` : ""}`.slice(0, 500); |
| 1341 | const files: NonNullable<KeptRecord["remote"]>["files"] = []; |
| 1342 | let error: string | undefined; |
| 1343 | const upload = async (kind: "image" | "text", filename: string, body: Buffer) => { |
| 1344 | if (mcp.missingScopes(BOOKMARK_SERVER).includes("files:upload")) { |
| 1345 | error = "saving files was not allowed when you connected; connect again to allow it"; |
| 1346 | return; |
| 1347 | } |
| 1348 | try { |
| 1349 | const out = await mcp.callDirect(BOOKMARK_SERVER, "upload_file", { filename, content_base64: body.toString("base64"), description }, { fixed: true }); |
| 1350 | let id: string | undefined; |
| 1351 | try { |
| 1352 | const j = JSON.parse(out) as Record<string, unknown>; |
| 1353 | id = typeof j.id === "string" ? j.id : typeof j.file_id === "string" ? j.file_id : undefined; |
| 1354 | } catch { |
| 1355 | /* an answer that is not JSON still means it was saved */ |
| 1356 | } |
| 1357 | files.push({ kind, filename, ...(id ? { id } : {}) }); |
| 1358 | } catch (e) { |
| 1359 | error = e instanceof Error ? e.message : String(e); |
| 1360 | } |
| 1361 | }; |
| 1362 | // The server's refusal, said plainly (it comes as {"error": "..."} text). |
| 1363 | const plain = (m: string) => { |
| 1364 | let t = m; |
| 1365 | try { |
| 1366 | const j = JSON.parse(m) as Record<string, unknown>; |
| 1367 | if (typeof j.error === "string") t = j.error; |
| 1368 | } catch { |
| 1369 | /* already text */ |
| 1370 | } |
| 1371 | return /not available for this connection|unknown tool|not found/i.test(t) ? "askrobots does not allow saving files for this connection yet (the copy is on this Mac)" : t.slice(0, 200); |
| 1372 | }; |
| 1373 | if (png) await upload("image", keptFilename(record, "png"), png); |
| 1374 | const header = `${record.title}\n${record.url}\nKept ${when} UTC${record.reason ? `\nWhy: ${record.reason}` : ""}\n\n`; |
| 1375 | await upload("text", keptFilename(record, "txt"), Buffer.from(header + text, "utf8")); |
| 1376 | record = (await keep.update(record.id, { remote: { files, ...(error ? { error: plain(error) } : {}) } })) ?? record; |
| 1377 | } |
| 1378 | if (o.close !== false) await askChrome("tab.close", { id: t.id }).catch(() => {}); |
| 1379 | emit({ kind: "kept", title: record.title, url: record.url, id: record.id, imageBytes: record.imageBytes, textChars: record.textChars }); |
| 1380 | return { ok: true, record, view: keptUrl(record.id), bookmarked, closed: o.close !== false }; |
| 1381 | }; |
| 1382 | ipcMain.handle("keep:tab", (_e, o: unknown) => keepTab((o && typeof o === "object" ? o : {}) as { tab?: number })); |
| 1383 | ipcMain.handle("keep:list", (_e, q: unknown) => keep.list(String(q ?? ""))); |
| 1384 | ipcMain.handle("keep:remove", (_e, id: unknown) => keep.remove(String(id ?? ""))); |
| 1385 | |
| 1386 | // The address bar: suggestions from open tabs, saved links and kept copies (all local), and search suggestions from the |
| 1387 | // search site for text that is not an address. Those go without cookies (so they are not tied to your account) and not at |
| 1388 | // all while the caller network is on. |
| 1389 | let keptCache: { at: number; list: Array<{ id: string; url: string; title: string; view: string }> } | null = null; |
| 1390 | ipcMain.handle("omnibox:suggest", async (_e, o: unknown) => { |
| 1391 | const q = (o && typeof o === "object" ? o : {}) as { text?: unknown; tabs?: unknown; activeTab?: unknown; autofill?: unknown }; |
| 1392 | const text = String(q.text ?? "").slice(0, 500); |
| 1393 | const tabs: OmniTab[] = (Array.isArray(q.tabs) ? q.tabs : []).slice(0, 300).flatMap((t) => (t && typeof t === "object" && typeof (t as OmniTab).id === "number" ? [{ id: (t as OmniTab).id, url: String((t as OmniTab).url ?? ""), title: String((t as OmniTab).title ?? "") }] : [])); |
| 1394 | if (text.trim().startsWith("/")) { |
| 1395 | // "/" commands: the tools of the askrobots sign-in, typed. Nothing is listed or sent without a sign-in. |
| 1396 | if (callerNet.enabled) return { autofill: null, rows: [{ kind: "notice", text: "Commands are off while the caller network is on" }] }; |
| 1397 | if (!mcp.isSignedIn(BOOKMARK_SERVER)) return { autofill: null, rows: [{ kind: "notice", text: "Connect askrobots to use / commands", connect: true }] }; |
| 1398 | try { |
| 1399 | const rows = commandRows(text, (await mcp.commandTools(BOOKMARK_SERVER)).map((t) => toCommand(t, mcp.fixedArgNames(BOOKMARK_SERVER, t.name)))); |
| 1400 | return { autofill: null, rows: rows.length ? rows : [{ kind: "notice", text: `askrobots has no command “${text.trim().split(/\s/)[0]}” for this sign-in` }] }; |
| 1401 | } catch (e) { |
| 1402 | return { autofill: null, rows: [{ kind: "notice", text: `Could not list the askrobots commands: ${e instanceof Error ? e.message : String(e)}`.slice(0, 200) }] }; |
| 1403 | } |
| 1404 | } |
| 1405 | if (!keptCache || Date.now() - keptCache.at > 5000) keptCache = { at: Date.now(), list: (await keep.records()).map((r) => ({ id: r.id, url: r.url, title: r.title, view: keptUrl(r.id) })) }; |
| 1406 | const bm = bookmarks.state(); |
| 1407 | return suggest({ text, tabs, ...(typeof q.activeTab === "number" ? { activeTab: q.activeTab } : {}), bookmarks: [...bm.items, ...bm.known], history: historyCopy?.pages() ?? [], kept: keptCache.list, autofill: q.autofill !== false }); |
| 1408 | }); |
| 1409 | // Run a "/" command you typed. Anything the server says may destroy or change things in a way it does not call harmless |
| 1410 | // asks once more (the second Enter), decided here, not by the window. |
| 1411 | ipcMain.handle("omnibox:run", async (_e, o: unknown) => { |
| 1412 | const q = (o && typeof o === "object" ? o : {}) as { text?: unknown; confirmed?: unknown }; |
| 1413 | const p = parseCommand(String(q.text ?? "").slice(0, 5000)); |
| 1414 | if (!p || !p.name) return { ok: false, message: "Type a command after /" }; |
| 1415 | if (callerNet.enabled) return { ok: false, message: "Commands are off while the caller network is on" }; |
| 1416 | if (!mcp.isSignedIn(BOOKMARK_SERVER)) return { ok: false, connect: true, message: "Connect askrobots to use / commands" }; |
| 1417 | try { |
| 1418 | const t = (await mcp.commandTools(BOOKMARK_SERVER)).find((x) => x.name === p.name); |
| 1419 | if (!t) return { ok: false, message: `askrobots has no /${p.typed} for this sign-in` }; |
| 1420 | const c = toCommand(t, mcp.fixedArgNames(BOOKMARK_SERVER, t.name)); |
| 1421 | const a = commandArgs(c, p.rest); |
| 1422 | if ("problem" in a) return { ok: false, message: `/${c.name}: ${a.problem}` }; |
| 1423 | if (c.destructive && q.confirmed !== true) return { ok: false, confirm: true, message: `/${c.name} may change or remove things on askrobots. Press Enter again to run it.` }; |
| 1424 | const text = await mcp.runCommand(BOOKMARK_SERVER, c.name, a.args); |
| 1425 | emit({ kind: "command", server: BOOKMARK_SERVER, tool: c.name }); |
| 1426 | // The answer goes into the chat, where it can be asked about next; the window shows the sentence. |
| 1427 | const d = describeResult(c.name, a.args, text, mcp.origin(BOOKMARK_SERVER), c.readOnly); |
| 1428 | chat.recordCommand({ typed: String(q.text ?? "").trim(), tool: c.name, readOnly: c.readOnly, args: a.args, server: BOOKMARK_SERVER, ...d }); |
| 1429 | return { ok: true, name: c.name, readOnly: c.readOnly, sentence: d.sentence, ...(d.page ? { page: d.page } : {}) }; |
| 1430 | } catch (e) { |
| 1431 | return { ok: false, message: (e instanceof Error ? e.message : String(e)).slice(0, 500) }; |
| 1432 | } |
| 1433 | }); |
| 1434 | const SUGGEST_URL = process.env.DBB_SUGGEST_URL || "https://askrobots.com/suggest/opensearch?q=%s"; |
| 1435 | const suggestCache = new Map<string, { at: number; list: string[] }>(); |
| 1436 | ipcMain.handle("omnibox:remote", async (_e, t: unknown) => { |
| 1437 | const text = String(t ?? "").trim(); |
| 1438 | if (callerNet.enabled || !remoteAllowed(text)) return []; |
| 1439 | const key = text.toLowerCase(); |
| 1440 | const hit = suggestCache.get(key); |
| 1441 | if (hit && Date.now() - hit.at < 120_000) return hit.list; |
| 1442 | try { |
| 1443 | const res = await fetch(SUGGEST_URL.replace("%s", encodeURIComponent(text)), { headers: { "user-agent": USER_AGENT, accept: "application/x-suggestions+json, application/json" }, credentials: "omit", signal: AbortSignal.timeout(1500) }); |
| 1444 | if (!res.ok) return []; |
| 1445 | const list = parseSuggestions((await res.text()).slice(0, 20_000), text); |
| 1446 | if (suggestCache.size > 200) suggestCache.clear(); |
| 1447 | suggestCache.set(key, { at: Date.now(), list }); |
| 1448 | return list; |
| 1449 | } catch { |
| 1450 | return []; |
| 1451 | } |
| 1452 | }); |
| 1453 | |
| 1454 | // The in-browser chat: a model, the page tools (run in-process, the same methods scripts use) and the person's say. |
| 1455 | const chat = new ChatService({ |
| 1456 | getAi: () => aiCfg, |
| 1457 | run: (m, p) => handleControl(controlDeps, m, p), |
| 1458 | toPanel: (e) => mainWindow?.webContents.send("chat:event", e), |
| 1459 | announce: (e) => emit(e), |
| 1460 | callerNetworkOn: () => callerNet.enabled, |
| 1461 | extraTools: () => mcp.toolDefs(), |
| 1462 | // The model picked in the assistant panel, remembered across restarts (no secrets: a provider and a model name). |
| 1463 | modelChoice: { |
| 1464 | load: () => { |
| 1465 | try { |
| 1466 | return parseSavedChoice(readFileSync(join(app.getPath("userData"), "chat-model.json"), "utf8")); |
| 1467 | } catch { |
| 1468 | return null; |
| 1469 | } |
| 1470 | }, |
| 1471 | save: (id) => { |
| 1472 | try { |
| 1473 | writeFileSync(join(app.getPath("userData"), "chat-model.json"), JSON.stringify({ model: id }) + "\n"); |
| 1474 | } catch { |
| 1475 | /* not remembered; it still applies this session */ |
| 1476 | } |
| 1477 | }, |
| 1478 | }, |
| 1479 | consent: async ({ model, where }) => { |
| 1480 | const opts: Electron.MessageBoxOptions = { |
| 1481 | type: "question", |
| 1482 | buttons: ["Send", "Cancel"], |
| 1483 | defaultId: 1, |
| 1484 | cancelId: 1, |
| 1485 | message: `Let the assistant send to ${where}?`, |
| 1486 | detail: `Your messages, and whatever the assistant reads from your open pages (text, field names, addresses), go to ${model} at ${where}. If you have connected services, what the assistant reads from them (for example contacts, notes and tasks) goes there too. It does not list or fill password, card number or one-time-code fields, but visible page text is visible to it. You approve each action before it happens. This question is asked once per model per session.`, |
| 1487 | }; |
| 1488 | const r = mainWindow ? await dialog.showMessageBox(mainWindow, opts) : await dialog.showMessageBox(opts); |
| 1489 | return r.response === 0; |
| 1490 | }, |
| 1491 | }); |
| 1492 | ipcMain.handle("chat:state", () => chat.state()); |
| 1493 | ipcMain.handle("chat:send", (_e, text: unknown) => chat.send(String(text ?? ""))); |
| 1494 | ipcMain.handle("chat:stop", () => (chat.stop(), true)); |
| 1495 | ipcMain.handle("chat:confirm", (_e, id: unknown, ok: unknown) => chat.confirm(String(id), ok === true)); |
| 1496 | ipcMain.handle("chat:clear", () => (chat.clear(), true)); |
| 1497 | ipcMain.handle("chat:mode", (_e, m: unknown) => chat.setMode(m)); |
| 1498 | ipcMain.handle("chat:model", (_e, id: unknown) => chat.setModel(id)); |
| 1499 | const controlDeps: ControlDeps = { |
| 1500 | askChrome, |
| 1501 | background, |
| 1502 | focusWindow: () => { |
| 1503 | const w = mainWindow; |
| 1504 | if (!w || background) return; // background mode never raises or focuses the window |
| 1505 | if (w.isMinimized()) w.restore(); |
| 1506 | w.show(); |
| 1507 | w.focus(); |
| 1508 | if (process.platform === "darwin") app.focus({ steal: true }); |
| 1509 | }, |
| 1510 | vault: vaultSvc, |
| 1511 | eventsSince: (n) => ({ events: eventLog.filter((e) => (e.seq as number) > n), next: eventSeq }), |
| 1512 | history: { |
| 1513 | state: () => (history ? { ...history.state(), copy: historyCopy?.state() } : null), |
| 1514 | flush: async () => { |
| 1515 | await history?.flush(); |
| 1516 | return history?.state() ?? null; |
| 1517 | }, |
| 1518 | pause: (on) => history?.setPaused(on) ?? Promise.resolve(null), |
| 1519 | forget: (scope, target) => forgetHistory(scope, target), |
| 1520 | syncCopy: async () => { |
| 1521 | await historyCopy?.sync(); |
| 1522 | return historyCopy?.state() ?? null; |
| 1523 | }, |
| 1524 | never: (host) => history?.neverRecord(host) ?? Promise.resolve(null), |
| 1525 | }, |
| 1526 | contextMenu: { |
| 1527 | last: () => (lastMenu ? { wcId: lastMenu.wcId, items: lastMenu.items } : null), |
| 1528 | pick: (id) => (lastMenu ? lastMenu.run(id) : false), |
| 1529 | }, |
| 1530 | getApproval: () => approval, |
| 1531 | setApproval: (p) => { |
| 1532 | approval = p; |
| 1533 | emit({ kind: "approval-changed", mode: p.mode, maxUsd: p.maxUsd }); |
| 1534 | }, |
| 1535 | reader: async (p) => { |
| 1536 | const r = await reader.open({ wcId: Number(p.wcId), interactive: false, withAi: p.ai !== false, acknowledge: p.acknowledge === true }); |
| 1537 | const ai = r.done && p.wait !== false ? await r.done : undefined; |
| 1538 | return { ok: r.ok, reason: r.reason, message: r.message, tab: r.tab, state: r.ai, summary: ai }; |
| 1539 | }, |
| 1540 | downloads: () => [...downloads.values()], |
| 1541 | getNetPolicy: () => ({ blockWebSockets: netPolicy.blockWebSockets || callerNet.enabled }), |
| 1542 | setNetPolicy: (p) => { |
| 1543 | if (typeof p.websockets === "boolean") netPolicy.blockWebSockets = p.websockets; |
| 1544 | emit({ kind: "net-policy-changed", blockWebSockets: netPolicy.blockWebSockets }); |
| 1545 | }, |
| 1546 | extensions, |
| 1547 | assertNotCallerNet: refuseWhileCallerNet, |
| 1548 | settle: (ctx, opts) => runSettle({ ...ctx, isWithCaller: (u) => callerNet.isParked(u) }, opts), |
| 1549 | callerNet: { |
| 1550 | state: () => ({ limits: { ...callerNet.limits }, cookies: cookiesPerVisit ? "visit" : "off", enabled: callerNet.enabled, userAgent: callerNet.userAgent, answerTimeoutMs: callerNet.answerTimeoutMs, waiting: callerNet.parkedCount() }), |
| 1551 | configure: configureCallerNet, |
| 1552 | pending: (afterId, waitMs) => callerNet.pending(afterId, waitMs), |
| 1553 | answer: (id, a) => callerNet.answer(id, a as unknown as Answer), |
| 1554 | fail: (id, kind, detail) => callerNet.fail(id, kind, detail), |
| 1555 | // A new visit starts with a clean slate: nothing a previous page left in the session (cookies, localStorage, |
| 1556 | // IndexedDB, caches, service workers) is there, and the page being left drops its sessionStorage. A page that |
| 1557 | // moves ITSELF is the same visit and keeps what it set. (Tabs share one session, so this is meant for one visit at a time.) |
| 1558 | freshVisit: async (wcId) => { |
| 1559 | if (!callerNet.enabled) return; |
| 1560 | callerNet.newVisit(); |
| 1561 | const wc = webContents.fromId(wcId); |
| 1562 | try { |
| 1563 | await Promise.race([wc?.executeJavaScript("try { sessionStorage.clear(); } catch {}", false), new Promise((r) => setTimeout(r, 1000))]); |
| 1564 | } catch { |
| 1565 | /* a page that cannot be asked has nothing we can clear */ |
| 1566 | } |
| 1567 | // Never let clearing storage hold a visit up for ever: past 8 s the visit goes ahead and the problem is announced. |
| 1568 | const cleared = await Promise.race([session.defaultSession.clearStorageData().then(() => true), new Promise<boolean>((r) => setTimeout(() => r(false), 8000))]); |
| 1569 | if (!cleared) emit({ kind: "visit-clean-slate-timeout", message: "clearing stored data took more than 8 s; the visit started anyway" }); |
| 1570 | }, |
| 1571 | registerDocument: (doc) => callerNet.registerDocument(doc as unknown as Document), |
| 1572 | noteKnownDocument, |
| 1573 | }, |
| 1574 | aiStatus: () => describeAi(aiCfg), |
| 1575 | chat, |
| 1576 | mcp, |
| 1577 | resources, |
| 1578 | bookmarks, |
| 1579 | keep: { tab: keepTab, list: (q: string) => keep.list(q), get: (id: string) => keep.get(id), remove: (id: string) => keep.remove(id) }, |
| 1580 | setAiProvider: (p) => (p === "anthropic" || p === "openai" ? setAiProvider(p) : false), |
| 1581 | spent: () => formatUsd(engine.policy.spentUsdMicro()), |
| 1582 | receipts: () => JSON.parse(JSON.stringify(engine.ledger.all(), (_k, v) => (typeof v === "bigint" ? v.toString() : v))), |
| 1583 | }; |
| 1584 | if (process.env.DBB_CONTROL === "1" || process.argv.includes("--control")) { |
| 1585 | startControl(controlDeps, { port: Number(process.env.DBB_CONTROL_PORT) || 9777, token: process.env.DBB_CONTROL_TOKEN }) |
| 1586 | .then((h) => { |
| 1587 | control = h; |
| 1588 | console.error(`[control] automation API on http://127.0.0.1:${h.port}/rpc — token in ${h.file}`); |
| 1589 | mainWindow?.webContents.send("ctl:status", { port: h.port }); |
| 1590 | buildMenu(); // refresh the Help menu's status line |
| 1591 | }) |
| 1592 | .catch((e) => console.error("[control] failed to start:", e)); |
| 1593 | } |
| 1594 | // Report the engine's real client-hint brands (navigator.userAgentData) to the transport, so the |
| 1595 | // HTTP hints can never disagree with what pages see in JS. |
| 1596 | mainWindow?.webContents.once("dom-ready", () => { |
| 1597 | mainWindow?.webContents |
| 1598 | .executeJavaScript( |
| 1599 | "(() => { const u = navigator.userAgentData; return u ? { brands: u.brands.map((b) => ({ brand: b.brand, version: b.version })), platform: u.platform, mobile: u.mobile } : null; })()", |
| 1600 | ) |
| 1601 | .then(setClientHints, () => setClientHints(null)); |
| 1602 | }); |
| 1603 | ipcMain.on("pref:motion", (_e, m: unknown) => { |
| 1604 | if ((m === "always" || m === "system" || m === "never") && m !== motionPref) { |
| 1605 | motionPref = m; |
| 1606 | buildMenu(); |
| 1607 | } |
| 1608 | }); |
| 1609 | // Per-request progress for the tab throbbers and status line. |
| 1610 | netEvents.on("event", (e: NetEvent) => mainWindow?.webContents.send("net:event", e)); |
| 1611 | mainWindow?.webContents.on("did-finish-load", () => { |
| 1612 | if (control) mainWindow?.webContents.send("ctl:status", { port: control.port }); |
| 1613 | }); |
| 1614 | // Show the balance on load, then poll — so funding shows up without a restart. |
| 1615 | mainWindow?.webContents.once("did-finish-load", () => void refreshBalance()); |
| 1616 | mainWindow?.webContents.once("did-finish-load", () => { if (callerNet.enabled) emit({ kind: "net-provider-changed", enabled: true, answerTimeoutMs: callerNet.answerTimeoutMs }); }); |
| 1617 | setInterval(() => void refreshBalance(), 20_000); |
| 1618 | |
| 1619 | app.on("activate", () => { |
| 1620 | if (BrowserWindow.getAllWindows().length === 0) createWindow(); |
| 1621 | }); |
| 1622 | }); |
| 1623 | |
| 1624 | app.on("window-all-closed", () => { |
| 1625 | if (process.platform !== "darwin") app.quit(); |
| 1626 | }); |