@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
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type Needs, type SourceSpan } from './errors.js';
|
|
2
|
+
import { type BuildOptions } from './executor.js';
|
|
3
|
+
/**
|
|
4
|
+
* `sitefile hosts` (issue #176): the hosts a build would contact, found from the plan alone (nothing is
|
|
5
|
+
* fetched), with what each is needed for and whether the current host rules allow it.
|
|
6
|
+
*
|
|
7
|
+
* What is listed: every remote IMPORT (https and git+https: the URL's host), every `FROM image` stage base
|
|
8
|
+
* with a registry, and the BASE image of an oci export (or `--base`): the registry's API host. What is not
|
|
9
|
+
* known before fetching, and so not listed: redirects, a registry's token realm and blob CDN, the inputs of
|
|
10
|
+
* an imported Sitefile (`IMPORT … AS sitefile`, marked `nested`), and the links `CHECKLINKS EXTERNAL`
|
|
11
|
+
* checks (reported as `checklinksExternal`). Those still come up one at a time at build time, each with an
|
|
12
|
+
* E_HOST_BLOCKED `needs`.
|
|
13
|
+
*/
|
|
14
|
+
export type HostStatus = 'allowed' | 'blocked' | 'denied';
|
|
15
|
+
export interface HostUse {
|
|
16
|
+
readonly kind: 'import' | 'image' | 'base';
|
|
17
|
+
/** The IMPORT name, the stage of a `FROM image` (its name, or `#<n>`), or `BASE`. */
|
|
18
|
+
readonly name: string;
|
|
19
|
+
/** The URL, or the canonical image reference. */
|
|
20
|
+
readonly source: string;
|
|
21
|
+
/** The instruction (null for a BASE given with --base or on EXPORT). */
|
|
22
|
+
readonly span: SourceSpan | null;
|
|
23
|
+
/** `IMPORT … SECRET` ids sent to this host. */
|
|
24
|
+
readonly secrets: readonly string[];
|
|
25
|
+
/** An imported Sitefile: its own inputs are only known once it is fetched. */
|
|
26
|
+
readonly nested: boolean;
|
|
27
|
+
/** Strict mode: the `--allow-secret-host` rule this use still needs (the first missing one). */
|
|
28
|
+
readonly needs: Needs | null;
|
|
29
|
+
}
|
|
30
|
+
export interface HostEntry {
|
|
31
|
+
/** As written in the URL (lowercase, IPv6 without brackets). */
|
|
32
|
+
readonly host: string;
|
|
33
|
+
readonly port: number;
|
|
34
|
+
readonly status: HostStatus;
|
|
35
|
+
/** For `blocked`: the `--allow-hosts` that allows it. */
|
|
36
|
+
readonly needs: Needs | null;
|
|
37
|
+
readonly uses: readonly HostUse[];
|
|
38
|
+
}
|
|
39
|
+
export interface HostsReport {
|
|
40
|
+
readonly strict: boolean;
|
|
41
|
+
readonly hosts: readonly HostEntry[];
|
|
42
|
+
/** Lines of `CHECKLINKS --external`, which contacts the hosts of the site's external links. */
|
|
43
|
+
readonly checklinksExternal: readonly number[];
|
|
44
|
+
}
|
|
45
|
+
export declare function hosts(options: BuildOptions): Promise<HostsReport>;
|
|
46
|
+
/** `HostsReport` as JSON, keys in the documented order (compared across implementations). */
|
|
47
|
+
export declare function hostsJson(r: HostsReport): string;
|
package/lib/src/hosts.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { isSitefileError, needsHost } from './errors.js';
|
|
2
|
+
import { loadProgram } from './executor.js';
|
|
3
|
+
import { plan } from './planner.js';
|
|
4
|
+
import { parseRef, registryApiHost, withDefaultRegistry } from './ref.js';
|
|
5
|
+
import { checkSecretHosts, hostAllowed, hostMatches, urlPort } from './resources/network.js';
|
|
6
|
+
function statusOf(host, port, network) {
|
|
7
|
+
if (hostAllowed(host, port, network))
|
|
8
|
+
return 'allowed';
|
|
9
|
+
return (network?.denyHosts ?? []).some((p) => hostMatches(host, port, p)) ? 'denied' : 'blocked';
|
|
10
|
+
}
|
|
11
|
+
function secretNeeds(name, ids, target, network, span) {
|
|
12
|
+
try {
|
|
13
|
+
checkSecretHosts(name, ids, target, network, span);
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
catch (e) {
|
|
17
|
+
if (isSitefileError(e) && e.needs)
|
|
18
|
+
return e.needs;
|
|
19
|
+
throw e;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export async function hosts(options) {
|
|
23
|
+
const { program } = await loadProgram(options);
|
|
24
|
+
const p = plan(program, options.buildArgs ?? {});
|
|
25
|
+
p.warnings.forEach((m) => options.onWarning?.(m));
|
|
26
|
+
const network = options.fetchPolicy?.network;
|
|
27
|
+
const entries = [];
|
|
28
|
+
const add = (host, port, use) => {
|
|
29
|
+
const h = host.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
30
|
+
let e = entries.find((x) => x.host === h && x.port === port);
|
|
31
|
+
if (!e)
|
|
32
|
+
entries.push((e = { host: h, port, uses: [] }));
|
|
33
|
+
e.uses.push(use);
|
|
34
|
+
};
|
|
35
|
+
for (const spec of p.imports) {
|
|
36
|
+
const loc = spec.location;
|
|
37
|
+
if (loc.kind === 'local')
|
|
38
|
+
continue;
|
|
39
|
+
const target = loc.kind === 'remote' ? loc.url : loc.repo;
|
|
40
|
+
let url;
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(target);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const ids = [...new Set((spec.secrets ?? []).map((s) => s.id))];
|
|
48
|
+
add(url.hostname, urlPort(url), {
|
|
49
|
+
kind: 'import',
|
|
50
|
+
name: spec.name,
|
|
51
|
+
source: loc.url,
|
|
52
|
+
span: spec.span,
|
|
53
|
+
secrets: ids,
|
|
54
|
+
nested: spec.as === 'sitefile',
|
|
55
|
+
needs: secretNeeds(spec.name, ids, target, network, spec.span),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const image = (kind, name, input, span) => {
|
|
59
|
+
const ref = withDefaultRegistry(parseRef(input));
|
|
60
|
+
const registry = ref.registry;
|
|
61
|
+
const source = `${registry}/${ref.name}${ref.tag !== undefined ? `:${ref.tag}` : ''}${ref.digest !== undefined ? `@${ref.digest}` : ''}`;
|
|
62
|
+
const api = registryApiHost(registry);
|
|
63
|
+
const m = /^(.*?)(?::(\d+))?$/.exec(api);
|
|
64
|
+
add(m[1], m[2] !== undefined ? Number(m[2]) : 443, { kind, name, source, span, secrets: [], nested: false, needs: null });
|
|
65
|
+
};
|
|
66
|
+
for (const [i, st] of p.stages.entries()) {
|
|
67
|
+
if (st.base.kind === 'image' && !st.base.local)
|
|
68
|
+
image('image', st.name ?? `#${i + 1}`, st.base.ref, st.base.span);
|
|
69
|
+
}
|
|
70
|
+
const baseInput = options.baseImage ?? (p.exportFormat === 'oci' ? p.exportBase : undefined);
|
|
71
|
+
if (baseInput !== undefined)
|
|
72
|
+
image('base', 'BASE', baseInput, null);
|
|
73
|
+
const checklinksExternal = p.stages.flatMap((st) => st.operations.flatMap((op) => (op.kind === 'CHECKLINKS' && op.external ? [op.span.line] : [])));
|
|
74
|
+
return {
|
|
75
|
+
strict: !!network?.strict,
|
|
76
|
+
hosts: entries.map((e) => {
|
|
77
|
+
const status = statusOf(e.host, e.port, network);
|
|
78
|
+
return { host: e.host, port: e.port, status, needs: status === 'blocked' ? needsHost(e.host) : null, uses: e.uses };
|
|
79
|
+
}),
|
|
80
|
+
checklinksExternal,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** `HostsReport` as JSON, keys in the documented order (compared across implementations). */
|
|
84
|
+
export function hostsJson(r) {
|
|
85
|
+
const needs = (n) => (n ? { kind: n.kind, name: n.name, flag: n.flag } : null);
|
|
86
|
+
return (JSON.stringify({
|
|
87
|
+
strict: r.strict,
|
|
88
|
+
hosts: r.hosts.map((h) => ({
|
|
89
|
+
host: h.host,
|
|
90
|
+
port: h.port,
|
|
91
|
+
status: h.status,
|
|
92
|
+
needs: needs(h.needs),
|
|
93
|
+
uses: h.uses.map((u) => ({
|
|
94
|
+
kind: u.kind,
|
|
95
|
+
name: u.name,
|
|
96
|
+
source: u.source,
|
|
97
|
+
span: u.span ? { file: u.span.file, line: u.span.line, column: u.span.column } : null,
|
|
98
|
+
secrets: u.secrets,
|
|
99
|
+
nested: u.nested,
|
|
100
|
+
needs: needs(u.needs),
|
|
101
|
+
})),
|
|
102
|
+
})),
|
|
103
|
+
checklinksExternal: r.checklinksExternal,
|
|
104
|
+
}, null, 2) + '\n');
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=hosts.js.map
|
package/lib/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { SitefileError, isSitefileError, formatSpan, needsPlugin, needsTool, type ErrorCode, type Needs, type SourceSpan } from './errors.js';
|
|
1
|
+
export { SitefileError, isSitefileError, formatSpan, needsPlugin, needsTool, needsHost, needsSecretHost, errorJson, type ErrorCode, type Needs, type SourceSpan } from './errors.js';
|
|
2
2
|
export type * from './language/ast.js';
|
|
3
3
|
export { parseSitefile } from './language/parser.js';
|
|
4
4
|
export { validate, parseProgram } from './language/validate.js';
|
package/lib/src/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { SitefileError, isSitefileError, formatSpan, needsPlugin, needsTool } from './errors.js';
|
|
1
|
+
export { SitefileError, isSitefileError, formatSpan, needsPlugin, needsTool, needsHost, needsSecretHost, errorJson } from './errors.js';
|
|
2
2
|
export { parseSitefile } from './language/parser.js';
|
|
3
3
|
export { validate, parseProgram } from './language/validate.js';
|
|
4
4
|
export { plan } from './planner.js';
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { Store } from './store.js';
|
|
2
|
+
import type { Tree } from './tree.js';
|
|
3
|
+
/**
|
|
4
|
+
* Per-file digest manifests (issue #211): every exported file with its size and SHA-256,
|
|
5
|
+
* plus a Merkle root over the sorted (path, digest) pairs, so a deployed or extracted
|
|
6
|
+
* copy can be checked file by file (`sitefile verify`) and a single file can be proven
|
|
7
|
+
* against the root with a path of hashes.
|
|
8
|
+
*
|
|
9
|
+
* The root is the RFC 6962 Merkle Tree Hash of the leaves `path 0x00 digest` (UTF-8,
|
|
10
|
+
* digest written `sha256:<hex>`) in path order: a leaf hashes as SHA-256(0x00 ‖ leaf),
|
|
11
|
+
* an inner node as SHA-256(0x01 ‖ left ‖ right), the split at the largest power of two
|
|
12
|
+
* below the count, and no files as SHA-256 of nothing.
|
|
13
|
+
*/
|
|
14
|
+
export declare const MANIFEST_MEDIA_TYPE = "application/vnd.sitefile.manifest.v1+json";
|
|
15
|
+
export interface ManifestFile {
|
|
16
|
+
readonly path: string;
|
|
17
|
+
readonly size: number;
|
|
18
|
+
/** `sha256:<hex>` of the file's bytes. */
|
|
19
|
+
readonly digest: string;
|
|
20
|
+
}
|
|
21
|
+
export interface Manifest {
|
|
22
|
+
readonly mediaType: typeof MANIFEST_MEDIA_TYPE;
|
|
23
|
+
/** `sha256:<hex>`: the Merkle root of {@link files}. */
|
|
24
|
+
readonly root: string;
|
|
25
|
+
readonly files: readonly ManifestFile[];
|
|
26
|
+
}
|
|
27
|
+
/** The Merkle root of `files` (in the order given; manifests list them by path). */
|
|
28
|
+
export declare function merkleRoot(files: readonly ManifestFile[]): string;
|
|
29
|
+
/** The manifest of a tree: every file in path order. */
|
|
30
|
+
export declare function manifestOf(tree: Tree): Manifest;
|
|
31
|
+
/** The manifest as written to a file: `JSON.stringify(manifest, null, 2)` and a newline. */
|
|
32
|
+
export declare function encodeManifest(m: Manifest): Uint8Array;
|
|
33
|
+
/** Parse a manifest file. Its root must match its files. */
|
|
34
|
+
export declare function parseManifest(bytes: Uint8Array, origin: string): Manifest;
|
|
35
|
+
/** What `verify` and `diff` compare: a directory, an archive file, or an image in the store. */
|
|
36
|
+
export type Target = {
|
|
37
|
+
readonly kind: 'dir' | 'archive';
|
|
38
|
+
readonly path: string;
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: 'image';
|
|
41
|
+
readonly ref: string;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Resolve a `verify`/`diff` argument: a path (written `./x`, `/x`, `x/`, …) is a directory or
|
|
45
|
+
* an archive file; anything else is an image reference or ID when the store has it, else a
|
|
46
|
+
* directory or file by that name.
|
|
47
|
+
*/
|
|
48
|
+
export declare function resolveTarget(arg: string, store: () => Promise<Store>): Promise<Target>;
|
|
49
|
+
/**
|
|
50
|
+
* The files of a target, hidden ones included (a manifest lists every exported file): a
|
|
51
|
+
* directory is read like a build context (symlinks must stay inside it; `.git` is skipped),
|
|
52
|
+
* an archive is extracted with the default limits, an image is loaded from the store with
|
|
53
|
+
* every blob's digest checked.
|
|
54
|
+
*/
|
|
55
|
+
export declare function loadTarget(t: Target, store: () => Promise<Store>): Promise<Tree>;
|
|
56
|
+
export interface VerifyChange {
|
|
57
|
+
readonly path: string;
|
|
58
|
+
readonly expected: {
|
|
59
|
+
readonly size: number;
|
|
60
|
+
readonly digest: string;
|
|
61
|
+
};
|
|
62
|
+
readonly actual: {
|
|
63
|
+
readonly size: number;
|
|
64
|
+
readonly digest: string;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export interface VerifyReport {
|
|
68
|
+
readonly ok: boolean;
|
|
69
|
+
readonly root: string;
|
|
70
|
+
/** Files the manifest lists. */
|
|
71
|
+
readonly files: number;
|
|
72
|
+
readonly missing: readonly string[];
|
|
73
|
+
readonly changed: readonly VerifyChange[];
|
|
74
|
+
readonly extra: readonly string[];
|
|
75
|
+
}
|
|
76
|
+
/** Compare `tree` with `manifest`. `ignore` is a path not counted as extra (the manifest itself, inside a verified directory). */
|
|
77
|
+
export declare function verifyTree(tree: Tree, manifest: Manifest, ignore?: string): VerifyReport;
|
|
78
|
+
/** The text report: one `missing|changed|extra <path>` line per difference, in path order. */
|
|
79
|
+
export declare function verifyText(r: VerifyReport): string;
|
|
80
|
+
/** The tree path of `file` when it lies inside directory `dir` (both real paths), else undefined. */
|
|
81
|
+
export declare function pathInside(dir: string, file: string): Promise<string | undefined>;
|
|
82
|
+
export interface DiffFile {
|
|
83
|
+
readonly path: string;
|
|
84
|
+
readonly size: number;
|
|
85
|
+
readonly digest: string;
|
|
86
|
+
/** `644` or `755`. */
|
|
87
|
+
readonly mode: string;
|
|
88
|
+
}
|
|
89
|
+
export interface RuleDiff {
|
|
90
|
+
readonly added: readonly string[];
|
|
91
|
+
readonly removed: readonly string[];
|
|
92
|
+
}
|
|
93
|
+
export interface DiffReport {
|
|
94
|
+
readonly added: readonly DiffFile[];
|
|
95
|
+
readonly removed: readonly DiffFile[];
|
|
96
|
+
readonly changed: ReadonlyArray<{
|
|
97
|
+
readonly path: string;
|
|
98
|
+
readonly before: DiffFile;
|
|
99
|
+
readonly after: DiffFile;
|
|
100
|
+
}>;
|
|
101
|
+
/** Rule changes in `/_redirects` and `/_headers`, when either side has the file and they differ. */
|
|
102
|
+
readonly rules: {
|
|
103
|
+
readonly [file: string]: RuleDiff;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The rules of a `_redirects` or `_headers` file, one string each: `_redirects` lines with their
|
|
108
|
+
* fields joined by one space; for `_headers`, `<path> <Name>: <value>` per header line. Blank lines
|
|
109
|
+
* and `#` comments are not rules.
|
|
110
|
+
*/
|
|
111
|
+
export declare function ruleLines(file: string, bytes: Uint8Array | undefined): string[];
|
|
112
|
+
/** Files added, removed and changed (digest or mode) going from `a` to `b`, in path order. */
|
|
113
|
+
export declare function diffTrees(a: Tree, b: Tree): DiffReport;
|
|
114
|
+
/** The text report: `A|D|C <path>` lines (with sizes), then rule changes, then a summary line. */
|
|
115
|
+
export declare function diffText(r: DiffReport): string;
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { SitefileError } from './errors.js';
|
|
5
|
+
import { INTEGRITY_RE } from './digest.js';
|
|
6
|
+
import { LocalContext } from './resources/local.js';
|
|
7
|
+
import { loadArchiveTree } from './servers.js';
|
|
8
|
+
/**
|
|
9
|
+
* Per-file digest manifests (issue #211): every exported file with its size and SHA-256,
|
|
10
|
+
* plus a Merkle root over the sorted (path, digest) pairs, so a deployed or extracted
|
|
11
|
+
* copy can be checked file by file (`sitefile verify`) and a single file can be proven
|
|
12
|
+
* against the root with a path of hashes.
|
|
13
|
+
*
|
|
14
|
+
* The root is the RFC 6962 Merkle Tree Hash of the leaves `path 0x00 digest` (UTF-8,
|
|
15
|
+
* digest written `sha256:<hex>`) in path order: a leaf hashes as SHA-256(0x00 ‖ leaf),
|
|
16
|
+
* an inner node as SHA-256(0x01 ‖ left ‖ right), the split at the largest power of two
|
|
17
|
+
* below the count, and no files as SHA-256 of nothing.
|
|
18
|
+
*/
|
|
19
|
+
export const MANIFEST_MEDIA_TYPE = 'application/vnd.sitefile.manifest.v1+json';
|
|
20
|
+
const sha = (...parts) => {
|
|
21
|
+
const h = createHash('sha256');
|
|
22
|
+
for (const p of parts)
|
|
23
|
+
h.update(p);
|
|
24
|
+
return h.digest();
|
|
25
|
+
};
|
|
26
|
+
const LEAF = new Uint8Array([0]);
|
|
27
|
+
const NODE = new Uint8Array([1]);
|
|
28
|
+
const enc = new TextEncoder();
|
|
29
|
+
function mth(leaves, lo, hi) {
|
|
30
|
+
const n = hi - lo;
|
|
31
|
+
if (n === 0)
|
|
32
|
+
return sha();
|
|
33
|
+
if (n === 1)
|
|
34
|
+
return sha(LEAF, leaves[lo]);
|
|
35
|
+
let k = 1;
|
|
36
|
+
while (k * 2 < n)
|
|
37
|
+
k *= 2;
|
|
38
|
+
return sha(NODE, mth(leaves, lo, lo + k), mth(leaves, lo + k, hi));
|
|
39
|
+
}
|
|
40
|
+
/** The Merkle root of `files` (in the order given; manifests list them by path). */
|
|
41
|
+
export function merkleRoot(files) {
|
|
42
|
+
const leaves = files.map((f) => enc.encode(`${f.path}\0${f.digest}`));
|
|
43
|
+
return 'sha256:' + mth(leaves, 0, leaves.length).toString('hex');
|
|
44
|
+
}
|
|
45
|
+
/** The manifest of a tree: every file in path order. */
|
|
46
|
+
export function manifestOf(tree) {
|
|
47
|
+
const files = tree.entries().map(([p, n]) => ({ path: p, size: n.bytes.byteLength, digest: n.digest }));
|
|
48
|
+
return { mediaType: MANIFEST_MEDIA_TYPE, root: merkleRoot(files), files };
|
|
49
|
+
}
|
|
50
|
+
/** The manifest as written to a file: `JSON.stringify(manifest, null, 2)` and a newline. */
|
|
51
|
+
export function encodeManifest(m) {
|
|
52
|
+
return enc.encode(JSON.stringify(m, null, 2) + '\n');
|
|
53
|
+
}
|
|
54
|
+
/** Parse a manifest file. Its root must match its files. */
|
|
55
|
+
export function parseManifest(bytes, origin) {
|
|
56
|
+
const bad = (why) => new SitefileError('E_INTEGRITY', `${origin}: ${why}`);
|
|
57
|
+
let v;
|
|
58
|
+
try {
|
|
59
|
+
v = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw bad('not a Sitefile manifest (invalid JSON)');
|
|
63
|
+
}
|
|
64
|
+
const o = v;
|
|
65
|
+
if (typeof o !== 'object' || o === null || Array.isArray(o) || o.mediaType !== MANIFEST_MEDIA_TYPE) {
|
|
66
|
+
throw bad(`not a Sitefile manifest (mediaType is not ${MANIFEST_MEDIA_TYPE})`);
|
|
67
|
+
}
|
|
68
|
+
if (typeof o.root !== 'string' || !INTEGRITY_RE.test(o.root) || !Array.isArray(o.files))
|
|
69
|
+
throw bad('not a Sitefile manifest (root or files missing)');
|
|
70
|
+
const files = [];
|
|
71
|
+
const seen = new Set();
|
|
72
|
+
for (const f of o.files) {
|
|
73
|
+
const e = f;
|
|
74
|
+
if (typeof e !== 'object' ||
|
|
75
|
+
e === null ||
|
|
76
|
+
typeof e.path !== 'string' ||
|
|
77
|
+
!e.path.startsWith('/') ||
|
|
78
|
+
typeof e.size !== 'number' ||
|
|
79
|
+
!Number.isSafeInteger(e.size) ||
|
|
80
|
+
e.size < 0 ||
|
|
81
|
+
typeof e.digest !== 'string' ||
|
|
82
|
+
!INTEGRITY_RE.test(e.digest)) {
|
|
83
|
+
throw bad('not a Sitefile manifest (a file entry needs path, size and digest)');
|
|
84
|
+
}
|
|
85
|
+
if (seen.has(e.path))
|
|
86
|
+
throw bad(`lists '${e.path}' twice`);
|
|
87
|
+
seen.add(e.path);
|
|
88
|
+
files.push({ path: e.path, size: e.size, digest: e.digest });
|
|
89
|
+
}
|
|
90
|
+
const root = merkleRoot(files);
|
|
91
|
+
if (root !== o.root)
|
|
92
|
+
throw bad(`its root ${o.root} does not match its files (${root})`);
|
|
93
|
+
return { mediaType: MANIFEST_MEDIA_TYPE, root, files };
|
|
94
|
+
}
|
|
95
|
+
/** True for an argument written as a path: `.`, `..`, `./x`, `../x`, `/x`, `~x`, `x/`. */
|
|
96
|
+
const looksLikePath = (arg) => /^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/.test(arg);
|
|
97
|
+
async function kindOnDisk(p) {
|
|
98
|
+
const st = await fs.stat(p).catch(() => undefined);
|
|
99
|
+
return st?.isDirectory() ? 'dir' : st?.isFile() ? 'archive' : undefined;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Resolve a `verify`/`diff` argument: a path (written `./x`, `/x`, `x/`, …) is a directory or
|
|
103
|
+
* an archive file; anything else is an image reference or ID when the store has it, else a
|
|
104
|
+
* directory or file by that name.
|
|
105
|
+
*/
|
|
106
|
+
export async function resolveTarget(arg, store) {
|
|
107
|
+
if (looksLikePath(arg)) {
|
|
108
|
+
const kind = await kindOnDisk(arg);
|
|
109
|
+
if (!kind)
|
|
110
|
+
throw new SitefileError('E_NOT_FOUND', `'${arg}' is not a directory or a file`);
|
|
111
|
+
return { kind, path: arg };
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
const s = await store();
|
|
115
|
+
await s.resolve(arg);
|
|
116
|
+
return { kind: 'image', ref: arg };
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
if (!(e instanceof SitefileError) || e.code !== 'E_NOT_FOUND')
|
|
120
|
+
throw e;
|
|
121
|
+
const kind = await kindOnDisk(arg);
|
|
122
|
+
if (kind)
|
|
123
|
+
return { kind, path: arg };
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The files of a target, hidden ones included (a manifest lists every exported file): a
|
|
129
|
+
* directory is read like a build context (symlinks must stay inside it; `.git` is skipped),
|
|
130
|
+
* an archive is extracted with the default limits, an image is loaded from the store with
|
|
131
|
+
* every blob's digest checked.
|
|
132
|
+
*/
|
|
133
|
+
export async function loadTarget(t, store) {
|
|
134
|
+
switch (t.kind) {
|
|
135
|
+
case 'image': {
|
|
136
|
+
const s = await store();
|
|
137
|
+
return s.loadTree(await s.resolve(t.ref));
|
|
138
|
+
}
|
|
139
|
+
case 'dir': {
|
|
140
|
+
const ctx = await LocalContext.open(t.path, { sitefileignore: false, allowHardlinks: true });
|
|
141
|
+
return (await ctx.readTree('', 'verify')).tree;
|
|
142
|
+
}
|
|
143
|
+
case 'archive':
|
|
144
|
+
return loadArchiveTree(t.path, undefined, { hidden: true });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Compare `tree` with `manifest`. `ignore` is a path not counted as extra (the manifest itself, inside a verified directory). */
|
|
148
|
+
export function verifyTree(tree, manifest, ignore) {
|
|
149
|
+
const listed = new Set(manifest.files.map((f) => f.path));
|
|
150
|
+
const missing = [];
|
|
151
|
+
const changed = [];
|
|
152
|
+
for (const f of manifest.files) {
|
|
153
|
+
const n = tree.get(f.path);
|
|
154
|
+
if (!n)
|
|
155
|
+
missing.push(f.path);
|
|
156
|
+
else if (n.digest !== f.digest || n.bytes.byteLength !== f.size) {
|
|
157
|
+
changed.push({ path: f.path, expected: { size: f.size, digest: f.digest }, actual: { size: n.bytes.byteLength, digest: n.digest } });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const extra = tree
|
|
161
|
+
.entries()
|
|
162
|
+
.map(([p]) => p)
|
|
163
|
+
.filter((p) => !listed.has(p) && p !== ignore);
|
|
164
|
+
return { ok: !missing.length && !changed.length && !extra.length, root: manifest.root, files: manifest.files.length, missing, changed, extra };
|
|
165
|
+
}
|
|
166
|
+
/** The text report: one `missing|changed|extra <path>` line per difference, in path order. */
|
|
167
|
+
export function verifyText(r) {
|
|
168
|
+
const lines = [
|
|
169
|
+
...r.missing.map((p) => [p, 'missing']),
|
|
170
|
+
...r.changed.map((c) => [c.path, 'changed']),
|
|
171
|
+
...r.extra.map((p) => [p, 'extra']),
|
|
172
|
+
].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
173
|
+
return lines.map(([p, k]) => `${k.padEnd(8)} ${p}\n`).join('');
|
|
174
|
+
}
|
|
175
|
+
/** The tree path of `file` when it lies inside directory `dir` (both real paths), else undefined. */
|
|
176
|
+
export async function pathInside(dir, file) {
|
|
177
|
+
const [d, f] = await Promise.all([fs.realpath(dir).catch(() => undefined), fs.realpath(file).catch(() => undefined)]);
|
|
178
|
+
if (d === undefined || f === undefined)
|
|
179
|
+
return undefined;
|
|
180
|
+
const rel = path.relative(d, f);
|
|
181
|
+
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel))
|
|
182
|
+
return undefined;
|
|
183
|
+
return '/' + rel.split(path.sep).join('/');
|
|
184
|
+
}
|
|
185
|
+
const RULE_FILES = ['/_redirects', '/_headers'];
|
|
186
|
+
/**
|
|
187
|
+
* The rules of a `_redirects` or `_headers` file, one string each: `_redirects` lines with their
|
|
188
|
+
* fields joined by one space; for `_headers`, `<path> <Name>: <value>` per header line. Blank lines
|
|
189
|
+
* and `#` comments are not rules.
|
|
190
|
+
*/
|
|
191
|
+
export function ruleLines(file, bytes) {
|
|
192
|
+
if (!bytes)
|
|
193
|
+
return [];
|
|
194
|
+
const text = new TextDecoder().decode(bytes);
|
|
195
|
+
const out = [];
|
|
196
|
+
let current;
|
|
197
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
198
|
+
const t = raw.trim();
|
|
199
|
+
if (t === '' || t.startsWith('#'))
|
|
200
|
+
continue;
|
|
201
|
+
if (file === '/_redirects')
|
|
202
|
+
out.push(t.split(/[ \t]+/).join(' '));
|
|
203
|
+
else if (!/^[ \t]/.test(raw))
|
|
204
|
+
current = t;
|
|
205
|
+
else
|
|
206
|
+
out.push(`${current ?? '(no path)'} ${t}`);
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
/** Lines of `a` not matched one for one in `b`, in `a`'s order. */
|
|
211
|
+
function minus(a, b) {
|
|
212
|
+
const left = new Map();
|
|
213
|
+
for (const l of b)
|
|
214
|
+
left.set(l, (left.get(l) ?? 0) + 1);
|
|
215
|
+
return a.filter((l) => {
|
|
216
|
+
const n = left.get(l) ?? 0;
|
|
217
|
+
if (n > 0)
|
|
218
|
+
left.set(l, n - 1);
|
|
219
|
+
return n === 0;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
const fileOf = (p, n) => ({ path: p, size: n.bytes.byteLength, digest: n.digest, mode: n.mode.toString(8) });
|
|
223
|
+
/** Files added, removed and changed (digest or mode) going from `a` to `b`, in path order. */
|
|
224
|
+
export function diffTrees(a, b) {
|
|
225
|
+
const am = new Map(a.entries());
|
|
226
|
+
const bm = new Map(b.entries());
|
|
227
|
+
const added = [];
|
|
228
|
+
const removed = [];
|
|
229
|
+
const changed = [];
|
|
230
|
+
for (const p of [...new Set([...am.keys(), ...bm.keys()])].sort((x, y) => (x < y ? -1 : x > y ? 1 : 0))) {
|
|
231
|
+
const x = am.get(p);
|
|
232
|
+
const y = bm.get(p);
|
|
233
|
+
if (!x && y)
|
|
234
|
+
added.push(fileOf(p, y));
|
|
235
|
+
else if (x && !y)
|
|
236
|
+
removed.push(fileOf(p, x));
|
|
237
|
+
else if (x && y && (x.digest !== y.digest || x.mode !== y.mode))
|
|
238
|
+
changed.push({ path: p, before: fileOf(p, x), after: fileOf(p, y) });
|
|
239
|
+
}
|
|
240
|
+
const rules = {};
|
|
241
|
+
for (const f of RULE_FILES) {
|
|
242
|
+
const x = am.get(f);
|
|
243
|
+
const y = bm.get(f);
|
|
244
|
+
if ((!x && !y) || x?.digest === y?.digest)
|
|
245
|
+
continue;
|
|
246
|
+
const before = ruleLines(f, x?.bytes);
|
|
247
|
+
const after = ruleLines(f, y?.bytes);
|
|
248
|
+
const r = { added: minus(after, before), removed: minus(before, after) };
|
|
249
|
+
if (r.added.length || r.removed.length)
|
|
250
|
+
rules[f] = r;
|
|
251
|
+
}
|
|
252
|
+
return { added, removed, changed, rules };
|
|
253
|
+
}
|
|
254
|
+
/** The text report: `A|D|C <path>` lines (with sizes), then rule changes, then a summary line. */
|
|
255
|
+
export function diffText(r) {
|
|
256
|
+
const size = (f) => `${f.size} B`;
|
|
257
|
+
const lines = [
|
|
258
|
+
...r.added.map((f) => [f.path, `A ${f.path} (${size(f)})`]),
|
|
259
|
+
...r.removed.map((f) => [f.path, `D ${f.path} (${size(f)})`]),
|
|
260
|
+
...r.changed.map((c) => [c.path, `C ${c.path} (${size(c.before)} -> ${size(c.after)}${c.before.mode !== c.after.mode ? `, mode ${c.before.mode} -> ${c.after.mode}` : ''})`]),
|
|
261
|
+
]
|
|
262
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
263
|
+
.map(([, l]) => l);
|
|
264
|
+
for (const [file, d] of Object.entries(r.rules)) {
|
|
265
|
+
for (const l of d.removed)
|
|
266
|
+
lines.push(`- ${file}: ${l}`);
|
|
267
|
+
for (const l of d.added)
|
|
268
|
+
lines.push(`+ ${file}: ${l}`);
|
|
269
|
+
}
|
|
270
|
+
lines.push(`${r.added.length} added, ${r.removed.length} removed, ${r.changed.length} changed`);
|
|
271
|
+
return lines.join('\n') + '\n';
|
|
272
|
+
}
|
|
273
|
+
//# sourceMappingURL=integrity.js.map
|