// 1.3 item 5: the gate's wrapper page (lib/wrapper.mjs) that keeps the plugin frame on the stable gate port
import { describe, expect, it } from "vitest";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { freePort, request } from "./helpers-net.js";
const root = resolve(__dirname, "..", "..");
const gateUrl = pathToFileURL(join(root, "lib", "gate.mjs")).href;
const wrapperUrl = pathToFileURL(join(root, "lib", "wrapper.mjs")).href;
type Msg = { source: unknown; data: unknown };
/** Runs the wrapper's script against a tiny fake DOM with a controllable clock */
async function runWrapper(hash: string, search = "", opts: { visible?: boolean } = {}) {
const { wrapperHtml, WRAP_TIMING } = await import(/* @vite-ignore */ wrapperUrl);
const html: string = wrapperHtml("n0nce", WRAP_TIMING);
const script = html.split('")[0]!;
let now = 1_800_000_000_000;
const intervals: (() => void)[] = [];
const childWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } };
const parentWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } };
const el = (id: string) => ({ id, hidden: id !== "f", textContent: "", src: "", disabled: false, onclick: null as null | (() => void),
classList: { set: new Set(), add(c: string) { this.set.add(c); }, remove(c: string) { this.set.delete(c); } },
on: {} as Record void>, addEventListener(t: string, fn: () => void) { this.on[t] = fn; } });
const els: Record> = { f: el("f"), m: el("m"), s: el("s"), r: el("r") };
(els.f as unknown as { contentWindow: unknown }).contentWindow = childWin;
let onMessage: (e: Msg) => void = () => {};
const loc = { hash, search, replaced: null as string | null, replace(u: string) { this.replaced = u; } };
const win: Record = {
parent: parentWin,
addEventListener: (t: string, fn: (e: Msg) => void) => { if (t === "message") onMessage = fn; },
};
const doc = { getElementById: (id: string) => els[id], documentElement: { className: "" }, visibilityState: opts.visible === false ? "hidden" : "visible" };
const DateFake = { now: () => now };
const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", script);
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams);
const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); } };
return {
els, loc, childWin, parentWin, tick, doc,
fromChild: (data: unknown) => onMessage({ source: childWin, data }),
fromParent: (data: unknown) => onMessage({ source: parentWin, data }),
fromOther: (data: unknown) => onMessage({ source: {}, data }),
jump: (ms: number) => { now += ms; },
now: () => now,
};
}
const TOKEN = "a".repeat(64);
const BACK = "http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html?x=1";
const hash = (o: Record) => "#" + new URLSearchParams(o).toString();
describe("gate /app", () => {
it("serves the wrapper with a fresh nonce CSP; Host and Origin checks still apply; no secrets in it", async () => {
const { createGate } = await import(/* @vite-ignore */ gateUrl);
const port = await freePort();
const key = "c".repeat(64);
const gate = createGate({ port, key, token: TOKEN, ensureDaemon: async () => ({ port: 4999 }) });
await gate.listen();
try {
const a = await request(port, "/app");
const b = await request(port, "/app?theme=dark");
expect(a.status).toBe(200);
expect(a.headers["content-type"]).toContain("text/html");
const csp = String(a.headers["content-security-policy"]);
expect(csp).toMatch(/script-src 'nonce-[A-Za-z0-9+/=]+'/);
expect(csp).toContain("default-src 'none'");
expect(csp).toContain("frame-src http://127.0.0.1:*");
// only loopback pages and Magpie's own window (wails://localhost, http://wails.localhost) may frame /app
expect(csp).toContain("frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:");
expect(csp).not.toMatch(/frame-ancestors[^;]*\s(\*|https:|http:)(\s|;|$)/); // never "any site"
expect(csp).not.toBe(String(b.headers["content-security-policy"]));
expect(a.headers["cache-control"]).toBe("no-store");
expect(a.body).not.toContain(TOKEN);
expect(a.body).not.toContain(key);
expect((await request(port, "/app", { host: `evil.example:${port}` })).status).toBe(421);
expect((await request(port, "/app", { origin: "null" })).status).toBe(403);
// ac_try is forwarded to the wrapper only in its exact shape
const ok = await request(port, `/open?k=${key}&ac_try=1800000000000.2`);
expect(new URL(String(ok.headers.location)).searchParams.get("ac_try")).toBe("1800000000000.2");
const bad = await request(port, `/open?k=${key}&ac_try=${encodeURIComponent("1.2