mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 08:15:41 -08:00
338 lines
16 KiB
JavaScript
338 lines
16 KiB
JavaScript
// Web console tests: PLAN2CODE_EMBED_ORIGIN opt-in embed mode. With the
|
|
// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly
|
|
// one allowed origin it names that origin; set to anything else it is ignored
|
|
// and 'none' stands. Each case boots its own server with the variable in its
|
|
// environment. Inside the macOS app the frame signs in by a path prefix on
|
|
// 127.0.0.1 instead of by cookie, and only there. Shared setup:
|
|
// ./web-console-test-helpers.mjs.
|
|
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import crypto from "node:crypto";
|
|
import fs from "node:fs";
|
|
import http from "node:http";
|
|
import path from "node:path";
|
|
import { spawn } from "node:child_process";
|
|
import { cookieFor, ENV, HOME, JPEG, ROOT } from "./web-console-test-helpers.mjs";
|
|
|
|
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
|
|
|
// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set
|
|
// to `origin` (or does not carry it at all when origin is undefined). Returns
|
|
// the child and its base URL; the caller always kills the child. `platform`
|
|
// fakes process.platform in the server before it loads (the whole server
|
|
// sees it, not only frameKey()), so the macOS-only frame sign-in is tested on
|
|
// every OS. `state` adds fields to state.json.
|
|
async function bootServer(origin, { platform, token = "t", state = {} } = {}) {
|
|
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
|
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting", ...state }));
|
|
const env = { ...ENV };
|
|
if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN;
|
|
else env.PLAN2CODE_EMBED_ORIGIN = origin;
|
|
const fake = platform
|
|
? ["--import", `data:text/javascript,Object.defineProperty(process,"platform",{value:${JSON.stringify(platform)}})`]
|
|
: [];
|
|
const child = spawn(process.execPath, [...fake, SERVER_JS, `--session=${dir}`, `--token=${token}`, `--project=${dir}`], {
|
|
env,
|
|
stdio: ["ignore", "pipe", "ignore"],
|
|
windowsHide: true,
|
|
});
|
|
const ready = await new Promise((resolve, reject) => {
|
|
let buf = "";
|
|
child.stdout.on("data", (c) => {
|
|
buf += c;
|
|
const line = buf.split("\n").find((l) => l.includes('"ready"'));
|
|
if (line) resolve(JSON.parse(line));
|
|
});
|
|
child.on("exit", () => reject(new Error("server exited before it was ready")));
|
|
});
|
|
return { child, dir, base: `http://127.0.0.1:${ready.port}`, port: ready.port };
|
|
}
|
|
|
|
// Fetch the session page with its token cookie and resolve to the page's
|
|
// content-security-policy header.
|
|
async function cspWith(origin) {
|
|
const { child, base } = await bootServer(origin);
|
|
try {
|
|
const res = await fetch(base + "/", { headers: { cookie: cookieFor(base, "t"), connection: "close" } });
|
|
assert.equal(res.status, 200);
|
|
await res.arrayBuffer();
|
|
return res.headers.get("content-security-policy");
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
}
|
|
|
|
// Fetch the sign-in redirect and resolve to its set-cookie header.
|
|
async function cookieWith(origin, options) {
|
|
const { child, base } = await bootServer(origin, options);
|
|
try {
|
|
const res = await fetch(`${base}/s/t/`, { redirect: "manual" });
|
|
assert.equal(res.status, 302);
|
|
await res.arrayBuffer();
|
|
return res.headers.get("set-cookie");
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
}
|
|
|
|
test("with PLAN2CODE_EMBED_ORIGIN unset the header keeps frame-ancestors 'none'", async () => {
|
|
const csp = await cspWith(undefined);
|
|
assert.match(csp, /frame-ancestors 'none'$/);
|
|
});
|
|
|
|
test("each allowed origin is named in frame-ancestors", async () => {
|
|
for (const origin of ["http://127.0.0.1:5173", "http://localhost:8080", "http://tauri.localhost", "https://tauri.localhost", "tauri://localhost"]) {
|
|
const csp = await cspWith(origin);
|
|
assert.ok(csp.endsWith(`frame-ancestors ${origin}`), `${origin}: ${csp}`);
|
|
}
|
|
});
|
|
|
|
test("the session cookie is Strict standalone and None; Secure under embed", async () => {
|
|
const plain = await cookieWith(undefined);
|
|
assert.match(plain, /SameSite=Strict/);
|
|
assert.doesNotMatch(plain, /SameSite=None/);
|
|
const embedded = await cookieWith("http://tauri.localhost");
|
|
assert.match(embedded, /SameSite=None; Secure/);
|
|
});
|
|
|
|
// WebKit (the app on Linux and macOS) drops a Secure cookie sent over plain
|
|
// http, so the page in the app's frame got a 403 after the sign-in.
|
|
test("the session cookie is Lax and never Secure under the tauri://localhost embed", async () => {
|
|
// Linux, where this frame signs in by cookie: on macOS it signs in by its
|
|
// path prefix instead (the frame tests below).
|
|
const embedded = await cookieWith("tauri://localhost", { platform: "linux" });
|
|
assert.match(embedded, /SameSite=Lax/);
|
|
assert.doesNotMatch(embedded, /Secure/);
|
|
assert.match(embedded, /HttpOnly/);
|
|
});
|
|
|
|
test("anything but exactly one allowed origin keeps frame-ancestors 'none'", async () => {
|
|
const rejected = [
|
|
"https://example.com",
|
|
"",
|
|
"http://127.0.0.1:5173 https://example.com",
|
|
"http://127.0.0.1:5173;evil",
|
|
"http://127.0.0.1:0",
|
|
"http://127.0.0.1:99999",
|
|
"http://127.0.0.1",
|
|
"https://127.0.0.1:443",
|
|
"*",
|
|
];
|
|
for (const origin of rejected) {
|
|
const csp = await cspWith(origin);
|
|
assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`);
|
|
}
|
|
});
|
|
|
|
/* ------------------------------------------- the macOS app's frame sign-in */
|
|
|
|
// fetch() will not send a Host header of the caller's choosing, and some of
|
|
// these requests must, so they go through node:http. Resolves to status,
|
|
// headers and body text; with `head` it resolves on the headers and drops
|
|
// the connection (the event stream never ends).
|
|
function raw(port, urlPath, { method = "GET", headers = {}, body, head = false } = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const req = http.request({ host: "127.0.0.1", port, path: urlPath, method, headers: { connection: "close", ...headers } }, (res) => {
|
|
if (head) {
|
|
resolve({ status: res.statusCode, headers: res.headers, body: "" });
|
|
return req.destroy();
|
|
}
|
|
let text = "";
|
|
res.setEncoding("utf8");
|
|
res.on("data", (c) => (text += c));
|
|
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: text }));
|
|
});
|
|
req.on("error", (e) => (head && e.code === "ECONNRESET" ? undefined : reject(e)));
|
|
req.end(body);
|
|
});
|
|
}
|
|
|
|
// The frame's key: a hash of the token, so the token the terminal prints
|
|
// never sits in the frame's address, and still 128 bits.
|
|
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
|
|
|
// A real token's shape: 16 random bytes in base64url, uppercase included.
|
|
const MIXED_TOKEN = "aB3xZ9-Qk_T7mN2pLw8RvY";
|
|
|
|
// A server in the macOS app's frame mode, its prefix, and the same-origin
|
|
// headers the frame's page sends with an origin-checked POST.
|
|
async function macFrame(options = {}) {
|
|
const server = await bootServer("tauri://localhost", { platform: "darwin", token: MIXED_TOKEN, ...options });
|
|
return { ...server, prefix: `/f/${frameKey(MIXED_TOKEN)}`, own: { origin: `http://127.0.0.1:${server.port}` } };
|
|
}
|
|
|
|
test("the macOS app's frame signs in by a path prefix on 127.0.0.1, with no cookie", async () => {
|
|
const { child, port, prefix, own } = await macFrame();
|
|
try {
|
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
|
assert.equal(signIn.status, 302);
|
|
assert.equal(signIn.headers.location, `${prefix}/`, "the same host, a path, never a host name");
|
|
assert.equal(signIn.headers["set-cookie"], undefined);
|
|
|
|
const page = await raw(port, `${prefix}/`);
|
|
assert.equal(page.status, 200);
|
|
assert.match(page.headers["content-security-policy"], /frame-ancestors tauri:\/\/localhost$/);
|
|
assert.equal((await raw(port, `${prefix}/state`)).status, 200);
|
|
assert.equal((await raw(port, `${prefix}/app.js`)).status, 200);
|
|
const events = await raw(port, `${prefix}/events`, { head: true });
|
|
assert.equal(events.status, 200);
|
|
assert.match(String(events.headers["content-type"]), /^text\/event-stream/);
|
|
|
|
// An origin-checked route takes the page's own origin under the prefix.
|
|
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: own })).status, 200);
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("under the frame's prefix the routes that read the raw request line answer, and still refuse `..`", async () => {
|
|
const project = fs.mkdtempSync(path.join(HOME, "embed-project-"));
|
|
const kept = "shot-1a2b3c4d.jpg";
|
|
fs.mkdirSync(path.join(project, "spec", "attachments"), { recursive: true });
|
|
fs.writeFileSync(path.join(project, "spec", "attachments", kept), JSON.stringify("not read as text"));
|
|
const { child, dir, port, prefix, own } = await macFrame({ state: { worktree: project, specDir: "spec" } });
|
|
try {
|
|
const jpeg = { ...own, "content-type": "image/jpeg" };
|
|
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
|
assert.equal((await raw(port, `${prefix}/uploads/${upload.id}.jpg`)).status, 200, "an upload");
|
|
assert.equal((await raw(port, `${prefix}/uploads/../uploads/${upload.id}.jpg`)).status, 404, "`..` is still refused");
|
|
|
|
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
|
assert.ok(note.ok, JSON.stringify(note));
|
|
const tab = /images\/([0-9a-f]{12})\//.exec(note.url)[1];
|
|
assert.equal((await raw(port, `${prefix}/notepad/images/${tab}/${note.id}.jpg`)).status, 200, "a notepad picture");
|
|
|
|
fs.mkdirSync(path.join(dir, "shots"));
|
|
fs.writeFileSync(path.join(dir, "shots", "run.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0]));
|
|
assert.equal((await raw(port, `${prefix}/shots/run.png`)).status, 200, "a shot");
|
|
assert.equal((await raw(port, `${prefix}/shots/../shots/run.png`)).status, 404, "`..` is still refused");
|
|
|
|
assert.equal((await raw(port, `${prefix}/attachments/${kept}`)).status, 200, "a kept attachment");
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("the links the server hands the page are page-relative", async () => {
|
|
const { child, port, prefix, own } = await macFrame();
|
|
try {
|
|
const jpeg = { ...own, "content-type": "image/jpeg" };
|
|
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
|
assert.equal(upload.url, `uploads/${upload.id}.jpg`);
|
|
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
|
assert.match(note.url, /^notepad\/images\/[0-9a-f]{12}\/[0-9a-f-]{36}\.jpg$/);
|
|
const pad = JSON.parse((await raw(port, `${prefix}/notepad`)).body);
|
|
assert.equal(pad.images.length, 1);
|
|
for (const img of pad.images) {
|
|
assert.doesNotMatch(img.url, /^\//, img.url);
|
|
assert.doesNotMatch(String(img.thumb ?? ""), /^\//, img.thumb);
|
|
}
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("a wrong or missing frame key is refused exactly as a request with no cookie is", async () => {
|
|
const { child, port, prefix } = await macFrame();
|
|
try {
|
|
const key = frameKey(MIXED_TOKEN);
|
|
const plain = await raw(port, "/state");
|
|
assert.equal(plain.status, 403);
|
|
const wrong = [
|
|
`/f/${frameKey("someone-else")}/state`,
|
|
`/f/${key.toUpperCase()}/state`,
|
|
`/f/${key.slice(0, -1)}/state`,
|
|
`/f/${key}x/state`,
|
|
`/f//state`,
|
|
`/f/state`,
|
|
`/f/${key}`,
|
|
`/F/${key}/state`,
|
|
`/f/%${key.charCodeAt(0).toString(16)}${key.slice(1)}/state`,
|
|
`/x/f/${key}/state`,
|
|
];
|
|
for (const p of wrong) {
|
|
const res = await raw(port, p);
|
|
assert.equal(res.status, plain.status, p);
|
|
assert.equal(res.body, plain.body, `${p} says no more than a request with no cookie`);
|
|
}
|
|
// The prefix comes off once: a second one is just a path, and nothing serves it.
|
|
assert.equal((await raw(port, `${prefix}${prefix}/state`)).status, 404);
|
|
assert.equal((await raw(port, `/s/${MIXED_TOKEN}x/`, { headers: { "sec-fetch-dest": "iframe" } })).status, 403);
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("a .localhost host name neither signs in nor passes the origin check", async () => {
|
|
const { child, port, prefix } = await macFrame();
|
|
try {
|
|
const key = frameKey(MIXED_TOKEN);
|
|
for (const host of [`${key}.localhost:${port}`, `x.localhost:${port}`, `${key}.localhost`]) {
|
|
assert.equal((await raw(port, "/state", { headers: { host } })).status, 403, host);
|
|
assert.equal((await raw(port, `${prefix}/state`, { headers: { host } })).status, 403, `${host} under the prefix`);
|
|
}
|
|
const foreign = await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: `http://${key}.localhost:${port}` } });
|
|
assert.equal(foreign.status, 403);
|
|
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: "http://evil.localhost:80" } })).status, 403);
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("a browser tab on the macOS app's console keeps the cookie and `/`", async () => {
|
|
const { child, port, prefix } = await macFrame();
|
|
try {
|
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "document" } });
|
|
assert.equal(signIn.status, 302);
|
|
assert.equal(signIn.headers.location, "/");
|
|
// The tauri://localhost cookie (cookieSameSite): Lax, never Secure,
|
|
// since Safari drops a Secure cookie on plain http.
|
|
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly; SameSite=Lax;/);
|
|
assert.doesNotMatch(String(signIn.headers["set-cookie"]), /Secure/);
|
|
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
|
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200);
|
|
assert.ok(!String(signIn.headers.location).includes(prefix));
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
});
|
|
|
|
test("the frame prefix is off everywhere but the macOS app, where `/f/` is just a path", async () => {
|
|
const cases = [
|
|
{ origin: "tauri://localhost", platform: "win32" },
|
|
{ origin: "tauri://localhost", platform: "linux" },
|
|
{ origin: "http://tauri.localhost", platform: "darwin" },
|
|
{ origin: "http://127.0.0.1:5173", platform: "darwin" },
|
|
{ origin: undefined, platform: "darwin" },
|
|
];
|
|
for (const { origin, platform } of cases) {
|
|
const label = `${origin} on ${platform}`;
|
|
const { child, port } = await bootServer(origin, { platform, token: MIXED_TOKEN });
|
|
try {
|
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
|
assert.equal(signIn.headers.location, "/", label);
|
|
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly/, label);
|
|
const prefixed = `/f/${frameKey(MIXED_TOKEN)}/state`;
|
|
assert.equal((await raw(port, prefixed)).status, 403, `${label}: no sign-in by path`);
|
|
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
|
assert.equal((await raw(port, prefixed, { headers: { cookie } })).status, 404, `${label}: never stripped`);
|
|
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200, `${label}: the cookie route as before`);
|
|
} finally {
|
|
child.kill();
|
|
}
|
|
}
|
|
});
|
|
|
|
test("the page-closed signal is a keepalive fetch, which carries the page's origin, not a beacon", () => {
|
|
// A body-less sendBeacon is a no-cors POST: under the console's
|
|
// `referrer-policy: no-referrer` it goes out with `Origin: null`, which /bye's
|
|
// origin check refuses (WebKit showed it; the Fetch standard says every engine
|
|
// does the same). A keepalive fetch is a cors request and sends the real origin.
|
|
const core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8");
|
|
const wire = core.slice(core.indexOf("export function wireChrome()"));
|
|
const pagehide = wire.slice(0, wire.indexOf("});"));
|
|
assert.match(pagehide, /fetch\("bye", \{ method: "POST", keepalive: true \}\)/, pagehide);
|
|
assert.doesNotMatch(core, /navigator\.sendBeacon\(/, "no beacon call left anywhere in the page's core");
|
|
});
|