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
plugins.ts · 11.6 KB · 220 lines
| 1 | /** |
| 2 | * Plugins, of two kinds. A view rule (kind "view-rule", power "read-posts") names, by CSS selectors only, where its |
| 3 | * sites keep their posts; it adds a button to the status bar on those sites that shows the posts as cards (cards.ts |
| 4 | * reads them and checks the rule). Its button's icon is one of a fixed set the browser draws. |
| 5 | * |
| 6 | * The first kind: the style rule. A style rule is CSS for the sites it names and nothing else: it cannot run code, |
| 7 | * read the page or send anything. That last promise is kept here, by refusing any CSS that could make a request (url(), |
| 8 | * @import, image-set(), @font-face…) or hide one behind an escape, so "style only" means what it says. |
| 9 | * |
| 10 | * A plugin lives in a repository on gitstable and is installed from a release tag, fetched file by file at the commit |
| 11 | * that tag points to. Every file is checked against the git blob id the server sends (X-Git-Blob), and its sha256 is |
| 12 | * kept, so a copy changed on disk afterwards is noticed at the next start and switched off. |
| 13 | * |
| 14 | * dbbasic-rule.json, v1: |
| 15 | * {"v":1, "id":"x-whole-window", "name":"X uses the whole window", "kind":"style-rule", "version":"2026.11v1", |
| 16 | * "sites":["x.com","twitter.com"], "powers":["style"], "style":"x-whole-window.css", "min_api":1, |
| 17 | * "tested_on":["2026.11v1"], "license":"MIT", "description":"…"} |
| 18 | * |
| 19 | * Pure functions only (no Electron, no fs), so all of it is unit-tested. |
| 20 | */ |
| 21 | import { createHash } from "node:crypto"; |
| 22 | |
| 23 | export const MANIFEST_FILE = "dbbasic-rule.json"; |
| 24 | export const MAX_MANIFEST_BYTES = 16 * 1024; |
| 25 | export const MAX_STYLE_BYTES = 256 * 1024; |
| 26 | /** The powers this browser knows. A plugin asking for any other is refused, never half-installed. */ |
| 27 | export const KNOWN_POWERS = ["style", "read-posts"] as const; |
| 28 | export const MAX_VIEW_BYTES = 64 * 1024; |
| 29 | /** |
| 30 | * The icons a plugin's status-bar button may use. They are drawn by the browser: a plugin names one and can't bring its |
| 31 | * own picture, so its button can't look like one of the browser's own controls. |
| 32 | */ |
| 33 | export const PLUGIN_ICONS = ["cards", "grid", "list", "columns"] as const; |
| 34 | |
| 35 | export type PluginKind = "style-rule" | "view-rule"; |
| 36 | export interface PluginButton { |
| 37 | label: string; |
| 38 | icon: (typeof PLUGIN_ICONS)[number]; |
| 39 | } |
| 40 | |
| 41 | export interface RuleManifest { |
| 42 | v: 1; |
| 43 | id: string; |
| 44 | name: string; |
| 45 | /** |
| 46 | * "style-rule": CSS for its sites (`style`, power "style"). "view-rule": where its sites keep their posts (`view`, a |
| 47 | * view rule: selectors only), shown as cards from a button in the status bar (`button`, power "read-posts"). |
| 48 | */ |
| 49 | kind: PluginKind; |
| 50 | version: string; |
| 51 | sites: string[]; |
| 52 | powers: string[]; |
| 53 | /** The .css file (style rules). */ |
| 54 | style: string; |
| 55 | /** The view rule's .json file (view rules). */ |
| 56 | view?: string; |
| 57 | /** Its status-bar button (view rules). */ |
| 58 | button?: PluginButton; |
| 59 | min_api: number; |
| 60 | tested_on: string[]; |
| 61 | license: string; |
| 62 | description: string; |
| 63 | } |
| 64 | |
| 65 | /** One installed plugin, as kept in plugins/installed.json. */ |
| 66 | export interface Installed { |
| 67 | id: string; |
| 68 | name: string; |
| 69 | version: string; |
| 70 | description: string; |
| 71 | license: string; |
| 72 | sites: string[]; |
| 73 | powers: string[]; |
| 74 | testedOn: string[]; |
| 75 | /** "style-rule" when missing (installed before view rules existed). */ |
| 76 | kind?: PluginKind; |
| 77 | /** A view rule's status-bar button. */ |
| 78 | button?: PluginButton; |
| 79 | /** Where it came from: the gitstable host, "owner/repo", the tag and the commit it was installed at. */ |
| 80 | source: { host: string; repository: string; tag: string; commit: string }; |
| 81 | files: Array<{ path: string; blob: string; sha256: string; bytes: number }>; |
| 82 | installedAt: string; |
| 83 | enabled: boolean; |
| 84 | } |
| 85 | |
| 86 | const ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/; |
| 87 | const HOST = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$|^(?:localhost|127\.0\.0\.1)$/; |
| 88 | const HEX40 = /^[0-9a-f]{40}$/; |
| 89 | const REPO = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; |
| 90 | const TAG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; |
| 91 | |
| 92 | /** A path inside the repository: relative, forward slashes, no "..", no hidden tricks. */ |
| 93 | export function safeRepoPath(p: unknown, ext: string): p is string { |
| 94 | return ( |
| 95 | typeof p === "string" && p.length > 0 && p.length <= 200 && p.endsWith(ext) && |
| 96 | /^[A-Za-z0-9._/-]+$/.test(p) && !p.startsWith("/") && !p.split("/").some((s) => s === "" || s === "." || s === "..") |
| 97 | ); |
| 98 | } |
| 99 | |
| 100 | /** Checks a dbbasic-rule.json. Returns the manifest, or what is wrong with it in words a person can act on. */ |
| 101 | export function validateManifest(raw: unknown, apiLevel: number): { ok: true; manifest: RuleManifest } | { ok: false; error: string } { |
| 102 | const bad = (error: string) => ({ ok: false as const, error }); |
| 103 | if (!raw || typeof raw !== "object" || Array.isArray(raw)) return bad("dbbasic-rule.json is not a JSON object"); |
| 104 | const m = raw as Record<string, unknown>; |
| 105 | if (m.v !== 1) return bad(`dbbasic-rule.json is format ${JSON.stringify(m.v)}; this browser reads format 1`); |
| 106 | if (m.kind !== "style-rule" && m.kind !== "view-rule") return bad(`this browser installs style rules and view rules, not "${String(m.kind)}"`); |
| 107 | if (typeof m.id !== "string" || !ID.test(m.id)) return bad("the plugin's id must be lowercase letters, digits and dashes"); |
| 108 | if (typeof m.name !== "string" || !m.name.trim() || m.name.length > 80) return bad("the plugin needs a name (up to 80 characters)"); |
| 109 | if (typeof m.version !== "string" || !TAG.test(m.version)) return bad("the plugin needs a version, such as 2026.11v1"); |
| 110 | if (!Array.isArray(m.sites) || !m.sites.length || m.sites.length > 50) return bad("the plugin must name the sites it changes (1 to 50)"); |
| 111 | const sites = m.sites.map((s) => String(s).trim().toLowerCase()); |
| 112 | const off = sites.find((s) => !HOST.test(s)); |
| 113 | if (off !== undefined) return bad(`"${off}" is not a site name (write x.com, or *.example.com for its subdomains only)`); |
| 114 | if (!Array.isArray(m.powers) || !m.powers.length) return bad("the plugin must say what it may do (powers)"); |
| 115 | const unknown = m.powers.find((p) => !(KNOWN_POWERS as readonly string[]).includes(String(p))); |
| 116 | if (unknown !== undefined) return bad(`the plugin asks for "${String(unknown)}", which this browser does not give plugins`); |
| 117 | const powers = [...new Set(m.powers.map(String))]; |
| 118 | let button: PluginButton | undefined; |
| 119 | if (m.kind === "style-rule") { |
| 120 | if (!safeRepoPath(m.style, ".css")) return bad("the plugin's style must be a .css file in its repository"); |
| 121 | if (powers.some((p) => p !== "style")) return bad(`a style rule may only ask for "style"`); |
| 122 | } else { |
| 123 | if (!safeRepoPath(m.view, ".json")) return bad("the plugin's view must be a .json file in its repository"); |
| 124 | if (powers.length !== 1 || powers[0] !== "read-posts") return bad(`a view rule asks for "read-posts" and nothing else`); |
| 125 | const b = m.button as Record<string, unknown> | undefined; |
| 126 | if (!b || typeof b.label !== "string" || !b.label.trim() || b.label.trim().length > 24) return bad("a view rule needs a button label (up to 24 characters)"); |
| 127 | if (!(PLUGIN_ICONS as readonly string[]).includes(String(b.icon))) return bad(`its button's icon must be one of ${PLUGIN_ICONS.join(", ")}`); |
| 128 | button = { label: b.label.trim(), icon: b.icon as PluginButton["icon"] }; |
| 129 | } |
| 130 | const minApi = m.min_api ?? 1; |
| 131 | if (typeof minApi !== "number" || !Number.isInteger(minApi) || minApi < 1) return bad("min_api must be a whole number from 1"); |
| 132 | if (minApi > apiLevel) return bad(`the plugin needs plugin level ${minApi}; this browser has ${apiLevel}. A newer browser will install it`); |
| 133 | const tested = Array.isArray(m.tested_on) ? m.tested_on.map(String).slice(0, 20) : []; |
| 134 | return { |
| 135 | ok: true, |
| 136 | manifest: { |
| 137 | v: 1, id: m.id, name: m.name.trim(), kind: m.kind, version: m.version, sites: [...new Set(sites)], |
| 138 | powers, style: m.kind === "style-rule" ? (m.style as string) : "", ...(m.kind === "view-rule" ? { view: m.view as string, button } : {}), |
| 139 | min_api: minApi, tested_on: tested, |
| 140 | license: typeof m.license === "string" ? m.license.slice(0, 40) : "", |
| 141 | description: typeof m.description === "string" ? m.description.slice(0, 300) : "", |
| 142 | }, |
| 143 | }; |
| 144 | } |
| 145 | |
| 146 | /** The id git gives a file's contents: sha1 of "blob <length>\0" and the bytes. */ |
| 147 | export function gitBlobId(bytes: Uint8Array): string { |
| 148 | return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex"); |
| 149 | } |
| 150 | |
| 151 | export function sha256(bytes: Uint8Array): string { |
| 152 | return createHash("sha256").update(bytes).digest("hex"); |
| 153 | } |
| 154 | |
| 155 | /** "x.com" covers x.com and its subdomains; "*.example.com" only the subdomains. */ |
| 156 | export function siteMatches(host: string, sites: readonly string[]): boolean { |
| 157 | const h = host.toLowerCase().replace(/\.$/, ""); |
| 158 | return sites.some((s) => (s.startsWith("*.") ? h.endsWith(s.slice(1)) : h === s || h.endsWith("." + s))); |
| 159 | } |
| 160 | |
| 161 | /** |
| 162 | * Why this CSS could make a request or read something, or null when it is look-only. Comments are removed first; any |
| 163 | * backslash escape is refused outright, since an escape can spell url( without the letters. |
| 164 | */ |
| 165 | export function styleProblem(css: string): string | null { |
| 166 | if (/\\/.test(css)) return "it uses a backslash escape, which could hide a web address"; |
| 167 | const s = css.replace(/\/\*[\s\S]*?(\*\/|$)/g, " ").toLowerCase(); |
| 168 | const rules: Array<[RegExp, string]> = [ |
| 169 | [/url\s*\(/, "it loads something from an address (url(…))"], |
| 170 | [/@import/, "it loads another style sheet (@import)"], |
| 171 | [/image-set\s*\(|image\s*\(|element\s*\(|cross-fade\s*\(/, "it loads or copies images (image-set(), image(), element())"], |
| 172 | [/@font-face/, "it loads a font (@font-face)"], |
| 173 | [/@namespace/, "it uses @namespace"], |
| 174 | [/expression\s*\(|behavior\s*:|-moz-binding/, "it tries to run code"], |
| 175 | [/src\s*\(/, "it loads something from an address (src(…))"], |
| 176 | ]; |
| 177 | for (const [re, why] of rules) if (re.test(s)) return why; |
| 178 | return null; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * What the person typed → where to install from. "askrobots/x-whole-window", "askrobots/x-whole-window@2026.11v1", or the |
| 183 | * repository's address on gitstable (its page, or the .git clone address). Only `origin` (gitstable) is accepted: an |
| 184 | * address on any other site is refused, so a plugin always comes from the one place that lists and checks plugins. |
| 185 | */ |
| 186 | export function parsePluginSource(text: string, origin: string): { repository: string; tag: string | null } | { error: string } { |
| 187 | let t = text.trim(); |
| 188 | const m = /^(https?:\/\/[^/]+)(\/.*)?$/i.exec(t); |
| 189 | if (m) { |
| 190 | if ((m[1] ?? "").toLowerCase() !== origin.toLowerCase()) return { error: `plugins install from ${origin.replace(/^https?:\/\//, "")} only` }; |
| 191 | t = (m[2] ?? "").replace(/^\/(?:repositories|git)\//, "/").replace(/^\//, "").replace(/\.git$/, "").replace(/\/+$/, ""); |
| 192 | } else { |
| 193 | t = t.replace(/^(?:www\.)?gitstable\.com\//i, ""); |
| 194 | } |
| 195 | const [repo = "", tag, ...more] = t.split("@"); |
| 196 | const repository = repo.split("/").slice(0, 2).join("/"); |
| 197 | if (more.length || !REPO.test(repository) || (tag !== undefined && !TAG.test(tag))) return { error: "write it as owner/repository, or owner/repository@version" }; |
| 198 | return { repository, tag: tag ?? null }; |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Reads the tags out of git's smart-HTTP ref advertisement (GET <repo>.git/info/refs?service=git-upload-pack). |
| 203 | * An annotated tag appears twice; its peeled line (^{}) names the commit, which is what we want. |
| 204 | */ |
| 205 | export function parseTagRefs(body: string): Map<string, string> { |
| 206 | const tags = new Map<string, string>(); |
| 207 | const peeled = new Map<string, string>(); |
| 208 | for (const line of body.split("\n")) { |
| 209 | const m = /([0-9a-f]{40}) refs\/tags\/([^\s\0^]+)(\^\{\})?/.exec(line); |
| 210 | if (!m) continue; |
| 211 | const [, sha = "", name = "", peel] = m; |
| 212 | (peel ? peeled : tags).set(name, sha); |
| 213 | } |
| 214 | for (const [name, sha] of peeled) tags.set(name, sha); |
| 215 | return tags; |
| 216 | } |
| 217 | |
| 218 | export function isCommit(s: unknown): s is string { |
| 219 | return typeof s === "string" && HEX40.test(s); |
| 220 | } |