Repository navigation
Expand file tree
/
Copy pathheaders.mjs
More file actions
123 lines (118 loc) · 6.21 KB
/
Copy pathheaders.mjs
File metadata and controls
123 lines (118 loc) · 6.21 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
// The HTTP headers a static host must send for the browser edition, in one place.
//
// They are written out as a `_headers` file (Netlify and Cloudflare Pages read it), an nginx
// snippet, and read back by web/serve.mjs so the end-to-end check runs under the same policy a
// release does. A policy that is only written down is a policy nobody has tried.
//
// What the editor needs, and why the policy is not tighter:
// script-src 'unsafe-eval' Monaco and the TextMate/WASM engines compile code at runtime.
// style-src 'unsafe-inline' the workbench sets styles from script.
// connect-src https: BYOK sends the user's key to the provider they chose, from the tab.
// frame-src webviews and (optionally) the extension host live on origins of
// their own; they are listed explicitly.
/**
* @param {{ account: string, webviewOrigin?: string, extHostOrigin?: string, base?: string }} o
* webviewOrigin / extHostOrigin: origin patterns such as https://*.view.example.com; omitted when the
* editor uses Code-OSS's default webview host (https://*.vscode-cdn.net) or an in-page extension host.
*/
export function policy(o) {
const frames = ["'self'"];
frames.push(o.webviewOrigin || 'https://*.vscode-cdn.net');
if (o.extHostOrigin) { frames.push(o.extHostOrigin); }
frames.push('data:');
const workbench = [
"default-src 'self'",
"script-src 'self' 'unsafe-eval' blob:",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' https: data: blob:",
"media-src 'self' blob: data:",
"font-src 'self' blob:",
`connect-src 'self' https: http://localhost:* http://127.0.0.1:*`,
`frame-src ${frames.join(' ')}`,
"worker-src 'self' data: blob:",
"child-src 'self' blob:",
"manifest-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join('; ');
const callback = [
"default-src 'none'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join('; ');
const common = {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
};
return {
// Exact paths first; a later rule only adds headers the earlier ones did not set.
rules: [
{ path: '/', headers: { ...common, 'Content-Security-Policy': workbench, 'Cache-Control': 'no-cache' } },
{ path: '/index.html', headers: { ...common, 'Content-Security-Policy': workbench, 'Cache-Control': 'no-cache' } },
{ path: '/callback.html', headers: { ...common, 'Content-Security-Policy': callback, 'Cache-Control': 'no-store' } },
{ path: '/callback.js', headers: { 'Cache-Control': 'no-cache' } },
{ path: '/callback.css', headers: { 'Cache-Control': 'no-cache' } },
{ path: '/manifest.webmanifest', headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'application/manifest+json' } },
// Everything under the build prefix is addressed by its build id: it never changes.
{ path: `${o.base || '/_'}/*`, headers: { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'public, max-age=31536000, immutable',
'Access-Control-Allow-Origin': '*', 'Cross-Origin-Resource-Policy': 'cross-origin' } },
],
};
}
/** Netlify / Cloudflare Pages `_headers` text. */
export function toHeadersFile(p) {
// Cloudflare Pages serves a page `x.html` at `/x` (it redirects /x.html there), and matches rules against the address
// asked for: a rule for /callback.html alone would leave the sign-in page it serves without its headers. So each
// page's rule is also written for its address without `.html` (/index.html's is `/`, which has its own rule).
const rules = p.rules.flatMap((r) => (/^\/[^/]+\.html$/.test(r.path) && r.path !== '/index.html' ? [r, { ...r, path: r.path.slice(0, -'.html'.length) }] : [r]));
return rules.map((r) => r.path + '\n' + Object.entries(r.headers).map(([k, v]) => ` ${k}: ${v}`).join('\n')).join('\n\n') + '\n';
}
/** Parse a `_headers` file back into rules (the dev server serves a built release with it). */
export function parseHeadersFile(text) {
const rules = [];
let cur = null;
for (const raw of text.split('\n')) {
if (!raw.trim() || raw.trim().startsWith('#')) { continue; }
if (!/^\s/.test(raw)) { cur = { path: raw.trim(), headers: {} }; rules.push(cur); continue; }
const i = raw.indexOf(':');
if (cur && i > 0) { cur.headers[raw.slice(0, i).trim()] = raw.slice(i + 1).trim(); }
}
return { rules };
}
/** Headers for a request path, later and more specific rules overriding earlier ones. */
export function headersFor(p, pathname) {
const out = {};
for (const r of p.rules) {
const star = r.path.indexOf('*');
const match = star < 0 ? r.path === pathname : pathname.startsWith(r.path.slice(0, star));
if (match) { for (const [k, v] of Object.entries(r.headers)) { if (!(k in out)) { out[k] = v; } } }
}
return out;
}
/** An nginx `server` fragment with the same rules, for a host that is not Netlify or Cloudflare. */
export function toNginx(p, root = '/srv/levelcode-web') {
const lines = ['# LevelCode in your browser: a static site, nothing else. Generated by scripts/build-web.mjs.',
'server {', ' listen 80;', ' server_name _;', ` root ${root};`, ' index index.html;', ' default_type application/octet-stream;', ' gzip on;',
' gzip_types text/css application/javascript text/javascript application/json image/svg+xml;', ''];
for (const r of p.rules) {
const star = r.path.indexOf('*');
const loc = star < 0 ? `location = ${r.path}` : `location ^~ ${r.path.slice(0, star)}`;
lines.push(` ${loc} {`);
for (const [k, v] of Object.entries(r.headers)) {
if (k === 'Content-Type') { lines.push(` types { } default_type ${v};`); continue; }
lines.push(` add_header ${k} "${v.replace(/"/g, '\\"')}" always;`);
}
// `try_files $uri` looks for a FILE, and `/` is a directory: the root rule would answer 404 before `index`
// could run, and an exact location keeps the request from reaching the fallback below. It names the page.
lines.push(r.path === '/' ? ' try_files /index.html =404;' : ' try_files $uri =404;', ' }', '');
}
lines.push(' location / { try_files $uri $uri/ =404; }', '}');
return lines.join('\n') + '\n';
}