A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.
Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.
Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
internal/pluginrt ok, plugins/... (budget groups middleware otel redact
rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.
Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.
Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.
Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
273 lines
10 KiB
JavaScript
273 lines
10 KiB
JavaScript
// The window's plugin kernel (docs/subsystems/plugin-runtime.md, P1). A
|
||
// plugin's page is a part it adds to the "page" slot: its markup, put in the
|
||
// page where index.html's <template data-slot="page"> is, and its hooks,
|
||
// which the shell calls through magpie.call. A hook that throws breaks only
|
||
// its own page: the page says so, with a Try again, and the other pages go
|
||
// on (the error boundary). ctx.ui is the kit a plugin draws with, and
|
||
// ui.form draws a plugin's settings from the schema the Go side made of
|
||
// them (pluginrt.SchemaOf).
|
||
//
|
||
// Loaded after i18n.js and before the plugins' scripts and app.js. A
|
||
// plugin's words come with it (its i18n.js, magpie.strings). Its scripts
|
||
// register at once, so its page is in the page before app.js looks for
|
||
// it, but run nothing of app.js's then: mount runs at magpie.start, which
|
||
// app.js calls once it is set up.
|
||
(() => {
|
||
const plugins = new Map(); // id → { id, config, onConfig: [], disposers: [] }
|
||
const pages = new Map(); // key → { plugin, part, main, mounted, broken }
|
||
let started = false;
|
||
|
||
function context(p) {
|
||
return {
|
||
id: p.id,
|
||
get config() { return p.config; },
|
||
// a change of the plugin's settings (Plugins › Built-in), after
|
||
// ctx.config has it
|
||
onConfig(fn) { p.onConfig.push(fn); },
|
||
onDispose(fn) { p.disposers.push(fn); },
|
||
// a page of the plugin's that broke after its hook returned (a
|
||
// frame's own error, one that never answered): it shows what broke,
|
||
// with a Try again, as a hook that throws does
|
||
broke(key, err) {
|
||
const page = pages.get(key);
|
||
if (page && page.plugin === p && !page.broken) fail(page, "open", [], err);
|
||
},
|
||
slots: { add: (slot, part) => add(p, slot, part) },
|
||
ui,
|
||
};
|
||
}
|
||
|
||
function add(p, slot, part) {
|
||
if (slot !== "page") throw new Error(`no slot ${slot}`);
|
||
if (!/^[a-z][a-z0-9-]*$/.test(part.key || "") || pages.has(part.key) || document.getElementById("view-" + part.key)) {
|
||
throw new Error(`page ${part.key} is taken`);
|
||
}
|
||
const main = document.createElement("main");
|
||
main.className = "view";
|
||
main.id = "view-" + part.key;
|
||
main.hidden = true;
|
||
main.dataset.feature = p.id;
|
||
main.innerHTML = part.html || "";
|
||
const anchor = document.querySelector('template[data-slot="page"]');
|
||
if (anchor) anchor.before(main);
|
||
else document.body.append(main);
|
||
const page = { plugin: p, part, main, mounted: false, broken: null };
|
||
pages.set(part.key, page);
|
||
if (started) run(page, "mount", [main]);
|
||
}
|
||
|
||
// The error boundary: a hook that throws (or whose promise fails) is
|
||
// caught here, and the page shows what broke instead of what it had.
|
||
function fail(page, hook, args, err) {
|
||
console.error(`[magpie] ${page.plugin.id}: ${page.part.key}.${hook}`, err);
|
||
page.broken = { hook, args };
|
||
const card = document.createElement("div");
|
||
card.className = "list slot-error";
|
||
card.setAttribute("role", "alert");
|
||
const row = document.createElement("div");
|
||
row.className = "row";
|
||
const who = document.createElement("div");
|
||
who.className = "who";
|
||
const name = document.createElement("div");
|
||
name.className = "name";
|
||
name.textContent = t("This page stopped working");
|
||
const sub = document.createElement("div");
|
||
sub.className = "sub";
|
||
sub.textContent = String(err?.message || err);
|
||
who.append(name, sub);
|
||
const again = document.createElement("button");
|
||
again.type = "button";
|
||
again.className = "text slot-again";
|
||
again.textContent = t("Try again");
|
||
again.onclick = () => retry(page);
|
||
row.append(who, again);
|
||
card.append(row);
|
||
page.main.classList.remove("loading");
|
||
page.main.removeAttribute("aria-busy");
|
||
page.main.replaceChildren(card);
|
||
}
|
||
|
||
// Try again: the page's markup as it came, mounted again, and the hook
|
||
// that broke run again with what it was given.
|
||
function retry(page) {
|
||
const { hook, args } = page.broken;
|
||
page.broken = null;
|
||
page.mounted = false;
|
||
page.main.innerHTML = page.part.html || "";
|
||
window.translateStatic?.();
|
||
if (hook !== "mount") run(page, "mount", [page.main]);
|
||
run(page, hook, args);
|
||
}
|
||
|
||
function run(page, hook, args) {
|
||
if (page.broken) return undefined;
|
||
if (hook === "mount") {
|
||
if (page.mounted) return undefined;
|
||
page.mounted = true;
|
||
} else if (!page.mounted && started) {
|
||
run(page, "mount", [page.main]);
|
||
if (page.broken) return undefined;
|
||
}
|
||
const fn = page.part[hook];
|
||
if (typeof fn !== "function") return undefined;
|
||
try {
|
||
const out = fn.apply(page.part, args);
|
||
if (out && typeof out.then === "function") {
|
||
return out.catch((err) => { if (!page.broken) fail(page, hook, args, err); });
|
||
}
|
||
return out;
|
||
} catch (err) {
|
||
fail(page, hook, args, err);
|
||
return undefined;
|
||
}
|
||
}
|
||
|
||
// ---------- the kit ----------
|
||
// What a plugin draws with, as the rest of the window draws: el, the app
|
||
// menu (never a native <select>), the switch, the settings row.
|
||
const ui = {
|
||
el: (tag, cls, text) => el(tag, cls, text),
|
||
button(label, onClick, cls = "text") {
|
||
const b = el("button", cls, label);
|
||
b.type = "button";
|
||
b.onclick = onClick;
|
||
return b;
|
||
},
|
||
toggle(on, label, onChange) {
|
||
const b = el("button", "lib-switch use-credits" + (on ? " on" : ""));
|
||
b.type = "button";
|
||
b.setAttribute("role", "switch");
|
||
b.setAttribute("aria-checked", String(on));
|
||
b.setAttribute("aria-label", label);
|
||
b.append(el("i"));
|
||
b.onclick = () => {
|
||
on = !on;
|
||
b.classList.toggle("on", on);
|
||
b.setAttribute("aria-checked", String(on));
|
||
onChange(on);
|
||
};
|
||
return b;
|
||
},
|
||
// a pick of one of opts ([{ v, name }]), in the app's menu
|
||
menu(opts, value, head, onPick) {
|
||
const b = el("button", "proto pick");
|
||
b.type = "button";
|
||
const paint = () => {
|
||
const o = opts.find((x) => x.v === value);
|
||
b.replaceChildren(el("span", "", o ? o.name : String(value)), svg(CHEV, 11, 1.6));
|
||
};
|
||
paint();
|
||
b.onclick = (ev) => {
|
||
ev.stopPropagation();
|
||
openProtoMenu(b, opts.map((o) => ({ ...o, literalName: true, note: "" })), value, (v) => {
|
||
value = v;
|
||
paint();
|
||
onPick(v);
|
||
}, head, "", "right");
|
||
};
|
||
return b;
|
||
},
|
||
// a settings row: what it is, and its control at the end
|
||
row(title, description, control) {
|
||
const r = el("div", "row pref");
|
||
const who = el("div", "who");
|
||
who.append(el("div", "name", title));
|
||
if (description) who.append(el("div", "sub", description));
|
||
r.append(who, control);
|
||
return r;
|
||
},
|
||
// The rows of a plugin's settings, drawn from its schema: true or false
|
||
// a switch, one of a few a menu, a number a field kept to its range,
|
||
// text a field. onChange gets { key: value } for the one changed.
|
||
form(schema, values, onChange) {
|
||
const rows = [];
|
||
for (const key of schema?.["x-order"] || Object.keys(schema?.properties || {})) {
|
||
const p = schema.properties[key];
|
||
if (!p) continue;
|
||
const value = values?.[key] ?? p.default;
|
||
const title = t(p.title), say = p.description ? t(p.description) : "";
|
||
let control;
|
||
if (p.type === "boolean") control = ui.toggle(!!value, title, (v) => onChange({ [key]: v }));
|
||
else if (p.enum?.length) {
|
||
control = ui.menu(p.enum.map((v) => ({ v, name: typeof v === "number" ? v.toLocaleString(locale) : t(String(v)) })), value, p.title, (v) => onChange({ [key]: v }));
|
||
} else {
|
||
const number = p.type === "integer" || p.type === "number";
|
||
control = el("input", "set-field");
|
||
control.type = number ? "number" : "text";
|
||
control.value = value ?? "";
|
||
control.setAttribute("aria-label", title);
|
||
if (number) {
|
||
if (p.minimum !== undefined) control.min = p.minimum;
|
||
if (p.maximum !== undefined) control.max = p.maximum;
|
||
if (p.type === "integer") control.step = 1;
|
||
}
|
||
control.onchange = () => {
|
||
let v = control.value;
|
||
if (number) {
|
||
v = Number(v);
|
||
const bad = control.value === "" || !Number.isFinite(v) || (p.type === "integer" && !Number.isInteger(v))
|
||
|| (p.minimum !== undefined && v < p.minimum) || (p.maximum !== undefined && v > p.maximum);
|
||
control.setAttribute("aria-invalid", String(bad));
|
||
if (bad) return;
|
||
}
|
||
onChange({ [key]: v });
|
||
};
|
||
}
|
||
const r = ui.row(title, say, control);
|
||
r.dataset.setting = key;
|
||
rows.push(r);
|
||
}
|
||
return rows;
|
||
},
|
||
};
|
||
|
||
window.magpie = {
|
||
ui,
|
||
plugin(id, setup) {
|
||
if (plugins.has(id)) throw new Error(`plugin ${id} is registered twice`);
|
||
const p = { id, config: { ...(window.bootPrefs?.pluginConfig?.[id] || {}) }, onConfig: [], disposers: [] };
|
||
plugins.set(id, p);
|
||
try {
|
||
setup(context(p));
|
||
} catch (err) {
|
||
console.error(`[magpie] ${id}: setup`, err);
|
||
}
|
||
},
|
||
// app.js, once it is set up: every page is mounted
|
||
start() {
|
||
if (started) return;
|
||
started = true;
|
||
for (const page of pages.values()) run(page, "mount", [page.main]);
|
||
},
|
||
// a page's hook, behind the boundary; nothing for a page no plugin has
|
||
call(key, hook, ...args) {
|
||
const page = pages.get(key);
|
||
return page ? run(page, hook, args) : undefined;
|
||
},
|
||
// a plugin's words in each language ({ zh: { English: 中文 }, … }),
|
||
// added to i18n.js's; one already there is a mistake, said and not
|
||
// taken, as the later one would silently win
|
||
strings(dict) {
|
||
for (const [lang, words] of Object.entries(dict)) {
|
||
const to = (I18N[lang] ||= {});
|
||
for (const [k, v] of Object.entries(words)) {
|
||
if (k in to) console.error(`[magpie] ${lang} ${JSON.stringify(k)} is said twice`);
|
||
else to[k] = v;
|
||
}
|
||
}
|
||
},
|
||
page: (key) => pages.get(key)?.part,
|
||
pages: () => [...pages.keys()],
|
||
// the plugins' settings as Plugins › Built-in or boot.js has them
|
||
configure(id, config) {
|
||
const p = plugins.get(id);
|
||
if (!p || !config) return;
|
||
if (JSON.stringify(p.config) === JSON.stringify(config)) return;
|
||
p.config = { ...config };
|
||
for (const fn of p.onConfig) {
|
||
try { fn(p.config); } catch (err) { console.error(`[magpie] ${id}: config`, err); }
|
||
}
|
||
},
|
||
};
|
||
})();
|