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

@@ -69,3 +69,5 @@ Key design points:
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-relative-urls`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
**Every URL the page uses is page-relative** (`fetch("state")`, `href="app.css"`, never a leading `/`), and so is every link the server hands it (`uploads/<id>.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), so a slash-leading URL misses the prefix and gets a 403 there, and only there. `scripts/test-web-console-relative-urls.mjs` names each one, and `scripts/test-web-console-page-frame.mjs` runs the page under the prefix; a game module is resolved against the page (`new URL(entry.module, document.baseURI)`), since `import()` takes no bare path.
@@ -109,6 +109,7 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
| Page styles (`public/styles/*.css`) or `public/index.html` | `npm run test:page -- scripts/test-web-console-page-layout.mjs`, plus the page file of a screen whose own look changed (`test:page` unsets the app variables, takes `--test-name-pattern`, and is the way to run any page file) |
| A music prototype (`prototypes/music/<game>/`) | `node prototypes/music/check.cjs <game>` (nothing in `npm test` reads `prototypes/`) |
| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-<area>.mjs` (the loop's is `test-web-console-loop.mjs`, the Review Loop's `test-web-console-review-loop.mjs` with `test-web-console-page-review-loop.mjs`), and its `test-web-console-page-<area>.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` |
| A URL the page uses, or a link the server builds for it | `node --test scripts/test-web-console-relative-urls.mjs scripts/test-web-console-page-frame.mjs` |
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
| Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` |
+1 -1
View File
@@ -161,7 +161,7 @@ Security, six controls, about 60 lines:
1. Bind `127.0.0.1`.
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free. The macOS desktop app's frame is the exception: WebKit gives a cross-site frame no cookie, so there the 302 goes to `/f/<sha256(token)[0:32]>/` on the same `127.0.0.1` address, the router takes that exact prefix off the raw request line once, and a request under it passes the token gate. The page uses only page-relative URLs, so it works at `/` and under the prefix alike. Not a `<key>.localhost` host name: macOS tries it on `[::1]` first, where another process can take the port.
5. `Origin` check on every mutating request.
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
+5
View File
@@ -133,6 +133,11 @@ this:
visiting from talking to it through a DNS rebinding trick.
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
on first load so it leaves your address bar, your history and any screenshot.
In the macOS desktop app the page's frame gets no cookie (WebKit blocks
cookies for a frame from another site), so the link sends that frame to
`/f/<key>/` on the same `127.0.0.1` address instead, where the key is a hash
of the token, and the server lets in only requests under that exact prefix.
The frame has no address bar, and a browser tab still gets the cookie.
- A strict Content Security Policy with no inline script allowed.
- Markdown written by the agent is turned into page elements directly and never
into an HTML string, so a document that quotes a hostile README cannot run
+1 -1
View File
@@ -120,5 +120,5 @@ When you make a mistake, get corrected, or discover something about this codebas
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome.
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome. On macOS WebKit gives the frame no cookie even with Lax, so it signs in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), and every URL the page uses must be page-relative (`scripts/test-web-console-relative-urls.mjs`).
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
+1 -1
View File
@@ -18,7 +18,7 @@
"pretest": "node scripts/fix-line-endings.mjs",
"test:fast": "node scripts/test-fast.mjs",
"test:page": "node scripts/run-page-tests.mjs",
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-frame.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
"test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs"
},
"devDependencies": {
+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");
});
+59 -8
View File
@@ -156,21 +156,24 @@ function noteEvent(dir, event) {
export function handle(req, res, ctx) {
const port = ctx.port();
if (!hostOk(req, ctx)) return send(res, 403, "", "text/plain");
// Before anything reads the path: the macOS app's frame comes in under its
// prefix, which comes off here, once.
const framed = takeFramePrefix(req, ctx);
const url = new URL(req.url, `http://127.0.0.1:${port}`);
const pathname = url.pathname;
if (!hostOk(req, port)) return send(res, 403, "", "text/plain");
let gated = false;
for (const route of ROUTES) {
if (!route.open && !gated) {
if (!authed(req, ctx)) return send(res, 403, "Open the link the terminal printed.", "text/plain");
if (!framed && !authed(req, ctx)) return send(res, 403, "Open the link the terminal printed.", "text/plain");
ctx.touch();
gated = true;
}
if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue;
if (route.method && req.method !== route.method) continue;
if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (route.origin && !originOk(req, ctx)) return json(res, 403, { error: "bad origin" });
try {
return route.run(req, res, ctx, url);
} catch (e) {
@@ -203,6 +206,16 @@ function signIn(req, res, ctx, url) {
const given = url.pathname.slice(3).replace(/\/$/, "");
if (!ctx.token || !timingSafeEq(given, ctx.token)) return send(res, 403, "Not found", "text/plain");
ctx.touch();
// The macOS app's frame goes under its prefix instead (takeFramePrefix):
// WebKit on macOS gives that cross-site frame no cookie, Lax included. A
// browser tab that sends `Sec-Fetch-Dest: document` keeps the cookie, so
// the prefix stays out of its address bar. A client that sends no such
// header gets the prefix, the answer that works for the frame.
const key = frameKey(ctx);
if (key && req.headers["sec-fetch-dest"] !== "document") {
res.writeHead(302, baseHeaders({ location: `/f/${key}/` }));
return res.end();
}
res.writeHead(
302,
baseHeaders({
@@ -223,7 +236,9 @@ function signIn(req, res, ctx, url) {
// arrives over plain http, so None; Secure never comes back and every
// request after the sign-in is a 403: the app shows "its page did not show
// in this window". Lax, without Secure, is kept and sent there (measured in
// WebKitGTK 2.52 under both its cookie policies).
// WebKitGTK 2.52 under both its cookie policies). macOS WebKit drops even
// Lax in a cross-site frame, so the macOS app's frame never gets this
// cookie: signIn() sends it under its path prefix instead (takeFramePrefix).
function cookieSameSite(ancestor) {
if (ancestor === "'none'") return "SameSite=Strict";
if (ancestor === "tauri://localhost") return "SameSite=Lax";
@@ -1533,7 +1548,7 @@ function uploads(req, res, ctx, url) {
});
}
if (req.method === "DELETE") {
if (!originOk(req, ctx.port())) return json(res, 403, { error: "bad origin" });
if (!originOk(req, ctx)) return json(res, 403, { error: "bad origin" });
const m = UPLOAD_ANY_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(ctx, m[1], m[2]) : null;
if (!file || !fs.existsSync(file)) return json(res, 404, { error: "not found" });
@@ -2106,6 +2121,40 @@ function authed(req, ctx) {
return c ? timingSafeEq(c, ctx.token) : false;
}
// The macOS app's frame signs in by a path prefix, not by cookie. The app's
// page is tauri://localhost, cross-site to this server, and WebKit gives a
// cross-site frame no cookie in any form (its third-party cookie blocking has
// no switch). So the sign-in link sends that frame to /f/<key>/ on this same
// 127.0.0.1 address, and a request under exactly that prefix is signed in.
// The key is a hash of the token, still 128 bits, so the token itself never
// sits in the frame's address. Unlike the HttpOnly cookie, the key is
// readable by the page's own script (location.pathname), so this relies on
// the page's strict CSP keeping any other script out. Off (null) everywhere
// else, Windows and Linux included. Not a host name such as <key>.localhost:
// macOS tries it on [::1] first, where another process can listen on the
// same port and be handed the key.
function frameKey(ctx) {
if (process.platform !== "darwin" || embedAncestor() !== "tauri://localhost" || !ctx.token) return null;
return crypto.createHash("sha256").update(ctx.token).digest("hex").slice(0, 32);
}
// True, with the prefix taken off req.url, for a request under the frame's
// prefix. It comes off the raw request line, not the parsed path, so the
// routes that refuse anything URL parsing had to fold (`..`) still see it.
// Only the first prefix comes off: a second is just a path, and nothing
// serves it. The page asks for everything page-relative (no leading slash),
// so the same page works at / in a browser tab and under the prefix here.
const FRAME_PREFIX = /^\/f\/([^/]*)\//;
function takeFramePrefix(req, ctx) {
const key = frameKey(ctx);
if (!key) return false;
const m = FRAME_PREFIX.exec(req.url);
if (!m || !timingSafeEq(m[1], key)) return false;
req.url = req.url.slice(m[0].length - 1);
return true;
}
/**
* The DNS-rebinding defense, and the highest-value check in this file.
*
@@ -2113,15 +2162,17 @@ function authed(req, ctx) {
* 127.0.0.1 and then talk to this server as same-origin. That is not
* theoretical: it is the exact shape of Vite's GHSA-vg6x-rcgg-rjx6.
*/
function hostOk(req, port) {
function hostOk(req, ctx) {
const host = req.headers.host;
if (!host) return false;
const port = ctx.port();
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
}
function originOk(req, port) {
function originOk(req, ctx) {
const origin = req.headers.origin;
if (!origin) return true; // same-origin fetches and plain navigations send none
const port = ctx.port();
return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
}