mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 08:15:41 -08:00
183 lines
8.9 KiB
JavaScript
183 lines
8.9 KiB
JavaScript
// Web console tests, the page's URLs: every URL the page uses is page-relative.
|
|
// The macOS app's frame gets no cookie, so it signs in by a path prefix
|
|
// (`/f/<key>/`, routes.mjs) and the page is served under it there, while a
|
|
// browser tab has it at `/`. A relative `state` reaches the server either
|
|
// way; a slash-leading `/state` drops the prefix and gets a 403, in the macOS
|
|
// app only, so no other test would notice. This guard reads the page's source
|
|
// (and the links the server hands it) and names each slash-leading one.
|
|
// Run with: node --test scripts/test-web-console-relative-urls.mjs
|
|
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { ROOT } from "./web-console-test-helpers.mjs";
|
|
|
|
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
|
const PUBLIC_DIR = path.join(CONSOLE_DIR, "public");
|
|
|
|
const WHY = "the macOS app serves the page under /f/<key>/, so a slash-leading URL misses the prefix and gets a 403 there; drop the leading slash";
|
|
|
|
// Slash-leading text that is not a URL. Any literal opening `/plan2code` is a
|
|
// slash command (no route starts so); anything else is named here, by file
|
|
// and exact literal, with its reason.
|
|
const SLASH_COMMAND = /^.\/plan2code(?![\w/])|^.\/plan2code-/;
|
|
const TEXT = new Map([
|
|
["answers.js", new Set(["`/${offer.skill}`"])], // a skill offer's slash command
|
|
["diff-parse.js", new Set(['"/dev/null"'])], // git's name for no file in a diff header, compared, never fetched
|
|
["loop-parts.js", new Set(['"/api/webhooks/"'])], // a path test on a Discord address the person typed
|
|
["skills.js", new Set(['"/"'])], // `"/" + entry.skill`, a skill's slash command
|
|
]);
|
|
|
|
// Every page file the rule reads: scripts, the page and stylesheets under
|
|
// public/, vendored code aside, as paths relative to it with forward slashes.
|
|
function pageFiles(rel = "") {
|
|
const out = [];
|
|
for (const e of fs.readdirSync(path.join(PUBLIC_DIR, rel), { withFileTypes: true })) {
|
|
const p = rel ? `${rel}/${e.name}` : e.name;
|
|
if (e.isDirectory()) {
|
|
if (p !== "vendor") out.push(...pageFiles(p));
|
|
} else if (/\.(js|html|css)$/.test(e.name)) out.push(p);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Each string literal in `text` (double quotes, single quotes or backticks)
|
|
* that makes a slash-leading URL, as `{ line, literal }`, in three shapes:
|
|
* text opening with `/` and a path character (a letter, digit, `_`, `.`, `-`
|
|
* or `${`); a lone `"/"` that starts an expression joined on with `+`
|
|
* (`fetch("/" + route)`; one joined in the middle of a path is fine); and
|
|
* markup in a string whose `src`, `href` or like attribute opens with `/`
|
|
* (`` `<img src="/x">` ``). A comment line and anything after a `//` outside
|
|
* a string are skipped; `//` opening a string is the protocol-relative case,
|
|
* which render.js blocks on its own. Quotes are tracked one line at a time, so
|
|
* a template literal that spans lines, or a regex literal holding a quote,
|
|
* can put the scan out of step for the rest of that line: a URL there goes
|
|
* unflagged, and only the frame page test, which loads the dashboard alone,
|
|
* would catch it at run time.
|
|
*/
|
|
function scriptUrls(text) {
|
|
const hits = [];
|
|
text.split("\n").forEach((line, i) => {
|
|
const t = line.trim();
|
|
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return;
|
|
for (let j = 0; j < line.length; j++) {
|
|
const c = line[j];
|
|
if (c === "/" && line[j + 1] === "/") break;
|
|
if (c !== '"' && c !== "'" && c !== "`") continue;
|
|
let k = j + 1;
|
|
while (k < line.length && line[k] !== c) k += line[k] === "\\" ? 2 : 1;
|
|
const body = line.slice(j + 1, k);
|
|
const opens = body[0] === "/" && /[A-Za-z0-9_.$-]/.test(body[1] || "");
|
|
const joined = body === "/" && /^\s*\+/.test(line.slice(k + 1)) && STARTS_EXPRESSION.test(line.slice(0, j));
|
|
if (opens || joined || ATTRIBUTE_URL.test(body)) hits.push({ line: i + 1, literal: line.slice(j, k + 1) });
|
|
j = k;
|
|
}
|
|
});
|
|
return hits;
|
|
}
|
|
|
|
// What may come right before an expression's first operand: nothing, an
|
|
// opening bracket, a separator, an operator or `return`.
|
|
const STARTS_EXPRESSION = /(?:^|[([{,=:?!&|>]|\breturn)\s*$/;
|
|
|
|
// An attribute that holds a URL, opening with `/` (but not `//`), in markup a
|
|
// script builds, quoted or not and with its quote escaped or not.
|
|
const ATTRIBUTE_URL = /\b(?:src|srcset|href|action|poster|data)=\\?["']?\/(?![/\\])/;
|
|
|
|
/** Each `src`, `srcset`, `href`, `action`, `poster` or `data` value opening with `/`, in either quotes. */
|
|
function htmlUrls(text) {
|
|
return text
|
|
.split("\n")
|
|
.flatMap((l, i) =>
|
|
[...l.matchAll(/\b(?:src|srcset|href|action|poster|data)=(?:"(\/[^"]*)"|'(\/[^']*)')/g)].map((m) => ({ line: i + 1, literal: m[1] ?? m[2] }))
|
|
);
|
|
}
|
|
|
|
/** Each `url(/...)` or `@import "/..."`. */
|
|
function cssUrls(text) {
|
|
return text
|
|
.split("\n")
|
|
.flatMap((l, i) => [...l.matchAll(/url\(\s*["']?(\/[^)"']*)|@import\s+["'](\/[^"']*)/g)].map((m) => ({ line: i + 1, literal: m[1] || m[2] })));
|
|
}
|
|
|
|
// A link the server builds for the page: a slash-leading literal given to a
|
|
// name holding `url`, `href` or `src` (`url: "/uploads/..."`, `imageUrl = (...) => "/..."`).
|
|
const SERVER_LINK = /\b\w*(?:url|href|src)\w*\s*[:=]\s*(?:\([^)]*\)\s*=>\s*)?["'`]\/(?!\/)/i;
|
|
|
|
function pageOffenders() {
|
|
const out = [];
|
|
for (const f of pageFiles()) {
|
|
const text = fs.readFileSync(path.join(PUBLIC_DIR, f), "utf8");
|
|
if (f.endsWith(".html")) {
|
|
out.push(...htmlUrls(text).map((h) => ({ file: f, ...h })));
|
|
continue;
|
|
}
|
|
if (f.endsWith(".css")) {
|
|
out.push(...cssUrls(text).map((h) => ({ file: f, ...h })));
|
|
continue;
|
|
}
|
|
for (const h of scriptUrls(text)) {
|
|
if (SLASH_COMMAND.test(h.literal) || TEXT.get(f)?.has(h.literal)) continue;
|
|
out.push({ file: f, ...h });
|
|
}
|
|
}
|
|
return out.map((h) => `public/${h.file}:${h.line} ${h.literal}`);
|
|
}
|
|
|
|
test("the scanner finds slash-leading literals and leaves comments, other schemes and slash commands alone", () => {
|
|
const found = (src) => scriptUrls(src).map((h) => h.literal);
|
|
assert.deepEqual(found('fetch("/state");'), ['"/state"']);
|
|
assert.deepEqual(found("x('/looks', `/${a}.mp3`)"), ["'/looks'", "`/${a}.mp3`"]);
|
|
assert.deepEqual(found('a("state"); b("https://x/y"); c("//cdn"); d("/");'), []);
|
|
assert.deepEqual(found('// fetch("/state")'), []);
|
|
assert.deepEqual(found(' * see "/state"'), []);
|
|
assert.deepEqual(found('go(); // then "/state"'), []);
|
|
assert.deepEqual(found('q("a\\"/b", "/c")'), ['"/c"']);
|
|
// A slash joined on at the start of an expression, and markup holding one.
|
|
assert.deepEqual(found('fetch("/" + route); x = "/" + y; return "/" + z;'), ['"/"', '"/"', '"/"']);
|
|
assert.deepEqual(found('a("notepad/images/" + tab + "/" + id); b(sep ? "/" : "")'), []);
|
|
assert.deepEqual(found('box.innerHTML = `<img src="/uploads/${id}.jpg">`;'), ['`<img src="/uploads/${id}.jpg">`']);
|
|
assert.deepEqual(found("h = '<a href=\\'/state\\'>'; s = \"<img src=\\\"/x.png\\\">\";").length, 2);
|
|
assert.deepEqual(found('h = `<img src="uploads/${id}.jpg"><a href="//cdn/x">`'), []);
|
|
assert.ok(SLASH_COMMAND.test('"/plan2code"') && SLASH_COMMAND.test('"/plan2code-review"'));
|
|
assert.ok(!SLASH_COMMAND.test('"/plan2codex"') && !SLASH_COMMAND.test('"/plan2code/x"'));
|
|
assert.deepEqual(htmlUrls('<link href="/app.css" /><script src="app.js"></script>'), [{ line: 1, literal: "/app.css" }]);
|
|
assert.deepEqual(htmlUrls("<img src='/x.png' srcset=\"/y.png 2x\">"), [
|
|
{ line: 1, literal: "/x.png" },
|
|
{ line: 1, literal: "/y.png 2x" },
|
|
]);
|
|
assert.deepEqual(cssUrls("a { background: url(/x.png) } @import \"/y.css\";"), [
|
|
{ line: 1, literal: "/x.png" },
|
|
{ line: 1, literal: "/y.css" },
|
|
]);
|
|
assert.ok(SERVER_LINK.test('url: "/uploads/" + id'));
|
|
assert.ok(SERVER_LINK.test('const imageUrl = (tab, id) => "/notepad/images/" + tab'));
|
|
assert.ok(!SERVER_LINK.test('url: "uploads/" + id') && !SERVER_LINK.test('{ path: "/state", run }'));
|
|
});
|
|
|
|
test("every URL in the page is page-relative", () => {
|
|
const offenders = pageOffenders();
|
|
assert.deepEqual(offenders, [], `${offenders.length} slash-leading URL(s) in the page (${WHY}):\n${offenders.join("\n")}`);
|
|
});
|
|
|
|
test("every link the server hands the page is page-relative", () => {
|
|
const offenders = [];
|
|
for (const f of fs.readdirSync(CONSOLE_DIR).filter((n) => n.endsWith(".mjs"))) {
|
|
fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8")
|
|
.split("\n")
|
|
.forEach((l, i) => {
|
|
if (!l.trim().startsWith("//") && SERVER_LINK.test(l)) offenders.push(`${f}:${i + 1} ${l.trim()}`);
|
|
});
|
|
}
|
|
assert.deepEqual(offenders, [], `slash-leading link(s) the server builds for the page (${WHY}):\n${offenders.join("\n")}`);
|
|
});
|
|
|
|
test("every name the rule lets through is still in its file", () => {
|
|
for (const [file, literals] of TEXT) {
|
|
const found = new Set(scriptUrls(fs.readFileSync(path.join(PUBLIC_DIR, file), "utf8")).map((h) => h.literal));
|
|
for (const literal of literals) assert.ok(found.has(literal), `${file} no longer has ${literal}: drop it from TEXT`);
|
|
}
|
|
});
|