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
plugin-service.ts · 22.6 KB · 481 lines
| 1 | /** |
| 2 | * Installed plugins on this computer: fetching one from gitstable, checking it, keeping it, and saying which style rules |
| 3 | * a page gets. No Electron here (the fetch and the folder are passed in), so it is tested without a browser. |
| 4 | * |
| 5 | * Install is two steps. preview() fetches and checks everything and keeps it in memory under a token; install(token) |
| 6 | * writes exactly what was previewed. What the person agreed to is what lands on disk, never a second download. |
| 7 | * |
| 8 | * On disk, in <dir> (the browser's userData/plugins, only you can read it): |
| 9 | * installed.json {v:1, allOff, plugins: Installed[]} |
| 10 | * <id>/<path> each file, as fetched |
| 11 | * load() checks each file's sha256 against installed.json; a plugin whose files changed is reported and not applied. |
| 12 | */ |
| 13 | import { randomUUID } from "node:crypto"; |
| 14 | import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 15 | import { dirname, join } from "node:path"; |
| 16 | import { compareVersions, parseVersion } from "./version.js"; |
| 17 | import { |
| 18 | MANIFEST_FILE, MAX_MANIFEST_BYTES, MAX_STYLE_BYTES, MAX_VIEW_BYTES, gitBlobId, isCommit, parsePluginSource, parseTagRefs, safeRepoPath, sha256, |
| 19 | siteMatches, styleProblem, validateManifest, type Installed, type PluginButton, type PluginKind, type RuleManifest, |
| 20 | } from "./plugins.js"; |
| 21 | import { validateViewRule, type ViewRule } from "./cards.js"; |
| 22 | |
| 23 | export interface Fetched { status: number; header(name: string): string | null; bytes: Uint8Array } |
| 24 | |
| 25 | export interface PluginDeps { |
| 26 | /** GET without cookies, outside the payment handler. Rejects on network failure. */ |
| 27 | /** `fresh`: ask the server whether a cached copy is still current (the plugin list); files at a commit never change. */ |
| 28 | fetch(url: string, fresh?: boolean): Promise<Fetched>; |
| 29 | /** The folder plugins are kept in. */ |
| 30 | dir: string; |
| 31 | /** gitstable, e.g. https://gitstable.com. */ |
| 32 | origin: string; |
| 33 | apiLevel: number; |
| 34 | /** The browser's version as shown (2026.11v1), to say whether a plugin was tested on it. */ |
| 35 | browserVersion: string; |
| 36 | now(): Date; |
| 37 | } |
| 38 | |
| 39 | export interface PluginView extends Installed { |
| 40 | /** Why it is not applied (its files changed on disk), or "" when it is fine. */ |
| 41 | problem: string; |
| 42 | testedHere: boolean; |
| 43 | } |
| 44 | |
| 45 | export interface PreviewView { |
| 46 | token: string; |
| 47 | id: string; |
| 48 | name: string; |
| 49 | version: string; |
| 50 | description: string; |
| 51 | license: string; |
| 52 | sites: string[]; |
| 53 | powers: string[]; |
| 54 | repository: string; |
| 55 | tag: string; |
| 56 | commit: string; |
| 57 | testedOn: string[]; |
| 58 | testedHere: boolean; |
| 59 | /** The version this would replace, when the same plugin is installed already. */ |
| 60 | replaces: string | null; |
| 61 | /** |
| 62 | * How this release compares with the installed one: "new" (not installed), "newer" (an update), "same" (this exact |
| 63 | * release and commit is what is installed), "older", or "other" (same plugin, a version that can't be compared). |
| 64 | */ |
| 65 | relation: "new" | "newer" | "same" | "older" | "other"; |
| 66 | /** The installed copy is switched off because its files changed: installing again repairs it. */ |
| 67 | installedProblem: boolean; |
| 68 | /** One sentence for the person: what it will do and what it can't. */ |
| 69 | says: string; |
| 70 | } |
| 71 | |
| 72 | /** One plugin in gitstable's list (/store/plugins.json), as much as the browser uses. */ |
| 73 | export interface Listed { |
| 74 | id: string; |
| 75 | kind: PluginKind; |
| 76 | name: string; |
| 77 | summary: string; |
| 78 | repository: string; |
| 79 | tag: string; |
| 80 | commit: string; |
| 81 | sites: string[]; |
| 82 | /** Its page on gitstable, and its repository's page: being on either offers to install it. */ |
| 83 | url: string; |
| 84 | repositoryUrl: string; |
| 85 | } |
| 86 | |
| 87 | /** How long a fetched list is used before it is fetched again (gitstable caches it for 5 minutes too). */ |
| 88 | export const LISTING_MS = 5 * 60_000; |
| 89 | /** On a plugin's own page, a list older than this is fetched again (see refreshListingOn). */ |
| 90 | export const LISTING_FRESH_ON_PAGE_MS = 60_000; |
| 91 | const MAX_LISTING_BYTES = 1024 * 1024; |
| 92 | |
| 93 | /** Reads gitstable's list, keeping only well-formed items whose pages are on gitstable itself. */ |
| 94 | export function parseListing(raw: unknown, origin: string): Listed[] { |
| 95 | const doc = raw as { v?: unknown; items?: unknown }; |
| 96 | if (!doc || doc.v !== 1 || !Array.isArray(doc.items)) return []; |
| 97 | const onSite = (u: unknown) => { |
| 98 | try { |
| 99 | return typeof u === "string" && new URL(u).origin === origin ? u : ""; |
| 100 | } catch { |
| 101 | return ""; |
| 102 | } |
| 103 | }; |
| 104 | const out: Listed[] = []; |
| 105 | for (const it of doc.items.slice(0, 1000) as Array<Record<string, unknown>>) { |
| 106 | if (!it || typeof it !== "object" || (it.kind !== "style-rule" && it.kind !== "view-rule")) continue; |
| 107 | const src = parsePluginSource(String(it.repository ?? ""), origin); |
| 108 | if ("error" in src || typeof it.id !== "string" || typeof it.name !== "string" || typeof it.tag !== "string" || !isCommit(it.commit)) continue; |
| 109 | out.push({ |
| 110 | id: it.id, kind: it.kind as PluginKind, name: it.name.slice(0, 80), summary: typeof it.summary === "string" ? it.summary.slice(0, 300) : "", repository: src.repository, |
| 111 | tag: it.tag, commit: it.commit, sites: Array.isArray(it.sites) ? it.sites.map(String).slice(0, 50) : [], |
| 112 | url: onSite(it.url), repositoryUrl: onSite(it.repository_url), |
| 113 | }); |
| 114 | } |
| 115 | return out; |
| 116 | } |
| 117 | |
| 118 | export class PluginError extends Error { |
| 119 | constructor(public code: string, message: string) { |
| 120 | super(message); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | interface Pending { view: PreviewView; manifest: RuleManifest; files: Array<{ path: string; bytes: Uint8Array; blob: string }>; at: number } |
| 125 | |
| 126 | const PENDING_MS = 10 * 60_000; |
| 127 | |
| 128 | /** "x.com", "x.com and twitter.com", "a, b and c", "a, b, c and 2 more". */ |
| 129 | export function siteList(sites: readonly string[]): string { |
| 130 | if (sites.length > 3) return `${sites.slice(0, 3).join(", ")} and ${sites.length - 3} more`; |
| 131 | return sites.length <= 1 ? sites.join("") : `${sites.slice(0, -1).join(", ")} and ${sites[sites.length - 1]}`; |
| 132 | } |
| 133 | |
| 134 | export function describePowers(sites: readonly string[], kind: PluginKind = "style-rule", button?: PluginButton): string { |
| 135 | const list = siteList(sites); |
| 136 | if (kind === "view-rule") { |
| 137 | return `It adds a ${button?.label ?? "view"} button to the status bar on ${list}: it reads the posts there and shows them as cards in a tab of the browser's own, scrolling the page to read more. It can't run code, change the page or send anything.`; |
| 138 | } |
| 139 | return `It changes how ${list} look${sites.length === 1 ? "s" : ""}. It can't run code, read the page or send anything.`; |
| 140 | } |
| 141 | |
| 142 | /** How a looked-up release compares with what is installed (see PreviewView.relation). */ |
| 143 | export function relationTo(installed: Installed | undefined, version: string, commit: string): PreviewView["relation"] { |
| 144 | if (!installed) return "new"; |
| 145 | if (installed.version === version && installed.source.commit === commit) return "same"; |
| 146 | const a = parseVersion(version); |
| 147 | const b = parseVersion(installed.version); |
| 148 | if (!a || !b) return "other"; |
| 149 | const c = compareVersions(a, b); |
| 150 | return c > 0 ? "newer" : c < 0 ? "older" : "other"; // same version name at another commit: a re-tag, shown as "other" |
| 151 | } |
| 152 | |
| 153 | export class PluginStore { |
| 154 | private plugins: Installed[] = []; |
| 155 | private problems = new Map<string, string>(); |
| 156 | private css = new Map<string, string>(); |
| 157 | private views = new Map<string, ViewRule>(); |
| 158 | private pending = new Map<string, Pending>(); |
| 159 | allOff = false; |
| 160 | private listing: Listed[] = []; |
| 161 | private listingAt = 0; |
| 162 | private listingFetch: Promise<boolean> | null = null; |
| 163 | |
| 164 | constructor(private d: PluginDeps) {} |
| 165 | |
| 166 | /** gitstable's list of plugins, as last fetched (empty until then). */ |
| 167 | listed(): Listed[] { |
| 168 | return this.listing; |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Fetches gitstable's list unless it was fetched in the last 5 minutes (or `force`). The whole list is fetched, never |
| 173 | * "what's there for this site", so gitstable doesn't learn which page anyone is on. Resolves true when it changed. |
| 174 | */ |
| 175 | refreshListing(force = false): Promise<boolean> { |
| 176 | if (!force && this.d.now().getTime() - this.listingAt < LISTING_MS) return Promise.resolve(false); |
| 177 | this.listingFetch ??= (async () => { |
| 178 | try { |
| 179 | const r = await this.get(`${this.d.origin}/store/plugins.json`, MAX_LISTING_BYTES, "the plugin list", true); |
| 180 | const next = parseListing(JSON.parse(new TextDecoder().decode(r.bytes)), this.d.origin); |
| 181 | this.listingAt = this.d.now().getTime(); |
| 182 | const changed = JSON.stringify(next) !== JSON.stringify(this.listing); |
| 183 | this.listing = next; |
| 184 | return changed; |
| 185 | } catch { |
| 186 | this.listingAt = this.d.now().getTime() - LISTING_MS + 60_000; // try again in a minute, not on every page |
| 187 | return false; |
| 188 | } finally { |
| 189 | this.listingFetch = null; |
| 190 | } |
| 191 | })(); |
| 192 | return this.listingFetch; |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * On gitstable: the list as usual (at most every 5 minutes), but on a listed plugin's own page a copy older than a |
| 197 | * minute is fetched again, so a release made minutes ago is offered there (Update), not the one before it. |
| 198 | */ |
| 199 | refreshListingOn(url: string): Promise<boolean> { |
| 200 | const page = (u: string) => { |
| 201 | try { |
| 202 | const x = new URL(u); |
| 203 | return x.origin + x.pathname.replace(/\/+$/, ""); |
| 204 | } catch { |
| 205 | return ""; |
| 206 | } |
| 207 | }; |
| 208 | const here = page(url); |
| 209 | const onPluginPage = !!here && this.listing.some((l) => (l.url && page(l.url) === here) || (l.repositoryUrl && page(l.repositoryUrl) === here)); |
| 210 | const stale = this.d.now().getTime() - this.listingAt >= LISTING_FRESH_ON_PAGE_MS; |
| 211 | return this.refreshListing(onPluginPage && stale); |
| 212 | } |
| 213 | |
| 214 | /** |
| 215 | * A gitstable page opened with ?install=owner/repo@tag (its Install button): the release to look up, but only for a |
| 216 | * plugin in gitstable's list. Anyone can make a repository there, so a link naming one that isn't listed does nothing. |
| 217 | * Nothing is installed here: the caller opens Plugins with this looked up, and Install stays the person's click. |
| 218 | */ |
| 219 | installLinkSource(url: string): string | null { |
| 220 | let asked: string | null = null; |
| 221 | try { |
| 222 | const u = new URL(url); |
| 223 | if (u.origin !== this.d.origin) return null; |
| 224 | asked = u.searchParams.get("install"); |
| 225 | } catch { |
| 226 | return null; |
| 227 | } |
| 228 | if (!asked || /:|\/\//.test(asked)) return null; |
| 229 | const src = parsePluginSource(asked, this.d.origin); |
| 230 | if ("error" in src || !this.listing.some((l) => l.repository === src.repository)) return null; |
| 231 | return src.tag ? `${src.repository}@${src.tag}` : src.repository; |
| 232 | } |
| 233 | |
| 234 | private get indexPath() { return join(this.d.dir, "installed.json"); } |
| 235 | |
| 236 | /** Reads what is installed and checks every file. Safe to call again (the automation API's recheck). */ |
| 237 | load(): void { |
| 238 | this.plugins = []; |
| 239 | this.problems.clear(); |
| 240 | this.css.clear(); |
| 241 | this.views.clear(); |
| 242 | let raw: { allOff?: unknown; plugins?: unknown } = {}; |
| 243 | try { |
| 244 | raw = JSON.parse(readFileSync(this.indexPath, "utf8")); |
| 245 | } catch { |
| 246 | raw = {}; |
| 247 | } |
| 248 | this.allOff = raw.allOff === true; |
| 249 | this.plugins = Array.isArray(raw.plugins) ? (raw.plugins as Installed[]).filter((p) => p && typeof p.id === "string") : []; |
| 250 | for (const p of this.plugins) { |
| 251 | try { |
| 252 | for (const f of p.files) { |
| 253 | if (!safeRepoPath(f.path, f.path.endsWith(".json") ? ".json" : ".css")) throw new Error("bad path"); |
| 254 | const bytes = readFileSync(join(this.d.dir, p.id, f.path)); |
| 255 | if (sha256(bytes) !== f.sha256) throw new Error("changed"); |
| 256 | const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); |
| 257 | if ((p.kind ?? "style-rule") === "style-rule" && f.path.endsWith(".css")) this.css.set(p.id, text); |
| 258 | if (p.kind === "view-rule" && f.path !== MANIFEST_FILE && f.path.endsWith(".json")) { |
| 259 | const r = validateViewRule(JSON.parse(text)); |
| 260 | if (!r.ok) throw new Error(r.error); |
| 261 | this.views.set(p.id, r.rule); |
| 262 | } |
| 263 | } |
| 264 | if (p.kind === "view-rule") { |
| 265 | if (!this.views.has(p.id)) throw new Error("its view file is missing"); |
| 266 | } else { |
| 267 | const css = this.css.get(p.id); |
| 268 | const why = css === undefined ? "its style file is missing" : styleProblem(css); |
| 269 | if (why) throw new Error(why); |
| 270 | } |
| 271 | } catch { |
| 272 | this.css.delete(p.id); |
| 273 | this.views.delete(p.id); |
| 274 | this.problems.set(p.id, "Its files changed on this computer since it was installed, so it is switched off. Remove it and install it again."); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | list(): PluginView[] { |
| 280 | return this.plugins.map((p) => ({ ...p, problem: this.problems.get(p.id) ?? "", testedHere: p.testedOn.includes(this.d.browserVersion) })); |
| 281 | } |
| 282 | |
| 283 | /** The style sheets a page on `host` gets: enabled, intact, matching plugins (none when all are off). */ |
| 284 | stylesFor(host: string): Array<{ id: string; css: string }> { |
| 285 | if (this.allOff || !host) return []; |
| 286 | const out: Array<{ id: string; css: string }> = []; |
| 287 | for (const p of this.plugins) { |
| 288 | const css = this.css.get(p.id); |
| 289 | if (p.enabled && css !== undefined && !this.problems.has(p.id) && siteMatches(host, p.sites)) out.push({ id: p.id, css }); |
| 290 | } |
| 291 | return out; |
| 292 | } |
| 293 | |
| 294 | /** The view rules for `host`: enabled, intact, matching plugins (none when all are off), each with its button. */ |
| 295 | viewsFor(host: string): Array<{ id: string; name: string; button: PluginButton; rule: ViewRule }> { |
| 296 | if (this.allOff || !host) return []; |
| 297 | const out: Array<{ id: string; name: string; button: PluginButton; rule: ViewRule }> = []; |
| 298 | for (const p of this.plugins) { |
| 299 | const rule = this.views.get(p.id); |
| 300 | if (p.kind === "view-rule" && p.button && rule && p.enabled && !this.problems.has(p.id) && siteMatches(host, p.sites)) out.push({ id: p.id, name: p.name, button: p.button, rule }); |
| 301 | } |
| 302 | return out; |
| 303 | } |
| 304 | |
| 305 | private async get(url: string, limit: number, what: string, fresh = false): Promise<Fetched> { |
| 306 | let r: Fetched; |
| 307 | try { |
| 308 | r = await this.d.fetch(url, fresh); |
| 309 | } catch (e) { |
| 310 | throw new PluginError("network", `Could not reach ${new URL(url).host} (${(e as Error).message})`); |
| 311 | } |
| 312 | if (r.status === 404) throw new PluginError("not-found", `${what} was not found on ${new URL(url).host}`); |
| 313 | if (r.status !== 200) throw new PluginError("server", `${new URL(url).host} answered ${r.status} for ${what}`); |
| 314 | if (r.bytes.length > limit) throw new PluginError("too-big", `${what} is larger than ${Math.round(limit / 1024)} KB`); |
| 315 | return r; |
| 316 | } |
| 317 | |
| 318 | /** A file at a commit, checked against the git blob id the server sends with it. */ |
| 319 | private async fileAt(repository: string, commit: string, path: string, limit: number): Promise<{ bytes: Uint8Array; blob: string }> { |
| 320 | const url = `${this.d.origin}/repositories/${repository}/raw/${path}?at=${commit}`; |
| 321 | const r = await this.get(url, limit, path); |
| 322 | const said = (r.header("x-git-blob") || "").toLowerCase(); |
| 323 | const sentCommit = (r.header("x-git-commit") || "").toLowerCase(); |
| 324 | if (sentCommit && sentCommit !== commit) throw new PluginError("mismatch", `${path} came from commit ${sentCommit.slice(0, 7)}, not ${commit.slice(0, 7)}`); |
| 325 | const blob = gitBlobId(r.bytes); |
| 326 | if (!isCommit(said)) throw new PluginError("unchecked", `${path} came without its git blob id (X-Git-Blob), so it can't be checked`); |
| 327 | if (said !== blob) throw new PluginError("mismatch", `${path} doesn't match its git blob id: it changed on the way`); |
| 328 | return { bytes: r.bytes, blob }; |
| 329 | } |
| 330 | |
| 331 | /** |
| 332 | * A plugin's name alone ("x-whole-window", "x-whole-window@2026.11v1") → owner/repository: an installed plugin's own |
| 333 | * source first, then gitstable's list (fetched now if it is older than 5 minutes; a look-up goes to gitstable anyway). |
| 334 | * Anything with a slash or an address is returned as typed. |
| 335 | */ |
| 336 | private async resolveName(source: string): Promise<string> { |
| 337 | const m = /^([A-Za-z0-9._-]+)(@[^@/\s]+)?$/.exec(source.trim()); |
| 338 | if (!m) return source; |
| 339 | const name = (m[1] ?? "").toLowerCase(); |
| 340 | const at = m[2] ?? ""; |
| 341 | const tail = (repo: string) => repo.split("/")[1]?.toLowerCase(); |
| 342 | const mine = this.plugins.find((p) => p.id === name || tail(p.source.repository) === name); |
| 343 | if (mine) return mine.source.repository + at; |
| 344 | await this.refreshListing(); |
| 345 | const listed = this.listing.filter((l) => l.id === name || tail(l.repository) === name); |
| 346 | if (listed.length === 1) return listed[0]!.repository + at; |
| 347 | if (listed.length > 1) throw new PluginError("bad-source", `more than one plugin is called ${name}: write it as owner/repository (${listed.map((l) => l.repository).join(", ")})`); |
| 348 | throw new PluginError("bad-source", `no installed or listed plugin is called ${name}: write it as owner/repository`); |
| 349 | } |
| 350 | |
| 351 | /** Fetches and checks a plugin; nothing is written. `source`: owner/repo, owner/repo@version, its gitstable address, or a plugin's name. */ |
| 352 | async preview(source: string): Promise<PreviewView> { |
| 353 | const src = parsePluginSource(await this.resolveName(source), this.d.origin); |
| 354 | if ("error" in src) throw new PluginError("bad-source", src.error); |
| 355 | const refsUrl = `${this.d.origin}/git/${src.repository}.git/info/refs?service=git-upload-pack`; |
| 356 | const refs = parseTagRefs(new TextDecoder().decode((await this.get(refsUrl, 2 * 1024 * 1024, `the repository ${src.repository}`)).bytes)); |
| 357 | let tag = src.tag; |
| 358 | if (!tag) { |
| 359 | const releases = [...refs.keys()].map((t) => ({ t, v: parseVersion(t) })).filter((x) => x.v && !x.v.pre); |
| 360 | releases.sort((a, b) => compareVersions(b.v!, a.v!)); |
| 361 | tag = releases[0]?.t ?? null; |
| 362 | if (!tag) throw new PluginError("no-release", `${src.repository} has no release yet (a tag such as 2026.11v1)`); |
| 363 | } |
| 364 | const commit = refs.get(tag); |
| 365 | if (!commit) throw new PluginError("not-found", `${src.repository} has no release ${tag}`); |
| 366 | |
| 367 | const mf = await this.fileAt(src.repository, commit, MANIFEST_FILE, MAX_MANIFEST_BYTES); |
| 368 | let raw: unknown; |
| 369 | try { |
| 370 | raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(mf.bytes)); |
| 371 | } catch { |
| 372 | throw new PluginError("bad-plugin", `${MANIFEST_FILE} is not valid JSON`); |
| 373 | } |
| 374 | const v = validateManifest(raw, this.d.apiLevel); |
| 375 | if (!v.ok) throw new PluginError("bad-plugin", v.error); |
| 376 | const m = v.manifest; |
| 377 | if (m.version !== tag) throw new PluginError("bad-plugin", `the release is tagged ${tag} but ${MANIFEST_FILE} says ${m.version}`); |
| 378 | const owner = this.plugins.find((p) => p.id === m.id); |
| 379 | if (owner && owner.source.repository.toLowerCase() !== src.repository.toLowerCase()) { |
| 380 | throw new PluginError("taken", `a different plugin called "${m.id}" is installed already (from ${owner.source.repository})`); |
| 381 | } |
| 382 | const mainPath = m.kind === "view-rule" ? m.view! : m.style; |
| 383 | const main = await this.fileAt(src.repository, commit, mainPath, m.kind === "view-rule" ? MAX_VIEW_BYTES : MAX_STYLE_BYTES); |
| 384 | let text: string; |
| 385 | try { |
| 386 | text = new TextDecoder("utf-8", { fatal: true }).decode(main.bytes); |
| 387 | } catch { |
| 388 | throw new PluginError("bad-plugin", `${mainPath} is not text`); |
| 389 | } |
| 390 | if (m.kind === "view-rule") { |
| 391 | let rawRule: unknown; |
| 392 | try { |
| 393 | rawRule = JSON.parse(text); |
| 394 | } catch { |
| 395 | throw new PluginError("bad-plugin", `${mainPath} is not valid JSON`); |
| 396 | } |
| 397 | const r = validateViewRule(rawRule); |
| 398 | if (!r.ok) throw new PluginError("not-view-only", `${mainPath} is refused: ${r.error}. A view rule may only name where a page keeps its posts`); |
| 399 | const outside = r.rule.sites.find((site) => !siteMatches(site, m.sites)); |
| 400 | if (outside) throw new PluginError("bad-plugin", `${mainPath} reads ${outside}, which the plugin doesn't name in its sites`); |
| 401 | } else { |
| 402 | const why = styleProblem(text); |
| 403 | if (why) throw new PluginError("not-style-only", `${m.style} is refused: ${why}. A style rule may only change how pages look`); |
| 404 | } |
| 405 | |
| 406 | for (const [t, p] of this.pending) if (this.d.now().getTime() - p.at > PENDING_MS) this.pending.delete(t); |
| 407 | const token = randomUUID(); |
| 408 | const view: PreviewView = { |
| 409 | token, id: m.id, name: m.name, version: m.version, description: m.description, license: m.license, sites: m.sites, powers: m.powers, |
| 410 | repository: src.repository, tag, commit, testedOn: m.tested_on, testedHere: m.tested_on.includes(this.d.browserVersion), |
| 411 | replaces: owner ? owner.version : null, relation: relationTo(owner, m.version, commit), |
| 412 | installedProblem: owner ? this.problems.has(owner.id) : false, says: describePowers(m.sites, m.kind, m.button), |
| 413 | }; |
| 414 | this.pending.set(token, { |
| 415 | view, manifest: m, at: this.d.now().getTime(), |
| 416 | files: [{ path: MANIFEST_FILE, ...mf }, { path: mainPath, ...main }], |
| 417 | }); |
| 418 | return view; |
| 419 | } |
| 420 | |
| 421 | /** Writes what preview() checked. The token is used once. */ |
| 422 | install(token: string): PluginView { |
| 423 | const p = this.pending.get(token); |
| 424 | if (!p || this.d.now().getTime() - p.at > PENDING_MS) throw new PluginError("expired", "That preview has expired; look the plugin up again"); |
| 425 | this.pending.delete(token); |
| 426 | const m = p.manifest; |
| 427 | const home = join(this.d.dir, m.id); |
| 428 | rmSync(home, { recursive: true, force: true }); |
| 429 | for (const f of p.files) { |
| 430 | const to = join(home, f.path); |
| 431 | mkdirSync(dirname(to), { recursive: true, mode: 0o700 }); |
| 432 | writeFileSync(to, f.bytes, { mode: 0o600 }); |
| 433 | } |
| 434 | const was = this.plugins.find((x) => x.id === m.id); |
| 435 | const rec: Installed = { |
| 436 | id: m.id, name: m.name, version: m.version, description: m.description, license: m.license, sites: m.sites, powers: m.powers, |
| 437 | testedOn: m.tested_on, kind: m.kind, ...(m.button ? { button: m.button } : {}), source: { host: new URL(this.d.origin).host, repository: p.view.repository, tag: p.view.tag, commit: p.view.commit }, |
| 438 | files: p.files.map((f) => ({ path: f.path, blob: f.blob, sha256: sha256(f.bytes), bytes: f.bytes.length })), |
| 439 | installedAt: this.d.now().toISOString(), enabled: was ? was.enabled : true, |
| 440 | }; |
| 441 | this.plugins = this.plugins.filter((x) => x.id !== m.id).concat(rec); |
| 442 | this.save(); |
| 443 | this.load(); |
| 444 | return this.list().find((x) => x.id === m.id)!; |
| 445 | } |
| 446 | |
| 447 | setEnabled(id: string, enabled: boolean): void { |
| 448 | const p = this.plugins.find((x) => x.id === id); |
| 449 | if (!p) throw new PluginError("not-found", `no plugin "${id}" is installed`); |
| 450 | p.enabled = enabled; |
| 451 | this.save(); |
| 452 | } |
| 453 | |
| 454 | setAllOff(off: boolean): void { |
| 455 | this.allOff = off; |
| 456 | this.save(); |
| 457 | } |
| 458 | |
| 459 | remove(id: string): void { |
| 460 | if (!this.plugins.some((x) => x.id === id)) throw new PluginError("not-found", `no plugin "${id}" is installed`); |
| 461 | this.plugins = this.plugins.filter((x) => x.id !== id); |
| 462 | this.save(); |
| 463 | rmSync(join(this.d.dir, id), { recursive: true, force: true }); |
| 464 | this.problems.delete(id); |
| 465 | this.css.delete(id); |
| 466 | this.views.delete(id); |
| 467 | } |
| 468 | |
| 469 | private save(): void { |
| 470 | mkdirSync(this.d.dir, { recursive: true, mode: 0o700 }); |
| 471 | writeFileSync(this.indexPath, JSON.stringify({ v: 1, allOff: this.allOff, plugins: this.plugins }, null, 2) + "\n", { mode: 0o600 }); |
| 472 | try { |
| 473 | chmodSync(this.indexPath, 0o600); |
| 474 | } catch {} |
| 475 | } |
| 476 | |
| 477 | /** For tests: whether anything is kept on disk at all. */ |
| 478 | hasIndex(): boolean { |
| 479 | return existsSync(this.indexPath); |
| 480 | } |
| 481 | } |