@johnhenry/sitefile 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +480 -3
- package/README.md +70 -21
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/canonical.d.ts +16 -0
- package/lib/src/canonical.js +46 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +3 -1
- package/lib/src/cli/index.js +31 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +46 -8
- package/lib/src/cli/servers.d.ts +124 -1
- package/lib/src/cli/servers.js +705 -62
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +192 -22
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +116 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +176 -7
- package/lib/src/language/validate.js +21 -0
- package/lib/src/links.d.ts +33 -0
- package/lib/src/links.js +271 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +69 -2
- package/lib/src/planner.js +150 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +144 -18
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +304 -0
- package/lib/src/resources/archive.d.ts +36 -0
- package/lib/src/resources/archive.js +338 -67
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +32 -0
- package/lib/src/serve-auth.js +112 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +437 -10
- package/lib/src/server.js +1236 -52
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +109 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +54 -0
- package/lib/src/site.js +204 -6
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
package/lib/src/server.js
CHANGED
|
@@ -1,25 +1,296 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
2
|
+
import https from 'node:https';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { isSitefileError, SitefileError } from './errors.js';
|
|
5
|
+
import { fetchRemote, redactUrl } from './resources/https.js';
|
|
6
|
+
import { DEFAULT_FETCH_POLICY } from './resources/types.js';
|
|
7
|
+
import { globMatch, headersFor, isRewriteStatus, matchRedirect, matchRule, parseHeaderRules, parseRedirectRules, substituteTarget } from './serve-rules.js';
|
|
8
|
+
import { deltaFor } from './dictionary.js';
|
|
4
9
|
import { nfc } from './paths.js';
|
|
10
|
+
import { gzip } from './deflate.js';
|
|
5
11
|
import { mimeTypeFor } from './wbn.js';
|
|
12
|
+
import { RELOAD_CLIENT } from './reload-client.js';
|
|
13
|
+
/** Response headers a proxy does not pass on (RFC 9110 section 7.6.1), and the length it recomputes. */
|
|
14
|
+
const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
|
|
15
|
+
/** Request headers passed to the upstream (no cookies or credentials: they belong to this server's origin). */
|
|
16
|
+
const PROXY_REQUEST_HEADERS = ['accept', 'accept-language', 'if-none-match', 'if-modified-since', 'range'];
|
|
17
|
+
/** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
|
|
18
|
+
export function acceptsGzip(header) {
|
|
19
|
+
if (header === undefined)
|
|
20
|
+
return false;
|
|
21
|
+
return header.split(',').some((part) => {
|
|
22
|
+
const [name, ...params] = part.trim().split(';');
|
|
23
|
+
if (name?.trim().toLowerCase() !== 'gzip' && name?.trim().toLowerCase() !== 'x-gzip')
|
|
24
|
+
return false;
|
|
25
|
+
const q = params.map((x) => x.trim()).find((x) => x.toLowerCase().startsWith('q='));
|
|
26
|
+
return q === undefined || Number(q.slice(2)) > 0;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
|
|
30
|
+
export function gzipMember(deflate, crc, size) {
|
|
31
|
+
const head = Buffer.from([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]);
|
|
32
|
+
const tail = Buffer.alloc(8);
|
|
33
|
+
tail.writeUInt32LE(crc >>> 0, 0);
|
|
34
|
+
tail.writeUInt32LE(size % 2 ** 32, 4);
|
|
35
|
+
return Buffer.concat([head, deflate, tail]);
|
|
36
|
+
}
|
|
6
37
|
/** Reserved for the live-reload event stream while `serve --watch` runs. */
|
|
7
38
|
export const RELOAD_PATH = '/__sitefile/reload';
|
|
8
|
-
/**
|
|
9
|
-
export const
|
|
10
|
-
/**
|
|
39
|
+
/** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
|
|
40
|
+
export const RELOAD_SCRIPT_PATH = '/__sitefile/reload.js';
|
|
41
|
+
/** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
|
|
42
|
+
export const RELOAD_SCRIPT = `<script src="${RELOAD_SCRIPT_PATH}"></script>`;
|
|
43
|
+
export { RELOAD_CLIENT };
|
|
44
|
+
/**
|
|
45
|
+
* Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
|
|
46
|
+
* when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
|
|
47
|
+
* `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
|
|
48
|
+
*/
|
|
49
|
+
export function isNavigation(headers) {
|
|
50
|
+
const one = (k) => {
|
|
51
|
+
const v = headers[k];
|
|
52
|
+
return Array.isArray(v) ? v.join(', ') : v;
|
|
53
|
+
};
|
|
54
|
+
const mode = one('sec-fetch-mode');
|
|
55
|
+
if (mode !== undefined)
|
|
56
|
+
return mode.trim().toLowerCase() === 'navigate';
|
|
57
|
+
const dest = one('sec-fetch-dest');
|
|
58
|
+
if (dest !== undefined)
|
|
59
|
+
return ['document', 'iframe', 'frame'].includes(dest.trim().toLowerCase());
|
|
60
|
+
return (one('accept') ?? '').toLowerCase().includes('text/html');
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
|
|
64
|
+
* a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
|
|
65
|
+
* undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
|
|
66
|
+
* `https:` count as allowing the server's own origin (host sources are not matched), and
|
|
67
|
+
* `'strict-dynamic'` makes `'self'` ignored for scripts.
|
|
68
|
+
*/
|
|
69
|
+
export function cspBlocksReload(value) {
|
|
70
|
+
for (const policy of value.split(',')) {
|
|
71
|
+
const directives = new Map();
|
|
72
|
+
for (const d of policy.split(';')) {
|
|
73
|
+
const [name, ...sources] = d.trim().split(/[\t\n\f\r ]+/).filter((t) => t !== '');
|
|
74
|
+
if (name !== undefined && !directives.has(name.toLowerCase()))
|
|
75
|
+
directives.set(name.toLowerCase(), sources.map((t) => t.toLowerCase()));
|
|
76
|
+
}
|
|
77
|
+
const effective = (names) => names.map((n) => directives.get(n)).find((v) => v !== undefined);
|
|
78
|
+
const allows = (sources, script) => sources === undefined ||
|
|
79
|
+
(!(script && sources.includes("'strict-dynamic'")) && sources.some((t) => t === "'self'" || t === '*' || t === 'http:' || t === 'https:'));
|
|
80
|
+
if (!allows(effective(['script-src-elem', 'script-src', 'default-src']), true))
|
|
81
|
+
return 'script-src';
|
|
82
|
+
if (!allows(effective(['connect-src', 'default-src']), false))
|
|
83
|
+
return 'connect-src';
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Heartbeat interval on the event stream. */
|
|
88
|
+
export const HEARTBEAT_MS = 15_000;
|
|
89
|
+
/** Headers of the event stream (also on HEAD): no proxy buffering (`X-Accel-Buffering`), no compression or other transforms. */
|
|
90
|
+
export const STREAM_HEADERS = {
|
|
91
|
+
'content-type': 'text/event-stream',
|
|
92
|
+
'cache-control': 'no-cache, no-transform',
|
|
93
|
+
'x-accel-buffering': 'no',
|
|
94
|
+
};
|
|
95
|
+
/** The script served at {@link RELOAD_SCRIPT_PATH}: {@link RELOAD_CLIENT} called with `options` (keys in a fixed order). */
|
|
96
|
+
export function clientScript(options = {}) {
|
|
97
|
+
return `${RELOAD_CLIENT}({"resetServiceWorkers":${options.resetServiceWorkers !== false},"cssInject":${options.cssInject !== false},"console":${options.console === true},"overlay":${options.overlay !== false},"navigateToChanged":${options.navigateToChanged === true},"reload":"${options.reload ?? 'morph'}"});\n`;
|
|
98
|
+
}
|
|
99
|
+
/** Reserved for browser console messages (POST) while `serve --watch` runs. */
|
|
100
|
+
export const CONSOLE_PATH = '/__sitefile/console';
|
|
101
|
+
/** Largest console message body accepted (bytes). */
|
|
102
|
+
export const MAX_CONSOLE_BODY = 16 * 1024;
|
|
103
|
+
/** At most this many console messages are logged per {@link CONSOLE_WINDOW_MS}. */
|
|
104
|
+
export const CONSOLE_LIMIT = 50;
|
|
105
|
+
export const CONSOLE_WINDOW_MS = 10_000;
|
|
106
|
+
/** `s` with each run of control characters made one space, trimmed, and cut to `max` code points (then `...`). */
|
|
107
|
+
function cleanText(s, max) {
|
|
108
|
+
const t = [...s.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim()];
|
|
109
|
+
return t.length > max ? t.slice(0, max).join('') + '...' : t.join('');
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The server-log lines for one console message body (JSON `{level, message, stack, url, line, col}`),
|
|
113
|
+
* or undefined when it is not one. `level` is error, warn, log or info; log and info give no lines
|
|
114
|
+
* unless `all` (`--console`). The first line is `browser <level>: <message> (<url>:<line>:<col>)`;
|
|
115
|
+
* up to 5 stack lines follow, indented.
|
|
116
|
+
*/
|
|
117
|
+
export function consoleLines(body, all) {
|
|
118
|
+
let v;
|
|
119
|
+
try {
|
|
120
|
+
v = JSON.parse(body);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v))
|
|
126
|
+
return undefined;
|
|
127
|
+
const o = v;
|
|
128
|
+
const level = o.level;
|
|
129
|
+
if (level !== 'error' && level !== 'warn' && level !== 'log' && level !== 'info')
|
|
130
|
+
return undefined;
|
|
131
|
+
if ((level === 'log' || level === 'info') && !all)
|
|
132
|
+
return [];
|
|
133
|
+
const message = cleanText(typeof o.message === 'string' ? o.message : '', 1000);
|
|
134
|
+
const num = (x) => (typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= Number.MAX_SAFE_INTEGER ? x : undefined);
|
|
135
|
+
const url = typeof o.url === 'string' ? cleanText(o.url, 300) : '';
|
|
136
|
+
const line = num(o.line);
|
|
137
|
+
const col = line === undefined ? undefined : num(o.col);
|
|
138
|
+
const at = url === '' ? '' : ` (${url}${line === undefined ? '' : `:${line}`}${col === undefined ? '' : `:${col}`})`;
|
|
139
|
+
const out = [`browser ${level}: ${message}${at}`];
|
|
140
|
+
if (typeof o.stack === 'string') {
|
|
141
|
+
const frames = o.stack
|
|
142
|
+
.split('\n')
|
|
143
|
+
.map((l) => cleanText(l, 300))
|
|
144
|
+
.filter((l) => l !== '' && l !== message);
|
|
145
|
+
for (const f of frames.slice(0, 5))
|
|
146
|
+
out.push(` ${f}`);
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
/** A console POST comes from a page of this server: `Origin` is `http(s)://<Host>`, and `Sec-Fetch-Site` (when sent) is same-origin. */
|
|
151
|
+
export function isSameOriginPost(headers) {
|
|
152
|
+
const one = (k) => {
|
|
153
|
+
const x = headers[k];
|
|
154
|
+
return Array.isArray(x) ? x.join(', ') : x;
|
|
155
|
+
};
|
|
156
|
+
const origin = one('origin');
|
|
157
|
+
const host = one('host');
|
|
158
|
+
if (origin === undefined || host === undefined || host === '')
|
|
159
|
+
return false;
|
|
160
|
+
const site = one('sec-fetch-site');
|
|
161
|
+
if (site !== undefined && site.trim().toLowerCase() !== 'same-origin')
|
|
162
|
+
return false;
|
|
163
|
+
return origin === `http://${host}` || origin === `https://${host}`;
|
|
164
|
+
}
|
|
165
|
+
/** The event that tells every page to reload. */
|
|
166
|
+
export const RELOAD_EVENT = '{"type":"reload"}';
|
|
167
|
+
/** Sent when a rebuild starts (pages show a Rebuilding badge). */
|
|
168
|
+
export const BUILDING_EVENT = '{"type":"building"}';
|
|
169
|
+
/** Sent after a good rebuild that changed nothing (pages clear the badge and any error overlay). */
|
|
170
|
+
export const OK_EVENT = '{"type":"ok"}';
|
|
171
|
+
/** The event for a failed rebuild: `{"type":"error","code","message"[,"file","line","column"]}`. */
|
|
172
|
+
export function errorEvent(e) {
|
|
173
|
+
return JSON.stringify({
|
|
174
|
+
type: 'error',
|
|
175
|
+
code: e.code,
|
|
176
|
+
message: e.detail,
|
|
177
|
+
...(e.span ? { file: e.span.file, line: e.span.line, column: e.span.column } : {}),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The URL path that serves `file`: `/dir/` for `/dir/index.html` (and `/` for `/index.html`),
|
|
182
|
+
* else the file path; each segment percent-encoded like encodeURIComponent.
|
|
183
|
+
*/
|
|
184
|
+
export function pageUrlFor(file) {
|
|
185
|
+
const segs = file.split('/').slice(1);
|
|
186
|
+
if (segs[segs.length - 1] === 'index.html')
|
|
187
|
+
segs[segs.length - 1] = '';
|
|
188
|
+
return '/' + segs.map(encodeURIComponent).join('/');
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The live-reload event for a new tree (undefined when no file changed): `{"type":"css","paths":[...]}`
|
|
192
|
+
* when `cssInject` is on and every changed file is a stylesheet that is in both trees (added or
|
|
193
|
+
* removed files always reload), else {@link RELOAD_EVENT}; with `navigate`, a reload where exactly
|
|
194
|
+
* one HTML file was added or changed also names its page: `{"type":"reload","path":"/posts/a/"}`.
|
|
195
|
+
* A reload where only existing HTML files changed (nothing added or removed, no other type) is
|
|
196
|
+
* marked `"morph":true`: pages may update in place. Paths are sorted.
|
|
197
|
+
*/
|
|
198
|
+
export function reloadEventFor(prev, next, cssInject, navigate = false) {
|
|
199
|
+
const changed = [];
|
|
200
|
+
const pages = [];
|
|
201
|
+
let cssOnly = cssInject;
|
|
202
|
+
let htmlOnly = true;
|
|
203
|
+
for (const [p, f] of next.entries()) {
|
|
204
|
+
const old = prev.get(p);
|
|
205
|
+
if (old !== undefined && old.digest === f.digest && old.mode === f.mode)
|
|
206
|
+
continue;
|
|
207
|
+
changed.push(p);
|
|
208
|
+
const html = mimeTypeFor(p).startsWith('text/html');
|
|
209
|
+
if (html)
|
|
210
|
+
pages.push(p);
|
|
211
|
+
if (old === undefined || !html)
|
|
212
|
+
htmlOnly = false;
|
|
213
|
+
if (old === undefined || !mimeTypeFor(p).startsWith('text/css'))
|
|
214
|
+
cssOnly = false;
|
|
215
|
+
}
|
|
216
|
+
for (const [p] of prev.entries()) {
|
|
217
|
+
if (!next.isFile(p)) {
|
|
218
|
+
changed.push(p);
|
|
219
|
+
cssOnly = false;
|
|
220
|
+
htmlOnly = false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (changed.length === 0)
|
|
224
|
+
return undefined;
|
|
225
|
+
if (!cssOnly) {
|
|
226
|
+
const path = navigate && pages.length === 1 ? pageUrlFor(pages[0]) : undefined;
|
|
227
|
+
if (path === undefined && !htmlOnly)
|
|
228
|
+
return RELOAD_EVENT;
|
|
229
|
+
return JSON.stringify({ type: 'reload', ...(path !== undefined ? { path } : {}), ...(htmlOnly ? { morph: true } : {}) });
|
|
230
|
+
}
|
|
231
|
+
return JSON.stringify({ type: 'css', paths: changed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) });
|
|
232
|
+
}
|
|
233
|
+
/** Open live-reload streams; {@link LiveReload.send} gives every page an event ({@link LiveReload.reload}: reload). */
|
|
11
234
|
export class LiveReload {
|
|
12
235
|
clients = new Set();
|
|
13
|
-
/**
|
|
236
|
+
/** The client script for this session ({@link clientScript}). */
|
|
237
|
+
script;
|
|
238
|
+
/** Time between heartbeat comments on an open stream (15 s; tests pass less). */
|
|
239
|
+
heartbeatMs;
|
|
240
|
+
constructor(options = {}, heartbeatMs = HEARTBEAT_MS) {
|
|
241
|
+
this.script = clientScript(options);
|
|
242
|
+
this.heartbeatMs = heartbeatMs;
|
|
243
|
+
this.console = options.console === true;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Hold `res` open as a text/event-stream until the client goes away. The headers keep proxies
|
|
247
|
+
* and tunnels from buffering or compressing it, and a comment every 15 s keeps idle
|
|
248
|
+
* connections from being cut (and finds clients that went away).
|
|
249
|
+
*/
|
|
14
250
|
attach(res, headers) {
|
|
15
|
-
res.writeHead(200, { ...headers,
|
|
251
|
+
res.writeHead(200, { ...headers, ...STREAM_HEADERS });
|
|
16
252
|
res.write('retry: 1000\n\n');
|
|
253
|
+
// A page opened while the last build is broken shows the error at once.
|
|
254
|
+
if (this.failure !== undefined)
|
|
255
|
+
res.write(`data: ${this.failure}\n\n`);
|
|
17
256
|
this.clients.add(res);
|
|
18
|
-
res.
|
|
257
|
+
const beat = setInterval(() => res.write(': ping\n\n'), this.heartbeatMs);
|
|
258
|
+
beat.unref();
|
|
259
|
+
res.on('close', () => {
|
|
260
|
+
clearInterval(beat);
|
|
261
|
+
this.clients.delete(res);
|
|
262
|
+
});
|
|
19
263
|
}
|
|
20
|
-
|
|
264
|
+
console;
|
|
265
|
+
consoleWindow = 0;
|
|
266
|
+
consoleCount = 0;
|
|
267
|
+
/**
|
|
268
|
+
* Whether one more console message may be logged now (at most {@link CONSOLE_LIMIT} per
|
|
269
|
+
* {@link CONSOLE_WINDOW_MS}); the first refused one in a window also returns a notice line.
|
|
270
|
+
*/
|
|
271
|
+
admitConsole(now) {
|
|
272
|
+
if (now - this.consoleWindow >= CONSOLE_WINDOW_MS) {
|
|
273
|
+
this.consoleWindow = now;
|
|
274
|
+
this.consoleCount = 0;
|
|
275
|
+
}
|
|
276
|
+
this.consoleCount++;
|
|
277
|
+
if (this.consoleCount <= CONSOLE_LIMIT)
|
|
278
|
+
return { ok: true };
|
|
279
|
+
return this.consoleCount === CONSOLE_LIMIT + 1 ? { ok: false, notice: `browser: more than ${CONSOLE_LIMIT} console messages in 10 s; dropping the rest` } : { ok: false };
|
|
280
|
+
}
|
|
281
|
+
/** The last error event, until a good build: sent to streams that open meanwhile. */
|
|
282
|
+
failure;
|
|
283
|
+
/** Send `event` (one line of JSON) to every open page. */
|
|
284
|
+
send(event) {
|
|
285
|
+
if (event.startsWith('{"type":"error"'))
|
|
286
|
+
this.failure = event;
|
|
287
|
+
else if (event !== BUILDING_EVENT)
|
|
288
|
+
this.failure = undefined;
|
|
21
289
|
for (const c of this.clients)
|
|
22
|
-
c.write(
|
|
290
|
+
c.write(`data: ${event}\n\n`);
|
|
291
|
+
}
|
|
292
|
+
reload() {
|
|
293
|
+
this.send(RELOAD_EVENT);
|
|
23
294
|
}
|
|
24
295
|
get size() {
|
|
25
296
|
return this.clients.size;
|
|
@@ -34,6 +305,10 @@ export function injectReloadScript(html) {
|
|
|
34
305
|
}
|
|
35
306
|
const NOT_FOUND_PAGE = '<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n';
|
|
36
307
|
const BAD_REQUEST_PAGE = '<!doctype html><meta charset="utf-8"><title>400 Bad Request</title><h1>400 Bad Request</h1>\n';
|
|
308
|
+
const FORBIDDEN_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1>\n';
|
|
309
|
+
const UNAUTHORIZED_PAGE = '<!doctype html><meta charset="utf-8"><title>401 Unauthorized</title><h1>401 Unauthorized</h1>\n';
|
|
310
|
+
const FORBIDDEN_HOST_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1><p>This server answers requests for localhost and IP addresses only. To allow another host name, restart it with <code>--allowed-host <name></code>.</p>\n';
|
|
311
|
+
const ERROR_PAGE = '<!doctype html><meta charset="utf-8"><title>500 Internal Server Error</title><h1>500 Internal Server Error</h1>\n';
|
|
37
312
|
const METHOD_PAGE = '<!doctype html><meta charset="utf-8"><title>405 Method Not Allowed</title><h1>405 Method Not Allowed</h1>\n';
|
|
38
313
|
/** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
|
|
39
314
|
export function safeSegments(rawPath) {
|
|
@@ -58,6 +333,379 @@ export function safeSegments(rawPath) {
|
|
|
58
333
|
}
|
|
59
334
|
return out;
|
|
60
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* An access-log line. Text: `METHOD target STATUS BYTES MSms` (then ` <remote>` with `--log-ip`). JSON, a stable
|
|
338
|
+
* contract (docs/CLI.md): `{"type":"request","ts","method","path","query","status","bytes","ms","encoding","range"}`
|
|
339
|
+
* and `"remote"` with `--log-ip`, in that order; `path` and `query` split the target at the first `?` (the `?`
|
|
340
|
+
* dropped), `ms` has one decimal, `range` is the response's `Content-Range` or null.
|
|
341
|
+
*/
|
|
342
|
+
export function accessLogLine(format, e) {
|
|
343
|
+
const target = printable(e.target);
|
|
344
|
+
if (format === 'text')
|
|
345
|
+
return `${e.method} ${target} ${e.status} ${e.bytes} ${e.ms.toFixed(1)}ms${e.note ?? ''}${e.remote !== undefined ? ` ${e.remote}` : ''}${e.device !== undefined ? ` ${e.device}` : ''}`;
|
|
346
|
+
const q = target.indexOf('?');
|
|
347
|
+
const path = q === -1 ? target : target.slice(0, q);
|
|
348
|
+
const query = q === -1 ? '' : target.slice(q + 1);
|
|
349
|
+
return (`{"type":"request","ts":${JSON.stringify(e.ts)},"method":${JSON.stringify(e.method)},"path":${JSON.stringify(path)},"query":${JSON.stringify(query)},` +
|
|
350
|
+
`"status":${e.status},"bytes":${e.bytes},"ms":${e.ms.toFixed(1)},"encoding":"identity","range":${e.range === undefined ? 'null' : JSON.stringify(e.range)}` +
|
|
351
|
+
`${e.note !== undefined ? `,"note":${JSON.stringify(e.note.replace(/^ \u2192 /, ''))}` : ''}` +
|
|
352
|
+
`${e.remote !== undefined ? `,"remote":${JSON.stringify(e.remote)}` : ''}${e.device !== undefined ? `,"device":${JSON.stringify(e.device)}` : ''}}`);
|
|
353
|
+
}
|
|
354
|
+
/** A log line that is not a request, as a JSON object (`--log-format json`): `warning: …` and `error…` lines get their own types. */
|
|
355
|
+
export function jsonLogLine(ts, line) {
|
|
356
|
+
const [type, message] = line.startsWith('warning: ') ? ['warning', line.slice(9)] : line.startsWith('error') ? ['error', line] : ['message', line];
|
|
357
|
+
return `{"type":${JSON.stringify(type)},"ts":${JSON.stringify(ts)},"message":${JSON.stringify(message)}}`;
|
|
358
|
+
}
|
|
359
|
+
/** `{"type":"started","ts","site","files","url"}`: a server is listening (`--log-format json`). */
|
|
360
|
+
export function startedLogLine(ts, site, files, url) {
|
|
361
|
+
return `{"type":"started","ts":${JSON.stringify(ts)},"site":${JSON.stringify(site)},"files":${files},"url":${JSON.stringify(url)}}`;
|
|
362
|
+
}
|
|
363
|
+
/** `{"type":"stopped","ts","signal"}`: a server shuts down (`--log-format json`). */
|
|
364
|
+
export function stoppedLogLine(ts, signal) {
|
|
365
|
+
return `{"type":"stopped","ts":${JSON.stringify(ts)},"signal":${JSON.stringify(signal)}}`;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* A detached server's log line as JSON (`server logs --json`): JSON lines as they are; a text line
|
|
369
|
+
* (`<ISO time> <rest>`) as a request, started, stopped, warning, error or message object.
|
|
370
|
+
*/
|
|
371
|
+
export function logLineAsJson(line) {
|
|
372
|
+
if (line.startsWith('{'))
|
|
373
|
+
return line;
|
|
374
|
+
const m = /^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z) (.*)$/.exec(line);
|
|
375
|
+
if (!m)
|
|
376
|
+
return jsonLogLine('', line);
|
|
377
|
+
const [, ts, rest] = m;
|
|
378
|
+
const r = /^([A-Z][A-Z-]*) (\S+) ([0-9]{3}) ([0-9]+) ([0-9]+\.[0-9])ms(?: (\S+))?$/.exec(rest);
|
|
379
|
+
if (r) {
|
|
380
|
+
return accessLogLine('json', { ts, method: r[1], target: r[2], status: Number(r[3]), bytes: Number(r[4]), ms: Number(r[5]), ...(r[6] !== undefined ? { remote: r[6] } : {}) });
|
|
381
|
+
}
|
|
382
|
+
const started = /^serving (.+) \(([0-9]+) files\) at (\S+)$/.exec(rest);
|
|
383
|
+
if (started)
|
|
384
|
+
return startedLogLine(ts, started[1], Number(started[2]), started[3]);
|
|
385
|
+
const stopped = /^received (SIG[A-Z]+), shutting down$/.exec(rest);
|
|
386
|
+
if (stopped)
|
|
387
|
+
return stoppedLogLine(ts, stopped[1]);
|
|
388
|
+
return jsonLogLine(ts, rest);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
|
|
392
|
+
* case-insensitive; an explicit entry wins over `*`.
|
|
393
|
+
*/
|
|
394
|
+
export function acceptsEncoding(header, coding) {
|
|
395
|
+
if (header === undefined)
|
|
396
|
+
return false;
|
|
397
|
+
let star;
|
|
398
|
+
for (const part of header.split(',')) {
|
|
399
|
+
const [name, ...params] = part.split(';').map((x) => x.trim());
|
|
400
|
+
const n = (name ?? '').replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
401
|
+
let q = 1;
|
|
402
|
+
for (const p of params) {
|
|
403
|
+
const m = /^[qQ][ \t]*=[ \t]*([0-9.]+)$/.exec(p);
|
|
404
|
+
if (m)
|
|
405
|
+
q = Number(m[1]);
|
|
406
|
+
}
|
|
407
|
+
const ok = Number.isFinite(q) && q > 0;
|
|
408
|
+
if (n === coding)
|
|
409
|
+
return ok;
|
|
410
|
+
if (n === '*')
|
|
411
|
+
star = ok;
|
|
412
|
+
}
|
|
413
|
+
return star ?? false;
|
|
414
|
+
}
|
|
415
|
+
/** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
|
|
416
|
+
export function isCompressible(type) {
|
|
417
|
+
const t = (type.split(';')[0] ?? '').trim();
|
|
418
|
+
return t.startsWith('text/') || t.endsWith('+json') || t.endsWith('+xml') || ['application/json', 'application/xml', 'application/javascript', 'application/wasm', 'image/svg+xml'].includes(t);
|
|
419
|
+
}
|
|
420
|
+
/** Presets: Chrome DevTools' "3G" (1.6 Mbit/s, 150 ms) and "Slow 3G" (400 kbit/s, 400 ms). */
|
|
421
|
+
export const THROTTLE_PRESETS = {
|
|
422
|
+
'3g': { bytesPerSecond: 200_000, latencyMs: 150 },
|
|
423
|
+
'slow-3g': { bytesPerSecond: 50_000, latencyMs: 400 },
|
|
424
|
+
};
|
|
425
|
+
/** `3g`, `slow-3g` or `<kbit/s>[/<latency ms>]`, else undefined. */
|
|
426
|
+
export function parseThrottle(value) {
|
|
427
|
+
const preset = THROTTLE_PRESETS[value];
|
|
428
|
+
if (preset)
|
|
429
|
+
return preset;
|
|
430
|
+
const m = /^([0-9]{1,7})(?:\/([0-9]{1,5}))?$/.exec(value);
|
|
431
|
+
if (!m || Number(m[1]) === 0)
|
|
432
|
+
return undefined;
|
|
433
|
+
return { bytesPerSecond: Number(m[1]) * 125, latencyMs: Number(m[2] ?? 0) };
|
|
434
|
+
}
|
|
435
|
+
/** A content type `--mime` accepts: `type/subtype`, then optional parameters, printable ASCII. */
|
|
436
|
+
const MIME_VALUE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*( *;[\x20-\x7e]*)?$/;
|
|
437
|
+
/** `--mime ext=type` (a leading `.` is dropped; the extension is lowercased), else undefined. */
|
|
438
|
+
export function parseMimeFlag(value) {
|
|
439
|
+
const i = value.indexOf('=');
|
|
440
|
+
if (i <= 0)
|
|
441
|
+
return undefined;
|
|
442
|
+
const ext = value.slice(0, i).replace(/^\./, '').replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
443
|
+
const type = value.slice(i + 1).trim();
|
|
444
|
+
return /^[a-z0-9_+-]+$/.test(ext) && MIME_VALUE.test(type) ? [ext, type] : undefined;
|
|
445
|
+
}
|
|
446
|
+
/** A `mime.types` file (nginx `types { type ext ...; }` or Apache `type ext ...` lines; `#` comments): ext → type. */
|
|
447
|
+
export function parseMimeTypes(text, origin) {
|
|
448
|
+
const out = new Map();
|
|
449
|
+
for (const [n, raw] of text.split('\n').entries()) {
|
|
450
|
+
const line = raw.replace(/#.*$/, '').replace(/^[ \t]*types\b/, ' ').replace(/[{};]/g, ' ').trim();
|
|
451
|
+
if (line === '')
|
|
452
|
+
continue;
|
|
453
|
+
const [type, ...exts] = line.split(/[ \t]+/);
|
|
454
|
+
if (type === undefined || !MIME_VALUE.test(type))
|
|
455
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: not a content type: ${type ?? ''}`);
|
|
456
|
+
for (const e of exts) {
|
|
457
|
+
const ext = e.replace(/^\./, '').replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
458
|
+
if (!/^[a-z0-9_+-]+$/.test(ext))
|
|
459
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: not an extension: ${e}`);
|
|
460
|
+
out.set(ext, type);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return out;
|
|
464
|
+
}
|
|
465
|
+
/** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
|
|
466
|
+
export function cacheControlFor(type, cache) {
|
|
467
|
+
if (cache === undefined)
|
|
468
|
+
return undefined;
|
|
469
|
+
if (type.startsWith('text/html'))
|
|
470
|
+
return cache.maxAgeHtml === undefined ? undefined : `public, max-age=${cache.maxAgeHtml}`;
|
|
471
|
+
if (cache.maxAge === undefined)
|
|
472
|
+
return undefined;
|
|
473
|
+
return `public, max-age=${cache.maxAge}${cache.immutable ? ', immutable' : ''}`;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
|
|
477
|
+
* section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
|
|
478
|
+
* `/` for an empty path); any other target is returned as it is. The authority is not checked.
|
|
479
|
+
*/
|
|
480
|
+
/** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
|
|
481
|
+
export function preflightHeaders(value) {
|
|
482
|
+
const v = value?.trim();
|
|
483
|
+
return v !== undefined && v !== '' && /^[A-Za-z0-9 \t,!#$%&'*+\-.^_`|~]+$/.test(v) ? v : undefined;
|
|
484
|
+
}
|
|
485
|
+
/** Loopback, also as an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`). */
|
|
486
|
+
function isLoopbackAddress(ip) {
|
|
487
|
+
return ip === '::1' || /^(::ffff:)?127\./i.test(ip);
|
|
488
|
+
}
|
|
489
|
+
/** Address bytes of an IPv4 or IPv6 literal (`::ffff:a.b.c.d` becomes IPv4), else undefined. */
|
|
490
|
+
export function ipBytes(text) {
|
|
491
|
+
const t = text.replace(/^::ffff:(?=[0-9]+\.)/i, '');
|
|
492
|
+
if (isIpv4(t))
|
|
493
|
+
return t.split('.').map(Number);
|
|
494
|
+
if (!/^[0-9A-Fa-f:]+$/.test(t) || !t.includes(':'))
|
|
495
|
+
return undefined;
|
|
496
|
+
const halves = t.split('::');
|
|
497
|
+
if (halves.length > 2)
|
|
498
|
+
return undefined;
|
|
499
|
+
const words = (h) => {
|
|
500
|
+
if (h === '')
|
|
501
|
+
return [];
|
|
502
|
+
const out = [];
|
|
503
|
+
for (const w of h.split(':')) {
|
|
504
|
+
if (!/^[0-9A-Fa-f]{1,4}$/.test(w))
|
|
505
|
+
return undefined;
|
|
506
|
+
out.push(parseInt(w, 16));
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
};
|
|
510
|
+
const a = words(halves[0]);
|
|
511
|
+
const b = halves.length === 2 ? words(halves[1]) : [];
|
|
512
|
+
if (a === undefined || b === undefined)
|
|
513
|
+
return undefined;
|
|
514
|
+
const fill = halves.length === 2 ? 8 - a.length - b.length : 0;
|
|
515
|
+
if (fill < (halves.length === 2 ? 1 : 0) || a.length + b.length + fill !== 8)
|
|
516
|
+
return undefined;
|
|
517
|
+
return [...a, ...new Array(fill).fill(0), ...b].flatMap((w) => [w >> 8, w & 0xff]);
|
|
518
|
+
}
|
|
519
|
+
/** `a.b.c.d/n`, `x::y/n` or a bare address (a /32 or /128), else undefined. */
|
|
520
|
+
export function parseCidr(text) {
|
|
521
|
+
const [addr, len, extra] = text.trim().split('/');
|
|
522
|
+
if (extra !== undefined || addr === undefined)
|
|
523
|
+
return undefined;
|
|
524
|
+
const bytes = ipBytes(addr);
|
|
525
|
+
if (bytes === undefined)
|
|
526
|
+
return undefined;
|
|
527
|
+
const max = bytes.length * 8;
|
|
528
|
+
if (len !== undefined && !/^[0-9]{1,3}$/.test(len))
|
|
529
|
+
return undefined;
|
|
530
|
+
const prefix = len === undefined ? max : Number(len);
|
|
531
|
+
return prefix <= max ? { bytes, prefix } : undefined;
|
|
532
|
+
}
|
|
533
|
+
function cidrContains(c, ip) {
|
|
534
|
+
if (c.bytes.length !== ip.length)
|
|
535
|
+
return false;
|
|
536
|
+
for (let bit = 0; bit < c.prefix; bit++) {
|
|
537
|
+
const mask = 0x80 >> bit % 8;
|
|
538
|
+
if ((c.bytes[bit >> 3] & mask) !== (ip[bit >> 3] & mask))
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
return true;
|
|
542
|
+
}
|
|
543
|
+
/** Whether `--allow-ip`/`--deny-ip` let a client in: loopback always; else not denied, and allowed when an allow list is given. */
|
|
544
|
+
export function ipAllowed(rules, remote) {
|
|
545
|
+
if (rules === undefined || isLoopbackAddress(remote))
|
|
546
|
+
return true;
|
|
547
|
+
const ip = ipBytes(remote);
|
|
548
|
+
if (ip === undefined)
|
|
549
|
+
return false;
|
|
550
|
+
if (rules.deny.some((c) => cidrContains(c, ip)))
|
|
551
|
+
return false;
|
|
552
|
+
return rules.allow.length === 0 || rules.allow.some((c) => cidrContains(c, ip));
|
|
553
|
+
}
|
|
554
|
+
/** A short device name from a `User-Agent` (`iPhone`, `iPad`, `Android`, `Windows`, `Mac`, `Linux`), or `other`. */
|
|
555
|
+
export function deviceOf(userAgent) {
|
|
556
|
+
const ua = userAgent ?? '';
|
|
557
|
+
for (const [needle, name] of [['iPhone', 'iPhone'], ['iPad', 'iPad'], ['Android', 'Android'], ['Windows', 'Windows'], ['Macintosh', 'Mac'], ['Linux', 'Linux']]) {
|
|
558
|
+
if (ua.includes(needle))
|
|
559
|
+
return name;
|
|
560
|
+
}
|
|
561
|
+
return 'other';
|
|
562
|
+
}
|
|
563
|
+
/** Whether `s` is a dotted-decimal IPv4 address. */
|
|
564
|
+
function isIpv4(s) {
|
|
565
|
+
const parts = s.split('.');
|
|
566
|
+
return parts.length === 4 && parts.every((p) => /^[0-9]{1,3}$/.test(p) && Number(p) <= 255);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* The DNS-rebinding guard of {@link SiteServerOptions.allowedHosts}: whether a `Host` header value
|
|
570
|
+
* may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
|
|
571
|
+
* attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
|
|
572
|
+
* port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
|
|
573
|
+
* it without the dot).
|
|
574
|
+
*/
|
|
575
|
+
export function hostAllowed(allowed, host) {
|
|
576
|
+
if (allowed === undefined || allowed.includes('*') || host === undefined)
|
|
577
|
+
return true;
|
|
578
|
+
const h = host.trim();
|
|
579
|
+
if (h === '')
|
|
580
|
+
return true;
|
|
581
|
+
if (h.startsWith('[')) {
|
|
582
|
+
const close = h.indexOf(']');
|
|
583
|
+
return close > 1 && /^[0-9A-Fa-f:.]+$/.test(h.slice(1, close)) && /^(:[0-9]*)?$/.test(h.slice(close + 1));
|
|
584
|
+
}
|
|
585
|
+
const m = /^(.*?)(:[0-9]*)?$/.exec(h);
|
|
586
|
+
let name = m[1].replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
587
|
+
if (name.endsWith('.'))
|
|
588
|
+
name = name.slice(0, -1);
|
|
589
|
+
if (isIpv4(name) || name === 'localhost' || name.endsWith('.localhost'))
|
|
590
|
+
return true;
|
|
591
|
+
return allowed.some((e) => (e.startsWith('.') ? name === e.slice(1) || name.endsWith(e) : name === e));
|
|
592
|
+
}
|
|
593
|
+
/** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
|
|
594
|
+
export function parseAllowedHost(value) {
|
|
595
|
+
const v = value.trim().replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
596
|
+
if (v === '*')
|
|
597
|
+
return v;
|
|
598
|
+
return /^\.?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/.test(v) ? v.replace(/\.$/, '') : undefined;
|
|
599
|
+
}
|
|
600
|
+
export function originForm(target) {
|
|
601
|
+
const m = /^https?:\/\/[^/?#]*/i.exec(target);
|
|
602
|
+
if (!m)
|
|
603
|
+
return target;
|
|
604
|
+
const rest = target.slice(m[0].length);
|
|
605
|
+
return rest.startsWith('/') ? rest : '/' + rest;
|
|
606
|
+
}
|
|
607
|
+
/** A request header as one string (repeated headers joined with `, `). */
|
|
608
|
+
function header(v) {
|
|
609
|
+
return Array.isArray(v) ? v.join(', ') : v;
|
|
610
|
+
}
|
|
611
|
+
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
612
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
613
|
+
/** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
|
|
614
|
+
export function httpDate(secs) {
|
|
615
|
+
return new Date(secs * 1000).toUTCString();
|
|
616
|
+
}
|
|
617
|
+
/** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
|
|
618
|
+
export function parseHttpDate(value) {
|
|
619
|
+
const m = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT$/.exec(value.trim());
|
|
620
|
+
if (!m)
|
|
621
|
+
return undefined;
|
|
622
|
+
const [day, month, year, h, min, sec] = [Number(m[2]), MONTHS.indexOf(m[3]), Number(m[4]), Number(m[5]), Number(m[6]), Number(m[7])];
|
|
623
|
+
if (day < 1 || h > 23 || min > 59 || sec > 59)
|
|
624
|
+
return undefined;
|
|
625
|
+
const ms = Date.UTC(year, month, day, h, min, sec);
|
|
626
|
+
const d = new Date(ms);
|
|
627
|
+
if (d.getUTCDate() !== day || DAYS[d.getUTCDay()] !== m[1])
|
|
628
|
+
return undefined;
|
|
629
|
+
return ms / 1000;
|
|
630
|
+
}
|
|
631
|
+
/** One link-value as Node's `writeEarlyHints` accepts it: `<uri>` and `; param[=value]` pairs. */
|
|
632
|
+
const LINK_VALUE = /^(?:<[^>\r\n]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
|
|
633
|
+
/**
|
|
634
|
+
* The link-values of a `Link` header that become `103 Early Hints`: split at commas outside `<…>`
|
|
635
|
+
* and quotes, kept when well formed and `rel=preload` or `rel=preconnect` (ASCII case-insensitive).
|
|
636
|
+
*/
|
|
637
|
+
export function earlyHints(link) {
|
|
638
|
+
const parts = [];
|
|
639
|
+
let cur = '';
|
|
640
|
+
let angle = false;
|
|
641
|
+
let quote = false;
|
|
642
|
+
for (const c of link) {
|
|
643
|
+
if (c === '<' && !quote)
|
|
644
|
+
angle = true;
|
|
645
|
+
else if (c === '>' && !quote)
|
|
646
|
+
angle = false;
|
|
647
|
+
else if (c === '"' && !angle)
|
|
648
|
+
quote = !quote;
|
|
649
|
+
if (c === ',' && !angle && !quote) {
|
|
650
|
+
parts.push(cur);
|
|
651
|
+
cur = '';
|
|
652
|
+
}
|
|
653
|
+
else
|
|
654
|
+
cur += c;
|
|
655
|
+
}
|
|
656
|
+
parts.push(cur);
|
|
657
|
+
return parts
|
|
658
|
+
.map((p) => p.trim())
|
|
659
|
+
.filter((p) => {
|
|
660
|
+
if (!LINK_VALUE.test(p))
|
|
661
|
+
return false;
|
|
662
|
+
const v = p.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/[ \t]/g, '');
|
|
663
|
+
return ['rel=preload', 'rel="preload"', 'rel=preconnect', 'rel="preconnect"'].some((t) => v.includes(t));
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
/** A `bytes=` value's number: digits only; more than 15 digits counts as larger than any file. */
|
|
667
|
+
function rangeNumber(s) {
|
|
668
|
+
if (!/^[0-9]+$/.test(s))
|
|
669
|
+
return undefined;
|
|
670
|
+
return s.length > 15 ? Number.POSITIVE_INFINITY : Number(s);
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
|
|
674
|
+
* `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
|
|
675
|
+
* asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
|
|
676
|
+
*/
|
|
677
|
+
export function byteRange(header, size) {
|
|
678
|
+
if (header === undefined)
|
|
679
|
+
return undefined;
|
|
680
|
+
const v = header.trim();
|
|
681
|
+
if (v.slice(0, 6).toLowerCase() !== 'bytes=')
|
|
682
|
+
return undefined;
|
|
683
|
+
const spec = v.slice(6).trim();
|
|
684
|
+
if (spec.includes(','))
|
|
685
|
+
return undefined;
|
|
686
|
+
const dash = spec.indexOf('-');
|
|
687
|
+
if (dash === -1)
|
|
688
|
+
return undefined;
|
|
689
|
+
const first = spec.slice(0, dash).trim();
|
|
690
|
+
const last = spec.slice(dash + 1).trim();
|
|
691
|
+
if (first === '') {
|
|
692
|
+
const n = rangeNumber(last);
|
|
693
|
+
if (n === undefined)
|
|
694
|
+
return undefined;
|
|
695
|
+
if (n === 0 || size === 0)
|
|
696
|
+
return 'unsatisfiable';
|
|
697
|
+
return [Math.max(0, size - n), size - 1];
|
|
698
|
+
}
|
|
699
|
+
const start = rangeNumber(first);
|
|
700
|
+
if (start === undefined)
|
|
701
|
+
return undefined;
|
|
702
|
+
const end = last === '' ? Number.POSITIVE_INFINITY : rangeNumber(last);
|
|
703
|
+
if (end === undefined || end < start)
|
|
704
|
+
return undefined;
|
|
705
|
+
if (start >= size)
|
|
706
|
+
return 'unsatisfiable';
|
|
707
|
+
return [start, Math.min(end, size - 1)];
|
|
708
|
+
}
|
|
61
709
|
function etagMatches(header, etag) {
|
|
62
710
|
if (header === undefined)
|
|
63
711
|
return false;
|
|
@@ -65,14 +713,152 @@ function etagMatches(header, etag) {
|
|
|
65
713
|
return true;
|
|
66
714
|
return header.split(',').some((t) => t.trim().replace(/^W\//, '') === etag);
|
|
67
715
|
}
|
|
716
|
+
/**
|
|
717
|
+
* The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
|
|
718
|
+
* else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
|
|
719
|
+
* has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
|
|
720
|
+
*/
|
|
721
|
+
export function spaFallback(segs, trailingSlash, isFile, fallback) {
|
|
722
|
+
if (fallback !== undefined)
|
|
723
|
+
return isFile(fallback) ? fallback : undefined;
|
|
724
|
+
const dirs = trailingSlash ? segs : segs.slice(0, -1);
|
|
725
|
+
for (let n = dirs.length; n >= 0; n--) {
|
|
726
|
+
const dir = `/${dirs.slice(0, n).map((d) => d + '/').join('')}`;
|
|
727
|
+
for (const name of ['200.html', 'index.html'])
|
|
728
|
+
if (isFile(dir + name))
|
|
729
|
+
return dir + name;
|
|
730
|
+
}
|
|
731
|
+
return undefined;
|
|
732
|
+
}
|
|
733
|
+
export const HTML_HANDLINGS = ['auto', 'force-slash', 'drop-slash', 'none'];
|
|
734
|
+
export const HOST_PROFILES = ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
|
|
735
|
+
/**
|
|
736
|
+
* The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
|
|
737
|
+
* undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
|
|
738
|
+
*
|
|
739
|
+
* | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
|
|
740
|
+
* | netlify | auto | 301 | yes | nearest 404.html |
|
|
741
|
+
* | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
|
|
742
|
+
* | vercel | none | 308 | no | /404.html |
|
|
743
|
+
* | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
|
|
744
|
+
* | firebase | none | 301 | no | /404.html |
|
|
745
|
+
*/
|
|
746
|
+
export function hostProfile(name, htmlHandling) {
|
|
747
|
+
const base = name === 'netlify'
|
|
748
|
+
? { htmlHandling: 'auto', redirectStatus: 301, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' }
|
|
749
|
+
: name === 'cloudflare'
|
|
750
|
+
? { htmlHandling: 'auto', redirectStatus: 307, siteFiles: true, notFound: 'index', slashHtml: 'redirect' }
|
|
751
|
+
: name === 'vercel'
|
|
752
|
+
? { htmlHandling: 'none', redirectStatus: 308, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
|
|
753
|
+
: name === 'github-pages'
|
|
754
|
+
? { redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'not-found' }
|
|
755
|
+
: name === 'firebase'
|
|
756
|
+
? { htmlHandling: 'none', redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
|
|
757
|
+
: { redirectStatus: 307, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' };
|
|
758
|
+
return htmlHandling === undefined ? base : { ...base, htmlHandling };
|
|
759
|
+
}
|
|
760
|
+
/** The server's routing profile for the flags (undefined: sitefile's own rules). */
|
|
761
|
+
export function routingFor(o) {
|
|
762
|
+
return o.hostProfile === undefined && o.htmlHandling === undefined ? undefined : hostProfile(o.hostProfile, o.htmlHandling);
|
|
763
|
+
}
|
|
764
|
+
const utf8Order = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
765
|
+
/**
|
|
766
|
+
* What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
|
|
767
|
+
* from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
|
|
768
|
+
* host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
|
|
769
|
+
* conditions do not, in file order.
|
|
770
|
+
*/
|
|
771
|
+
export function nearMisses(tree, isFile, vpath, redirects, req) {
|
|
772
|
+
const lower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
773
|
+
const wanted = new Set([vpath, `${vpath === '/' ? '' : vpath}.html`, `${vpath === '/' ? '' : vpath}/index.html`].map(lower));
|
|
774
|
+
const out = [];
|
|
775
|
+
const files = tree
|
|
776
|
+
.entries()
|
|
777
|
+
.map(([p]) => p)
|
|
778
|
+
.filter((p) => isFile(p) && wanted.has(lower(p)))
|
|
779
|
+
.sort(utf8Order);
|
|
780
|
+
for (const p of files)
|
|
781
|
+
out.push({ path: p, why: 'the letter case differs (a case-insensitive disk finds it, a host does not)' });
|
|
782
|
+
for (const r of redirects) {
|
|
783
|
+
if (matchRedirect(r, vpath) !== undefined && matchRule(r, vpath, req) === undefined) {
|
|
784
|
+
out.push({ line: r.line, why: `matches the path but not its ${r.query.length > 0 ? 'query parameters' : 'conditions'}${r.query.length > 0 && r.conditions.length > 0 ? ' or conditions' : ''}` });
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return out.slice(0, 20);
|
|
788
|
+
}
|
|
789
|
+
const escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => (c === '&' ? '&' : c === '<' ? '<' : c === '>' ? '>' : '"'));
|
|
790
|
+
/** The development 404 page listing near misses. */
|
|
791
|
+
export function nearMissPage(vpath, misses, mount = '') {
|
|
792
|
+
let out = `<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n<p>Nothing is served at <code>${escapeHtml(vpath)}</code>. Near misses:</p>\n<ul>\n`;
|
|
793
|
+
for (const m of misses) {
|
|
794
|
+
const what = m.path !== undefined ? `<a href="${escapeHtml(mount + encodePath(m.path))}">${escapeHtml(m.path)}</a>` : `<code>_redirects:${m.line}</code>`;
|
|
795
|
+
out += `<li>${what}: ${escapeHtml(m.why)}</li>\n`;
|
|
796
|
+
}
|
|
797
|
+
return out + '</ul>\n';
|
|
798
|
+
}
|
|
799
|
+
/** A `Host` header safe to write into a page: a name, IPv4 or bracketed IPv6 address, and a port. */
|
|
800
|
+
const SAFE_HOST = /^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?$/;
|
|
801
|
+
/** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
|
|
802
|
+
export function isRebasedType(type) {
|
|
803
|
+
return type.startsWith('text/html') || type.startsWith('text/css') || type.split(';', 1)[0].includes('xml');
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
|
|
807
|
+
* fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
|
|
808
|
+
* http(s) URL with a host.
|
|
809
|
+
*/
|
|
810
|
+
export function normalizeProductionUrl(raw) {
|
|
811
|
+
const m = /^(https?:\/\/[^/?#\s]+)(\/[^?#\s]*)?$/i.exec(raw.replace(/[?#].*$/, ''));
|
|
812
|
+
if (!m)
|
|
813
|
+
return undefined;
|
|
814
|
+
return m[1] + (m[2] ?? '').replace(/\/+$/, '');
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
|
|
818
|
+
* the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
|
|
819
|
+
* so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
|
|
820
|
+
*/
|
|
821
|
+
export function rewriteBaseUrls(body, from, to) {
|
|
822
|
+
const text = Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('latin1');
|
|
823
|
+
let out = '';
|
|
824
|
+
let i = 0;
|
|
825
|
+
for (;;) {
|
|
826
|
+
const at = text.indexOf(from, i);
|
|
827
|
+
if (at === -1)
|
|
828
|
+
break;
|
|
829
|
+
const next = text[at + from.length];
|
|
830
|
+
out += text.slice(i, at) + (next !== undefined && /[A-Za-z0-9._~:%-]/.test(next) ? from : to);
|
|
831
|
+
i = at + from.length;
|
|
832
|
+
}
|
|
833
|
+
if (i === 0)
|
|
834
|
+
return body;
|
|
835
|
+
return Buffer.from(out + text.slice(i), 'latin1');
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
|
|
839
|
+
* safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
|
|
840
|
+
*/
|
|
841
|
+
export function normalizeBase(raw) {
|
|
842
|
+
const m = /^https?:\/\/[^/?#]*(\/[^?#]*)?/i.exec(raw);
|
|
843
|
+
const p = m ? (m[1] ?? '/') : raw;
|
|
844
|
+
const segs = safeSegments(p.startsWith('/') ? p : '/' + p);
|
|
845
|
+
if (!segs)
|
|
846
|
+
return undefined;
|
|
847
|
+
return segs.length === 0 ? '/' : `/${segs.map(encodeURIComponent).join('/')}/`;
|
|
848
|
+
}
|
|
849
|
+
/** A tree path with each segment percent-encoded like encodeURIComponent. */
|
|
850
|
+
function encodePath(p) {
|
|
851
|
+
return p.split('/').map(encodeURIComponent).join('/');
|
|
852
|
+
}
|
|
68
853
|
function printable(s) {
|
|
69
854
|
return s.replace(/[^\x21-\x7e]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).slice(0, 512);
|
|
70
855
|
}
|
|
71
856
|
/**
|
|
72
857
|
* An HTTP server for an immutable Tree. GET and HEAD only; nothing outside the tree is
|
|
73
858
|
* ever reachable because lookups are exact map keys built from validated segments.
|
|
74
|
-
* Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves),
|
|
75
|
-
* `/about` with `/about.html` when there is no such file or directory
|
|
859
|
+
* Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), answers
|
|
860
|
+
* `/about` with `/about.html` when there is no such file or directory, and redirects `/about/`
|
|
861
|
+
* to `/about` when only `/about.html` answers it.
|
|
76
862
|
*/
|
|
77
863
|
export function createSiteServer(site, options = {}) {
|
|
78
864
|
// A function is read per request (`serve --watch` swaps in each good rebuild).
|
|
@@ -80,6 +866,15 @@ export function createSiteServer(site, options = {}) {
|
|
|
80
866
|
const base = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' };
|
|
81
867
|
if (options.serverId)
|
|
82
868
|
base['x-sitefile-server'] = options.serverId;
|
|
869
|
+
if (options.cors)
|
|
870
|
+
base['access-control-allow-origin'] = '*';
|
|
871
|
+
if (options.noindex)
|
|
872
|
+
base['x-robots-tag'] = 'noindex';
|
|
873
|
+
if (options.isolate !== undefined) {
|
|
874
|
+
base['cross-origin-opener-policy'] = 'same-origin';
|
|
875
|
+
base['cross-origin-embedder-policy'] = options.isolate;
|
|
876
|
+
base['cross-origin-resource-policy'] = 'same-origin';
|
|
877
|
+
}
|
|
83
878
|
// `_redirects` / `_headers` are parsed once per tree (a watched server gets a new tree per rebuild).
|
|
84
879
|
let rulesTree;
|
|
85
880
|
let rules = { redirects: [], headers: [] };
|
|
@@ -87,69 +882,289 @@ export function createSiteServer(site, options = {}) {
|
|
|
87
882
|
if (t !== rulesTree) {
|
|
88
883
|
const text = (p) => {
|
|
89
884
|
const f = t.get(p);
|
|
90
|
-
return f ? new TextDecoder().decode(f.bytes) : '';
|
|
885
|
+
return f ? new TextDecoder().decode(options.content?.read(p) ?? f.bytes) : '';
|
|
91
886
|
};
|
|
92
887
|
rules = { redirects: parseRedirectRules(text('/_redirects')), headers: parseHeaderRules(text('/_headers')) };
|
|
93
888
|
rulesTree = t;
|
|
94
889
|
}
|
|
95
890
|
return rules;
|
|
96
891
|
};
|
|
892
|
+
// One warning per policy text: a site usually sends the same CSP on every page.
|
|
893
|
+
const warnedCsp = new Set();
|
|
894
|
+
const warnCsp = (served, policy) => {
|
|
895
|
+
if (policy === undefined || options.warn === undefined || warnedCsp.has(policy))
|
|
896
|
+
return;
|
|
897
|
+
const blocked = cspBlocksReload(policy);
|
|
898
|
+
if (blocked === undefined)
|
|
899
|
+
return;
|
|
900
|
+
warnedCsp.add(policy);
|
|
901
|
+
const what = blocked === 'script-src' ? `scripts from 'self' (${RELOAD_SCRIPT_PATH})` : `connections to 'self' (${RELOAD_PATH})`;
|
|
902
|
+
options.warn(`live reload: the Content-Security-Policy that _headers sets for ${served} does not allow ${what}, so open pages will not reload: ${policy}`);
|
|
903
|
+
};
|
|
904
|
+
/** --compress: gzip output by file digest (at most 256 files), so a file is compressed once. */
|
|
905
|
+
const gzipCache = new Map();
|
|
906
|
+
const gzipped = (digest, bytes) => {
|
|
907
|
+
let out = gzipCache.get(digest);
|
|
908
|
+
if (out === undefined) {
|
|
909
|
+
if (gzipCache.size >= 256)
|
|
910
|
+
gzipCache.clear();
|
|
911
|
+
out = gzip(bytes);
|
|
912
|
+
gzipCache.set(digest, out);
|
|
913
|
+
}
|
|
914
|
+
return out;
|
|
915
|
+
};
|
|
916
|
+
/** Connections over --max-connections-per-ip: they get one 503. */
|
|
917
|
+
const busy = new WeakSet();
|
|
97
918
|
const handler = (req, res) => {
|
|
98
919
|
const started = process.hrtime.bigint();
|
|
99
920
|
const method = req.method ?? 'GET';
|
|
100
|
-
|
|
921
|
+
/** A non-loopback client of a server with client info: its address and device go into the access log. */
|
|
922
|
+
const shared = !!options.clientInfo && !isLoopbackAddress(req.socket.remoteAddress ?? '');
|
|
923
|
+
const target = req.url ?? '/';
|
|
924
|
+
const url = originForm(target);
|
|
101
925
|
let bytes = 0;
|
|
102
|
-
|
|
926
|
+
/** What answered, for the access log (` → /new (_redirects:3)`), when a rule did. */
|
|
927
|
+
let note = '';
|
|
928
|
+
const finish = (status, headers, body, quiet = false) => {
|
|
103
929
|
const buf = body === undefined ? undefined : typeof body === 'string' ? Buffer.from(body) : body;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
930
|
+
// 103 Early Hints before an HTML page whose `Link` (from `_headers`) preloads or preconnects.
|
|
931
|
+
const link = headers.link;
|
|
932
|
+
const html = String(headers['content-type'] ?? '').startsWith('text/html');
|
|
933
|
+
if (status === 200 && method === 'GET' && html && typeof link === 'string' && (req.httpVersionMajor > 1 || req.httpVersionMinor >= 1)) {
|
|
934
|
+
const hints = earlyHints(link);
|
|
935
|
+
if (hints.length > 0)
|
|
936
|
+
res.writeEarlyHints({ link: hints });
|
|
937
|
+
}
|
|
938
|
+
const send = buf !== undefined && method !== 'HEAD' && status !== 304 ? buf : undefined;
|
|
939
|
+
if (send !== undefined)
|
|
940
|
+
bytes = send.byteLength;
|
|
941
|
+
const t = options.throttle;
|
|
942
|
+
if (t === undefined) {
|
|
943
|
+
res.writeHead(status, { ...base, ...headers });
|
|
944
|
+
res.end(send);
|
|
108
945
|
}
|
|
109
946
|
else {
|
|
110
|
-
|
|
947
|
+
// --throttle: wait the latency, then send the body in 100 ms slices of the bandwidth.
|
|
948
|
+
const slice = Math.max(1, Math.floor(t.bytesPerSecond / 10));
|
|
949
|
+
setTimeout(() => {
|
|
950
|
+
res.writeHead(status, { ...base, ...headers });
|
|
951
|
+
if (send === undefined)
|
|
952
|
+
return void res.end();
|
|
953
|
+
let at = 0;
|
|
954
|
+
const next = () => {
|
|
955
|
+
if (res.destroyed)
|
|
956
|
+
return;
|
|
957
|
+
const end = Math.min(send.byteLength, at + slice);
|
|
958
|
+
res.write(send.subarray(at, end));
|
|
959
|
+
at = end;
|
|
960
|
+
if (at >= send.byteLength)
|
|
961
|
+
res.end();
|
|
962
|
+
else
|
|
963
|
+
setTimeout(next, 100);
|
|
964
|
+
};
|
|
965
|
+
next();
|
|
966
|
+
}, t.latencyMs);
|
|
111
967
|
}
|
|
112
968
|
const ms = Number((process.hrtime.bigint() - started) / 1000n) / 1000;
|
|
969
|
+
if (quiet)
|
|
970
|
+
return;
|
|
113
971
|
// `servers` probes carry the server's own id; they would only clutter the access log.
|
|
114
972
|
if (options.serverId !== undefined && req.headers['x-sitefile-probe'] === options.serverId)
|
|
115
973
|
return;
|
|
116
|
-
|
|
974
|
+
if (options.quiet)
|
|
975
|
+
return;
|
|
976
|
+
const range = headers['content-range'];
|
|
977
|
+
options.log?.(accessLogLine(options.logFormat ?? 'text', {
|
|
978
|
+
ts: new Date().toISOString(),
|
|
979
|
+
method,
|
|
980
|
+
target,
|
|
981
|
+
status,
|
|
982
|
+
bytes,
|
|
983
|
+
ms,
|
|
984
|
+
...(range !== undefined ? { range: String(range) } : {}),
|
|
985
|
+
...(options.logIp || shared ? { remote: req.socket.remoteAddress ?? '' } : {}),
|
|
986
|
+
...(shared ? { device: deviceOf(req.headers['user-agent']) } : {}),
|
|
987
|
+
...(note !== '' ? { note } : {}),
|
|
988
|
+
...(options.logIp ? { remote: req.socket.remoteAddress ?? '' } : {}),
|
|
989
|
+
}));
|
|
117
990
|
};
|
|
118
991
|
const page = (status, html, extra = {}) => finish(status, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html), ...extra }, html);
|
|
992
|
+
if (!ipAllowed(options.ipRules, req.socket.remoteAddress ?? ''))
|
|
993
|
+
return page(403, FORBIDDEN_PAGE);
|
|
994
|
+
if (busy.has(req.socket))
|
|
995
|
+
return finish(503, { 'retry-after': '1', 'content-length': 0, connection: 'close' }, undefined);
|
|
996
|
+
// DNS rebinding: a page on another name must not read this server (before anything else).
|
|
997
|
+
const hostHeader = req.headers.host;
|
|
998
|
+
if (!hostAllowed(options.allowedHosts, hostHeader))
|
|
999
|
+
return page(403, FORBIDDEN_HOST_PAGE);
|
|
1000
|
+
// Basic authentication covers everything, the live-reload endpoints too.
|
|
1001
|
+
if (options.auth !== undefined && !options.auth.allows(req.headers.authorization)) {
|
|
1002
|
+
return page(401, UNAUTHORIZED_PAGE, { 'www-authenticate': 'Basic realm="sitefile", charset="UTF-8"' });
|
|
1003
|
+
}
|
|
1004
|
+
const live = options.liveReload;
|
|
1005
|
+
if (live && url.split(/[?#]/, 1)[0] === CONSOLE_PATH) {
|
|
1006
|
+
// Browser console messages (the client script sends them; not access-logged).
|
|
1007
|
+
if (method !== 'POST')
|
|
1008
|
+
return finish(405, { allow: 'POST', 'content-length': 0 }, undefined, true);
|
|
1009
|
+
if (!isSameOriginPost(req.headers))
|
|
1010
|
+
return finish(403, { 'content-length': 0 }, undefined, true);
|
|
1011
|
+
const chunks = [];
|
|
1012
|
+
let size = 0;
|
|
1013
|
+
let tooBig = false;
|
|
1014
|
+
req.on('data', (c) => {
|
|
1015
|
+
size += c.byteLength;
|
|
1016
|
+
if (size > MAX_CONSOLE_BODY)
|
|
1017
|
+
tooBig = true;
|
|
1018
|
+
else
|
|
1019
|
+
chunks.push(c);
|
|
1020
|
+
});
|
|
1021
|
+
req.on('end', () => {
|
|
1022
|
+
if (tooBig)
|
|
1023
|
+
return finish(413, { 'content-length': 0, connection: 'close' }, undefined, true);
|
|
1024
|
+
const lines = consoleLines(Buffer.concat(chunks).toString('utf8'), live.console);
|
|
1025
|
+
if (lines === undefined)
|
|
1026
|
+
return finish(400, { 'content-length': 0 }, undefined, true);
|
|
1027
|
+
if (lines.length > 0) {
|
|
1028
|
+
const admitted = live.admitConsole(Date.now());
|
|
1029
|
+
if (admitted.notice !== undefined)
|
|
1030
|
+
options.log?.(admitted.notice);
|
|
1031
|
+
if (admitted.ok)
|
|
1032
|
+
for (const l of lines)
|
|
1033
|
+
options.log?.(l);
|
|
1034
|
+
}
|
|
1035
|
+
finish(204, {}, undefined, true);
|
|
1036
|
+
});
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (options.cors && method === 'OPTIONS') {
|
|
1040
|
+
// A CORS preflight: any path, nothing is looked up.
|
|
1041
|
+
const allowHeaders = preflightHeaders(req.headers['access-control-request-headers']);
|
|
1042
|
+
return finish(204, { 'access-control-allow-methods': 'GET, HEAD', ...(allowHeaders !== undefined ? { 'access-control-allow-headers': allowHeaders } : {}), 'access-control-max-age': '600' }, undefined);
|
|
1043
|
+
}
|
|
119
1044
|
if (method !== 'GET' && method !== 'HEAD')
|
|
120
|
-
return page(405, METHOD_PAGE, { allow: 'GET, HEAD' });
|
|
1045
|
+
return page(405, METHOD_PAGE, { allow: options.cors ? 'GET, HEAD, OPTIONS' : 'GET, HEAD' });
|
|
121
1046
|
const tree = current();
|
|
122
|
-
const
|
|
123
|
-
const
|
|
1047
|
+
const profile = options.profile;
|
|
1048
|
+
const siteFiles = profile?.siteFiles !== false;
|
|
1049
|
+
const { redirects, headers: headerRules } = siteFiles ? rulesFor(tree) : { redirects: [], headers: [] };
|
|
1050
|
+
const isFile = (p) => tree.isFile(p) && !(siteFiles && (p === '/_redirects' || p === '/_headers'));
|
|
124
1051
|
const q = url.indexOf('?');
|
|
125
1052
|
const hash = url.indexOf('#');
|
|
126
1053
|
const end = Math.min(q === -1 ? url.length : q, hash === -1 ? url.length : hash);
|
|
127
1054
|
const rawPath = url.slice(0, end);
|
|
128
1055
|
if (options.liveReload && rawPath === RELOAD_PATH) {
|
|
129
1056
|
if (method === 'HEAD')
|
|
130
|
-
return finish(200, {
|
|
1057
|
+
return finish(200, { ...STREAM_HEADERS }, undefined);
|
|
131
1058
|
return options.liveReload.attach(res, base); // not access-logged: one long request per open page
|
|
132
1059
|
}
|
|
1060
|
+
if (options.liveReload && rawPath === RELOAD_SCRIPT_PATH) {
|
|
1061
|
+
// not access-logged either: every page load fetches it
|
|
1062
|
+
const js = options.liveReload.script;
|
|
1063
|
+
return finish(200, { 'content-type': 'text/javascript; charset=utf-8', 'content-length': Buffer.byteLength(js) }, js, true);
|
|
1064
|
+
}
|
|
133
1065
|
const search = q === -1 ? '' : url.slice(q, hash === -1 || hash < q ? undefined : hash);
|
|
134
|
-
const
|
|
135
|
-
if (!
|
|
1066
|
+
const allSegs = safeSegments(rawPath);
|
|
1067
|
+
if (!allSegs)
|
|
136
1068
|
return page(400, BAD_REQUEST_PAGE);
|
|
137
1069
|
const trailingSlash = rawPath.endsWith('/');
|
|
1070
|
+
// `--base`: the site lives under `mount`; requests outside it are 404 (or redirected into it).
|
|
1071
|
+
const baseNow = typeof options.base === 'function' ? options.base() : options.base;
|
|
1072
|
+
const baseSegs = baseNow === undefined ? [] : (safeSegments(baseNow) ?? []);
|
|
1073
|
+
/** The `--base` prefix of generated `Location`s (`''` without one), percent-encoded. */
|
|
1074
|
+
const mount = baseSegs.length === 0 ? '' : '/' + baseSegs.map(encodeURIComponent).join('/');
|
|
1075
|
+
let segs = allSegs;
|
|
1076
|
+
if (baseSegs.length > 0) {
|
|
1077
|
+
const inside = baseSegs.every((b, i) => allSegs[i] === b);
|
|
1078
|
+
if (inside && allSegs.length === baseSegs.length && !trailingSlash)
|
|
1079
|
+
return finish(301, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
|
|
1080
|
+
if (!inside && allSegs.length === 0 && !options.hideBase)
|
|
1081
|
+
return finish(302, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
|
|
1082
|
+
if (!inside)
|
|
1083
|
+
return page(404, NOT_FOUND_PAGE);
|
|
1084
|
+
segs = allSegs.slice(baseSegs.length);
|
|
1085
|
+
}
|
|
138
1086
|
const vpath = '/' + segs.join('/');
|
|
139
1087
|
// `_headers` patterns match the request path (with its trailing slash).
|
|
140
1088
|
const custom = headersFor(headerRules, vpath + (trailingSlash && segs.length > 0 ? '/' : ''));
|
|
141
1089
|
const sendFile = (status, served) => {
|
|
142
1090
|
const file = tree.get(served);
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
-
const
|
|
1091
|
+
const ext = served.slice(served.lastIndexOf('/') + 1).split('.').slice(1).pop()?.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
1092
|
+
const type = (ext !== undefined ? options.mime?.get(ext) : undefined) ?? mimeTypeFor(served);
|
|
1093
|
+
const live = options.liveReload !== undefined && type.startsWith('text/html') && isNavigation(req.headers);
|
|
1094
|
+
if (live)
|
|
1095
|
+
warnCsp(served, custom['content-security-policy']);
|
|
1096
|
+
const prodNow = typeof options.rewriteBase === 'function' ? options.rewriteBase() : options.rewriteBase;
|
|
1097
|
+
const host = req.headers.host;
|
|
1098
|
+
const rebase = prodNow !== undefined && isRebasedType(type) && host !== undefined && SAFE_HOST.test(host) ? { from: prodNow, to: `http://${host}${mount}` } : undefined;
|
|
1099
|
+
// A `.dcz` sidecar (build --experimental-dictionary): sent when the request offers its dictionary.
|
|
1100
|
+
const delta = live || rebase ? undefined : deltaFor(tree, served, header(req.headers['available-dictionary']), header(req.headers['accept-encoding']));
|
|
1101
|
+
const dictionaryVary = tree.isFile(`${served}.dcz`);
|
|
1102
|
+
// A deflated zip entry goes to a gzip client as is, wrapped in a gzip header and trailer (not for a
|
|
1103
|
+
// range request: ranges are served from the identity body).
|
|
1104
|
+
const deflated = !live && !delta && !rebase && req.headers.range === undefined && acceptsGzip(req.headers['accept-encoding']) ? options.content?.deflated?.(served) : undefined;
|
|
1105
|
+
let body;
|
|
1106
|
+
try {
|
|
1107
|
+
body = deflated ? gzipMember(deflated.deflate, deflated.crc, deflated.size) : (options.content?.read(served) ?? file.bytes);
|
|
1108
|
+
}
|
|
1109
|
+
catch (e) {
|
|
1110
|
+
options.log?.(`error: ${e instanceof SitefileError ? e.message : String(e)}`);
|
|
1111
|
+
return page(500, ERROR_PAGE);
|
|
1112
|
+
}
|
|
1113
|
+
if (rebase)
|
|
1114
|
+
body = rewriteBaseUrls(body, rebase.from, rebase.to);
|
|
1115
|
+
if (live)
|
|
1116
|
+
body = injectReloadScript(body);
|
|
1117
|
+
// Otherwise: a precompressed `<path>.br` / `<path>.gz` the client accepts (br first), else gzip on the fly
|
|
1118
|
+
// under --compress. Range requests, live pages, rebased pages and deltas are never compressed here.
|
|
1119
|
+
const ae = req.headers['accept-encoding'];
|
|
1120
|
+
const plain = !deflated && !delta && !rebase && status === 200;
|
|
1121
|
+
const hasBr = plain && isFile(`${served}.br`);
|
|
1122
|
+
const hasGz = plain && isFile(`${served}.gz`);
|
|
1123
|
+
const onTheFly = plain && !!options.compress && isCompressible(type) && body.byteLength >= 1024;
|
|
1124
|
+
const negotiated = !live && (hasBr || hasGz || onTheFly);
|
|
1125
|
+
let coding;
|
|
1126
|
+
if (negotiated && req.headers.range === undefined) {
|
|
1127
|
+
if (hasBr && acceptsEncoding(ae, 'br'))
|
|
1128
|
+
[coding, body] = ['br', tree.get(`${served}.br`).bytes];
|
|
1129
|
+
else if (hasGz && acceptsEncoding(ae, 'gzip'))
|
|
1130
|
+
[coding, body] = ['gzip', tree.get(`${served}.gz`).bytes];
|
|
1131
|
+
else if (onTheFly && acceptsEncoding(ae, 'gzip'))
|
|
1132
|
+
[coding, body] = ['gzip', gzipped(file.digest, body)];
|
|
1133
|
+
}
|
|
1134
|
+
const varyOn = dictionaryVary ? 'accept-encoding, available-dictionary' : 'accept-encoding';
|
|
1135
|
+
const vary = deflated || negotiated || dictionaryVary ? { vary: varyOn } : {};
|
|
1136
|
+
const encoding = deflated ? { 'content-encoding': 'gzip', ...vary } : coding ? { 'content-encoding': coding, ...vary } : vary;
|
|
146
1137
|
if (status !== 200)
|
|
147
|
-
return finish(status, { 'content-type': type, 'content-length': body.byteLength, ...custom }, body);
|
|
148
|
-
|
|
149
|
-
const
|
|
1138
|
+
return finish(status, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...custom }, body);
|
|
1139
|
+
const preview = cacheControlFor(type, options.cache);
|
|
1140
|
+
const cc = preview === undefined ? {} : { 'cache-control': preview };
|
|
1141
|
+
// An injected page, a rebased page, a compressed response and a delta are other representations of the
|
|
1142
|
+
// file: they get their own ETags.
|
|
1143
|
+
const etag = `"${file.digest.replace(/^sha256:/, '')}${rebase ? '-rebased' : ''}${live ? '-live' : ''}${deflated ? '-gzip' : coding ? `-${coding}` : ''}${delta ? '-dcz' : ''}"`;
|
|
1144
|
+
const modified = options.lastModified?.();
|
|
1145
|
+
const lm = modified === undefined ? {} : { 'last-modified': httpDate(modified) };
|
|
150
1146
|
if (etagMatches(req.headers['if-none-match'], etag))
|
|
151
|
-
return finish(304, { ...custom, etag }, undefined);
|
|
152
|
-
|
|
1147
|
+
return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
|
|
1148
|
+
// If-Modified-Since only counts without If-None-Match (RFC 9110 section 13.2.2).
|
|
1149
|
+
const ims = req.headers['if-none-match'] === undefined ? req.headers['if-modified-since'] : undefined;
|
|
1150
|
+
const since = ims === undefined ? undefined : parseHttpDate(ims);
|
|
1151
|
+
if (modified !== undefined && since !== undefined && modified <= since)
|
|
1152
|
+
return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
|
|
1153
|
+
// The delta is sent whole (no byte ranges of an encoded body).
|
|
1154
|
+
if (delta)
|
|
1155
|
+
return finish(200, { 'content-type': type, 'content-length': delta.byteLength, ...cc, ...custom, ...vary, 'content-encoding': 'dcz', etag, ...lm }, delta);
|
|
1156
|
+
// A single byte range of a GET (`If-Range` must name this ETag); anything else gets the whole file.
|
|
1157
|
+
const ifRange = req.headers['if-range'];
|
|
1158
|
+
const range = method === 'GET' && (ifRange === undefined || ifRange.trim() === etag) ? byteRange(req.headers.range, body.byteLength) : undefined;
|
|
1159
|
+
if (range === 'unsatisfiable') {
|
|
1160
|
+
return finish(416, { ...custom, ...vary, 'accept-ranges': 'bytes', 'content-range': `bytes */${body.byteLength}`, 'content-length': 0 }, undefined);
|
|
1161
|
+
}
|
|
1162
|
+
if (range !== undefined) {
|
|
1163
|
+
const [start, end] = range;
|
|
1164
|
+
const part = body.subarray(start, end + 1);
|
|
1165
|
+
return finish(206, { 'content-type': type, 'content-length': part.byteLength, ...cc, ...encoding, ...custom, etag, ...lm, 'accept-ranges': 'bytes', 'content-range': `bytes ${start}-${end}/${body.byteLength}` }, part);
|
|
1166
|
+
}
|
|
1167
|
+
finish(200, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...cc, ...custom, etag, ...lm, 'accept-ranges': 'bytes' }, body);
|
|
153
1168
|
};
|
|
154
1169
|
/** The file for a path: exact, `<path>.html` (clean URLs), or `<dir>/index.html` with a trailing slash. */
|
|
155
1170
|
const resolve = (p, slash) => {
|
|
@@ -164,26 +1179,75 @@ export function createSiteServer(site, options = {}) {
|
|
|
164
1179
|
}
|
|
165
1180
|
return undefined;
|
|
166
1181
|
};
|
|
1182
|
+
const one = (k) => {
|
|
1183
|
+
const v = req.headers[k];
|
|
1184
|
+
return Array.isArray(v) ? v.join(', ') : v;
|
|
1185
|
+
};
|
|
1186
|
+
const ruleRequest = { search, acceptLanguage: one('accept-language'), cookie: one('cookie'), country: options.country };
|
|
1187
|
+
/** Answer from `target` (an http(s) URL) under the proxy policy; a refusal or a failed fetch is a 502. */
|
|
1188
|
+
const proxyTo = (target, from) => {
|
|
1189
|
+
note = ` \u2192 ${redactUrl(target)} (proxy, ${from})`;
|
|
1190
|
+
const headers = {};
|
|
1191
|
+
for (const k of PROXY_REQUEST_HEADERS) {
|
|
1192
|
+
const v = one(k);
|
|
1193
|
+
if (v !== undefined)
|
|
1194
|
+
headers[k] = v;
|
|
1195
|
+
}
|
|
1196
|
+
const policy = options.proxy?.policy ?? { ...DEFAULT_FETCH_POLICY, network: { strict: true } };
|
|
1197
|
+
fetchRemote(target, policy, undefined, { method: method === 'HEAD' ? 'HEAD' : 'GET', raw: true, headers }).then((r) => {
|
|
1198
|
+
const out = {};
|
|
1199
|
+
for (const [n, vs] of r.headers ?? [])
|
|
1200
|
+
if (!HOP_BY_HOP.has(n))
|
|
1201
|
+
out[n] = vs.length === 1 ? vs[0] : [...vs];
|
|
1202
|
+
const upstreamLength = r.headers?.find(([n]) => n === 'content-length')?.[1][0];
|
|
1203
|
+
out['content-length'] = method === 'HEAD' && upstreamLength !== undefined ? upstreamLength : String(r.bytes.byteLength);
|
|
1204
|
+
finish(r.status ?? 502, out, r.bytes);
|
|
1205
|
+
}, (e) => {
|
|
1206
|
+
const why = isSitefileError(e) ? `error[${e.code}]: ${e.detail}` : `error: ${String(e)}`;
|
|
1207
|
+
note += ` ${why}`;
|
|
1208
|
+
const text = `502 Bad Gateway: ${why}\n`;
|
|
1209
|
+
finish(502, { 'content-type': 'text/plain; charset=utf-8', 'content-length': Buffer.byteLength(text) }, text);
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1212
|
+
// `--proxy` routes come first: they are what this server is asked to front.
|
|
1213
|
+
for (const route of options.proxy?.routes ?? []) {
|
|
1214
|
+
const inside = route.prefix === '/' || vpath === route.prefix || vpath.startsWith(`${route.prefix}/`);
|
|
1215
|
+
if (!inside)
|
|
1216
|
+
continue;
|
|
1217
|
+
const rest = (route.prefix === '/' ? vpath : vpath.slice(route.prefix.length)) + (trailingSlash && segs.length > 0 ? '/' : '');
|
|
1218
|
+
const encoded = rest.split('/').map((p) => encodeURIComponent(p)).join('/');
|
|
1219
|
+
return proxyTo(route.target.replace(/\/$/, '') + encoded + search, `--proxy ${route.prefix}`);
|
|
1220
|
+
}
|
|
167
1221
|
/** Apply the first matching `_redirects` rule (forced ones, or the others); false when none applies. */
|
|
168
1222
|
const redirect = (forced) => {
|
|
169
1223
|
for (const r of redirects) {
|
|
170
1224
|
if (r.force !== forced)
|
|
171
1225
|
continue;
|
|
172
|
-
const
|
|
173
|
-
if (
|
|
1226
|
+
const caps = matchRule(r, vpath, ruleRequest);
|
|
1227
|
+
if (caps === undefined)
|
|
174
1228
|
continue;
|
|
175
|
-
const target = r.
|
|
176
|
-
if (r.status
|
|
177
|
-
|
|
1229
|
+
const target = substituteTarget(r.to, caps);
|
|
1230
|
+
if (!isRewriteStatus(r.status)) {
|
|
1231
|
+
// A rule that matches query parameters passes on only what its target names.
|
|
1232
|
+
const mounted = target.startsWith('/') ? mount + target : target;
|
|
1233
|
+
const location = mounted.includes('?') || r.query.length > 0 ? mounted : mounted + search;
|
|
1234
|
+
note = ` \u2192 ${location} (_redirects:${r.line})`;
|
|
1235
|
+
finish(r.status, { location, 'content-length': 0 }, undefined);
|
|
178
1236
|
return true;
|
|
179
1237
|
}
|
|
180
|
-
|
|
1238
|
+
if (r.status === 200 && /^https?:\/\//i.test(target)) {
|
|
1239
|
+
// A proxy rule (#172): the request's query string goes along unless the target has one.
|
|
1240
|
+
proxyTo(target.includes('?') || r.query.length > 0 ? target : target + search, `_redirects:${r.line}`);
|
|
1241
|
+
return true;
|
|
1242
|
+
}
|
|
1243
|
+
// 200 (rewrite), 404, 410 and 451: serve the target path's file with that status.
|
|
181
1244
|
const tq = target.indexOf('?');
|
|
182
1245
|
const tpath = tq === -1 ? target : target.slice(0, tq);
|
|
183
1246
|
const tsegs = safeSegments(tpath);
|
|
184
1247
|
const served = tsegs ? resolve('/' + tsegs.join('/'), tpath.endsWith('/')) : undefined;
|
|
185
1248
|
if (served === undefined)
|
|
186
1249
|
continue;
|
|
1250
|
+
note = ` \u2192 ${encodePath(served)} (_redirects:${r.line})`;
|
|
187
1251
|
sendFile(r.status, served);
|
|
188
1252
|
return true;
|
|
189
1253
|
}
|
|
@@ -191,22 +1255,115 @@ export function createSiteServer(site, options = {}) {
|
|
|
191
1255
|
};
|
|
192
1256
|
if (redirect(true))
|
|
193
1257
|
return;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
1258
|
+
const handling = profile?.htmlHandling;
|
|
1259
|
+
let served;
|
|
1260
|
+
if (handling !== undefined) {
|
|
1261
|
+
// `--html-handling` (Cloudflare's modes): one canonical spelling per page, the others redirect to it.
|
|
1262
|
+
const go = (to, slash) => {
|
|
1263
|
+
const path = to.length === 0 ? '/' : '/' + to.map(encodeURIComponent).join('/') + (slash ? '/' : '');
|
|
1264
|
+
finish(profile.redirectStatus, { location: mount + path + search, 'content-length': 0 }, undefined);
|
|
1265
|
+
};
|
|
1266
|
+
const last = segs[segs.length - 1];
|
|
1267
|
+
const index = vpath === '/' ? '/index.html' : `${vpath}/index.html`;
|
|
1268
|
+
const hasIndex = isFile(index);
|
|
1269
|
+
const hasHtml = segs.length > 0 && isFile(`${vpath}.html`);
|
|
1270
|
+
if (!trailingSlash && last !== undefined && last.endsWith('.html') && isFile(vpath) && handling !== 'none') {
|
|
1271
|
+
// `/x.html` and `/x/index.html` are spelled out: send them to the clean form.
|
|
1272
|
+
const dir = segs.slice(0, -1);
|
|
1273
|
+
if (last === 'index.html')
|
|
1274
|
+
return go(dir, dir.length > 0 && handling !== 'drop-slash');
|
|
1275
|
+
return go([...dir, last.slice(0, -'.html'.length)], handling === 'force-slash');
|
|
1276
|
+
}
|
|
1277
|
+
if (!trailingSlash && isFile(vpath))
|
|
1278
|
+
served = vpath;
|
|
1279
|
+
else if (handling === 'none')
|
|
1280
|
+
served = trailingSlash && hasIndex ? index : undefined;
|
|
1281
|
+
else if (segs.length === 0)
|
|
1282
|
+
served = hasIndex ? index : undefined;
|
|
1283
|
+
else if (handling === 'auto') {
|
|
1284
|
+
if (hasIndex) {
|
|
1285
|
+
if (!trailingSlash)
|
|
1286
|
+
return go(segs, true);
|
|
1287
|
+
served = index;
|
|
1288
|
+
}
|
|
1289
|
+
else if (hasHtml) {
|
|
1290
|
+
if (trailingSlash)
|
|
1291
|
+
return go(segs, false);
|
|
1292
|
+
served = `${vpath}.html`;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
else if (hasIndex || hasHtml) {
|
|
1296
|
+
const slash = handling === 'force-slash';
|
|
1297
|
+
if (trailingSlash !== slash)
|
|
1298
|
+
return go(segs, slash);
|
|
1299
|
+
served = slash ? (hasIndex ? index : `${vpath}.html`) : hasHtml ? `${vpath}.html` : index;
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
else
|
|
1303
|
+
served = resolve(vpath, trailingSlash);
|
|
1304
|
+
if (handling === undefined && served === undefined && !trailingSlash && tree.isDirectory(vpath)) {
|
|
1305
|
+
const location = mount + '/' + segs.map(encodeURIComponent).join('/') + '/' + search;
|
|
197
1306
|
return finish(301, { location, 'content-length': 0 }, undefined);
|
|
198
1307
|
}
|
|
199
1308
|
if (served === undefined && redirect(false))
|
|
200
1309
|
return;
|
|
201
|
-
|
|
202
|
-
|
|
1310
|
+
// `/about/` when only `/about.html` answers: redirect to the clean URL `/about` (relative links in the
|
|
1311
|
+
// page then resolve as they do at `/about`). `_redirects` rules for the path come first.
|
|
1312
|
+
if (handling === undefined && profile?.slashHtml !== 'not-found' && served === undefined && trailingSlash && segs.length > 0 && isFile(`${vpath}.html`)) {
|
|
1313
|
+
const location = mount + '/' + segs.map(encodeURIComponent).join('/') + search;
|
|
1314
|
+
return finish(301, { location, 'content-length': 0 }, undefined);
|
|
1315
|
+
}
|
|
1316
|
+
if (served === undefined && options.spa && isNavigation(req.headers) && !(options.spaExclude ?? []).some((g) => globMatch(g, vpath + (trailingSlash && segs.length > 0 ? '/' : '')))) {
|
|
1317
|
+
served = spaFallback(segs, trailingSlash, isFile, options.spaFallback);
|
|
1318
|
+
if (served !== undefined)
|
|
1319
|
+
note = ` \u2192 ${encodePath(served)} (spa fallback)`;
|
|
1320
|
+
}
|
|
1321
|
+
if (served !== undefined && note === '' && served === `${vpath}.html`)
|
|
1322
|
+
note = ` \u2192 ${encodePath(served)} (clean URL)`;
|
|
203
1323
|
if (served !== undefined)
|
|
204
1324
|
return sendFile(200, served);
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
1325
|
+
// The nearest 404.html: in the request's directory, then each parent up to the root (only the
|
|
1326
|
+
// root one for a profile whose host does not look further).
|
|
1327
|
+
const dirs = trailingSlash ? segs : segs.slice(0, -1);
|
|
1328
|
+
for (let n = profile?.notFound === 'root' ? 0 : dirs.length; n >= 0; n--) {
|
|
1329
|
+
const notFound = `/${dirs.slice(0, n).map((d) => d + '/').join('')}404.html`;
|
|
1330
|
+
if (isFile(notFound)) {
|
|
1331
|
+
note = ` \u2192 ${encodePath(notFound)}`;
|
|
1332
|
+
return sendFile(404, notFound);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
// Cloudflare Pages: a site without a 404.html is taken for a single-page app.
|
|
1336
|
+
if (profile?.notFound === 'index' && isFile('/index.html')) {
|
|
1337
|
+
note = ' \u2192 /index.html (no 404.html)';
|
|
1338
|
+
return sendFile(200, '/index.html');
|
|
1339
|
+
}
|
|
1340
|
+
const misses = options.devNotFound ? nearMisses(tree, isFile, vpath, redirects, ruleRequest) : [];
|
|
1341
|
+
page(404, misses.length === 0 ? NOT_FOUND_PAGE : nearMissPage(vpath, misses, mount), custom);
|
|
208
1342
|
};
|
|
209
|
-
|
|
1343
|
+
// HTTPS when a certificate is given (same handler; an https.Server has the http.Server API).
|
|
1344
|
+
const server = options.tls
|
|
1345
|
+
? https.createServer({ cert: Buffer.from(options.tls.cert), key: Buffer.from(options.tls.key) }, handler)
|
|
1346
|
+
: http.createServer(handler);
|
|
1347
|
+
const limit = options.maxConnectionsPerIp ?? 0;
|
|
1348
|
+
if (limit > 0) {
|
|
1349
|
+
const perIp = new Map();
|
|
1350
|
+
server.on('connection', (socket) => {
|
|
1351
|
+
const ip = socket.remoteAddress ?? '';
|
|
1352
|
+
if (!options.limitLoopback && isLoopbackAddress(ip))
|
|
1353
|
+
return;
|
|
1354
|
+
const n = (perIp.get(ip) ?? 0) + 1;
|
|
1355
|
+
perIp.set(ip, n);
|
|
1356
|
+
if (n > limit)
|
|
1357
|
+
busy.add(socket);
|
|
1358
|
+
socket.once('close', () => {
|
|
1359
|
+
const left = (perIp.get(ip) ?? 1) - 1;
|
|
1360
|
+
if (left === 0)
|
|
1361
|
+
perIp.delete(ip);
|
|
1362
|
+
else
|
|
1363
|
+
perIp.set(ip, left);
|
|
1364
|
+
});
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
210
1367
|
server.on('clientError', (_err, socket) => {
|
|
211
1368
|
if (socket.writable)
|
|
212
1369
|
socket.end('HTTP/1.1 400 Bad Request\r\nconnection: close\r\ncontent-length: 0\r\n\r\n');
|
|
@@ -239,8 +1396,35 @@ export function closeServer(server) {
|
|
|
239
1396
|
server.closeAllConnections();
|
|
240
1397
|
});
|
|
241
1398
|
}
|
|
242
|
-
|
|
1399
|
+
/**
|
|
1400
|
+
* The addresses other machines can reach a server bound to all interfaces at: the up, non-loopback
|
|
1401
|
+
* interface addresses, IPv4 for `0.0.0.0`, IPv4 then IPv6 for `::` (IPv6 link-local `fe80::/10`
|
|
1402
|
+
* left out: it needs a zone), each family sorted as text, without duplicates. Empty for any other bind.
|
|
1403
|
+
*/
|
|
1404
|
+
export function networkAddresses(bindHost) {
|
|
1405
|
+
if (bindHost !== '0.0.0.0' && bindHost !== '::')
|
|
1406
|
+
return [];
|
|
1407
|
+
const v4 = new Set();
|
|
1408
|
+
const v6 = new Set();
|
|
1409
|
+
for (const list of Object.values(os.networkInterfaces())) {
|
|
1410
|
+
for (const a of list ?? []) {
|
|
1411
|
+
if (a.internal)
|
|
1412
|
+
continue;
|
|
1413
|
+
if (a.family === 'IPv4')
|
|
1414
|
+
v4.add(a.address);
|
|
1415
|
+
else if (bindHost === '::' && !/^fe[89ab]/i.test(a.address))
|
|
1416
|
+
v6.add(a.address.toLowerCase());
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1420
|
+
return [...sorted(v4), ...sorted(v6)];
|
|
1421
|
+
}
|
|
1422
|
+
/** {@link networkAddresses} as URLs. */
|
|
1423
|
+
export function networkUrls(bindHost, port, scheme = 'http') {
|
|
1424
|
+
return networkAddresses(bindHost).map((a) => formatUrl(a, port, scheme));
|
|
1425
|
+
}
|
|
1426
|
+
export function formatUrl(host, port, scheme = 'http') {
|
|
243
1427
|
const shown = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
|
|
244
|
-
return
|
|
1428
|
+
return `${scheme}://${shown.includes(':') ? `[${shown}]` : shown}:${port}/`;
|
|
245
1429
|
}
|
|
246
1430
|
//# sourceMappingURL=server.js.map
|