// The connection test's loopback service. A Magpie page runs with // connect-src 'none', so the settings page cannot fetch Mem. The page's Test // button navigates the frame here; the test page asks for a click, then this // service checks the saved connection with the plugin's own options. No URL, // key or Space comes from the page, so a page cannot aim it at another host. import { randomBytes, timingSafeEqual } from "node:crypto"; import { testConnection, textsFor } from "./probe.mjs"; const DEFAULT_PORT = 3479; const TOKEN = randomBytes(32).toString("hex"); const TOKEN_HEADER = "x-nmem-token"; let running; let pluginOptions = {}; const messages = { en: textsFor("en"), zh: textsFor("zh"), "zh-TW": textsFor("zh-TW"), ja: textsFor("ja"), de: textsFor("de"), }; function page() { return ` Nowledge Mem

Nowledge Mem

`; } function hostOK(req, port = running?.port) { if (!port) return false; const host = String(req.headers.get("host") ?? "").toLowerCase(); return host === `127.0.0.1:${port}` || host === `localhost:${port}`; } function originOK(req, port = running?.port) { const origin = req.headers.get("origin"); if (origin === null || origin === "null") return true; return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`; } function cors(req) { if (req.headers.get("origin") !== "null") return {}; return { "access-control-allow-origin": "null", "access-control-allow-headers": TOKEN_HEADER, "access-control-allow-methods": "POST, OPTIONS", vary: "Origin", }; } function tokenOK(req) { const got = Buffer.from(String(req.headers.get(TOKEN_HEADER) ?? "")); const want = Buffer.from(TOKEN); return got.length === want.length && timingSafeEqual(got, want); } async function handle(req) { if (!hostOK(req)) return new Response("Forbidden", { status: 403 }); const url = new URL(req.url); if (req.method === "OPTIONS") { if (!originOK(req)) return new Response("Forbidden", { status: 403 }); return new Response(null, { status: 204, headers: cors(req) }); } if (url.pathname === "/test" && req.method === "GET") return new Response(page(), { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" } }); if (url.pathname === "/api/test" && req.method === "POST") { if (!originOK(req) || !tokenOK(req)) return new Response("Forbidden", { status: 403 }); const result = await testConnection(pluginOptions); return Response.json(result, { headers: cors(req) }); } return new Response("Not found", { status: 404 }); } export default { id: "magpie-nowledge-mem", async server(_input, options) { pluginOptions = options ?? {}; if (running) return {}; const port = Number(pluginOptions.port ?? DEFAULT_PORT); if (!Number.isInteger(port) || port < 1024 || port > 65535) { console.error(`[nowledge-mem] the connection test needs a port, got ${pluginOptions.port}`); return {}; } try { running = Bun.serve({ hostname: "127.0.0.1", port, fetch: handle }); console.log(`[nowledge-mem] connection test on http://127.0.0.1:${running.port}`); } catch (error) { console.error(`[nowledge-mem] the connection test could not start on port ${port}: ${error?.message ?? error}`); } return {}; }, }; export const _internal = { hostOK, originOK, stop() { running?.stop(true); running = undefined; }, };