// 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; sessionStorage?: Record; framed?: boolean; ua?: string } = {}, ) { 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 winOn: Record void)[]> = {}; const docOn: Record void)[]> = {}; const loc = { hash, search, replaced: null as string | null, reloaded: 0, replace(u: string) { this.replaced = u; }, reload() { this.reloaded++; }, }; const store = new Map(Object.entries(opts.sessionStorage ?? {})); const sessionStorage = { getItem(k: string) { return store.has(k) ? store.get(k)! : null; }, setItem(k: string, v: string) { store.set(k, String(v)); }, removeItem(k: string) { store.delete(k); }, clear() { store.clear(); }, }; const win: Record = { parent: parentWin, addEventListener: (t: string, fn: (e: Msg) => void) => { if (t === "message") onMessage = fn; else (winOn[t] ??= []).push(fn as unknown as () => void); }, }; // Magpie hosts the wrapper in an iframe (parent !== window). Top-level /app uses framed: false. if (opts.framed === false) win.parent = win; const doc = { getElementById: (id: string) => els[id], documentElement: { className: "" }, visibilityState: opts.visible === false ? "hidden" : "visible", addEventListener: (t: string, fn: () => void) => { (docOn[t] ??= []).push(fn); }, }; const DateFake = { now: () => now }; type TO = { at: number; fn: () => void }; const timeouts: TO[] = []; const setTimeoutFake = (f: () => void, ms = 0) => { timeouts.push({ at: now + ms, fn: f }); return timeouts.length; }; const flushTimeouts = () => { let ran = true; while (ran) { ran = false; for (let i = timeouts.length - 1; i >= 0; i--) { if (timeouts[i]!.at <= now) { const t = timeouts.splice(i, 1)[0]!; t.fn(); ran = true; } } } }; const fn = new Function("window", "document", "location", "setInterval", "setTimeout", "Date", "URL", "URLSearchParams", "sessionStorage", "navigator", script); fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, setTimeoutFake, DateFake, URL, URLSearchParams, sessionStorage, { userAgent: opts.ua ?? "X11; Linux x86_64" }); const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); flushTimeouts(); } }; return { els, loc, childWin, parentWin, tick, doc, store, flushTimeouts, 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; flushTimeouts(); }, hide: () => { doc.visibilityState = "hidden"; (docOn.visibilitychange ?? []).forEach((f) => f()); }, show: () => { doc.visibilityState = "visible"; (docOn.visibilitychange ?? []).forEach((f) => f()); }, focus: () => { (winOn.focus ?? []).forEach((f) => f()); }, 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