askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
extensions.ts · 5.3 KB · 106 lines
| 1 | /** |
| 2 | * Local extensions: extra automation methods, supplied by code you have on this machine. |
| 3 | * |
| 4 | * DBB_EXTENSIONS=/abs/path/one.mjs:/abs/path/two.mjs |
| 5 | * |
| 6 | * Each file is an ES module that exports `register(api)`. It adds methods with `api.method(name, handler)`; a method is |
| 7 | * reached through the automation API as `ext.<name>`. The handler gets the request's parameters and a few tools |
| 8 | * (`tools.webContents(params)` returns the page of the tab the request names, without raising the window). |
| 9 | * |
| 10 | * Extensions run with the browser's own privileges, so load only code you trust. The files and their folder must belong to you and |
| 11 | * not be writable by anyone else. An extension can also use Electron directly, so "built-in methods cannot be replaced" is about |
| 12 | * method names only: trusted code can still change how the browser works. They are loaded from an environment variable |
| 13 | * only (never from a page, the network or the automation API), only from absolute paths to local files, each load is announced, |
| 14 | * and an extension that fails to load stops the browser from starting, so it never runs half set up. Built-in methods cannot |
| 15 | * be replaced: everything an extension adds lives under `ext.`. |
| 16 | * |
| 17 | * No electron import: what it needs from the browser is handed in, so it can be tested on its own. |
| 18 | */ |
| 19 | |
| 20 | import { existsSync, statSync } from "node:fs"; |
| 21 | import { dirname, isAbsolute } from "node:path"; |
| 22 | import { pathToFileURL } from "node:url"; |
| 23 | |
| 24 | export interface ExtensionTools<Page> { |
| 25 | /** The page of the tab named by `params.tab` (default: the active tab). The window is not raised. */ |
| 26 | webContents(params: Record<string, unknown>): Promise<Page>; |
| 27 | } |
| 28 | |
| 29 | export type ExtensionHandler<Page = unknown> = (params: Record<string, unknown>, tools: ExtensionTools<Page>) => Promise<unknown> | unknown; |
| 30 | |
| 31 | export interface ExtensionApi<Page = unknown> { |
| 32 | /** Add the automation method `ext.<name>`. Names are lower-case letters, digits and hyphens, optionally with one dot. */ |
| 33 | method(name: string, handler: ExtensionHandler<Page>): void; |
| 34 | } |
| 35 | |
| 36 | const NAME = /^[a-z][a-z0-9-]{0,40}(\.[a-z][a-z0-9-]{0,40})?$/; |
| 37 | |
| 38 | export class ExtensionRegistry<Page = unknown> { |
| 39 | private methods = new Map<string, ExtensionHandler<Page>>(); |
| 40 | /** The files that were loaded (absolute), kept for the log. */ |
| 41 | loaded: string[] = []; |
| 42 | /** Their base names: what the status report shows, so a log or a bug report does not carry a folder layout. */ |
| 43 | loadedNames(): string[] { |
| 44 | return this.loaded.map((f) => f.slice(f.lastIndexOf("/") + 1)); |
| 45 | } |
| 46 | |
| 47 | has(method: string): boolean { |
| 48 | return this.methods.has(method); |
| 49 | } |
| 50 | |
| 51 | names(): string[] { |
| 52 | return [...this.methods.keys()].sort(); |
| 53 | } |
| 54 | |
| 55 | call(method: string, params: Record<string, unknown>, tools: ExtensionTools<Page>): Promise<unknown> { |
| 56 | const h = this.methods.get(method); |
| 57 | if (!h) return Promise.reject(new Error(`no extension method ${method}`)); |
| 58 | return Promise.resolve().then(() => h(params, tools)); |
| 59 | } |
| 60 | |
| 61 | /** The registration surface handed to one extension. */ |
| 62 | apiFor(file: string): ExtensionApi<Page> { |
| 63 | return { |
| 64 | method: (name, handler) => { |
| 65 | if (typeof name !== "string" || !NAME.test(name)) throw new Error(`${file}: "${String(name)}" is not a valid method name`); |
| 66 | if (typeof handler !== "function") throw new Error(`${file}: the handler for "${name}" must be a function`); |
| 67 | const full = `ext.${name}`; |
| 68 | if (this.methods.has(full)) throw new Error(`${file}: ${full} is already registered`); |
| 69 | this.methods.set(full, handler); |
| 70 | }, |
| 71 | }; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /** Split DBB_EXTENSIONS into absolute paths. Anything else is an error, not a guess. */ |
| 76 | export function parseExtensionPaths(value: string | undefined): string[] { |
| 77 | if (!value || !value.trim()) return []; |
| 78 | const out: string[] = []; |
| 79 | for (const raw of value.split(":")) { |
| 80 | const p = raw.trim(); |
| 81 | if (!p) continue; |
| 82 | if (!isAbsolute(p)) throw new Error(`DBB_EXTENSIONS: "${p}" is not an absolute path`); |
| 83 | if (!/\.(mjs|js)$/.test(p)) throw new Error(`DBB_EXTENSIONS: "${p}" is not a .mjs or .js file`); |
| 84 | if (!existsSync(p) || !statSync(p).isFile()) throw new Error(`DBB_EXTENSIONS: "${p}" is not a file`); |
| 85 | // Code that runs with the browser's privileges must belong to the person running it and not be changeable by anyone else. |
| 86 | const uid = typeof process.getuid === "function" ? process.getuid() : null; |
| 87 | for (const path of [p, dirname(p)]) { |
| 88 | const st = statSync(path); |
| 89 | if (uid !== null && st.uid !== uid) throw new Error(`DBB_EXTENSIONS: "${path}" is not owned by the user running the browser`); |
| 90 | if ((st.mode & 0o022) !== 0) throw new Error(`DBB_EXTENSIONS: "${path}" can be written by other users (group or others); tighten its permissions`); |
| 91 | } |
| 92 | out.push(p); |
| 93 | } |
| 94 | return out; |
| 95 | } |
| 96 | |
| 97 | /** Load each file and let it register. Throws on the first failure. */ |
| 98 | export async function loadExtensions<Page>(paths: string[], registry: ExtensionRegistry<Page>, announce: (file: string) => void = () => {}): Promise<void> { |
| 99 | for (const file of paths) { |
| 100 | const mod = (await import(/* @vite-ignore */ pathToFileURL(file).href)) as { register?: (api: ExtensionApi<Page>) => unknown }; |
| 101 | if (typeof mod.register !== "function") throw new Error(`${file}: an extension must export a function named register`); |
| 102 | await mod.register(registry.apiFor(file)); |
| 103 | registry.loaded.push(file); |
| 104 | announce(file); |
| 105 | } |
| 106 | } |