Skip to content
59 linesCodeBlameRaw
1/**
2 * The headers every answer from the site carries, and the policy its pages
3 * run under. No Workers imports, so it can be tested under Node.
4 *
5 * - Nothing is sniffed: a download or a data request is only the type it says.
6 * - A link to another site sends the origin, never the path.
7 * - No other site may put g1t's pages in a frame.
8 * - A page runs only the scripts the site served it: its own files, and the
9 * inline scripts React and React Router write, each carrying the page's
10 * nonce. Styles may be inline (highlighting and layout set them); images
11 * may come from any HTTPS address (pictures in a README); requests may go
12 * to any HTTPS address (the status page's summary).
13 */
14
15/** A fresh nonce for one page: 128 random bits, base64. */
16export function makeNonce(): string {
17 const bytes = crypto.getRandomValues(new Uint8Array(16));
18 return btoa(String.fromCharCode(...bytes));
19}
20
21/**
22 * The Content-Security-Policy of a page rendered with `nonce`. `usercontent`
23 * is where repository files and avatars are served (lib/usercontent.ts),
24 * named for an installation that serves them over plain HTTP.
25 */
26export function pagePolicy(nonce: string, usercontent?: string): string {
27 const files = usercontent && /^http:/.test(usercontent) ? ` ${new URL(usercontent).origin}` : "";
28 return [
29 "default-src 'self'",
30 // Cloudflare's Web Analytics beacon, when the zone turns it on.
31 `script-src 'self' 'nonce-${nonce}' https://static.cloudflareinsights.com`,
32 "style-src 'self' 'unsafe-inline'",
33 `img-src 'self' https: data: blob:${files}`,
34 `media-src 'self' https:${files}`,
35 "font-src 'self' data:",
36 "connect-src 'self' https:",
37 "frame-src 'none'",
38 "object-src 'none'",
39 "base-uri 'self'",
40 "frame-ancestors 'none'",
41 ].join("; ");
42}
43
44/**
45 * The answer with the site's headers added. A header the answer already
46 * has is kept. An upgrade to a WebSocket is passed on as it is.
47 */
48export function withSiteHeaders(response: Response): Response {
49 if (response.status === 101 || (response as Response & { webSocket?: unknown }).webSocket) return response;
50 // A redirect's headers cannot be changed, so the answer is copied.
51 const answer = new Response(response.body, response);
52 const headers = answer.headers;
53 if (!headers.has("x-content-type-options")) headers.set("x-content-type-options", "nosniff");
54 if (!headers.has("referrer-policy")) headers.set("referrer-policy", "strict-origin-when-cross-origin");
55 if (/^text\/html\b/i.test(headers.get("content-type") ?? "") && !headers.has("x-frame-options")) {
56 headers.set("x-frame-options", "DENY");
57 }
58 return answer;
59}