Setup 972f6209639122f32f032d5f2f9fc5a4808e0d4a810f88ae38ec9a1275ac52ac
Portable a9771f054ec36b9aff6ddee958cecf7e84cdacd4d7932aa8385c445aab4d29be
User-visible rename: the Settings tab and its labels say "Extensions"
now instead of "Add-ons". Internal identifiers (disabledAddons, the
addons/ folder, IPC channels, capability strings) stay put — code
churn wasn't worth it, and users only see the user-facing text.
Draggable sidebar. sidebar-preload.js now injects a 5px grip strip
along the LEFT edge of every panel document. mousedown+mousemove
streams delta-x px to main via sidebar-drag IPC; main clamps to
[200, 800] and debounces a save to settings.sidebarWidth. Width is
restored on next launch. The default is still 340. Faint acid-green
highlight on hover so the affordance is discoverable.
New extension capability: session-proxy. An extension whose addon.json
declares "session-proxy" gets api.setSessionProxy(rules) which routes
to session.defaultSession.setProxy — the same primitive Tor already
uses under the hood. Rules can be a string ("socks5://host:port") or
an object matching Electron's setProxy shape; null clears. The
capability is opt-in: an extension without the declaration gets an
error if it tries to call setSessionProxy. This is the framework
surface a private 3-VPS relay extension would build on (extension
folder stays on the operator's disk only; nothing about it appears in
the public build).
Deployed: scp installers + manifest + tools/ + releases/ pages to
VPS, sia-upload of both trees, verified HEAD 200 and manifest 0.2.2.
216 lines
9.4 KiB
JavaScript
216 lines
9.4 KiB
JavaScript
// Theseus add-on framework — loader + API surface.
|
|
//
|
|
// Add-ons live in <userData>/addons/<id>/ as ordinary folders on disk. Each
|
|
// carries an `addon.json` manifest and (per the manifest's `main` field) a
|
|
// CommonJS entry that exports `activate(api)` and optionally `deactivate()`.
|
|
// Nothing about an add-on ships in the Theseus repo or installer — drop a
|
|
// folder, restart Theseus, it's live. This is the same trust model as
|
|
// dev-mode browser extensions: the user is choosing to run local code with
|
|
// the app's full privileges.
|
|
//
|
|
// Loading is synchronous at app-ready time; there is no hot-reload. Failed
|
|
// activations are logged and skipped without breaking the app.
|
|
//
|
|
// Persistence:
|
|
// settings.disabledAddons — ids the user has toggled off
|
|
// <userData>/addons-data/<id>.json — per-add-on kv store (api.storage)
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
// Extension points the framework understands. Extending this list means also
|
|
// teaching main.js and (typically) the chrome renderer about the new point.
|
|
// Right now only sidebar panels are wired — future rev adds toolbar-chip,
|
|
// proxy, page-inject, etc.
|
|
const KNOWN_CAPABILITIES = new Set(["sidebar-panel", "session-proxy"]);
|
|
|
|
// Manifest field guardrails. Reject anything shape-suspicious so a bad
|
|
// addon.json can't get past the loader gate.
|
|
function validateManifest(raw, folderName) {
|
|
const m = raw && typeof raw === "object" ? raw : {};
|
|
const id = String(m.id || "").trim();
|
|
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(id)) {
|
|
throw new Error(`invalid or missing "id" (allowed: [a-z0-9._-], up to 64 chars) — folder ${folderName}`);
|
|
}
|
|
const name = String(m.name || id);
|
|
const version = String(m.version || "0.0.0");
|
|
const description = String(m.description || "");
|
|
const author = String(m.author || "");
|
|
const icon = String(m.icon || "🧩");
|
|
const main = String(m.main || "index.js");
|
|
if (main.includes("..") || path.isAbsolute(main)) {
|
|
throw new Error(`addon "${id}": main must be a relative path inside the addon folder`);
|
|
}
|
|
const capabilities = Array.isArray(m.capabilities) ? m.capabilities.map(String) : [];
|
|
for (const cap of capabilities) {
|
|
if (!KNOWN_CAPABILITIES.has(cap)) {
|
|
// Not fatal — log later. Unknown caps are silently dropped.
|
|
}
|
|
}
|
|
return { id, name, version, description, author, icon, main, capabilities };
|
|
}
|
|
|
|
// Loader singleton. `discoverAndActivate(opts)` returns a snapshot the rest
|
|
// of the app queries via `getActive()` / `getInstalled()`.
|
|
class AddonHost {
|
|
constructor({ addonsDir, dataDir, isDisabled, logger, setSessionProxy }) {
|
|
this.addonsDir = addonsDir;
|
|
this.dataDir = dataDir;
|
|
this.isDisabled = isDisabled || (() => false);
|
|
this.log = logger || ((...a) => console.log("[addons]", ...a));
|
|
this._installed = []; // [{ manifest, folder, error? }]
|
|
this._active = new Map(); // id -> { manifest, folder, exports, sidebarPanels: [...] }
|
|
// Session-proxy hook — injected by main so add-ons can swap the default
|
|
// session's proxy rules (e.g. a "route everything through my VPS" add-on).
|
|
// Signature: (rules: string | { proxyRules, proxyBypassRules }) => Promise<void>
|
|
// A `null` rule clears the proxy. Kept as a callback rather than requiring
|
|
// the loader itself import electron.
|
|
this._setSessionProxy = typeof setSessionProxy === "function" ? setSessionProxy : null;
|
|
}
|
|
|
|
ensureDirs() {
|
|
for (const d of [this.addonsDir, this.dataDir]) {
|
|
try { fs.mkdirSync(d, { recursive: true }); } catch (e) { this.log("mkdir failed", d, e?.message); }
|
|
}
|
|
}
|
|
|
|
discoverAndActivate() {
|
|
this.ensureDirs();
|
|
this._installed = [];
|
|
let entries = [];
|
|
try { entries = fs.readdirSync(this.addonsDir, { withFileTypes: true }); } catch { entries = []; }
|
|
for (const dirent of entries) {
|
|
if (!dirent.isDirectory()) continue;
|
|
const folder = path.join(this.addonsDir, dirent.name);
|
|
try {
|
|
const manifest = this._readManifest(folder, dirent.name);
|
|
this._installed.push({ manifest, folder });
|
|
if (this.isDisabled(manifest.id)) {
|
|
this.log(`skipping disabled add-on ${manifest.id}`);
|
|
continue;
|
|
}
|
|
this._activateOne(manifest, folder);
|
|
} catch (e) {
|
|
this.log(`failed to load ${dirent.name}: ${e?.message || e}`);
|
|
this._installed.push({ manifest: null, folder, error: String(e?.message || e) });
|
|
}
|
|
}
|
|
return this.snapshot();
|
|
}
|
|
|
|
_readManifest(folder, folderName) {
|
|
const p = path.join(folder, "addon.json");
|
|
const raw = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
return validateManifest(raw, folderName);
|
|
}
|
|
|
|
_activateOne(manifest, folder) {
|
|
const mainPath = path.join(folder, manifest.main);
|
|
// require() from a folder outside asar is fine — Electron just uses Node's
|
|
// resolver. This is where the trust decision lives: we're loading arbitrary
|
|
// JS into the main process with full API access.
|
|
let mod;
|
|
try {
|
|
// Bust the require cache so a manual reload (future feature) picks up
|
|
// edits — cheap since add-ons are small.
|
|
delete require.cache[require.resolve(mainPath)];
|
|
mod = require(mainPath);
|
|
} catch (e) {
|
|
throw new Error(`require() failed: ${e?.message || e}`);
|
|
}
|
|
if (!mod || typeof mod.activate !== "function") {
|
|
throw new Error(`main file must export an activate(api) function`);
|
|
}
|
|
const active = { manifest, folder, exports: mod, sidebarPanels: [] };
|
|
const api = this._makeApi(active);
|
|
try { mod.activate(api); }
|
|
catch (e) { throw new Error(`activate() threw: ${e?.message || e}`); }
|
|
this._active.set(manifest.id, active);
|
|
this.log(`activated ${manifest.id} v${manifest.version}`);
|
|
}
|
|
|
|
_makeApi(active) {
|
|
const { manifest, folder } = active;
|
|
const storageFile = path.join(this.dataDir, `${manifest.id}.json`);
|
|
return {
|
|
// Metadata the add-on may want to reflect on
|
|
id: manifest.id,
|
|
folder,
|
|
log: (...a) => this.log(`[${manifest.id}]`, ...a),
|
|
// Persistent per-add-on storage. Small kv JSON on disk.
|
|
storage: {
|
|
get: (key, fallback = null) => {
|
|
try {
|
|
const raw = JSON.parse(fs.readFileSync(storageFile, "utf8"));
|
|
return key in raw ? raw[key] : fallback;
|
|
} catch { return fallback; }
|
|
},
|
|
set: (key, value) => {
|
|
let store = {};
|
|
try { store = JSON.parse(fs.readFileSync(storageFile, "utf8")); } catch {}
|
|
store[key] = value;
|
|
try { fs.writeFileSync(storageFile, JSON.stringify(store)); } catch (e) { this.log(`[${manifest.id}] storage.set failed:`, e?.message); }
|
|
},
|
|
all: () => { try { return JSON.parse(fs.readFileSync(storageFile, "utf8")); } catch { return {}; } },
|
|
},
|
|
// Register a sidebar panel — a right-side WebContentsView that hosts
|
|
// one of the add-on's HTML pages. `page` is a path RELATIVE to the
|
|
// add-on folder. `title` shows in the sidebar tab strip. `icon` is
|
|
// a short emoji/glyph.
|
|
registerSidebarPanel: ({ id, title, icon = manifest.icon, page }) => {
|
|
if (!id || !title || !page) throw new Error(`registerSidebarPanel needs {id, title, page}`);
|
|
const abs = path.join(folder, String(page).replace(/^[\\/]/, ""));
|
|
if (!fs.existsSync(abs)) throw new Error(`sidebar panel page not found: ${abs}`);
|
|
// Namespaced id so two add-ons can't collide.
|
|
const panelId = `${manifest.id}:${id}`;
|
|
active.sidebarPanels.push({ panelId, title, icon, pageFile: abs, addonId: manifest.id });
|
|
this.log(`[${manifest.id}] registered sidebar panel: ${panelId}`);
|
|
},
|
|
// Swap the default session's proxy. Rules follow Chromium's proxy
|
|
// format ("socks5://1.2.3.4:1080" for a single SOCKS server,
|
|
// "http=1.2.3.4:8080;https=5.6.7.8:8080" for scheme-split HTTP, etc.).
|
|
// Pass null to clear. Add-ons that opt into this capability are
|
|
// fully replacing the browser's outgoing network path — they're
|
|
// the trust boundary while active. Same-signature as the built-in
|
|
// Tor toggle uses under the hood.
|
|
setSessionProxy: async (rules) => {
|
|
if (!this._setSessionProxy) {
|
|
this.log(`[${manifest.id}] setSessionProxy unavailable (host not wired)`);
|
|
return;
|
|
}
|
|
if (!manifest.capabilities.includes("session-proxy")) {
|
|
throw new Error(`add-on "${manifest.id}" must declare the "session-proxy" capability in addon.json`);
|
|
}
|
|
await this._setSessionProxy(rules, manifest.id);
|
|
},
|
|
};
|
|
}
|
|
|
|
// Read-only views for the rest of the app.
|
|
snapshot() {
|
|
return {
|
|
installed: this._installed.map(({ manifest, folder, error }) => ({
|
|
id: manifest?.id ?? null,
|
|
name: manifest?.name ?? null,
|
|
version: manifest?.version ?? null,
|
|
description: manifest?.description ?? "",
|
|
author: manifest?.author ?? "",
|
|
icon: manifest?.icon ?? "🧩",
|
|
capabilities: manifest?.capabilities ?? [],
|
|
folder,
|
|
enabled: manifest?.id ? this._active.has(manifest.id) : false,
|
|
error: error || null,
|
|
})),
|
|
sidebarPanels: this.getSidebarPanels(),
|
|
};
|
|
}
|
|
getSidebarPanels() {
|
|
const out = [];
|
|
for (const active of this._active.values()) out.push(...active.sidebarPanels);
|
|
return out;
|
|
}
|
|
getInstalled() { return this._installed.slice(); }
|
|
isActive(id) { return this._active.has(id); }
|
|
}
|
|
|
|
module.exports = { AddonHost, KNOWN_CAPABILITIES, validateManifest };
|