Skip to content

Latest commit

 

History

History
69 lines (53 loc) · 24.8 KB

security.md

File metadata and controls

69 lines (53 loc) · 24.8 KB

Security headers and CSP

The app reads font files that users choose and builds CSS and previews from them, so the page runs under a strict Content Security Policy and a baseline set of response headers.

How it is delivered

  • public/_headers is served by Cloudflare Workers static assets (production and previews) and carries the headers that cannot live in a <meta> tag.
  • Astro CSP (security.csp in astro.config.mjs) emits a <meta http-equiv="content-security-policy"> per page with SHA-256 hashes for every inline script and style it generates, plus our extra directives. A browser enforces the header policy and the meta policy together, so the header deliberately omits script-src and style-src.

Policy

Directive or header Value Why
default-src 'self' Nothing is loaded from other origins.
script-src, style-src 'self' plus Astro's hashes No 'unsafe-inline' and no 'unsafe-eval'.
script-src on the generator page (/:locale/) also 'wasm-unsafe-eval' Added per page with Astro.csp.insertScriptResource in src/app/pages/[locale]/index.astro, only where the optimizer runs. It lets the bundled, same-origin HarfBuzz module (harfbuzzjs, shapes the width ratios) compile; it does not allow eval or new Function. It lives in the meta policy because a header cannot widen it (both policies are enforced), so every other page keeps the strict policy.
worker-src 'self' The font parser worker is a same-origin bundled module; no blob workers.
frame-src 'self' Same-origin frames only (planned CLS simulator).
font-src 'self' blob: data: Uploaded fonts are loaded from bytes in memory.
connect-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com https://cdn.jsdelivr.net, plus https: on the generator page (/:locale/) only The font pickers (jsDelivr hosts arbitrary npm and GitHub packages and CSP cannot restrict a path, so the code checks the host and the /fontsource/fonts/ path and pins the package version from the bundled catalog): Google Fonts (stylesheet and font file downloads) and Fontsource (font files from jsDelivr); fonts are then loaded from memory. The generator page adds https: with Astro.csp.insertDirective in src/app/pages/[locale]/index.astro, because the direct import (see Site import) reads a website the user names, which an origin list cannot cover. Plain http:, ws: and wss: stay blocked, and every other page keeps the list.
img-src 'self' data: blob:
object-src, base-uri 'none'
form-action 'self'
frame-ancestors 'self' (header only) Not valid in a meta tag. Other sites cannot frame the app; same-origin frames (the planned CLS simulator) still work.
X-Content-Type-Options nosniff
Referrer-Policy strict-origin-when-cross-origin
Permissions-Policy camera=(), microphone=(), geolocation=(), payment=() Only features supported by all major browsers, to avoid console noise.
Cross-Origin-Opener-Policy same-origin, detached on /:locale/import/ The import page must keep window.opener to answer the site that opened it (see Site import).
Cross-Origin-Resource-Policy same-origin
Cache-Control on /_astro/* public, max-age=31536000, immutable Build output is content-hashed.

script-src and style-src exist only in the meta policy, and a meta policy applies only to content parsed after it. Astro places it early in <head>, and the app has no HTML injection sink, so the rule against dangerouslySetInnerHTML and similar sinks is load-bearing. Possible later hardening: require-trusted-types-for 'script'.

Site import

The bookmarklet and the browser extension (extension/) send the fonts and sizes of any website to the generator, so the data is untrusted and the sending page is hostile by assumption.

  • Isolated receiver. Only /<locale>/import/ (the import-receiver module, no UI) drops Cross-Origin-Opener-Policy so that the opener survives. They run no app code: a few lines read a token from the URL fragment, wait for one message, sanitize it, store it in IndexedDB and redirect to the generator (which has the strict policy).
  • Handshake. The page announces itself to window.opener (fontstay:ready, no secrets, so its target origin is *) unless the extension opened the page (&via=ext in the fragment). The sender replies once with fontstay:import, the random token from the URL (96+ bits) and the payload, addressed to the exact origin of the generator. The receiver accepts a message only from window.opener (unless the fragment says the extension opened the page) or from its own window for the extension relay and only with the matching token, once, within 60 seconds. The origin shown to the user is event.origin, never the payload's claim; the extension channel is the only one that supplies its own claim, because its content script runs in the page itself.
  • Sanitizing (src/modules/import-receiver/lib/payload.ts). The payload is rebuilt field by field, never copied: unknown keys and prototype tricks are dropped, numbers are range checked, text loses control, bidi and format characters and is capped by code points, file names become a safe base name, URLs must be https without credentials, counts and sizes are bounded (8 files, 10 MB each, 30 MB in total, 64 faces, 256 @font-face rules for the split-font audit, 60 element boxes). An element box (blocks: tag from a fixed list of seven, text of at most 400 code points, font size, box width, indent, margins, padding, line height) is rebuilt number by number with range checks; the text only ever reaches textContent of an element in the sandboxed measuring frame and the width model, never HTML. The collector reads the boxes of visible headings, paragraphs, list items, quotes and buttons of the page, so a few hundred characters of each are sent to the generator window only, like the fonts; they wait in the handoff IndexedDB database until the user accepts the import (at most 10 minutes, and Forget deletes it), then live in memory until the page is closed or reloaded; they are not put into share links, exports or the clipboard. Elements inside nav, a top-level header, footer, aside or aria-hidden containers are skipped. A direct URL import has no DOM and carries no boxes. Each rule's unicode-range must match [Uu+0-9a-fA-F?,\s-] and be at most 1500 characters; the audit (auditSplitFaces) only parses it and caps its own work. Font bytes are not trusted either: they go through the normal font parser worker after the user confirms.
  • Confirmation. Nothing is used until the user accepts the summary ("Import from ?") in the generator; data older than 10 minutes is ignored.
  • Clipboard fallback. The pasted JSON carries metadata only (no files) and its origin is shown as unverified. It does include the page title, which the alert tells the user, because clipboard managers can read it. The boxes of the page elements (blocks, with up to 400 characters of text each) are left out of the clipboard JSON, so no page text is copied.
  • Links. A font that could not be fetched is listed with a download link that shows the host the sender chose; links open with noopener noreferrer.
  • Direct import (site-import/lib/direct-fetch.ts). The user types an address and the browser fetches the page, its stylesheets (up to 6, @import followed 2 levels, 500 kB each) and up to 8 font files (10 MB each, 30 MB in total) with mode: 'cors', credentials: 'omit' and no referrer, so it works only when the site sends CORS headers, and nothing is sent to a server of ours. Only https: addresses without credentials or a port are accepted, and localhost, single-label, IP-literal and .local/.internal-style hosts are refused before every request, including the stylesheet and font URLs the page names, and again for the final URL after redirects (response.url). A redirect to a private host is already requested by then (a blind, credential-less GET; the response is dropped, and CORS stops any page from reading it), and a public name that resolves to a private address is not detected; browsers' private-network protections cover that part. The HTML and CSS are scanned as text (scan.ts: no DOMParser, so no resource loads, with bounded indexOf scans and caps instead of backtracking regexes), URLs resolve to https: only, and the result goes through the same sanitizeImport and confirmation as a bookmarklet payload. Font bytes still reach the parser worker only after the user accepts. This is why the generator page's connect-src allows https:.
  • Limits. A page with a strict CSP can block a bookmarklet (Firefox does) or the font downloads (connect-src); the extension and the clipboard path cover that. A hostile page can still open the import page and push data, which is why the confirmation exists.

Rules for code

  • No inline <style> elements or style attributes in HTML at build time; dynamic CSS goes through CSSStyleSheet and document.adoptedStyleSheets (see Preview.tsx), and per-element styles through the CSSOM.
  • No eval, no inline event handlers, no dangerouslySetInnerHTML.
  • New origins, blob: or data: sources, or any 'unsafe-*' keyword must be justified in the PR and listed in the table above.
  • Same-origin iframes (CLS simulator) are allowed by frame-ancestors 'self'; framing by other origins is not.
  • A share link may list fonts to download (sources). Each entry is validated by parseOrigin and must match a family, style and subset of the bundled catalog before any URL is built, and nothing is fetched until the recipient confirms, because the download shows their IP address to Google or jsDelivr.
  • Features that load external resources add their origin to the matching directive in the PR that introduces them (the Google Fonts picker adds https://fonts.googleapis.com and https://fonts.gstatic.com, the Fontsource picker https://cdn.jsdelivr.net, to connect-src).
  • The service worker (/sw.js, generated after the build by scripts/pwa/build-pwa.mjs) is same-origin, covered by worker-src 'self', and served with Cache-Control: no-cache; it precaches only same-origin files and never handles cross-origin requests.
  • The saved appearance settings are applied by /appearance-init.js, a same-origin parser-blocking script in the head (covered by script-src 'self', no inline code), served with Cache-Control: no-cache; it reads localStorage through an allowlist, so unknown values are ignored.

Testing

tests/e2e/serve.mjs serves dist/ with public/_headers applied the way Cloudflare does, and every e2e test fails if the page reports a CSP violation (securitypolicyviolation). tests/e2e/security-headers.spec.ts checks the headers and the policy's shape.

Background image

The preview settings accept an image that sits behind the preview text. The file is untrusted input and never leaves the tab.

  • Allowlist by content. Only PNG, JPEG, WebP and GIF are accepted, decided by the file's magic bytes (src/modules/generator/lib/background-image.ts), not by its name or declared type. SVG is refused.
  • Bounds. At most 8 MiB, 8192 px on a side and 24 megapixels; the dimensions come from the header before the browser decodes anything. Only the first 256 KiB is read to sniff the header.
  • Re-typed object URL. The accepted bytes get a Blob typed with the sniffed type, shown through a blob: URL (covered by img-src) and revoked when the image is replaced or removed and when the panel unmounts. A decode failure revokes the URL and reports an error.
  • CSP. The URL and the position, fit and fade values reach the page as CSS custom properties set through the CSSOM; no inline <style> and no 'unsafe-*' source is added.