Skip to content
41 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { test } from "node:test";
3
4import { makeNonce, pagePolicy, withSiteHeaders } from "./page-headers.ts";
5
6test("a page runs only its own scripts and is never framed", () => {
7 const nonce = makeNonce();
8 assert.match(nonce, /^[A-Za-z0-9+/]{22}==$/);
9 assert.notEqual(nonce, makeNonce());
10 const policy = pagePolicy(nonce);
11 assert.ok(policy.includes(`script-src 'self' 'nonce-${nonce}'`));
12 assert.doesNotMatch(policy, /script-src[^;]*'unsafe-inline'/);
13 assert.match(policy, /frame-ancestors 'none'/);
14 assert.match(policy, /object-src 'none'/);
15 assert.match(policy, /base-uri 'self'/);
16 // Pictures in a README come from anywhere on HTTPS.
17 assert.match(policy, /img-src 'self' https: data: blob:;/);
18 // An installation serving its files over plain HTTP names that origin.
19 assert.match(pagePolicy(nonce, "http://files.local:8787"), /img-src 'self' https: data: blob: http:\/\/files\.local:8787;/);
20 assert.match(pagePolicy(nonce, "https://g1tusercontent.com"), /img-src 'self' https: data: blob:;/);
21});
22
23test("every answer gains nosniff and a referrer policy; pages are not framed", () => {
24 const page = withSiteHeaders(new Response("<p>hi</p>", { headers: { "content-type": "text/html" } }));
25 assert.equal(page.headers.get("x-content-type-options"), "nosniff");
26 assert.equal(page.headers.get("referrer-policy"), "strict-origin-when-cross-origin");
27 assert.equal(page.headers.get("x-frame-options"), "DENY");
28
29 const data = withSiteHeaders(new Response("{}", { headers: { "content-type": "application/json" } }));
30 assert.equal(data.headers.get("x-content-type-options"), "nosniff");
31 assert.equal(data.headers.get("x-frame-options"), null);
32
33 // A redirect's headers are fixed; the answer is copied, status and all.
34 const moved = withSiteHeaders(Response.redirect("https://docs.g1t.sh/", 301));
35 assert.equal(moved.status, 301);
36 assert.equal(moved.headers.get("location"), "https://docs.g1t.sh/");
37 assert.equal(moved.headers.get("referrer-policy"), "strict-origin-when-cross-origin");
38
39 const own = withSiteHeaders(new Response("", { headers: { "referrer-policy": "no-referrer" } }));
40 assert.equal(own.headers.get("referrer-policy"), "no-referrer");
41});