Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
224 lines (204 loc) · 7.78 KB
/
Copy pathworker.js
File metadata and controls
224 lines (204 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const HTML_MEDIA_TYPE = "text/html; charset=utf-8";
const MARKDOWN_MEDIA_TYPE = "text/markdown; charset=utf-8";
const RATIONALE_IMAGE_ORIGIN = "https://passo.uno";
// GoatCounter: `count.js` is served from one origin and reports hits to
// another, so the two are named separately below.
const ANALYTICS_SCRIPT_ORIGIN = "https://gc.zgo.at";
const ANALYTICS_COLLECTOR_ORIGIN = "https://passouno.goatcounter.com";
/**
* Fetch directives for the Content-Security-Policy.
*
* The stylesheet, both fonts, and the social card all ship with the assets, so
* every fetch directive stays at 'self' with one exception: the rationale page
* embeds two illustrations hosted on the source essay's blog, and `img-src`
* has to name that origin or the browser blocks them. Copying those two files
* into `static/` would let the directive go back to 'self' alone.
* `script-src` is the other compromise. The JSON-LD blocks in head.html
* are rebuilt per page from that page's permalink, title, and modification
* date, so their hashes differ at every URL and cannot be listed ahead of
* time. Dropping 'unsafe-inline' would stop search engines and agents from
* reading the structured data this site exists to publish. Per-request nonces
* through HTMLRewriter would close the gap; until then the other directives
* still cut off the injection routes that do not need inline script:
* rewriting <base>, loading a plugin, posting a form elsewhere, and framing.
*
* Page views go to GoatCounter, which needs three of its own openings:
* `script-src` for the counter itself, and `img-src` plus `connect-src` for
* the hit it sends back — `count.js` reports through an <img> and falls back
* to sendBeacon, and a blocked beacon fails silently.
*/
const CSP_DIRECTIVES = [
"default-src 'self'",
"base-uri 'self'",
"object-src 'none'",
"frame-ancestors 'none'",
"form-action 'none'",
`script-src 'self' 'unsafe-inline' ${ANALYTICS_SCRIPT_ORIGIN}`,
"style-src 'self'",
`img-src 'self' data: ${RATIONALE_IMAGE_ORIGIN} ${ANALYTICS_COLLECTOR_ORIGIN}`,
"font-src 'self'",
`connect-src 'self' ${ANALYTICS_COLLECTOR_ORIGIN}`,
];
const SECURITY_HEADERS = {
// Two same-origin routes serve bytes that Hugo's HTML renderer never
// sanitizes: the Markdown mirrors, which emit a page's raw source verbatim,
// and the SVG favicon and social card. Refusing to sniff stops a browser
// from ever deciding to read either one back as HTML.
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
// frame-ancestors covers this on current browsers; kept for the older ones.
"X-Frame-Options": "DENY",
"Cross-Origin-Opener-Policy": "same-origin",
"Permissions-Policy":
"accelerometer=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",
};
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Every response leaves through here — redirects, 404s from the asset
// binding, and Markdown mirrors included — so no route can miss the
// security headers by returning early.
return withSecurityHeaders(await route(request, env, url), url);
},
};
async function route(request, env, url) {
// Keep one crawlable English home and one protocol. `wrangler dev` serves
// plain HTTP on localhost, so exempt it or local runs redirect in a loop.
if (url.protocol !== "https:" && !isLocalHost(url.hostname)) {
url.protocol = "https:";
return Response.redirect(url.toString(), 301);
}
if (url.pathname === "/en" || url.pathname === "/en/") {
url.pathname = "/";
return Response.redirect(url.toString(), 301);
}
// An agent that asks for Markdown gets the mirror of the same page,
// at the same URL, rather than HTML it has to strip.
if (acceptsMarkdown(request)) {
const mirror = await fetchMarkdownMirror(request, env, url);
if (mirror) {
return mirror;
}
}
const response = await env.ASSETS.fetch(request);
if (!response.ok) {
return response;
}
return withAgentHeaders(response, url);
}
/**
* Applied to every response. Responses from the asset binding and from
* `Response.redirect` both carry immutable headers, so this rebuilds rather
* than mutating in place.
*/
function withSecurityHeaders(response, url) {
const local = isLocalHost(url.hostname);
const headers = new Headers(response.headers);
const directives = local
? CSP_DIRECTIVES
: [...CSP_DIRECTIVES, "upgrade-insecure-requests"];
headers.set("Content-Security-Policy", directives.join("; "));
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
headers.set(name, value);
}
// HSTS is scoped to a hostname, not a port: pinning it during `wrangler dev`
// would force HTTPS on every other service the developer runs on localhost.
if (!local) {
headers.set(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains",
);
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
function isLocalHost(hostname) {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
}
function acceptsMarkdown(request) {
return /\btext\/(x-)?markdown\b/i.test(request.headers.get("accept") || "");
}
/**
* The Markdown mirror of a pretty URL: Hugo writes it next to index.html.
* Only directory-style paths negotiate; asset paths are served as they are.
*/
function markdownMirrorPath(pathname) {
return pathname.endsWith("/") ? `${pathname}index.md` : null;
}
async function fetchMarkdownMirror(request, env, url) {
// Only reads negotiate. Forwarding the original request wholesale would
// hand the asset binding a method and body it has no use for.
if (request.method !== "GET" && request.method !== "HEAD") {
return null;
}
const mirrorPath = markdownMirrorPath(url.pathname);
if (!mirrorPath) {
return null;
}
const mirrorURL = new URL(url.toString());
mirrorURL.pathname = mirrorPath;
const mirror = await env.ASSETS.fetch(
new Request(mirrorURL.toString(), {
method: request.method,
headers: request.headers,
}),
);
if (!mirror.ok) {
return null;
}
const headers = new Headers(mirror.headers);
headers.set("Content-Type", MARKDOWN_MEDIA_TYPE);
headers.set("Link", `<${url.origin}${url.pathname}>; rel="canonical"`);
headers.set("Vary", "Accept");
return new Response(mirror.body, {
status: mirror.status,
statusText: mirror.statusText,
headers,
});
}
/**
* Declare the charset, type the Markdown mirrors, and point every
* non-HTML representation back at the page it mirrors.
*/
function withAgentHeaders(response, url) {
const headers = new Headers(response.headers);
const contentType = headers.get("content-type") || "";
if (contentType.startsWith("text/html")) {
headers.set("Content-Type", HTML_MEDIA_TYPE);
headers.set("Vary", "Accept");
} else if (url.pathname.endsWith(".md")) {
headers.set("Content-Type", MARKDOWN_MEDIA_TYPE);
}
const canonicalPath = canonicalHtmlPath(url.pathname);
if (canonicalPath) {
headers.set("Link", `<${url.origin}${canonicalPath}>; rel="canonical"`);
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
function canonicalHtmlPath(pathname) {
if (pathname.endsWith("/index.md")) {
return pathname.slice(0, -"index.md".length);
}
if (
pathname === "/llms.txt" ||
pathname === "/model.json" ||
pathname === "/sitemap.md" ||
pathname === "/AGENTS.md"
) {
return "/";
}
const localizedMirror = pathname.match(
/^\/[a-z]{2}(?:-[a-z]{2})?\/(?:llms\.txt|model\.json|sitemap\.md)$/i,
);
if (localizedMirror) {
return pathname.replace(/(?:llms\.txt|model\.json|sitemap\.md)$/, "");
}
return null;
}