Files
plugins/packages/agent-console/lib/gate.mjs
T
qingnian108 08ad5e3956 page-agent-console 1.1.0: QA fixes, neutral accent, own dropdown menus, self-heal after a host restart, by qingnian108 (#569)
page-agent-console 1.1.0, by qingnian108 (#569).

QA fixes B1-B21, a reworked UI, a new logo, and self-heal after a plugin host restart. In this version:
- Accent: a fixed neutral grey (charcoal in light mode, light grey in dark mode). Magpie's accent tokens are dropped on purpose. Surfaces, text, lines, fonts and semantic colours still follow magpie.
- Every native <select> (composer effort/mode/Cursor fast, Settings, Debug) is now the page's own SelectMenu, a button plus a listbox.
- The registry summary again discloses the 127.0.0.1 service and its lifecycle, that only its own page gets the token, the ~46 MB first install, and that Claude Code isn't bundled (en, zh).
- session.js is written once at bind with beat:false, and beats every 4s only after the first /open. A new host deletes a dead host's session.js at startup (owner pid in session-owner.json, outside the page folder).
- The daemon swallows console EPIPE after a hard host kill and handles a lifeline close once.

Run at 930c6e2 on macOS (mote, Node 22), in a fresh copy:
- npm ci, then npm run check (tsc daemon + web): ok
- npx vitest run: 46 files, 288 passed, 17 skipped
- npm run verify:build: app.js, app.css, index.html and daemon/dist/main.js(.map) rebuild byte-identical
- bun scripts/check.mjs agent-console: ok
- Playwright Chromium and WebKit, light and dark, sandbox HOME, page served under /_magpie/plugin/<id>/page with a stub bridge passing accent #ff0000:
  - accent: --accent and the primary button stay grey (rgb(38,38,38) light, rgb(229,229,229) dark); no <select> anywhere.
  - Settings menus: click opens the menu inside the window; ArrowDown+Enter picks, closes and refocuses the trigger; the pick persists through the daemon.
  - Esc closes the menu, not the dialog, and then closes the dialog. Clicking an option keeps the dialog open; a click outside closes the menu.
  - A host that was never opened writes beat:false and doesn't rewrite session.js. SIGKILL it, start a new host: the stale file is removed and the page reaches the new daemon.
  - After an open, session.js beats. SIGKILL the host: the page heals in ~5.3s and stays. A daemon-only crash heals in ~5.3s.
  - Daemon logs: no uncaughtException or EPIPE, one lifeline line per daemon exit.
Not tried: the composer pickers in a browser (they need a thread with an installed agent; same SelectMenu component), magpie's real sandboxed frame, Windows and Linux.
2026-11-01 00:37:07 +08:00

178 lines
7.9 KiB
JavaScript

// Plugin gate: runs inside Magpie's Bun plugin host process and listens on 127.0.0.1:<port> (default 3488).
//
// Two independent secrets:
// - gate key (key): written to page/session.js; the plugin page uses it to open the gate.
// - daemon token (token): unlocks the daemon's API / WebSocket; it only appears in the # fragment of the gate's 302
// and is never written to any static file.
//
// Why separate them: Magpie serves the page directory at /_magpie/plugin/<token that changes every launch>/ without checking Origin,
// Host, Sec-Fetch-* or cookies; the only protection is that the path can't be guessed. session.js is a script, and any page that knows the path
// can include it with <script src> and read its contents (classic script includes aren't subject to CORS). So session.js may only hold
// things that can't reach the daemon even if leaked: the gate key only buys one navigation to the daemon, and the token sits in the target window's
// # fragment, which cross-origin pages can't read.
//
// Token handoff:
// 1. The plugin host's server() creates the key and token; once the gate binds its port it writes page/session.js (port and key only).
// 2. The plugin page (sandbox iframe) reads session.js and navigates itself to http://127.0.0.1:<port>/open?k=<key>.
// This is an ordinary navigation: no Origin header, and the gate returns no CORS headers, so other pages can't read the response.
// 3. The gate checks the key, starts (or reuses) the daemon and 302s to http://127.0.0.1:<daemonPort>/?<theme params>#t=<token>.
// The token lives only in the # fragment: fragments aren't sent to servers and don't appear in Referer or daemon logs;
// after the navigation the window belongs to the daemon's origin (opaque inside the plugin iframe), and the initiating page can't read its URL.
//
// The gate itself: every request checks Host (blocks DNS rebinding); any request with an Origin header is refused (navigations only);
// everything except GET /open is 404.
import http from "node:http";
import { createHash, timingSafeEqual } from "node:crypto";
// Constant-time compare against timing attacks; hash to the same length first.
function tokenEqual(a, b) {
const left = createHash("sha256").update(a).digest();
const right = createHash("sha256").update(b).digest();
return timingSafeEqual(left, right);
}
const SAFE_HEADERS = {
"cache-control": "no-store",
"x-content-type-options": "nosniff",
"referrer-policy": "no-referrer",
};
function respond(res, status, body) {
res.writeHead(status, { ...SAFE_HEADERS, "content-type": "text/html; charset=utf-8" });
res.end(body);
}
function escapeHtml(text) {
return String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}
/** 503 page: show only a userMessage that ensureDaemon explicitly provides (e.g. "Node.js not found"); other error details go to the log only. */
export function failureHtml(error) {
const hint = typeof error?.userMessage === "string" && error.userMessage ? error.userMessage : "";
return (
"<!doctype html><meta charset=utf-8><p>Agent Console: 本地服务启动失败 / local service failed to start</p>" +
(hint ? `<p>${escapeHtml(hint)}</p>` : "") +
"<p>日志 / log: ~/.config/magpie/agent-console/logs/daemon-spawn.log</p>"
);
}
/**
* The Magpie plugin page boot.js came from (?back=), so the daemon page can go back through it after the plugin host restarts
* (fresh session.js → new gate → new daemon). Only a loopback Magpie plugin page is accepted, so the daemon page can't be turned
* into an open redirect; it travels in the 302's # fragment next to the token and never reaches a server.
* Keep in sync with web/src/api/backToMagpie.ts.
*/
export function safeBackUrl(raw) {
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
let u;
try { u = new URL(raw); } catch { return null; }
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
if (u.username || u.password) return null;
const hostname = u.hostname.toLowerCase();
if (hostname !== "127.0.0.1" && hostname !== "localhost" && hostname !== "[::1]") return null;
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
}
const REOPEN_HTML =
"<!doctype html><meta charset=utf-8><p>Agent Console: 链接已失效,请在 Magpie 里重新打开插件页。" +
"<br>The link is no longer valid. Please reopen the Agent Console page in Magpie.</p>";
/**
* @param {object} options
* @param {number} options.port gate port
* @param {string} options.key gate key (the one in session.js), only used to open /open
* @param {string} options.token daemon token, only placed in the 302's # fragment
* @param {() => Promise<{ port: number }>} options.ensureDaemon starts or reuses the daemon and returns its actual port
* @param {string} [options.host] listen address, default 127.0.0.1
*/
export function createGate({ port, key, token, ensureDaemon, host = "127.0.0.1" }) {
if (typeof key !== "string" || key.length < 32 || typeof token !== "string" || token.length < 32 || key === token) {
throw new Error("gate: key and token must be two different secrets");
}
let server = null;
// Concurrent /open calls share one ensureDaemon so two daemons are never started
let opening = null;
async function handle(req, res) {
const expectedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
if (!expectedHosts.includes(String(req.headers.host ?? "").toLowerCase())) {
respond(res, 421, "Bad Host");
return;
}
// The gate only accepts top-level navigations of the plugin page, which carry no Origin. Anything with an Origin (including null) is a script request.
if (req.headers.origin !== undefined) {
respond(res, 403, "Origin not allowed");
return;
}
const url = new URL(req.url ?? "/", `http://${host}:${port}`);
if (url.pathname !== "/open" || req.method !== "GET") {
respond(res, 404, "Not found");
return;
}
if (!tokenEqual(url.searchParams.get("k") ?? "", key)) {
respond(res, 403, REOPEN_HTML);
return;
}
if (!opening) {
opening = Promise.resolve()
.then(() => ensureDaemon())
.finally(() => {
opening = null;
});
}
let daemon;
try {
daemon = await opening;
} catch (error) {
respond(res, 503, failureHtml(error));
return;
}
// Theme, language and color tokens are forwarded to the daemon page as-is; the daemon token goes only into the # fragment
const query = new URLSearchParams();
for (const name of ["theme", "lang", "tokens"]) {
if (url.searchParams.has(name)) query.set(name, url.searchParams.get(name));
}
const back = safeBackUrl(url.searchParams.get("back"));
const fragment = `t=${encodeURIComponent(token)}` + (back ? `&b=${encodeURIComponent(back)}` : "");
const location = `http://127.0.0.1:${daemon.port}/?${query}#${fragment}`;
res.writeHead(302, { ...SAFE_HEADERS, location });
res.end();
}
function listen() {
return new Promise((resolve, reject) => {
const candidate = http.createServer((req, res) => {
handle(req, res).catch(() => {
if (!res.headersSent) respond(res, 500, "Internal error");
else res.end();
});
});
candidate.once("error", reject);
candidate.listen(port, host, () => {
candidate.off("error", reject);
server = candidate;
resolve(candidate);
});
});
}
function close() {
return new Promise((resolve) => {
const current = server;
server = null;
if (!current) {
resolve();
return;
}
current.close(() => resolve());
// Don't wait for keep-alive connections to close by themselves; free the port immediately
current.closeAllConnections?.();
});
}
return { listen, close };
}