Sign the macOS app's dashboard frame in by a path prefix, since WebKit gives it no cookie

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 00:10:44 -08:00
1 parent 1d007737b1
commit 98bdbc97c3
10 files changed
+411 -21

No files matched your search

+1
View File
@@ -120,6 +120,7 @@
"test-web-console-page-cards.mjs",
"test-web-console-page-changes.mjs",
"test-web-console-page-dashboard.mjs",
"test-web-console-page-frame.mjs",
"test-web-console-page-layout.mjs",
"test-web-console-page-git.mjs",
"test-web-console-page-help.mjs",
+221 -10
View File
@@ -2,27 +2,37 @@
// 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. Shared setup: ./web-console-test-helpers.mjs.
// 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, ROOT } from "./web-console-test-helpers.mjs";
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.
async function bootServer(origin) {
// 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" }));
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 child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], {
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,
@@ -36,7 +46,7 @@ async function bootServer(origin) {
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
return { child, base: `http://127.0.0.1:${ready.port}` };
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
@@ -54,8 +64,8 @@ async function cspWith(origin) {
}
// Fetch the sign-in redirect and resolve to its set-cookie header.
async function cookieWith(origin) {
const { child, base } = await bootServer(origin);
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);
@@ -89,7 +99,9 @@ test("the session cookie is Strict standalone and None; Secure under embed", asy
// 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 () => {
const embedded = await cookieWith("tauri://localhost");
// 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/);
@@ -113,6 +125,205 @@ test("anything but exactly one allowed origin keeps frame-ancestors 'none'", asy
}
});
/* ------------------------------------------- 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
+119
View File
@@ -0,0 +1,119 @@
// Web console page tests: the page as the macOS app's frame has it. WebKit
// gives that frame no cookie, so the console signs it in by a path prefix
// (`/f/<key>/`, routes.mjs) and the page runs under it. Every request the page
// makes there must stay under the prefix: one that leaves it gets a 403, and
// only in the macOS app. This file opens the page that way in a browser
// context with no cookie, uses the parts that fetch, and fails on any request
// that left the prefix or was refused. Run with:
// node --test scripts/test-web-console-page-frame.mjs
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
import { until, HOME } from "./web-console-test-helpers.mjs";
import { createTab, listTabs } from "../src/web-console/notepads.mjs";
const suite = pageSuite(test);
const LOOKS_FILE = path.join(HOME, "looks.json");
// The server takes the app's frame mode only on macOS, with the app's page as
// the embed ancestor. On any other OS this makes the server alone believe it
// runs on macOS (the CLI that starts it is left as it is), so CI's Linux run
// checks the same thing. The whole server sees darwin, not only frameKey():
// every macOS branch in it runs here too.
const FAKE_MAC =
"data:text/javascript," +
encodeURIComponent('if (/server\\.mjs$/.test(process.argv[1] || "")) Object.defineProperty(process, "platform", { value: "darwin" });');
const FRAME_ENV = { PLAN2CODE_EMBED_ORIGIN: "tauri://localhost", NODE_OPTIONS: `--import=${FAKE_MAC}` };
// The frame's key, as routes.mjs makes it from the session token.
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
test("under the frame's prefix, with no cookie, the dashboard draws, its stream connects, and nothing it asks for leaves the prefix", async (t) => {
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, hideActivities: false } }));
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
const browser = await suite.browser();
const s = await openSession(browser, { t, workflow: "dashboard", env: FRAME_ENV });
if (!listTabs(s.project).tabs.length) createTab(s.project, "Notes");
const signIn = new URL(s.url);
const token = /^\/s\/([^/]+)\/$/.exec(signIn.pathname)[1];
const prefix = `/f/${frameKey(token)}/`;
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
t.after(() => context.close().catch(() => {}));
const page = await context.newPage();
page.setDefaultTimeout(60000);
const left = [];
const refused = [];
const errors = [];
let streamed = false;
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (r) => {
const u = new URL(r.url());
if (u.origin === signIn.origin && !u.pathname.startsWith(prefix)) left.push(`${r.method()} ${u.pathname}`);
});
page.on("response", (r) => {
const u = new URL(r.url());
if (u.origin !== signIn.origin) return;
if (r.status() === 403 || r.status() === 404) refused.push(`${r.status()} ${u.pathname}`);
if (u.pathname === `${prefix}events` && r.status() === 200) streamed = true;
});
const res = await page.goto(signIn.origin + prefix, { waitUntil: "domcontentloaded" });
assert.equal(res.status(), 200, "the page itself, under the prefix");
await drawn(page);
// Past Planny's wake-up, to the menu.
const skip = page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
await page.locator("#main section.dash-group").first().waitFor();
assert.deepEqual(await context.cookies(), [], "the frame signs in with no cookie");
await until(() => streamed, 10000);
assert.ok(streamed, "the event stream connected under the prefix");
// A step that waits on a request the server refused times out; the
// requests that left the prefix or were refused are the reason, so they
// are reported first.
try {
// The Notebook: its tab list and note come from the server.
await page.click("#btn-notepad");
await page.locator("#notepad-modal[open]").waitFor({ timeout: 15000 });
await page.waitForFunction(
() => {
const c = document.querySelector(".notepad-cm-host")?.shadowRoot?.querySelector(".cm-content");
return Boolean(c) && c.getAttribute("aria-readonly") !== "true";
},
null,
{ timeout: 15000 }
);
await page.click("#notepad-close");
// User Preferences: a change of theme is saved to the server.
await page.click("#btn-looks");
await page.locator("#looks-modal[open]").waitFor({ timeout: 15000 });
const saved = page.waitForResponse((r) => r.url().endsWith(`${prefix}looks`) && r.request().method() === "POST", { timeout: 15000 });
await page.locator('input[name="looks-theme"][value="dark"]').check();
assert.equal((await saved).status(), 200, "the looks were saved");
await page.keyboard.press("Escape");
// Activities: a game's module, loaded the first time it opens.
await page.click("#btn-activities");
await page.locator("#activities-modal[open]").waitFor({ timeout: 15000 });
await page.locator('#activities-picker .activities-row[data-activity="snake"]').click();
await page.locator("#activities-board").waitFor({ timeout: 15000 });
} finally {
await until(async () => {
const n = refused.length + left.length;
await new Promise((r) => setTimeout(r, 300));
return n === refused.length + left.length;
}, 5000);
assert.deepEqual(left, [], "every request stays under the prefix");
assert.deepEqual(refused, [], "no request is refused or missing");
}
assert.deepEqual(errors, [], "no error on the page");
});