diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6f8dfab..2f0cc1c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,16 +13,16 @@ jobs: name: ci runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm - run: npm ci - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 id: playwright-cache with: path: ~/.cache/ms-playwright diff --git a/README.md b/README.md index eb85677..5830d7f 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ Now share a URL from Safari or another app, choose the shortcut, and URL Cleaner ### Share Sheet limitations -- The Shortcut passes the link after the `#`, which browsers never send to a server, so the link stays on your device. Older Shortcuts that use `?url=` still work, but that form sends the link to the web host in the page request; switch them to `/#url=`. +- The Shortcut passes the link after the `#`, which browsers never send to a server, so the link stays on your device. The Android share target POSTs into the service worker, which redirects to `/#url=` without a network request. Older Shortcuts that use `?url=` still work, but that form sends the link to the web host in the page request; switch them to `/#url=`. - The **Share** button uses the browser's Web Share support. It appears only where that API is available; **Copy** remains the fallback. - iOS and macOS may block silent clipboard writes when a page opens without a direct user gesture. The app therefore always displays the cleaned URL, and the **Share** and **Copy** buttons remain reliable final steps. - The app removes the handoff value from the address bar after loading it. @@ -213,7 +213,7 @@ The test suite covers: - Local tracker explanations, rich tracker-of-the-day profiles, and deterministic daily selection - Tracking fingerprint scoring, URL X-Ray categorization, encoded value decoding, and weirdness flags - Opt-in aggressive cleaning and identical-duplicate cleanup, including batch mode -- Share-target, `#url=` and `?url=` handoff parsing +- Share-target POST, `#url=` and `?url=` handoff parsing - Manifest, service worker, and CSP constraints for the installable app - Every root web file matching its `dist/` copy byte-for-byte, since Vercel serves `dist/` @@ -231,7 +231,8 @@ GitHub Actions runs `npm test` on every push to `main` and on pull requests. | [handoff.js](./handoff.js) | Share-target, hash handoff, and clipboard-permission helpers | | [app.js](./app.js) | Form, clipboard, settings, and copy interactions | | [manifest.webmanifest](./manifest.webmanifest) | Web app manifest and share target | -| [sw.js](./sw.js) | Minimal service worker for installability (no caching) | +| [sw.js](./sw.js) | Service worker for installability and local share-target POST handoff (no caching, no network) | +| [middleware.js](./middleware.js) | Vercel Routing Middleware: 303 share-target POSTs to `/` without reading the body | | [tests/](./tests) | Automated tests (cleaning, batch, explanations, handoff, PWA, favicon, production URL, `dist/` sync) | | [vercel.json](./vercel.json) | Vercel config: serves `dist/` and sets the security headers | | [.github/workflows/test.yml](./.github/workflows/test.yml) | Runs `npm test` in CI | @@ -261,9 +262,10 @@ How a link reaches the app matters: - **Paste, Paste button, clipboard offer:** the link never leaves the page. - **Shortcut (`/#url=`):** the link is passed after the `#`. Browsers do not send that part to the server, so the host only sees a plain request for the page. -- **Android share target and old `?url=` links:** the Web Share Target API can only pass the link as a query string, so the shared link is included in the page request to the static host (Vercel) before the app cleans it and removes it from the address bar. Use the Shortcut or paste if you want to avoid that. +- **Android share target:** the installed PWA receives a POST. When the service worker is controlling the page, it intercepts that POST and redirects to a `/#url=&text=&title=` hash, so the shared fields never leave the device and an invalid `url` field can still fall back to a link in `text` or `title`. If the worker is not yet active (first launch or cleared storage), Vercel Routing Middleware responds `303` to `/` without reading the POST body, so the host never logs the shared link; the URL is dropped and you can paste or share again after install. +- **Old `?url=` links:** still work, but that form sends the link to the web host in the page request. Use `/#url=` or paste if you want to avoid that. -The hosted site enforces this with security headers set in [vercel.json](./vercel.json). The Content Security Policy uses `connect-src 'none'`, so the page cannot make network requests even if it tried, and only loads its own scripts and styles. It also sends `Referrer-Policy: no-referrer`, refuses to be framed, and disables camera, microphone, geolocation, payment, and USB access. The service worker exists only for installability and caches nothing. +The hosted site enforces this with security headers set in [vercel.json](./vercel.json). The Content Security Policy uses `connect-src 'none'`, so the page cannot make network requests even if it tried, and only loads its own scripts and styles. It also sends `Referrer-Policy: no-referrer`, refuses to be framed, and disables camera, microphone, geolocation, payment, and USB access. The service worker exists for installability and to keep share-target POSTs on-device; it caches nothing and never fetches the shared URL. ## License diff --git a/app.js b/app.js index f2b18dc..f6c230f 100644 --- a/app.js +++ b/app.js @@ -8,7 +8,7 @@ import { removedDuplicateIndicesForBeforeView } from "./cleaner.js"; import { explainParameter, trackerOfTheDay } from "./explanations.js"; -import { canReadClipboard, parseHandoffUrl } from "./handoff.js"; +import { canReadClipboard, hasHandoffFields, parseHandoffUrl } from "./handoff.js"; import { createIcon, wrapIconButton } from "./icons.js"; import { breakableUrlMarkup } from "./url-break.js"; import { @@ -685,12 +685,16 @@ function clearHandoffFromAddressBar() { } function loadHandoff() { - const handedOff = parseHandoffUrl(window.location.href); - if (!handedOff) return false; - input.value = handedOff; - runClean({ allowAutoCopy: false }); - clearHandoffFromAddressBar(); - return true; + const href = window.location.href; + const handedOff = parseHandoffUrl(href); + if (handedOff) { + input.value = handedOff; + runClean({ allowAutoCopy: false }); + } + if (handedOff || hasHandoffFields(href)) { + clearHandoffFromAddressBar(); + } + return Boolean(handedOff); } initTheme(); diff --git a/cleaner.js b/cleaner.js index bb88f36..f34033a 100644 --- a/cleaner.js +++ b/cleaner.js @@ -60,6 +60,13 @@ const REDIRECT_RELATED_PARAMETERS = new Set([ export const MAX_UNWRAP_DEPTH = 5; +export class InputError extends Error { + constructor(message) { + super(message); + this.name = "InputError"; + } +} + // %30-%39 (0-9), %41-%5A (A-Z) and %61-%7A (a-z). const ENCODED_ALPHANUMERIC_PATTERN = /%(?:3[0-9]|4[1-9a-f]|5[0-9a]|6[1-9a-f]|7[0-9a])/i; @@ -136,17 +143,17 @@ function getWrapperInfo(url) { function parseHttpUrl(input) { const value = String(input ?? "").trim(); - if (!value) throw new TypeError("Enter a URL to clean."); + if (!value) throw new InputError("Enter a URL to clean."); let url; try { url = new URL(value); } catch { - throw new TypeError("Enter a valid URL, including https:// or http://."); + throw new InputError("Enter a valid URL, including https:// or http://."); } if (!isHttpUrl(url)) { - throw new TypeError("Enter a valid URL, including https:// or http://."); + throw new InputError("Enter a valid URL, including https:// or http://."); } return url; @@ -432,7 +439,7 @@ export function cleanUrl(input, options = {}) { }; } -export function cleanBatch(text, options = {}) { +export function cleanBatch(text, options = {}, clean = cleanUrl) { const lines = String(text ?? "").split(/\r?\n/); const results = []; @@ -445,14 +452,16 @@ export function cleanBatch(text, options = {}) { line: index + 1, input, ok: true, - result: cleanUrl(input, options) + result: clean(input, options) }); } catch (error) { results.push({ line: index + 1, input, ok: false, - error: error.message + error: error instanceof InputError + ? error.message + : "Internal error while cleaning this URL." }); } } diff --git a/handoff.js b/handoff.js index fdf614d..e16ef77 100644 --- a/handoff.js +++ b/handoff.js @@ -71,13 +71,21 @@ export function parseHandoffParams(searchParams) { return ""; } -// Links handed over after the "#" (#url=) are never sent to the server, so -// they win. The ?url= form stays for the share target and legacy handoff links. +// Links handed over after the "#" are never sent to the server, so they win. +// The Android share target POSTs into the service worker, which redirects to +// /#url=&text=&title= without a network request so parseHandoffParams can try +// each field. The ?url= form stays for legacy handoff links only. export function parseHandoffUrl(href) { const url = new URL(href); return parseHandoffParams(url.hash.slice(1)) || parseHandoffParams(url.searchParams); } +export function hasHandoffFields(href) { + const parsed = new URL(href); + const sources = [new URLSearchParams(parsed.hash.slice(1)), parsed.searchParams]; + return sources.some((params) => ["url", "text", "title"].some((name) => params.has(name))); +} + export function canReadClipboard(permissionState) { return permissionState === "granted"; } diff --git a/manifest.webmanifest b/manifest.webmanifest index 3302dfc..f5159ea 100644 --- a/manifest.webmanifest +++ b/manifest.webmanifest @@ -22,7 +22,7 @@ ], "share_target": { "action": "./", - "method": "GET", + "method": "POST", "enctype": "application/x-www-form-urlencoded", "params": { "title": "title", diff --git a/mcp/.env.example b/mcp/.env.example index 7a10a28..78be7b8 100644 --- a/mcp/.env.example +++ b/mcp/.env.example @@ -4,7 +4,8 @@ HOST=127.0.0.1 PORT=8787 # Optional: comma-separated full origins (scheme+host+port) for POST /mcp; loopback on any port is always allowed # MCP_ALLOWED_ORIGINS=https://app.example:8443,http://localhost:3000 -# Optional: Host header allowlist (literal match); include :port when PORT is not 80 -# MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859,mcp.example.com +# Optional: extra Host header values (literal match); include :port when PORT is not 80. +# Loopback names are already allowed when HOST is 127.0.0.1 or a wildcard (0.0.0.0 / ::). +# MCP_ALLOWED_HOSTS=mcp.example.com # Optional: override engine location (default is repo root, one level up from mcp/) # ENGINE_DIR=.. diff --git a/mcp/README.md b/mcp/README.md index 1724728..7ffab49 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -5,7 +5,7 @@ Official MCP adapter for [URL Cleaner](https://github.com/heyandromeda/url-clean Every tool result comes from engine functions only. The server does not fetch or open URLs. Each result includes `engineInvoked` (function names + best-effort git SHA of the loaded engine). - **stdio** (default): newline-delimited JSON-RPC for Cursor, Claude Code, Codex, and other local MCP clients. -- **HTTP**: Streamable HTTP on `POST /mcp` (JSON responses), bearer auth, binds `127.0.0.1` by default. `GET /healthz` is public. +- **HTTP**: Streamable HTTP on `POST /mcp` (JSON responses), bearer auth, binds `127.0.0.1` by default. `GET /healthz` is unauthenticated and Host-checked (`{ ok: true }` only). - Protocol: `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`. JSON-RPC batches accepted. - Logs (stderr): tool name, duration, status, and auth rejections only — never URLs, arguments, or tokens. @@ -40,7 +40,7 @@ Environment: | Variable | Purpose | |---|---| | `MCP_AUTH_TOKEN` | Required for HTTP mode (≥ 24 characters) | -| `HOST` | Default `127.0.0.1`. With `HOST=0.0.0.0`, the default allowed `Host` set follows the bind address only and **excludes** `localhost` and `127.0.0.1`; local clients must set `MCP_ALLOWED_HOSTS` (see **Host** below). | +| `HOST` | Default `127.0.0.1`. Binding `0.0.0.0` or `::` also allows loopback `Host` values (`localhost`, `127.0.0.1`, `[::1]`, with and without port). Proxy hostnames still need `MCP_ALLOWED_HOSTS` (see **Host** below). | | `PORT` | Default `8787` | | `ENGINE_DIR` | Default `..` (repo root) | | `ENGINE_SHA` | Optional override for `engineInvoked.sha` | @@ -53,7 +53,7 @@ Environment: **Origin (DNS rebinding):** On `POST /mcp`, if the client sends an `Origin` header it must pass **either** the default loopback rule (`http`/`https` on `localhost`, `127.0.0.1`, or `[::1]` on **any** port) **or** match a full origin in `MCP_ALLOWED_ORIGINS` (scheme, host, and port compared via `URL().origin` — `https://app.example:8443` does not admit `http://app.example` or `https://app.example:9999`). A disallowed Origin returns **403** before auth or body handling. Requests with no `Origin` header are still accepted. -**Host:** The `Host` header must match the bound loopback address/port **or** an entry in `MCP_ALLOWED_HOSTS` (comma-separated, lowercase). Values are compared literally to the request `Host` header. Include the port in each entry when the server listens on a non-80 port (e.g. `MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859`); a bare host such as `127.0.0.1` does **not** match `127.0.0.1:8859` and returns **403**. On port **80** only, clients may send a host without `:80`, so a bare entry can match. Use this when binding `0.0.0.0` or when a reverse proxy forwards with a public hostname. `/healthz` is not subject to Origin checks. +**Host:** The `Host` header must match the bound address/port **or** an entry in `MCP_ALLOWED_HOSTS` (comma-separated, lowercase). Values are compared literally to the request `Host` header. Include the port in each entry when the server listens on a non-80 port (e.g. `MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859`); a bare host such as `127.0.0.1` does **not** match `127.0.0.1:8859` and returns **403**. On port **80** only, clients may send a host without `:80`, so a bare entry can match. When binding `0.0.0.0` or `::`, the defaults also include loopback names (`localhost`, `127.0.0.1`, `[::1]`, with and without the listen port) so local clients work without `MCP_ALLOWED_HOSTS`. Use `MCP_ALLOWED_HOSTS` when a reverse proxy forwards with a public hostname. `/healthz` is Host-checked the same way, is not subject to Origin or token checks, and does not include the engine SHA. There is **no** public hosted MCP endpoint in this repo. Run stdio locally or bind HTTP on localhost for your own clients. diff --git a/mcp/scripts/http-smoke.sh b/mcp/scripts/http-smoke.sh index 1aae9ef..3b6ddbb 100755 --- a/mcp/scripts/http-smoke.sh +++ b/mcp/scripts/http-smoke.sh @@ -2,10 +2,12 @@ # Local-only smoke test: starts the server on 127.0.0.1 with a random throwaway token (never printed), runs curl calls, stops it. set -uo pipefail cd "$(dirname "$0")/.." +WORKDIR="$(mktemp -d)" export MCP_AUTH_TOKEN="$(node -e 'process.stdout.write(require("crypto").randomBytes(32).toString("hex"))')" export PORT="${PORT:-8799}" HOST=127.0.0.1 -node server.mjs --http 2> /tmp/ucmcp-http.log & PID=$! -trap 'kill $PID 2>/dev/null' EXIT +node server.mjs --http 2> "$WORKDIR/http.log" & PID=$! +cleanup() { kill "$PID" 2>/dev/null || true; rm -rf "$WORKDIR"; } +trap cleanup EXIT for i in $(seq 1 30); do curl -s "http://127.0.0.1:$PORT/healthz" >/dev/null && break; sleep 0.1; done U="http://127.0.0.1:$PORT/mcp" rpc() { curl -s -w ' [HTTP %{http_code}]\n' -H "Authorization: Bearer $MCP_AUTH_TOKEN" -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -d "$1" "$U"; } @@ -15,7 +17,7 @@ echo "### wrong token"; curl -s -o /dev/null -w '[HTTP %{http_code}]\n' -H 'Auth echo "### initialize"; rpc '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' echo "### initialized"; rpc '{"jsonrpc":"2.0","method":"notifications/initialized"}' echo "### ping"; rpc '{"jsonrpc":"2.0","id":2,"method":"ping"}' -echo "### tools/list"; rpc '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' > /tmp/ucmcp-list.json; cat /tmp/ucmcp-list.json | tail -c 40 +echo "### tools/list"; rpc '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' > "$WORKDIR/list.json"; cat "$WORKDIR/list.json" | tail -c 40 for spec in \ '10|clean_url|{"url":"https://example.com/p?utm_source=x&utm_medium=y&id=5&fbclid=abc"}' \ '11|clean_url|{"url":"https://www.google.com/url?q=https%3A%2F%2Fexample.com%2F%3Futm_source%3Dx"}' \ @@ -30,6 +32,6 @@ for spec in \ '60|clean_url|{}' \ '61|no_such_tool|{}' ; do IFS='|' read -r id name args <<< "$spec" - echo "### $id $name $args"; call "$id" "$name" "$args" > "/tmp/ucmcp-$id.json"; tail -c 20 "/tmp/ucmcp-$id.json" + echo "### $id $name $args"; call "$id" "$name" "$args" > "$WORKDIR/$id.json"; tail -c 20 "$WORKDIR/$id.json" done -echo "### server log (stderr)"; cat /tmp/ucmcp-http.log +echo "### server log (stderr)"; cat "$WORKDIR/http.log" diff --git a/mcp/server.mjs b/mcp/server.mjs index efe2f06..f8b815c 100644 --- a/mcp/server.mjs +++ b/mcp/server.mjs @@ -29,13 +29,17 @@ const MAX_BATCH = 100; const MAX_URL_LEN = 8192; const MAX_HTTP_BODY_BYTES = 1_000_000; const BATCH_ITEM_ERROR = "Every item must be a non-empty single-line string."; +const BATCH_ITEM_TOO_LONG = `URL is longer than ${MAX_URL_LEN} characters.`; const OPAQUE_SHORTENER_WARNING = "Opaque shortener host: the real destination is hidden and URL Cleaner does not follow links, so it cannot be cleaned further."; const proof = (...fns) => ({ engineInvoked: { functions: fns, module: "url-cleaner/cleaner.js", sha: ENGINE_SHA } }); const queryNames = (href) => [...new URL(href).searchParams.keys()]; -class InputError extends Error {} +export function resolveInputError(engineModule) { + return engineModule?.InputError ?? class InputError extends Error {}; +} +const InputError = resolveInputError(engine); function needUrl(args) { const url = args?.url; if (typeof url !== "string" || !url.trim()) throw new InputError("Missing required argument `url` (a string)."); @@ -97,6 +101,10 @@ const TOOLS = { results[index] = { index, ok: false, original: String(u ?? ""), error: BATCH_ITEM_ERROR }; continue; } + if (u.length > MAX_URL_LEN) { + results[index] = { index, ok: false, original: u.slice(0, 64), error: BATCH_ITEM_TOO_LONG }; + continue; + } validLines.push({ index, input: u.trim() }); } let batchEntries = []; @@ -266,12 +274,13 @@ function handle(msg) { if (method === "tools/list") return ok(msg.id, { tools: Object.entries(TOOLS).map(([name, t]) => ({ name, description: t.description, inputSchema: t.inputSchema, annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true } })) }); if (method === "tools/call") { - const name = params?.name; const tool = TOOLS[name]; - if (!tool) return err(msg.id, -32602, `Unknown tool: ${String(name).slice(0, 64)}`); + const name = params?.name; + if (!Object.hasOwn(TOOLS, name)) return err(msg.id, -32602, `Unknown tool: ${String(name).slice(0, 64)}`); + const tool = TOOLS[name]; const t0 = performance.now(); let status = "ok"; try { return ok(msg.id, toolResult(tool.run(params.arguments || {}), false, name)); } catch (e) { - status = e instanceof InputError || e instanceof TypeError ? "input_error" : "error"; + status = e instanceof InputError ? "input_error" : "error"; const message = status === "error" ? "Internal error while running the URL Cleaner engine." : e.message; return ok(msg.id, toolResult({ error: message, tool: name, engine: { sha: ENGINE_SHA } }, true, name)); } finally { log({ tool: name, ms: Math.round(performance.now() - t0), status }); } @@ -340,6 +349,17 @@ function originHeaderAllowed(originHeader, explicitAllowedOrigins) { return explicitAllowedOrigins.has(originUrl.origin); } +function addLoopbackHostHeaders(allowed, withPort) { + allowed.add(withPort("127.0.0.1").toLowerCase()); + allowed.add(withPort("localhost").toLowerCase()); + allowed.add("127.0.0.1"); + allowed.add("localhost"); + allowed.add(withPort("[::1]").toLowerCase()); + allowed.add(withPort("::1").toLowerCase()); + allowed.add("[::1]"); + allowed.add("::1"); +} + function defaultAllowedHostHeaders(bindHost, bindPort) { const allowed = new Set(); const bind = bindHost.toLowerCase(); @@ -358,6 +378,9 @@ function defaultAllowedHostHeaders(bindHost, bindPort) { const name = bindHost.includes(":") ? `[${bindHost}]` : bindHost; allowed.add(withPort(name).toLowerCase()); allowed.add(name.toLowerCase()); + if (bind === "0.0.0.0" || bind === "::" || bind === "[::]") { + addLoopbackHostHeaders(allowed, withPort); + } } return allowed; } @@ -393,7 +416,12 @@ function startHttp() { }; const server = http.createServer((req, res) => { const pathname = (req.url || "").split("?")[0]; - if (req.method === "GET" && pathname === "/healthz") return send(res, 200, { ok: true, engineSha: ENGINE_SHA }); + if (req.method === "GET" && pathname === "/healthz") { + if (!hostHeaderAllowed(req.headers.host, HOST, PORT, allowedHostHeaders)) { + return rejectMcp(res, "Host not allowed"); + } + return send(res, 200, { ok: true }); + } if (pathname !== "/mcp") return send(res, 404, { error: "not found" }); if (req.headers.origin && !originHeaderAllowed(req.headers.origin, explicitAllowedOrigins)) { return rejectMcp(res, "Origin not allowed"); @@ -444,5 +472,7 @@ export { loopbackOriginAllowed, loadExplicitAllowedOrigins, loadAllowedHostHeaders, - defaultAllowedHostHeaders + defaultAllowedHostHeaders, + InputError, + MAX_URL_LEN }; diff --git a/mcp/tests/dev-22.test.mjs b/mcp/tests/dev-22.test.mjs new file mode 100644 index 0000000..bb46bb6 --- /dev/null +++ b/mcp/tests/dev-22.test.mjs @@ -0,0 +1,189 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { spawn, spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import http from "node:http"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { + TOOLS, + handle, + defaultAllowedHostHeaders, + MAX_URL_LEN, + resolveInputError +} from "../server.mjs"; +import { InputError as EngineInputError } from "../../cleaner.js"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const TRACKED = "https://example.com/?utm_source=x"; + +function summaryText(result) { + assert.equal(result.content?.length, 1); + return result.content[0].text; +} + +test("clean_urls_batch caps each item at MAX_URL_LEN (DEV-22 F1)", () => { + const long = `https://example.com/${"a".repeat(9000)}`; + const out = TOOLS.clean_urls_batch.run({ urls: [long, TRACKED] }); + assert.equal(out.results[0].ok, false); + assert.match(out.results[0].error, new RegExp(String(MAX_URL_LEN))); + assert.equal(out.results[1].ok, true); + assert.equal(out.results[1].cleaned, "https://example.com/"); + assert.equal(out.okCount, 1); + assert.equal(out.count, 2); +}); + +test("tools/call inherited names are unknown tools (DEV-22 F2)", () => { + for (const name of ["__proto__", "constructor", "toString"]) { + const res = handle({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name, arguments: {} } + }); + assert.equal(res.error?.code, -32602, name); + assert.match(res.error?.message ?? "", /Unknown tool/, name); + assert.equal(res.result, undefined, name); + } +}); + +test("tools/call TypeError is not echoed (DEV-22 F3)", () => { + const serverHref = pathToFileURL(path.join(ROOT, "server.mjs")).href; + const child = spawnSync(process.execPath, ["--input-type=module", "-e", ` + import { handle, TOOLS } from ${JSON.stringify(serverHref)}; + TOOLS.clean_url.run = () => { throw new TypeError("internal detail"); }; + const res = handle({ + jsonrpc: "2.0", + id: 99, + method: "tools/call", + params: { name: "clean_url", arguments: { url: "https://example.com/" } } + }); + const text = res.result?.content?.[0]?.text ?? ""; + if (!res.result?.isError) { console.error("expected isError"); process.exit(1); } + if (!text.includes("Internal error while running the URL Cleaner engine.")) { console.error(text); process.exit(1); } + if (text.includes("internal detail")) { console.error("leaked: " + text); process.exit(1); } + `], { encoding: "utf8" }); + assert.equal(child.status, 0, child.stderr || child.stdout); +}); + +test("tools/call still echoes InputError validation messages (DEV-22 F3)", () => { + const res = handle({ + jsonrpc: "2.0", + id: 100, + method: "tools/call", + params: { name: "clean_url", arguments: { url: "ht!tp:/bad" } } + }); + assert.equal(res.result.isError, true); + assert.match(summaryText(res.result), /valid URL/); + assert.doesNotMatch(summaryText(res.result), /Internal error/); +}); + +test("HOST=0.0.0.0 defaults include loopback Host names (DEV-22 F6)", () => { + const allowed = defaultAllowedHostHeaders("0.0.0.0", 8787); + for (const host of [ + "0.0.0.0:8787", + "0.0.0.0", + "127.0.0.1:8787", + "localhost:8787", + "[::1]:8787", + "127.0.0.1", + "localhost", + "[::1]" + ]) { + assert.equal(allowed.has(host), true, host); + } + + const loopbackOnly = defaultAllowedHostHeaders("127.0.0.1", 8787); + assert.equal(loopbackOnly.has("127.0.0.1:8787"), true); + assert.equal(loopbackOnly.has("0.0.0.0:8787"), false); +}); + +function postMcpWithHost(port, body, { token, host } = {}) { + return new Promise((resolve, reject) => { + const req = http.request( + { + hostname: "127.0.0.1", + port, + path: "/mcp", + method: "POST", + headers: { + host, + "content-type": "application/json", + ...(token ? { authorization: `Bearer ${token}` } : {}) + } + }, + (res) => { + res.resume(); + res.on("end", () => resolve({ status: res.statusCode })); + } + ); + req.on("error", reject); + req.end(JSON.stringify(body)); + }); +} + +test("http: HOST=0.0.0.0 accepts loopback Host without MCP_ALLOWED_HOSTS (DEV-22 F6)", async () => { + const token = randomBytes(32).toString("hex"); + const port = 21000 + Math.floor(Math.random() * 1000); + const child = spawn(process.execPath, ["server.mjs", "--http"], { + cwd: ROOT, + env: { ...process.env, MCP_AUTH_TOKEN: token, PORT: String(port), HOST: "0.0.0.0" }, + stdio: ["ignore", "ignore", "pipe"] + }); + await new Promise((resolve) => child.stderr.once("data", resolve)); + try { + const ping = { jsonrpc: "2.0", id: 1, method: "ping" }; + assert.equal( + (await postMcpWithHost(port, ping, { token, host: `localhost:${port}` })).status, + 200 + ); + assert.equal( + (await postMcpWithHost(port, ping, { token, host: `127.0.0.1:${port}` })).status, + 200 + ); + assert.equal( + (await postMcpWithHost(port, ping, { token, host: "evil.example" })).status, + 403 + ); + } finally { + child.kill(); + } +}); + +test("resolveInputError falls back when the engine omits InputError (DEV-22 N1)", () => { + const Fallback = resolveInputError({}); + const err = new Fallback("missing url"); + assert.equal(err.message, "missing url"); + assert.ok(err instanceof Error); + assert.equal(resolveInputError({ InputError: EngineInputError }), EngineInputError); +}); + +test("legacy ENGINE_DIR without InputError still validates (DEV-22 N1)", () => { + const fixture = path.join(ROOT, "tests/fixtures/legacy-engine"); + const serverHref = pathToFileURL(path.join(ROOT, "server.mjs")).href; + const child = spawnSync(process.execPath, ["--input-type=module", "-e", ` + const { handle } = await import(${JSON.stringify(serverHref)}); + const res = handle({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "clean_url", arguments: {} } + }); + const text = res.result?.content?.[0]?.text ?? ""; + if (res.result?.isError !== true) { console.error(JSON.stringify(res)); process.exit(1); } + if (!text.includes("Missing required argument")) { console.error(text); process.exit(1); } + `], { + cwd: ROOT, + env: { ...process.env, ENGINE_DIR: fixture }, + encoding: "utf8" + }); + assert.equal(child.status, 0, child.stderr || child.stdout); +}); + +test("http-smoke.sh uses mktemp and cleans up (DEV-22 F8)", () => { + const sh = readFileSync(path.join(ROOT, "scripts/http-smoke.sh"), "utf8"); + assert.match(sh, /mktemp -d/); + assert.match(sh, /trap\s+\w+\s+EXIT/); + assert.doesNotMatch(sh, /\/tmp\/ucmcp/); +}); diff --git a/mcp/tests/fixtures/legacy-engine/cleaner.js b/mcp/tests/fixtures/legacy-engine/cleaner.js new file mode 100644 index 0000000..497c902 --- /dev/null +++ b/mcp/tests/fixtures/legacy-engine/cleaner.js @@ -0,0 +1,30 @@ +export function cleanUrl() { + throw new Error("legacy engine cleanUrl should not run in this fixture"); +} +export function cleanBatch() { + return []; +} +export function cleanedUrlsFromBatch() { + return []; +} +export function inspectUrl() { + return {}; +} +export function trackingFingerprint() { + return {}; +} +export function fingerprintRemovedKeptDetail() { + return null; +} +export function isOpaqueShortener() { + return false; +} +export function categorizeParameter() { + return "unknown"; +} +export const TRACKING_PARAMETERS = new Set(); +export const TRACKING_PARAMETER_PREFIXES = []; +export const HOST_TRACKING_PARAMETERS = new Map(); +export const AGGRESSIVE_PARAMETERS = new Set(); +export const OPAQUE_SHORTENER_HOSTS = new Set(); +export const MAX_UNWRAP_DEPTH = 5; diff --git a/mcp/tests/fixtures/legacy-engine/explanations.js b/mcp/tests/fixtures/legacy-engine/explanations.js new file mode 100644 index 0000000..7ea99af --- /dev/null +++ b/mcp/tests/fixtures/legacy-engine/explanations.js @@ -0,0 +1,7 @@ +export function explainParameter() { + return ""; +} +export function getTrackerProfile() { + return null; +} +export const TRACKER_PROFILES = {}; diff --git a/mcp/tests/origin-http.test.mjs b/mcp/tests/origin-http.test.mjs index 0b5f588..09980a4 100644 --- a/mcp/tests/origin-http.test.mjs +++ b/mcp/tests/origin-http.test.mjs @@ -105,6 +105,47 @@ test("http: /healthz ignores Origin checks", async () => { await withHttpServer(async ({ base }) => { const res = await fetch(`${base}/healthz`, { headers: { Origin: "http://evil.example" } }); assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.ok, true); + assert.equal(body.engineSha, undefined); + }); +}); + +function getHealthzWithHost(port, host) { + return new Promise((resolve, reject) => { + const req = http.request( + { + hostname: "127.0.0.1", + port, + path: "/healthz", + method: "GET", + headers: { host } + }, + (res) => { + const bufs = []; + res.on("data", (c) => bufs.push(c)); + res.on("end", () => resolve({ + status: res.statusCode, + body: Buffer.concat(bufs).toString("utf8") + })); + } + ); + req.on("error", reject); + req.end(); + }); +} + +test("http: /healthz applies Host check and omits engineSha (DEV-22 F7)", async () => { + await withHttpServer(async ({ port }) => { + const denied = await getHealthzWithHost(port, "evil.example"); + assert.equal(denied.status, 403); + assert.doesNotMatch(denied.body, /engineSha/); + + const allowed = await getHealthzWithHost(port, `127.0.0.1:${port}`); + assert.equal(allowed.status, 200); + const body = JSON.parse(allowed.body); + assert.equal(body.ok, true); + assert.equal(body.engineSha, undefined); }); }); diff --git a/middleware.js b/middleware.js new file mode 100644 index 0000000..c1a440a --- /dev/null +++ b/middleware.js @@ -0,0 +1,23 @@ +export const config = { + matcher: ["/", "/index.html"] +}; + +export function isShareTargetPost(method, pathname) { + if (method !== "POST") return false; + return pathname === "/" || pathname === "/index.html" || pathname === ""; +} + +// First-launch share POSTs must not be parsed here: reading the body would +// put the shared link on the server. Drop it and 303 to `/` instead. +export function shareTargetFallbackResponse() { + return new Response(null, { + status: 303, + headers: { Location: "/" } + }); +} + +export default function middleware(request) { + const pathname = new URL(request.url).pathname; + if (!isShareTargetPost(request.method, pathname)) return; + return shareTargetFallbackResponse(); +} diff --git a/package.json b/package.json index 5a7396b..d838063 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "build": "node scripts/build.mjs", "pretest": "npm run build", "test": "node --test tests/*.test.js", - "test:playwright": "npm run build && node tests/app-boot.playwright.mjs && node tests/design-audit.playwright.mjs && node tests/dark-mode.playwright.mjs && node tests/audit-pass-2.playwright.mjs && node tests/theo-followups.playwright.mjs && node tests/original-url-highlight.playwright.mjs" + "test:playwright": "npm run build && node tests/app-boot.playwright.mjs && node tests/design-audit.playwright.mjs && node tests/dark-mode.playwright.mjs && node tests/audit-pass-2.playwright.mjs && node tests/theo-followups.playwright.mjs && node tests/original-url-highlight.playwright.mjs && node tests/share-target.playwright.mjs" }, "devDependencies": { "playwright": "^1.55.0" diff --git a/scripts/build.mjs b/scripts/build.mjs index fdb0893..cbdd085 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -3,10 +3,15 @@ import { dirname, extname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; const WEB_EXTENSIONS = new Set([".js", ".html", ".css", ".webmanifest", ".png", ".ico"]); +const SKIP_WEB_FILES = new Set(["middleware.js"]); export function listWebRootFiles(root) { return readdirSync(root, { withFileTypes: true }) - .filter((entry) => entry.isFile() && WEB_EXTENSIONS.has(extname(entry.name))) + .filter((entry) => ( + entry.isFile() + && WEB_EXTENSIONS.has(extname(entry.name)) + && !SKIP_WEB_FILES.has(entry.name) + )) .map((entry) => entry.name) .sort(); } diff --git a/sw.js b/sw.js index dbb12eb..f2deed0 100644 --- a/sw.js +++ b/sw.js @@ -5,3 +5,42 @@ self.addEventListener("install", () => { self.addEventListener("activate", (event) => { event.waitUntil(self.clients.claim()); }); + +function isShareTargetPost(request) { + if (request.method !== "POST") return false; + let path; + try { + path = new URL(request.url).pathname; + } catch { + return false; + } + return path === "/" || path === "/index.html"; +} + +function shareTargetHash(formData) { + const params = new URLSearchParams(); + for (const name of ["url", "text", "title"]) { + const value = formData.get(name); + if (value == null) continue; + const text = String(value); + if (!text) continue; + params.set(name, text); + } + return params.toString(); +} + +async function shareTargetRedirect(request) { + const origin = new URL(request.url).origin; + let hash = ""; + try { + hash = shareTargetHash(await request.formData()); + } catch { + hash = ""; + } + return Response.redirect(hash ? `${origin}/#${hash}` : `${origin}/`, 303); +} + +self.addEventListener("fetch", (event) => { + if (!isShareTargetPost(event.request)) return; + event.respondWith(shareTargetRedirect(event.request)); +}); diff --git a/tests/batch.test.js b/tests/batch.test.js index 10a9eed..f15a5ed 100644 --- a/tests/batch.test.js +++ b/tests/batch.test.js @@ -46,6 +46,16 @@ test("skips blank lines and records original line numbers", () => { assert.equal(results[1].line, 5); }); +test("cleanBatch hides non-InputError messages (DEV-22 F3)", () => { + const results = cleanBatch("https://example.com/", {}, () => { + throw new TypeError("internal detail"); + }); + assert.equal(results.length, 1); + assert.equal(results[0].ok, false); + assert.equal(results[0].error, "Internal error while cleaning this URL."); + assert.doesNotMatch(results[0].error, /internal detail/); +}); + test("cleanBatch does not fetch or follow opaque shorteners", () => { const results = cleanBatch("https://bit.ly/abc?utm_source=x"); assert.equal(results[0].ok, true); diff --git a/tests/ci-pin.test.js b/tests/ci-pin.test.js new file mode 100644 index 0000000..d599127 --- /dev/null +++ b/tests/ci-pin.test.js @@ -0,0 +1,40 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const USES = /^\s*-?\s*uses:\s*(\S+)/gm; + +test("CI pin scanner matches uses with or without a list dash (DEV-22 F5)", () => { + const sample = [ + "uses: actions/checkout@0123456789abcdef0123456789abcdef01234567", + " - uses: actions/setup-node@89abcdef0123456789abcdef0123456789abcdef", + " uses: actions/cache@not-a-sha" + ].join("\n"); + const uses = [...sample.matchAll(USES)].map((match) => match[1]); + assert.deepEqual(uses, [ + "actions/checkout@0123456789abcdef0123456789abcdef01234567", + "actions/setup-node@89abcdef0123456789abcdef0123456789abcdef", + "actions/cache@not-a-sha" + ]); +}); + +test("CI actions are pinned to full commit SHAs (DEV-22 F5)", () => { + const dir = join(root, ".github/workflows"); + const files = readdirSync(dir).filter((name) => name.endsWith(".yml") || name.endsWith(".yaml")); + assert.ok(files.length >= 1, "expected at least one workflow file"); + const uses = []; + for (const name of files) { + const yml = readFileSync(join(dir, name), "utf8"); + uses.push(...[...yml.matchAll(USES)].map((match) => match[1])); + } + assert.ok(uses.length >= 3, "expected checkout, setup-node, and cache"); + for (const spec of uses) { + const at = spec.lastIndexOf("@"); + assert.ok(at > 0, spec); + const pin = spec.slice(at + 1); + assert.match(pin, /^[0-9a-f]{40}$/i, spec); + } +}); diff --git a/tests/dist-sync.test.js b/tests/dist-sync.test.js index c8797c5..7c49868 100644 --- a/tests/dist-sync.test.js +++ b/tests/dist-sync.test.js @@ -3,10 +3,11 @@ import assert from "node:assert/strict"; import { readdirSync, readFileSync, existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { buildDist, listWebRootFiles } from "../scripts/build.mjs"; +import { listWebRootFiles } from "../scripts/build.mjs"; const root = join(dirname(fileURLToPath(import.meta.url)), ".."); -buildDist(root); +// pretest already ran `npm run build`. Rebuilding here deletes dist/ while +// other files import from it and flakes `npm test` under parallel workers. const dist = join(root, "dist"); const rootWebFiles = listWebRootFiles(root); diff --git a/tests/handoff.test.js b/tests/handoff.test.js index bbea7c8..922c438 100644 --- a/tests/handoff.test.js +++ b/tests/handoff.test.js @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { canReadClipboard, extractHttpUrl, + hasHandoffFields, parseHandoffParams, parseHandoffUrl } from "../dist/handoff.js"; @@ -27,6 +28,54 @@ test("share-target and query handoff read url, then text, then title", () => { assert.equal(parseHandoffParams("text=no%20link%20here"), ""); }); +test("share-target hash falls back from an invalid url field to text, then title", () => { + const app = "https://andromeda-url-cleaner.vercel.app/"; + const hash = (fields) => { + const params = new URLSearchParams(); + for (const [name, value] of Object.entries(fields)) params.set(name, value); + return `${app}#${params}`; + }; + + assert.equal( + parseHandoffUrl(hash({ + url: "not-a-url", + text: "Check this https://from-text.example/a?fbclid=1 please" + })), + "https://from-text.example/a?fbclid=1" + ); + assert.equal( + parseHandoffUrl(hash({ + url: "javascript:alert(1)", + text: "no link here", + title: "https://from-title.example/ok" + })), + "https://from-title.example/ok" + ); +}); + +test("failed share-target parse still flags handoff fields so the address bar can be cleared", () => { + const app = "https://andromeda-url-cleaner.vercel.app/"; + const leftover = `${app}#url=not-a-url&text=shared%20secret%20words`; + assert.equal(parseHandoffUrl(leftover), ""); + assert.equal(hasHandoffFields(leftover), true); + assert.equal(hasHandoffFields(`${app}?title=just%20words`), true); + assert.equal(hasHandoffFields(`${app}#unrelated`), false); + assert.equal(hasHandoffFields(app), false); +}); + +test("valid url field wins over an embedded &url= in text", () => { + const app = "https://andromeda-url-cleaner.vercel.app/"; + const params = new URLSearchParams({ + url: "https://good.example/page", + text: "notes &url=https://evil.example/phish" + }); + assert.equal(parseHandoffUrl(`${app}#${params}`), "https://good.example/page"); + assert.equal( + parseHandoffParams(params), + "https://good.example/page" + ); +}); + test("fragment handoff is read and preferred over the query string", () => { const encoded = encodeURIComponent("https://example.com/page?utm_source=x&id=1"); const app = "https://andromeda-url-cleaner.vercel.app/"; @@ -42,7 +91,7 @@ test("fragment handoff is read and preferred over the query string", () => { ); }); -test("query handoff still works for the share target and legacy ?url= links", () => { +test("query handoff still works for legacy ?url= links", () => { const app = "https://andromeda-url-cleaner.vercel.app/"; assert.equal(parseHandoffUrl(`${app}?url=${encodeURIComponent("https://example.com/a")}`), "https://example.com/a"); diff --git a/tests/playwright-static-server.mjs b/tests/playwright-static-server.mjs index 32b3909..e06887a 100644 --- a/tests/playwright-static-server.mjs +++ b/tests/playwright-static-server.mjs @@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { buildDist } from "../scripts/build.mjs"; +import { isShareTargetPost } from "../middleware.js"; const repoRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); @@ -20,12 +21,20 @@ export function distSiteRoot() { return join(repoRoot, "dist"); } -export function startDistServer() { +export function startDistServer({ onRequest } = {}) { const siteRoot = distSiteRoot(); return new Promise((resolve) => { const server = createServer((request, response) => { - const path = request.url === "/" ? "/index.html" : request.url.split("?")[0]; + onRequest?.(request); + const pathname = (request.url || "/").split("?")[0]; + if (isShareTargetPost(request.method, pathname)) { + request.resume(); + response.writeHead(303, { Location: "/" }); + response.end(); + return; + } + const path = request.url === "/" ? "/index.html" : pathname; const filePath = join(siteRoot, decodeURIComponent(path.slice(1))); if (!existsSync(filePath)) { response.writeHead(404); diff --git a/tests/pwa.test.js b/tests/pwa.test.js index 3e38cb8..396021e 100644 --- a/tests/pwa.test.js +++ b/tests/pwa.test.js @@ -29,11 +29,12 @@ test("root static files match the dist copies used by Vercel", () => { } }); -test("web app manifest uses local UC icons and a GET share_target", () => { +test("web app manifest uses local UC icons and a POST share_target", () => { const manifest = JSON.parse(readFileSync(join(root, "manifest.webmanifest"), "utf8")); assert.equal(manifest.display, "standalone"); assert.equal(manifest.start_url, "./"); - assert.equal(manifest.share_target.method, "GET"); + assert.equal(manifest.share_target.method, "POST"); + assert.equal(manifest.share_target.enctype, "application/x-www-form-urlencoded"); assert.equal(manifest.share_target.action, "./"); assert.equal(manifest.share_target.params.url, "url"); assert.deepEqual( @@ -63,10 +64,23 @@ test("index.html links the manifest and existing icons", () => { assert.match(app, /serviceWorker\.register\("\.\/sw\.js"\)/); assert.match(app, /canReadClipboard/); assert.match(app, /parseHandoffUrl/); + assert.match(app, /hasHandoffFields/); }); -test("service worker does not cache or fetch URLs", () => { +test("Vercel middleware 303s share POST when the service worker is not active", () => { + const source = readFileSync(join(root, "middleware.js"), "utf8"); + assert.match(source, /status:\s*303/); + assert.match(source, /Location:\s*["']\//); + assert.doesNotMatch(source, /formData|request\.text|request\.json/); +}); + +test("service worker intercepts share POST locally and does not cache or fetch URLs", () => { const sw = readFileSync(join(root, "sw.js"), "utf8"); + assert.match(sw, /addEventListener\(\s*["']fetch["']/); + assert.match(sw, /#\$\{hash\}|#url=/); + assert.match(sw, /formData/); + assert.match(sw, /\["url", "text", "title"\]/); + assert.doesNotMatch(sw, /formData\.get\(["']url["']\)\s*\|\|/); assert.doesNotMatch(sw, /fetch\s*\(/); assert.doesNotMatch(sw, /caches/); assert.match(sw, /skipWaiting/); diff --git a/tests/share-target-fallback.test.js b/tests/share-target-fallback.test.js new file mode 100644 index 0000000..426df55 --- /dev/null +++ b/tests/share-target-fallback.test.js @@ -0,0 +1,80 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import middleware, { isShareTargetPost, shareTargetFallbackResponse } from "../middleware.js"; +import { listWebRootFiles } from "../scripts/build.mjs"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); + +function wrapBodyReaders(request) { + let read = false; + for (const name of ["text", "json", "formData", "arrayBuffer", "blob"]) { + const original = request[name].bind(request); + request[name] = (...args) => { + read = true; + return original(...args); + }; + } + return () => read; +} + +test("share-target fallback 303s POST / without reading the body (DEV-22 F4)", async () => { + const request = new Request("http://127.0.0.1/", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: "url=https://secret.example/reset?token=abc" + }); + const bodyWasRead = wrapBodyReaders(request); + const response = await middleware(request); + assert.equal(response.status, 303); + assert.equal(response.headers.get("Location"), "/"); + assert.equal(bodyWasRead(), false); + assert.equal(isShareTargetPost("POST", "/index.html"), true); + assert.equal(isShareTargetPost("GET", "/"), false); + assert.equal(shareTargetFallbackResponse().status, 303); +}); + +test("share-target fallback lets GET / through (DEV-22 F4)", async () => { + const response = await middleware(new Request("http://127.0.0.1/", { method: "GET" })); + assert.equal(response, undefined); +}); + +test("local static server 303s share POST without serving the body (DEV-22 F4)", async () => { + const server = http.createServer((request, response) => { + const pathname = (request.url || "/").split("?")[0]; + if (isShareTargetPost(request.method, pathname)) { + request.resume(); + response.writeHead(303, { Location: "/" }); + response.end(); + return; + } + response.writeHead(200); + response.end("should-not-serve-share-post"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = server.address().port; + try { + const res = await fetch(`http://127.0.0.1:${port}/`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: "url=https://secret.example/reset?token=abc", + redirect: "manual" + }); + assert.equal(res.status, 303); + assert.equal(res.headers.get("location"), "/"); + const body = await res.text(); + assert.doesNotMatch(body, /should-not-serve-share-post|secret\.example/); + } finally { + server.close(); + } +}); + +test("middleware.js is not copied into dist (DEV-22 F4)", () => { + assert.equal(existsSync(join(root, "middleware.js")), true); + assert.equal(listWebRootFiles(root).includes("middleware.js"), false); + const source = readFileSync(join(root, "middleware.js"), "utf8"); + assert.doesNotMatch(source, /\.text\s*\(|\.json\s*\(|\.formData\s*\(/); +}); diff --git a/tests/share-target.playwright.mjs b/tests/share-target.playwright.mjs new file mode 100644 index 0000000..392f59e --- /dev/null +++ b/tests/share-target.playwright.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { startDistServer } from "./playwright-static-server.mjs"; + +const SHARED = "https://secret.example/reset?token=super-secret-handoff&utm_source=share"; + +async function waitForServiceWorker(page) { + await page.evaluate(async () => { + if (!("serviceWorker" in navigator)) { + throw new Error("serviceWorker unavailable"); + } + if (!(await navigator.serviceWorker.getRegistration())) { + await navigator.serviceWorker.register("./sw.js"); + } + await navigator.serviceWorker.ready; + if (!navigator.serviceWorker.controller) { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("service worker did not claim the page")), 8000); + navigator.serviceWorker.addEventListener("controllerchange", () => { + clearTimeout(timer); + resolve(); + }, { once: true }); + }); + } + }); +} + +const serverPosts = []; +const server = await startDistServer({ + onRequest(request) { + if (request.method === "POST") { + serverPosts.push(request.url); + } + } +}); +const port = server.address().port; +const baseUrl = `http://127.0.0.1:${port}/`; +const browser = await chromium.launch(); + +try { + const context = await browser.newContext(); + const setupPage = await context.newPage(); + await setupPage.goto(baseUrl, { waitUntil: "networkidle" }); + await waitForServiceWorker(setupPage); + + const sharePage = await context.newPage(); + const redirect = sharePage.waitForResponse((response) => ( + response.request().method() === "POST" && [301, 302, 303, 307, 308].includes(response.status()) + )); + + await sharePage.setContent(` +
+`); + + const response = await redirect; + const location = response.headers().location || ""; + assert.match(location, /#/, `share redirect Location was ${location || "(empty)"}`); + const redirected = new URL(location, baseUrl); + assert.equal(new URLSearchParams(redirected.hash.slice(1)).get("url"), SHARED); + + await sharePage.waitForFunction((expected) => { + const input = document.querySelector("#url-input"); + return Boolean(input && input.value.includes(expected)); + }, "secret.example"); + + const inputValue = await sharePage.locator("#url-input").inputValue(); + assert.equal(inputValue, SHARED); + + const fallbackPage = await context.newPage(); + const fallbackRedirect = fallbackPage.waitForResponse((response) => ( + response.request().method() === "POST" && [301, 302, 303, 307, 308].includes(response.status()) + )); + await fallbackPage.setContent(` + +`); + const fallbackResponse = await fallbackRedirect; + const fallbackLocation = new URL(fallbackResponse.headers().location || "", baseUrl); + const fallbackParams = new URLSearchParams(fallbackLocation.hash.slice(1)); + assert.equal(fallbackParams.get("url"), "not-a-url"); + assert.match(fallbackParams.get("text") || "", /from-text\.example/); + await fallbackPage.waitForFunction((expected) => { + const input = document.querySelector("#url-input"); + return Boolean(input && input.value.includes(expected)); + }, "from-text.example"); + + assert.deepEqual(serverPosts, [], "share POST must be answered by the service worker, not the static server"); + + const leftoverPage = await context.newPage(); + await leftoverPage.goto(`${baseUrl}#url=not-a-url&text=shared%20secret%20words`, { waitUntil: "networkidle" }); + await leftoverPage.waitForFunction(() => !window.location.hash && !window.location.search); + assert.doesNotMatch(leftoverPage.url(), /shared|secret|url=|text=/); + + console.log("share-target playwright checks passed (POST intercepted, hash handoff, no server POST)"); +} finally { + await browser.close(); + server.close(); +} diff --git a/tests/url-cleaner.test.js b/tests/url-cleaner.test.js index eea9dff..a55d23d 100644 --- a/tests/url-cleaner.test.js +++ b/tests/url-cleaner.test.js @@ -4,6 +4,7 @@ import { cleanBatch, cleanUrl, detectWeirdness, + InputError, inspectUrl, isOpaqueShortener, MAX_UNWRAP_DEPTH, @@ -50,6 +51,8 @@ test("preserves a hash fragment", () => { test("rejects invalid input", () => { assert.throws(() => cleanUrl("not a URL"), /valid URL/); + assert.throws(() => cleanUrl("not a URL"), InputError); + assert.throws(() => cleanUrl(""), InputError); }); test("matches tracker names case-insensitively", () => {