Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/studio/public/_headers
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
# their own (packages/service-kit json()). The script hash is the theme script in index.html: after
# editing it, `node scripts/csp-hash.mjs` prints the new one (`pnpm build` fails until it matches).
# connect-src 'self' covers the phone link's websocket. style-src 'unsafe-inline': the components position with style attributes.
# img-src https://tile.openstreetmap.org: the map tiles (places/map.tsx, #559). Every outside origin the code loads from must be
# named here: `node scripts/csp-hash.mjs --check` (run by the build) fails otherwise.
/*
Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-ubsi6/JVImjCRRFnF8USuyWGW86uBuuRXa5NNT17beY='; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'
Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-ubsi6/JVImjCRRFnF8USuyWGW86uBuuRXa5NNT17beY='; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://tile.openstreetmap.org; connect-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=()
1 change: 1 addition & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pnpm test # unit and route tests (docs/testing.md):
pnpm build # scripts/build-check.sh, dry runs only, nothing is deployed:
# vite build in apps/studio and apps/admin
# scripts/csp-hash.mjs --check: each _headers CSP still allows its index.html inline script
# and every https:// origin its code loads from (#559)
# wrangler deploy --dry-run in apps/worker and apps/admin (tracked local wrangler.jsonc,
# after the Vite builds: both serve them as assets)
# expo export --platform android in apps/mobile: proves Metro can bundle
Expand Down
3 changes: 1 addition & 2 deletions docs/infrastructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ Everything runs on one Cloudflare account per instance; nothing else is needed.
| Durable Object `PreviewRoom` (SQLite-backed) | Binding `PREVIEW`, migration tag `v1` (applied by `wrangler deploy`). One room per user for the live layout preview; holds websockets, no data. |
| Cloudflare Access | The admin plane's sign-in. |
| Android signing key | Per deployment, made once with `scripts/keystore.sh` (into a folder outside the checkout); in the deployment's GitHub secrets and a backup, never in git or a checkout. The staging app (`org.openclapper.staging`) uses the same key. Builds need no other service; the only build-time setting is `EXPO_PUBLIC_API_URL` ([self-hosting](self-hosting.md#the-phone)) |
| Open-Meteo | Weather forecast, called from the Studio browser directly (free, no key); the only origin besides the tiles in the Studio's CSP `connect-src` |
| OpenStreetMap tiles | Maps in the Studio (Leaflet, `mapTiles.ts`) and the phone (Leaflet in a WebView, loaded from unpkg). Straight from `tile.openstreetmap.org` under its [usage policy](https://operations.osmfoundation.org/policies/tiles/): attribution and a valid Referer. The Studio's page policy is `same-origin`, so the tile layers send the origin themselves; the phone's map page takes the instance's origin as its base URL (issue #281) |
| OpenStreetMap tiles | Maps in the Studio (Leaflet, `places/map.tsx`; allowed in the Studio's CSP `img-src`, the only outside origin it loads from, #559) and the phone (Leaflet in a WebView, loaded from unpkg). Straight from `tile.openstreetmap.org` under its [usage policy](https://operations.osmfoundation.org/policies/tiles/): attribution and a valid Referer. The Studio's page policy is `same-origin`, so the tile layers send the origin themselves; the phone's map page takes the instance's origin as its base URL (issue #281) |

## Auth

Expand Down
2 changes: 1 addition & 1 deletion scripts/build-check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ trap 'rm -rf "$out"' EXIT
(cd apps/studio && npx vite build)
(cd apps/admin && npx vite build)
(cd apps/specimen && npx vite build)
node scripts/csp-hash.mjs --check # the CSP in each public/_headers still allows the inline script
node scripts/csp-hash.mjs --check # the CSP in each public/_headers still allows the inline script and every outside origin the code loads from (#559)
(cd apps/worker && npx wrangler deploy --dry-run --outdir "$out/worker")
(cd apps/admin && npx wrangler deploy --dry-run --outdir "$out/admin")
(cd apps/mobile && npx expo export --platform android --output-dir /tmp/openclapper-export)
34 changes: 29 additions & 5 deletions scripts/csp-hash.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,39 @@
//
// node scripts/csp-hash.mjs prints the hash of each app's inline scripts
// node scripts/csp-hash.mjs --check after `vite build`: fails when a built index.html has an inline
// script whose hash is not in the built _headers (pnpm build runs it)
// script whose hash is not in the built _headers (pnpm build runs it),
// or when the app's code loads from an origin the policy does not name
//
// The second check (#559): every "https://host" in an app's source (and the design system it uses) must be in its
// _headers, so a new outside source (map tiles, an API) cannot ship blocked. Links (href="https://…") and XML
// namespaces navigate or name, they load nothing, and are left out.
//
// The hash covers the script's text exactly as it stands between <script> and </script>.
import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { fileURLToPath, pathToFileURL } from "node:url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const check = process.argv.includes("--check");
const apps = [
{ name: "studio", html: "apps/studio/index.html", dist: "apps/studio/dist" },
{ name: "admin", html: "apps/admin/ui/index.html", dist: "apps/admin/dist" },
{ name: "studio", html: "apps/studio/index.html", dist: "apps/studio/dist", src: ["apps/studio/src", "packages/design/src"] },
{ name: "admin", html: "apps/admin/ui/index.html", dist: "apps/admin/dist", src: ["apps/admin/ui/src", "packages/design/src"] },
];

const inlineScripts = (html) =>
[...html.matchAll(/<script(\s[^>]*)?>([\s\S]*?)<\/script>/g)].filter((m) => !/\ssrc=/.test(m[1] ?? "")).map((m) => m[2]);
/** The origins a source tree loads from: "https://host" in its code, not in a link or an XML namespace. */
export function originsIn(text) {
return [...text.matchAll(/(href=|xmlns(?::\w+)?=)?["'`]https:\/\/([a-zA-Z0-9.-]+)/g)].filter((m) => !m[1]).map((m) => `https://${m[2]}`);
}
const filesIn = (dir) => (!existsSync(dir) ? [] : readdirSync(dir).flatMap((f) => { const x = join(dir, f); return statSync(x).isDirectory() ? filesIn(x) : /\.(ts|tsx)$/.test(f) && !/\.test\.tsx?$/.test(f) ? [x] : []; }));
const hash = (text) => `'sha256-${createHash("sha256").update(text, "utf8").digest("base64")}'`;

// Run as a script only; the tests import originsIn.
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) main();

function main() {
let failed = false;
for (const app of apps) {
const htmlPath = join(root, check ? join(app.dist, "index.html") : app.html);
Expand All @@ -36,5 +50,15 @@ for (const app of apps) {
failed = true;
}
}
const csp = headers.match(/Content-Security-Policy:(.*)/)?.[1] ?? "";
for (const file of app.src.flatMap((d) => filesIn(join(root, d)))) {
for (const origin of new Set(originsIn(readFileSync(file, "utf8")))) {
if (!csp.split(/[\s;]+/).includes(origin)) {
console.error(`csp-hash: ${app.name}: ${file.slice(root.length + 1)} loads from ${origin}, which its _headers Content-Security-Policy does not allow; add it to the directive that loads it (img-src, connect-src, …)`);
failed = true;
}
}
}
}
if (failed) process.exit(1);
}
10 changes: 10 additions & 0 deletions scripts/csp-hash.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// The CSP check's reading of outside origins (#559): what is loaded counts, links and XML namespaces do not.
import { test } from "node:test";
import assert from "node:assert/strict";
import { originsIn } from "./csp-hash.mjs";

test("origins the code loads from, not links or namespaces", () => {
const code = `L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: '<a href="https://www.openstreetmap.org/copyright">OSM</a>' });
fetch(\`https://api.example.com/v1\`); const svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink">';`;
assert.deepEqual(originsIn(code), ["https://tile.openstreetmap.org", "https://api.example.com"]);
});
Loading