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