@johnhenry/sitefile 0.0.3 → 0.0.5
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 +59 -0
- package/README.md +5 -4
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +6 -3
- package/lib/src/canonical.js +25 -11
- package/lib/src/cli/index.d.ts +4 -1
- package/lib/src/cli/index.js +5 -2
- package/lib/src/cli/serve-worker.js +76 -3
- package/lib/src/cli/servers.d.ts +7 -1
- package/lib/src/cli/servers.js +56 -17
- package/lib/src/executor.js +42 -5
- package/lib/src/explain.js +2 -1
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/language/ast.d.ts +14 -4
- package/lib/src/language/parser.js +18 -4
- package/lib/src/language/validate.js +3 -0
- package/lib/src/links.d.ts +14 -0
- package/lib/src/links.js +22 -4
- package/lib/src/planner.d.ts +18 -0
- package/lib/src/planner.js +39 -0
- package/lib/src/precompress.d.ts +11 -2
- package/lib/src/precompress.js +36 -5
- package/lib/src/reload-client.js +116 -1
- package/lib/src/resources/archive.d.ts +1 -1
- package/lib/src/resources/archive.js +24 -13
- package/lib/src/serve-auth.d.ts +3 -2
- package/lib/src/serve-auth.js +14 -6
- package/lib/src/server.d.ts +92 -1
- package/lib/src/server.js +205 -7
- package/lib/src/servers.d.ts +6 -0
- package/lib/src/site.d.ts +6 -2
- package/lib/src/site.js +21 -8
- package/package.json +1 -1
package/lib/src/links.js
CHANGED
|
@@ -505,6 +505,16 @@ export function integrityTags(text) {
|
|
|
505
505
|
* there is no `</head>`. Comments, declarations and raw text are skipped as in {@link scanHtml}.
|
|
506
506
|
*/
|
|
507
507
|
export function canonicalSlot(text) {
|
|
508
|
+
const h = headLinks(text);
|
|
509
|
+
return h.canonical ? 'has' : h.at;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Where links go in a page's head and which it already has (ASCII case-insensitive `rel` tokens). Comments,
|
|
513
|
+
* declarations and raw text are skipped as in {@link scanHtml}.
|
|
514
|
+
*/
|
|
515
|
+
export function headLinks(text) {
|
|
516
|
+
let canonical = false;
|
|
517
|
+
let hreflang = false;
|
|
508
518
|
const n = text.length;
|
|
509
519
|
let i = 0;
|
|
510
520
|
while (i < n) {
|
|
@@ -521,7 +531,7 @@ export function canonicalSlot(text) {
|
|
|
521
531
|
if (next === '/') {
|
|
522
532
|
const end = i + 6;
|
|
523
533
|
if (lowerAscii(text.slice(i + 2, end)) === 'head' && (end >= n || isWs(text[end]) || text[end] === '/' || text[end] === '>'))
|
|
524
|
-
return i;
|
|
534
|
+
return { at: i, canonical, hreflang };
|
|
525
535
|
}
|
|
526
536
|
if (next === '!' || next === '?' || next === '/') {
|
|
527
537
|
const j = text.indexOf('>', i + 2);
|
|
@@ -538,6 +548,7 @@ export function canonicalSlot(text) {
|
|
|
538
548
|
const tag = lowerAscii(text.slice(i + 1, j));
|
|
539
549
|
i = j;
|
|
540
550
|
let rel;
|
|
551
|
+
let lang = false;
|
|
541
552
|
for (;;) {
|
|
542
553
|
while (i < n && (isWs(text[i]) || text[i] === '/'))
|
|
543
554
|
i++;
|
|
@@ -552,6 +563,8 @@ export function canonicalSlot(text) {
|
|
|
552
563
|
while (i < n && !isWs(text[i]) && text[i] !== '/' && text[i] !== '>' && text[i] !== '=')
|
|
553
564
|
i++;
|
|
554
565
|
const name = lowerAscii(text.slice(nameStart, i));
|
|
566
|
+
if (name === 'hreflang')
|
|
567
|
+
lang = true;
|
|
555
568
|
let k = i;
|
|
556
569
|
while (k < n && isWs(text[k]))
|
|
557
570
|
k++;
|
|
@@ -578,12 +591,17 @@ export function canonicalSlot(text) {
|
|
|
578
591
|
if (name === 'rel' && rel === undefined)
|
|
579
592
|
rel = text.slice(start, end);
|
|
580
593
|
}
|
|
581
|
-
if (tag === 'link' && rel !== undefined
|
|
582
|
-
|
|
594
|
+
if (tag === 'link' && rel !== undefined) {
|
|
595
|
+
const tokens = lowerAscii(decodeHtmlText(rel)).split(/[ \t\n\r\f]+/);
|
|
596
|
+
if (tokens.includes('canonical'))
|
|
597
|
+
canonical = true;
|
|
598
|
+
if (lang && tokens.includes('alternate'))
|
|
599
|
+
hreflang = true;
|
|
600
|
+
}
|
|
583
601
|
if (RAW_TEXT.has(tag))
|
|
584
602
|
i = indexOfCloseTag(text, tag, i);
|
|
585
603
|
}
|
|
586
|
-
return undefined;
|
|
604
|
+
return { at: undefined, canonical, hreflang };
|
|
587
605
|
}
|
|
588
606
|
/** The inline scripts and styles of an HTML text (comments and other raw text skipped as in {@link scanHtml}). */
|
|
589
607
|
export function inlineBlocks(text) {
|
package/lib/src/planner.d.ts
CHANGED
|
@@ -127,6 +127,20 @@ export interface CspSpec {
|
|
|
127
127
|
}
|
|
128
128
|
/** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
|
|
129
129
|
export declare const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
|
|
130
|
+
/**
|
|
131
|
+
* LANGUAGES, evaluated, as CANONICAL and SITEMAP see it: the language folders, the DEFAULT language, and the
|
|
132
|
+
* stage's `RENDER … FOR` lines before them (without BY or PAGE), whose documents may set `lang` and
|
|
133
|
+
* `translationKey`.
|
|
134
|
+
*/
|
|
135
|
+
export interface LanguagesSpec {
|
|
136
|
+
readonly codes: readonly string[];
|
|
137
|
+
readonly default?: string;
|
|
138
|
+
readonly sources: ReadonlyArray<{
|
|
139
|
+
readonly as: string;
|
|
140
|
+
readonly list: string;
|
|
141
|
+
readonly dest: Operand;
|
|
142
|
+
}>;
|
|
143
|
+
}
|
|
130
144
|
export type Operation = {
|
|
131
145
|
/** Report the references in the tree's HTML and CSS files that point at nothing. */
|
|
132
146
|
readonly kind: 'CHECKLINKS';
|
|
@@ -159,6 +173,8 @@ export type Operation = {
|
|
|
159
173
|
/** The EXPORT path: a page's URL is its path below it. */
|
|
160
174
|
readonly root: string;
|
|
161
175
|
readonly span: SourceSpan;
|
|
176
|
+
/** With LANGUAGES: hreflang alternates too. */
|
|
177
|
+
readonly languages?: LanguagesSpec;
|
|
162
178
|
} | {
|
|
163
179
|
/** Write a `.gz` sidecar for each matching compressible file of at least `min` bytes, when smaller. */
|
|
164
180
|
readonly kind: 'PRECOMPRESS';
|
|
@@ -186,6 +202,8 @@ export type Operation = {
|
|
|
186
202
|
readonly dest: string;
|
|
187
203
|
readonly overwrite: boolean;
|
|
188
204
|
readonly span: SourceSpan;
|
|
205
|
+
/** With LANGUAGES: `xhtml:link` alternates too. */
|
|
206
|
+
readonly languages?: LanguagesSpec;
|
|
189
207
|
} | {
|
|
190
208
|
/** An Atom feed of a list import; `link` is interpolated per element (`${item…}`). */
|
|
191
209
|
readonly kind: 'FEED';
|
package/lib/src/planner.js
CHANGED
|
@@ -3,6 +3,7 @@ import { importedStage, isFragment, isImageBase, isInline, stageNames } from './
|
|
|
3
3
|
import { normalizeLocal, normalizeVirtual } from './paths.js';
|
|
4
4
|
import { parseRef } from './ref.js';
|
|
5
5
|
import { checkPattern } from './fingerprint.js';
|
|
6
|
+
import { isLanguageTag } from './hreflang.js';
|
|
6
7
|
import { checkBaseUrl, checkFieldUri, checkCspPolicy, checkHeaderName, checkHeaderValue, checkMimeExtension, checkMimeType, checkRedirectTarget, checkSitePath, pageUrl, parseFeedDate, robotsTxt, securityTxt } from './site.js';
|
|
7
8
|
import { coerce, evaluateOperand } from './values.js';
|
|
8
9
|
import { isGitUri, parseGitUri } from './resources/git.js';
|
|
@@ -28,6 +29,7 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
28
29
|
const sitemapUrls = [];
|
|
29
30
|
const robots = [];
|
|
30
31
|
let csp;
|
|
32
|
+
let languages;
|
|
31
33
|
const mimes = new Map();
|
|
32
34
|
const warnings = [];
|
|
33
35
|
const declaredArgs = new Set();
|
|
@@ -304,6 +306,26 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
304
306
|
});
|
|
305
307
|
break;
|
|
306
308
|
}
|
|
309
|
+
case 'LANGUAGES': {
|
|
310
|
+
if (languages)
|
|
311
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES given twice (line ${languages.span.line} already lists the languages)`, ins.span);
|
|
312
|
+
const codes = [];
|
|
313
|
+
for (const o of ins.codes) {
|
|
314
|
+
const code = languageTag(evaluateOperand(o, vars), o.span);
|
|
315
|
+
if (codes.some((c) => c.toLowerCase() === code.toLowerCase()))
|
|
316
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${code}' is listed twice`, o.span);
|
|
317
|
+
codes.push(code);
|
|
318
|
+
}
|
|
319
|
+
let dflt;
|
|
320
|
+
if (ins.default) {
|
|
321
|
+
dflt = languageTag(evaluateOperand(ins.default, vars), ins.default.span);
|
|
322
|
+
const d = dflt;
|
|
323
|
+
if (!codes.some((c) => c === d))
|
|
324
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES … DEFAULT ${d}: '${d}' is not one of the languages listed (${codes.join(' ')})`, ins.default.span);
|
|
325
|
+
}
|
|
326
|
+
languages = { codes, ...(dflt !== undefined ? { default: dflt } : {}), span: ins.span };
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
307
329
|
case 'CSP': {
|
|
308
330
|
if (csp)
|
|
309
331
|
throw new SitefileError('E_VALIDATION', `CSP given twice (line ${csp.span.line} already sets the policy)`, ins.span);
|
|
@@ -359,6 +381,17 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
359
381
|
if (op.kind === 'CHECKLINKS')
|
|
360
382
|
st.operations[i] = { ...op, root: exportPath ?? '/', redirects: redirects.map((r) => r.from) };
|
|
361
383
|
});
|
|
384
|
+
if (languages) {
|
|
385
|
+
// Each CANONICAL and SITEMAP sees the stage's RENDER … FOR lines before it.
|
|
386
|
+
const sources = [];
|
|
387
|
+
st.operations.forEach((op, i) => {
|
|
388
|
+
if (op.kind === 'RENDER' && op.each && op.each.by === undefined && op.each.page === undefined)
|
|
389
|
+
sources.push({ as: op.each.as, list: op.each.list, dest: op.each.dest });
|
|
390
|
+
if (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') {
|
|
391
|
+
st.operations[i] = { ...op, languages: { codes: languages.codes, ...(languages.default !== undefined ? { default: languages.default } : {}), sources: [...sources] } };
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
362
395
|
}
|
|
363
396
|
// An unnamed stage can be neither a FROM base nor a COPY --from source; only the last one is useful (EXPORT reads it).
|
|
364
397
|
for (const st of stages.slice(0, -1)) {
|
|
@@ -455,6 +488,12 @@ function minSize(op, vars) {
|
|
|
455
488
|
}
|
|
456
489
|
return Number(raw);
|
|
457
490
|
}
|
|
491
|
+
/** A LANGUAGES code: a basic BCP 47 tag (`E_VALIDATION` otherwise). */
|
|
492
|
+
function languageTag(raw, span) {
|
|
493
|
+
if (!isLanguageTag(raw))
|
|
494
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${raw}' is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
|
|
495
|
+
return raw;
|
|
496
|
+
}
|
|
458
497
|
/** `TO <dest>` of SITEMAP/FEED or `MANIFEST <dest>` of FINGERPRINT (a file path), or the default. */
|
|
459
498
|
function fileDest(op, vars, fallback, what) {
|
|
460
499
|
if (!op)
|
package/lib/src/precompress.d.ts
CHANGED
|
@@ -1,18 +1,27 @@
|
|
|
1
1
|
import type { SourceSpan } from './errors.js';
|
|
2
|
+
import type { PrecompressFormat } from './language/ast.js';
|
|
2
3
|
import { type Tree } from './tree.js';
|
|
3
4
|
/** Extensions (lowercase, after the last dot) of the file types PRECOMPRESS compresses: text, scripts, data, fonts without their own compression. */
|
|
4
5
|
export declare const COMPRESSIBLE: Set<string>;
|
|
5
6
|
/** Whether a path names a compressible file type (by its extension, ASCII case-insensitive). */
|
|
6
7
|
export declare function compressible(path: string): boolean;
|
|
8
|
+
/** The Brotli encoder version rust/vendor/brotli holds; br sidecars match the Rust port's only while Node bundles it. */
|
|
9
|
+
export declare const BROTLI_VERSION = "1.2.0";
|
|
10
|
+
/** `data` as Brotli: quality 11, window 22 (4 MiB), generic mode, one FINISH over the whole input (rust/src/brotli.rs). */
|
|
11
|
+
export declare function brotli(data: Uint8Array): Uint8Array;
|
|
12
|
+
/** The file a sidecar compresses: `path` without its `.gz` or `.br`. */
|
|
13
|
+
export declare function sidecarSource(path: string): string;
|
|
7
14
|
export interface PrecompressOp {
|
|
15
|
+
readonly formats: readonly PrecompressFormat[];
|
|
8
16
|
readonly patterns: readonly string[];
|
|
9
17
|
readonly min: number;
|
|
10
18
|
readonly overwrite: boolean;
|
|
11
19
|
readonly span: SourceSpan;
|
|
12
20
|
}
|
|
13
21
|
/**
|
|
14
|
-
* The tree with a `<path>.gz
|
|
15
|
-
*
|
|
22
|
+
* The tree with a sidecar per format (`<path>.gz`: gzip, fixed header; `<path>.br`: Brotli) for every file
|
|
23
|
+
* that matches a pattern, is compressible and has at least `min` bytes, when that format compresses it to
|
|
24
|
+
* fewer bytes than it has. Sidecars keep the
|
|
16
25
|
* file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
|
|
17
26
|
* `overwrite`. Warns when no file matches the patterns.
|
|
18
27
|
*/
|
package/lib/src/precompress.js
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
// PRECOMPRESS (docs/LANGUAGE.md, "Precompressed sidecars"): write `<file>.gz` and/or `<file>.br` next to
|
|
2
|
+
// compressible files, for hosts and servers that serve them in place of the file (nginx gzip_static,
|
|
3
|
+
// Caddy precompressed, sirv). Ported as rust/src/precompress.rs. gzip uses the shared deflate encoder
|
|
4
|
+
// (src/deflate.ts); br uses node:zlib's Brotli, and the Rust port compiles the same C encoder at the
|
|
5
|
+
// same version (rust/vendor/brotli, rust/src/brotli.rs) with the same settings, so the sidecars are
|
|
6
|
+
// byte-identical.
|
|
7
|
+
import { brotliCompressSync, constants } from 'node:zlib';
|
|
1
8
|
import { gzip } from './deflate.js';
|
|
2
9
|
import { globMatches } from './fingerprint.js';
|
|
3
10
|
import { makeFile } from './tree.js';
|
|
@@ -12,9 +19,30 @@ export function compressible(path) {
|
|
|
12
19
|
const dot = base.lastIndexOf('.');
|
|
13
20
|
return dot > 0 && COMPRESSIBLE.has(base.slice(dot + 1).toLowerCase());
|
|
14
21
|
}
|
|
22
|
+
/** The Brotli encoder version rust/vendor/brotli holds; br sidecars match the Rust port's only while Node bundles it. */
|
|
23
|
+
export const BROTLI_VERSION = '1.2.0';
|
|
24
|
+
/** `data` as Brotli: quality 11, window 22 (4 MiB), generic mode, one FINISH over the whole input (rust/src/brotli.rs). */
|
|
25
|
+
export function brotli(data) {
|
|
26
|
+
return new Uint8Array(brotliCompressSync(data, {
|
|
27
|
+
params: {
|
|
28
|
+
[constants.BROTLI_PARAM_QUALITY]: 11,
|
|
29
|
+
[constants.BROTLI_PARAM_LGWIN]: 22,
|
|
30
|
+
[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_GENERIC,
|
|
31
|
+
},
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
34
|
+
const ENCODERS = {
|
|
35
|
+
gzip: { ext: '.gz', encode: gzip },
|
|
36
|
+
br: { ext: '.br', encode: brotli },
|
|
37
|
+
};
|
|
38
|
+
/** The file a sidecar compresses: `path` without its `.gz` or `.br`. */
|
|
39
|
+
export function sidecarSource(path) {
|
|
40
|
+
return path.endsWith('.gz') || path.endsWith('.br') ? path.slice(0, -3) : path;
|
|
41
|
+
}
|
|
15
42
|
/**
|
|
16
|
-
* The tree with a `<path>.gz
|
|
17
|
-
*
|
|
43
|
+
* The tree with a sidecar per format (`<path>.gz`: gzip, fixed header; `<path>.br`: Brotli) for every file
|
|
44
|
+
* that matches a pattern, is compressible and has at least `min` bytes, when that format compresses it to
|
|
45
|
+
* fewer bytes than it has. Sidecars keep the
|
|
18
46
|
* file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
|
|
19
47
|
* `overwrite`. Warns when no file matches the patterns.
|
|
20
48
|
*/
|
|
@@ -26,9 +54,12 @@ export function precompress(tree, op, origin, warn) {
|
|
|
26
54
|
for (const [p, node] of matched) {
|
|
27
55
|
if (!compressible(p) || node.bytes.byteLength < op.min)
|
|
28
56
|
continue;
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
57
|
+
for (const format of op.formats) {
|
|
58
|
+
const { ext, encode } = ENCODERS[format];
|
|
59
|
+
const out = encode(node.bytes);
|
|
60
|
+
if (out.byteLength < node.bytes.byteLength)
|
|
61
|
+
files.push([p + ext, makeFile(out, origin, node.mode)]);
|
|
62
|
+
}
|
|
32
63
|
}
|
|
33
64
|
return files.length ? tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span) : tree;
|
|
34
65
|
}
|
package/lib/src/reload-client.js
CHANGED
|
@@ -268,14 +268,128 @@ export const RELOAD_CLIENT = String.raw `(function (options) {
|
|
|
268
268
|
overlay = null;
|
|
269
269
|
}
|
|
270
270
|
|
|
271
|
+
// --sync: this page reports where it is (its path and fragment, its title and, with
|
|
272
|
+
// --sync=scroll, how far down it is) and follows the navigation (and scrolling) of the other open
|
|
273
|
+
// pages, unless a form field has focus. It never sends query strings, form contents, keys or cookies.
|
|
274
|
+
var sync = options.sync === "nav" || options.sync === "scroll";
|
|
275
|
+
var syncScroll = options.sync === "scroll";
|
|
276
|
+
function stored(k) {
|
|
277
|
+
try {
|
|
278
|
+
return sessionStorage.getItem(k);
|
|
279
|
+
} catch (_) {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function store(k, v) {
|
|
284
|
+
try {
|
|
285
|
+
sessionStorage.setItem(k, v);
|
|
286
|
+
} catch (_) {}
|
|
287
|
+
}
|
|
288
|
+
// One ID per tab, kept across its page loads.
|
|
289
|
+
var clientId = sync ? stored("sitefile:client") || "" : "";
|
|
290
|
+
if (sync && !/^[0-9a-f]{16}$/.test(clientId)) {
|
|
291
|
+
var bytes = new Uint8Array(8);
|
|
292
|
+
if (window.crypto && crypto.getRandomValues) crypto.getRandomValues(bytes);
|
|
293
|
+
else for (var b = 0; b < 8; b++) bytes[b] = Math.floor(Math.random() * 256);
|
|
294
|
+
clientId = Array.prototype.map.call(bytes, function (x) { return (x < 16 ? "0" : "") + x.toString(16); }).join("");
|
|
295
|
+
store("sitefile:client", clientId);
|
|
296
|
+
}
|
|
297
|
+
var atKey = "sitefile:at";
|
|
298
|
+
function where() {
|
|
299
|
+
return (location.pathname + location.hash).slice(0, 2048);
|
|
300
|
+
}
|
|
301
|
+
function scrolled() {
|
|
302
|
+
var el = document.scrollingElement || document.documentElement;
|
|
303
|
+
var w = el.scrollWidth - window.innerWidth;
|
|
304
|
+
var h = el.scrollHeight - window.innerHeight;
|
|
305
|
+
var part = function (at, size) { return size > 0 ? Math.min(10000, Math.max(0, Math.round((at / size) * 10000))) : 0; };
|
|
306
|
+
return [part(window.scrollX, w), part(window.scrollY, h)];
|
|
307
|
+
}
|
|
308
|
+
var clientUrl = new URL("client", base).href;
|
|
309
|
+
function report(nav, withScroll) {
|
|
310
|
+
try {
|
|
311
|
+
var body = { id: clientId, url: where(), title: String(document.title || "").slice(0, 200), nav: nav };
|
|
312
|
+
if (withScroll) body.scroll = scrolled();
|
|
313
|
+
fetch(clientUrl, { method: "POST", body: JSON.stringify(body), keepalive: true }).catch(function () {});
|
|
314
|
+
} catch (_) {
|
|
315
|
+
// never let reporting break the page
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// Once its stream is open, a page reports itself: as a navigation only when this tab showed
|
|
319
|
+
// another page before (not on a reload, a reconnect, a new tab or a page another one led here).
|
|
320
|
+
function arrived() {
|
|
321
|
+
var at = where();
|
|
322
|
+
var before = stored(atKey);
|
|
323
|
+
store(atKey, at);
|
|
324
|
+
report(before !== null && before !== at, syncScroll);
|
|
325
|
+
}
|
|
326
|
+
function moved() {
|
|
327
|
+
var at = where();
|
|
328
|
+
if (stored(atKey) === at) return;
|
|
329
|
+
store(atKey, at);
|
|
330
|
+
report(true, false);
|
|
331
|
+
}
|
|
332
|
+
if (sync) {
|
|
333
|
+
["pushState", "replaceState"].forEach(function (name) {
|
|
334
|
+
var original = history[name];
|
|
335
|
+
if (typeof original !== "function") return;
|
|
336
|
+
history[name] = function () {
|
|
337
|
+
var r = original.apply(this, arguments);
|
|
338
|
+
moved();
|
|
339
|
+
return r;
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
window.addEventListener("popstate", moved);
|
|
343
|
+
window.addEventListener("hashchange", moved);
|
|
344
|
+
}
|
|
345
|
+
function editing() {
|
|
346
|
+
var a = document.activeElement;
|
|
347
|
+
if (!a) return false;
|
|
348
|
+
var t = a.localName;
|
|
349
|
+
return t === "input" || t === "textarea" || t === "select" || a.isContentEditable === true;
|
|
350
|
+
}
|
|
351
|
+
var quietUntil = 0;
|
|
352
|
+
function follow(ev) {
|
|
353
|
+
if (!sync || typeof ev.url !== "string" || ev.url.charAt(0) !== "/" || ev.url.charAt(1) === "/") return;
|
|
354
|
+
var hash = ev.url.indexOf("#");
|
|
355
|
+
var path = hash === -1 ? ev.url : ev.url.slice(0, hash);
|
|
356
|
+
if (ev.type === "navigate") {
|
|
357
|
+
if (ev.url === where() || editing()) return;
|
|
358
|
+
store(atKey, ev.url); // the page this leads to is not a navigation of its own
|
|
359
|
+
if (hash !== -1 && path === location.pathname) location.hash = ev.url.slice(hash);
|
|
360
|
+
else location.assign(ev.url);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (!syncScroll || path !== location.pathname || editing()) return;
|
|
364
|
+
if (typeof ev.x !== "number" || typeof ev.y !== "number") return;
|
|
365
|
+
var el = document.scrollingElement || document.documentElement;
|
|
366
|
+
quietUntil = Date.now() + 500; // the scroll this causes is not reported back
|
|
367
|
+
window.scrollTo((ev.x / 10000) * Math.max(0, el.scrollWidth - window.innerWidth), (ev.y / 10000) * Math.max(0, el.scrollHeight - window.innerHeight));
|
|
368
|
+
}
|
|
369
|
+
if (syncScroll) {
|
|
370
|
+
var scrollTimer = null;
|
|
371
|
+
window.addEventListener(
|
|
372
|
+
"scroll",
|
|
373
|
+
function () {
|
|
374
|
+
if (Date.now() < quietUntil || scrollTimer !== null) return;
|
|
375
|
+
scrollTimer = setTimeout(function () {
|
|
376
|
+
scrollTimer = null;
|
|
377
|
+
if (Date.now() >= quietUntil) report(false, true);
|
|
378
|
+
}, 250);
|
|
379
|
+
},
|
|
380
|
+
{ passive: true }
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
271
384
|
// EventSource reconnects by itself after a dropped connection (the server sends retry: 1000),
|
|
272
385
|
// but gives up for good when an answer is not an event stream (a proxy or tunnel error page):
|
|
273
386
|
// then try again, waiting twice as long each time, up to 30 s.
|
|
274
387
|
var delay = 1000;
|
|
275
388
|
function connect() {
|
|
276
|
-
var source = new EventSource(new URL("reload", base).href);
|
|
389
|
+
var source = new EventSource(new URL(sync ? "reload?client=" + clientId : "reload", base).href);
|
|
277
390
|
source.onopen = function () {
|
|
278
391
|
delay = 1000;
|
|
392
|
+
if (sync) arrived();
|
|
279
393
|
};
|
|
280
394
|
source.onmessage = function (e) {
|
|
281
395
|
var ev;
|
|
@@ -284,6 +398,7 @@ export const RELOAD_CLIENT = String.raw `(function (options) {
|
|
|
284
398
|
} catch (_) {
|
|
285
399
|
ev = { type: "reload" };
|
|
286
400
|
}
|
|
401
|
+
if (ev.type === "navigate" || ev.type === "scroll") return follow(ev);
|
|
287
402
|
if (ev.type === "building") return showBadge();
|
|
288
403
|
if (ev.type === "error") return showError(ev);
|
|
289
404
|
hideBadge();
|
|
@@ -2,7 +2,7 @@ import { type SourceSpan } from '../errors.js';
|
|
|
2
2
|
import { Tree } from '../tree.js';
|
|
3
3
|
import { type ArchiveLimits } from './types.js';
|
|
4
4
|
/**
|
|
5
|
-
* Extract a tar, tar.gz/tgz, zip or Web Bundle (b1/b2) archive into a Tree. The format is detected
|
|
5
|
+
* Extract a tar, tar.gz/tgz, tar.zst/tzst, zip or Web Bundle (b1/b2, plain or gzip-wrapped) archive into a Tree. The format is detected
|
|
6
6
|
* from magic bytes, never from the name. Nothing is inflated beyond the limits,
|
|
7
7
|
* and unsafe entries (absolute or `..` paths, backslashes, NUL, symlinks, hard
|
|
8
8
|
* links, devices) are rejected, not skipped. A single top-level directory is
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
-
import { crc32, gunzip as gunzipCb, inflateRaw as inflateRawCb, inflateRawSync } from 'node:zlib';
|
|
2
|
+
import { crc32, gunzip as gunzipCb, inflateRaw as inflateRawCb, inflateRawSync, zstdDecompress as zstdDecompressCb } from 'node:zlib';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
4
|
import { SitefileError } from '../errors.js';
|
|
5
5
|
import { normalizeVirtual } from '../paths.js';
|
|
@@ -10,10 +10,11 @@ import { isWebBundle, readWebBundle, webBundleToTree } from './wbn-reader.js';
|
|
|
10
10
|
const RATIO_FLOOR = 1024 * 1024;
|
|
11
11
|
const gunzipAsync = promisify(gunzipCb);
|
|
12
12
|
const inflateRawAsync = promisify(inflateRawCb);
|
|
13
|
+
const zstdDecompressAsync = promisify(zstdDecompressCb);
|
|
13
14
|
/** Tar framing per entry, worst case: header + padding + a pax/GNU long-name header and its padding. */
|
|
14
15
|
const TAR_OVERHEAD_PER_ENTRY = 4 * 512;
|
|
15
16
|
/**
|
|
16
|
-
* Extract a tar, tar.gz/tgz, zip or Web Bundle (b1/b2) archive into a Tree. The format is detected
|
|
17
|
+
* Extract a tar, tar.gz/tgz, tar.zst/tzst, zip or Web Bundle (b1/b2, plain or gzip-wrapped) archive into a Tree. The format is detected
|
|
17
18
|
* from magic bytes, never from the name. Nothing is inflated beyond the limits,
|
|
18
19
|
* and unsafe entries (absolute or `..` paths, backslashes, NUL, symlinks, hard
|
|
19
20
|
* links, devices) are rejected, not skipped. A single top-level directory is
|
|
@@ -23,11 +24,15 @@ export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIM
|
|
|
23
24
|
if (isWebBundle(bytes))
|
|
24
25
|
return webBundleToTree(readWebBundle(bytes, origin, limits, span), origin, span);
|
|
25
26
|
const { add, files } = collector(origin, limits, span, true);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const compression = isGzip(bytes) ? 'gzip' : isZstd(bytes) ? 'zstd' : undefined;
|
|
28
|
+
if (compression) {
|
|
29
|
+
const inner = await decompress(compression, bytes, origin, limits, span);
|
|
30
|
+
// gzip(application/webbundle), as @johnhenry/fileable (encode="wbn") and packfile's toArchive() write it
|
|
31
|
+
if (isWebBundle(inner))
|
|
32
|
+
return webBundleToTree(readWebBundle(inner, origin, limits, span), origin, span);
|
|
33
|
+
if (!isTar(inner))
|
|
34
|
+
throw new SitefileError('E_TYPE', `${origin}: ${compression} content is not a tar archive`, span);
|
|
35
|
+
readTar(inner, origin, limits, span, add);
|
|
31
36
|
}
|
|
32
37
|
else if (isZip(bytes)) {
|
|
33
38
|
await readZip(bytes, origin, limits, span, add);
|
|
@@ -37,7 +42,7 @@ export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIM
|
|
|
37
42
|
}
|
|
38
43
|
else {
|
|
39
44
|
const what = otherFormat(bytes);
|
|
40
|
-
throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (${what ?? 'expected tar, tar.gz, zip or web bundle'})`, span);
|
|
45
|
+
throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (${what ?? 'expected tar, tar.gz, tar.zst, zip or web bundle'})`, span);
|
|
41
46
|
}
|
|
42
47
|
return Tree.fromFiles(files);
|
|
43
48
|
}
|
|
@@ -99,8 +104,6 @@ function otherFormat(b) {
|
|
|
99
104
|
const starts = (...m) => b.length >= m.length && m.every((x, i) => b[i] === x);
|
|
100
105
|
if (starts(0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00))
|
|
101
106
|
return 'it is xz-compressed, e.g. .tar.xz; recompress it as .tar.gz or zip';
|
|
102
|
-
if (starts(0x28, 0xb5, 0x2f, 0xfd))
|
|
103
|
-
return 'it is zstd-compressed, e.g. .tar.zst; recompress it as .tar.gz or zip';
|
|
104
107
|
if (starts(0x42, 0x5a, 0x68) && b.length > 3 && b[3] >= 0x31 && b[3] <= 0x39)
|
|
105
108
|
return 'it is bzip2-compressed, e.g. .tar.bz2; recompress it as .tar.gz or zip';
|
|
106
109
|
if (starts(0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c))
|
|
@@ -110,6 +113,8 @@ function otherFormat(b) {
|
|
|
110
113
|
return undefined;
|
|
111
114
|
}
|
|
112
115
|
const isGzip = (b) => b.length > 2 && b[0] === 0x1f && b[1] === 0x8b;
|
|
116
|
+
/** A Zstandard frame (RFC 8878); a stream that starts with a skippable frame is not recognized. */
|
|
117
|
+
const isZstd = (b) => b.length >= 4 && b[0] === 0x28 && b[1] === 0xb5 && b[2] === 0x2f && b[3] === 0xfd;
|
|
113
118
|
const isZip = (b) => b.length >= 4 && b[0] === 0x50 && b[1] === 0x4b && ((b[2] === 3 && b[3] === 4) || (b[2] === 5 && b[3] === 6));
|
|
114
119
|
const isTar = (b) => b.length >= 512 &&
|
|
115
120
|
(ascii(b, 257, 262) === 'ustar' ||
|
|
@@ -131,14 +136,20 @@ function archivePath(name, span) {
|
|
|
131
136
|
throw bad("'..' segment");
|
|
132
137
|
return normalizeVirtual('/' + name, span, 'archive entry').path;
|
|
133
138
|
}
|
|
134
|
-
//
|
|
135
|
-
|
|
139
|
+
// ------------------------------------------------------------ gzip, zstd
|
|
140
|
+
/**
|
|
141
|
+
* Decompress a gzip or zstd stream within the limits (the same ratio and size caps for both). zstd is
|
|
142
|
+
* Node's libzstd (frames that need a window over 128 MiB are refused; rust/src/resources/archive.rs
|
|
143
|
+
* matches what it accepts).
|
|
144
|
+
*/
|
|
145
|
+
async function decompress(kind, bytes, origin, limits, span) {
|
|
136
146
|
const byRatio = Math.max(bytes.length * limits.maxRatio, RATIO_FLOOR);
|
|
137
147
|
// The inflated stream is tar: file data plus headers and padding for every entry.
|
|
138
148
|
const byTotal = limits.maxTotalBytes + (limits.maxEntries + 2) * TAR_OVERHEAD_PER_ENTRY;
|
|
139
149
|
try {
|
|
140
150
|
// Async so a large archive doesn't stall other imports' sockets and timers.
|
|
141
|
-
|
|
151
|
+
const options = { maxOutputLength: Math.min(byRatio, byTotal) };
|
|
152
|
+
return kind === 'gzip' ? await gunzipAsync(bytes, options) : await zstdDecompressAsync(bytes, options);
|
|
142
153
|
}
|
|
143
154
|
catch (e) {
|
|
144
155
|
throw inflateError(e, origin, byRatio <= byTotal, limits, span);
|
package/lib/src/serve-auth.d.ts
CHANGED
|
@@ -14,8 +14,9 @@ export declare function makeVerifier(password: string, salt?: Uint8Array, iterat
|
|
|
14
14
|
/** Whether `password` matches `verifier` (false for a malformed verifier). Constant time in the key comparison. */
|
|
15
15
|
export declare function verifyPassword(verifier: string, password: string): boolean;
|
|
16
16
|
/**
|
|
17
|
-
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped).
|
|
18
|
-
*
|
|
17
|
+
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped). `{SHA}` (htpasswd -s) and bcrypt
|
|
18
|
+
* (`$2y$`, `$2a$`, `$2b$`, cost 4 to 31; htpasswd -B) entries are accepted; a malformed bcrypt hash, `$apr1$`,
|
|
19
|
+
* crypt and plain-text entries are `E_USAGE` errors naming the user.
|
|
19
20
|
*/
|
|
20
21
|
export declare function parseHtpasswd(text: string, origin: string): AuthEntry[];
|
|
21
22
|
/** The `user` and `password` of an `Authorization: Basic …` value, or undefined. */
|
package/lib/src/serve-auth.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
// A credential is kept only as a verifier, never as the password:
|
|
5
5
|
// pbkdf2-sha256$<iterations>$<salt base64>$<32-byte key base64> (what --auth and SITEFILE_SERVE_AUTH become)
|
|
6
6
|
// {SHA}<base64 SHA-1 of the password> (an htpasswd -s entry, --auth-file)
|
|
7
|
+
// $2y$<cost>$<salt><hash> (also $2a$, $2b$) (an htpasswd -B bcrypt entry, --auth-file; #278)
|
|
7
8
|
import { createHash, pbkdf2Sync, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
9
|
+
import { isBcryptPrefix, parseBcrypt, verifyBcrypt } from './bcrypt.js';
|
|
8
10
|
import { SitefileError } from './errors.js';
|
|
9
11
|
/** PBKDF2 rounds of a verifier made here; checks are cached per server, so this is paid once per credential. */
|
|
10
12
|
export const AUTH_ITERATIONS = 20000;
|
|
@@ -30,6 +32,8 @@ function equal(a, b) {
|
|
|
30
32
|
}
|
|
31
33
|
/** Whether `password` matches `verifier` (false for a malformed verifier). Constant time in the key comparison. */
|
|
32
34
|
export function verifyPassword(verifier, password) {
|
|
35
|
+
if (isBcryptPrefix(verifier))
|
|
36
|
+
return verifyBcrypt(verifier, password);
|
|
33
37
|
const pw = Buffer.from(password, 'utf8');
|
|
34
38
|
if (verifier.startsWith('{SHA}')) {
|
|
35
39
|
const want = b64(verifier.slice(5));
|
|
@@ -46,8 +50,9 @@ export function verifyPassword(verifier, password) {
|
|
|
46
50
|
return equal(pbkdf2Sync(pw, salt, iterations, 32, 'sha256'), want);
|
|
47
51
|
}
|
|
48
52
|
/**
|
|
49
|
-
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped).
|
|
50
|
-
*
|
|
53
|
+
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped). `{SHA}` (htpasswd -s) and bcrypt
|
|
54
|
+
* (`$2y$`, `$2a$`, `$2b$`, cost 4 to 31; htpasswd -B) entries are accepted; a malformed bcrypt hash, `$apr1$`,
|
|
55
|
+
* crypt and plain-text entries are `E_USAGE` errors naming the user.
|
|
51
56
|
*/
|
|
52
57
|
export function parseHtpasswd(text, origin) {
|
|
53
58
|
const out = [];
|
|
@@ -60,10 +65,13 @@ export function parseHtpasswd(text, origin) {
|
|
|
60
65
|
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: expected user:hash`);
|
|
61
66
|
const user = line.slice(0, i);
|
|
62
67
|
const hash = line.slice(i + 1);
|
|
63
|
-
if (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
68
|
+
if (isBcryptPrefix(hash)) {
|
|
69
|
+
if (!parseBcrypt(hash))
|
|
70
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: user '${user}': malformed bcrypt hash (expected $2y$, $2a$ or $2b$, a cost of 04 to 31 and 53 characters of salt and hash)`);
|
|
71
|
+
}
|
|
72
|
+
else if (!/^\{SHA\}[A-Za-z0-9+/]{27}=$/.test(hash)) {
|
|
73
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: user '${user}': unsupported password hash (only {SHA} and bcrypt entries, htpasswd -s or -B)`);
|
|
74
|
+
}
|
|
67
75
|
out.push({ user, verifier: hash });
|
|
68
76
|
}
|
|
69
77
|
return out;
|