loremfile 0.1.0
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/README.md +75 -0
- package/bin/loremfile.js +6 -0
- package/package.json +28 -0
- package/src/api.js +392 -0
- package/src/cli.js +279 -0
package/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# loremfile
|
|
2
|
+
|
|
3
|
+
Download [loremfile.dev](https://loremfile.dev) sample files and check every byte against
|
|
4
|
+
the published manifest.
|
|
5
|
+
|
|
6
|
+
```console
|
|
7
|
+
$ npx loremfile get pdf/minimal.pdf mp4/720p-5s.mp4
|
|
8
|
+
written mp4/720p-5s.mp4 1,974,574 bytes
|
|
9
|
+
written pdf/minimal.pdf 586 bytes
|
|
10
|
+
files=2, dest=loremfile-fixtures
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`npx` runs it without a global install; `npm install --global loremfile` puts it on `PATH`.
|
|
14
|
+
Everything it does can be done with `curl` and `sha256sum -c`. What it adds is doing it
|
|
15
|
+
correctly by default: every file is verified, and a file that fails is not written.
|
|
16
|
+
|
|
17
|
+
## Commands
|
|
18
|
+
|
|
19
|
+
| Command | |
|
|
20
|
+
|---|---|
|
|
21
|
+
| `loremfile get PATH…` | Download those fixtures into `--dest` (default `loremfile-fixtures`), verifying each. |
|
|
22
|
+
| `loremfile get --format svg --format pdf` | The same for every published file of a format. |
|
|
23
|
+
| `loremfile list [--format F] [--tag T] [--max-bytes N]` | What is published, without downloading. |
|
|
24
|
+
| `loremfile verify [PATH…]` | Check files already on disk against the manifest. |
|
|
25
|
+
|
|
26
|
+
Every command takes `--json` for scripts, `--quiet`, and `--catalog-version X.Y.Z` to
|
|
27
|
+
refuse to run if loremfile.dev has moved on. `get` also takes `--force` (overwrite) and
|
|
28
|
+
`--dry-run` (what it would fetch, and how many bytes).
|
|
29
|
+
|
|
30
|
+
Exit codes: `0` fine, `1` a file failed verification or is missing, `2` the request was
|
|
31
|
+
wrong, `3` loremfile.dev could not be read.
|
|
32
|
+
|
|
33
|
+
## What it will not do
|
|
34
|
+
|
|
35
|
+
- **Write a file it could not verify.** Bytes go to a hidden temporary file beside the
|
|
36
|
+
destination, are hashed as they arrive, and are renamed into place only when the hash
|
|
37
|
+
matches; on a mismatch or a dropped connection the temporary file is deleted. There is no
|
|
38
|
+
`--no-verify`.
|
|
39
|
+
- **Talk to any host but loremfile.dev.** No mirror option, and redirects off the host are
|
|
40
|
+
not followed.
|
|
41
|
+
- **Take credentials.** Nothing it does needs authentication, so it accepts none.
|
|
42
|
+
- **Exceed the published rate limit**: one file at a time, a pause between them, and a
|
|
43
|
+
429 is waited out rather than retried tightly.
|
|
44
|
+
- **Generate fixtures.** Those are built in a pinned toolchain image; a client that made
|
|
45
|
+
its own would produce different bytes and undermine the only promise the project makes.
|
|
46
|
+
- **Install anything else or run anything on install.** No dependencies, and no install
|
|
47
|
+
scripts of any kind.
|
|
48
|
+
|
|
49
|
+
## Node versions
|
|
50
|
+
|
|
51
|
+
Node 20, 22 and 24, tested in CI on Linux, macOS and Windows. Zero dependencies — Node's
|
|
52
|
+
built-in modules only.
|
|
53
|
+
|
|
54
|
+
## In GitHub Actions, prefer the action
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
- uses: kumarprabhashanand/loremfile/action@action-v1
|
|
58
|
+
with:
|
|
59
|
+
paths: pdf/minimal.pdf mp4/720p-5s.mp4
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
It is shell only and needs no install step. This client is for everywhere else: a laptop,
|
|
63
|
+
an npm script, a CI system that is not Actions, or Windows — which the action does not
|
|
64
|
+
support because it needs `sha256sum`.
|
|
65
|
+
|
|
66
|
+
## One name, two clients
|
|
67
|
+
|
|
68
|
+
The Python client, `pip install loremfile`, installs a command with the same name and the
|
|
69
|
+
same three commands. On a machine with both, `loremfile` runs whichever comes first on
|
|
70
|
+
`PATH` — and where the two install into the same directory, whichever was installed last.
|
|
71
|
+
Either one checks every byte the same way.
|
|
72
|
+
|
|
73
|
+
## Licence
|
|
74
|
+
|
|
75
|
+
MIT for the client; the files it downloads are CC0.
|
package/bin/loremfile.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The command npm installs, and the one `npx loremfile` runs. Everything is in src/; this file
|
|
3
|
+
// only turns main's answer into the process's exit code.
|
|
4
|
+
import { main } from "../src/cli.js";
|
|
5
|
+
|
|
6
|
+
process.exitCode = await main(process.argv.slice(2));
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "loremfile",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Download CC0 sample files from loremfile.dev and verify every byte",
|
|
5
|
+
"keywords": ["fixtures", "test-data", "sample-files", "cc0", "download"],
|
|
6
|
+
"homepage": "https://loremfile.dev",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/kumarprabhashanand/loremfile/issues"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/kumarprabhashanand/loremfile.git",
|
|
13
|
+
"directory": "client-js"
|
|
14
|
+
},
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "the loremfile.dev contributors",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"bin": {
|
|
19
|
+
"loremfile": "bin/loremfile.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"bin/",
|
|
23
|
+
"src/"
|
|
24
|
+
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/api.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// Fetching fixtures from loremfile.dev, and checking every byte that arrives.
|
|
2
|
+
//
|
|
3
|
+
// Node built-ins only, on purpose: a client whose job is to download a file and hash it
|
|
4
|
+
// should not ask anyone to resolve a dependency tree, and the smaller the supply chain the
|
|
5
|
+
// less there is to audit. The sibling of client/src/loremfile_client/api.py, decision for
|
|
6
|
+
// decision.
|
|
7
|
+
//
|
|
8
|
+
// The one thing to know about this module: BASE_URL is a constant. There is no flag, no
|
|
9
|
+
// configuration file and no environment variable that points the client at another host —
|
|
10
|
+
// only a loopback override this project's own tests inject, refused for anything that is
|
|
11
|
+
// not 127.0.0.1, ::1 or localhost.
|
|
12
|
+
|
|
13
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
14
|
+
import { createReadStream } from "node:fs";
|
|
15
|
+
import { mkdir, open, rename, rm, stat } from "node:fs/promises";
|
|
16
|
+
import http from "node:http";
|
|
17
|
+
import https from "node:https";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
20
|
+
|
|
21
|
+
/** The only host this client talks to. */
|
|
22
|
+
export const BASE_URL = "https://loremfile.dev/";
|
|
23
|
+
|
|
24
|
+
/** Injected by this project's tests so they never touch production. Loopback only. */
|
|
25
|
+
export const OVERRIDE = "LOREMFILE_BASE_URL";
|
|
26
|
+
export const LOOPBACK = ["http://127.0.0.1:", "http://localhost:", "http://[::1]:"];
|
|
27
|
+
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
28
|
+
|
|
29
|
+
// The published rate limit is 30 requests a second per client; one file at a time with a
|
|
30
|
+
// pause between them is well under it, and a 429 is answered with patience.
|
|
31
|
+
export const PAUSE_MS = 500;
|
|
32
|
+
export const BACKOFF_MS = [2000, 4000, 8000];
|
|
33
|
+
export const TIMEOUT_MS = 300_000;
|
|
34
|
+
export const USER_AGENT = "loremfile-client";
|
|
35
|
+
|
|
36
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
37
|
+
const MAX_REDIRECTS = 10;
|
|
38
|
+
|
|
39
|
+
/** The request was wrong: an unknown path, a bad override, a version that has moved. */
|
|
40
|
+
export class Refused extends Error {}
|
|
41
|
+
|
|
42
|
+
/** loremfile.dev could not be read. */
|
|
43
|
+
export class Unreachable extends Error {}
|
|
44
|
+
|
|
45
|
+
/** Bytes arrived that are not the bytes the manifest describes. */
|
|
46
|
+
export class Mismatch extends Error {}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The two waits, in one object so a test can make them instant and the rate manners stay a
|
|
50
|
+
* property of this module rather than of whoever loops.
|
|
51
|
+
*/
|
|
52
|
+
export const timing = {
|
|
53
|
+
pace: () => sleep(PAUSE_MS),
|
|
54
|
+
backoff: (ms) => sleep(ms),
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export function baseUrl(env = process.env) {
|
|
58
|
+
const override = (env[OVERRIDE] ?? "").trim();
|
|
59
|
+
if (!override) {
|
|
60
|
+
return BASE_URL;
|
|
61
|
+
}
|
|
62
|
+
if (!isLoopback(override)) {
|
|
63
|
+
throw new Refused(
|
|
64
|
+
`${OVERRIDE} accepts a loopback address only, so that this project's tests can run ` +
|
|
65
|
+
`without touching production; ${JSON.stringify(override)} is not one. There is no ` +
|
|
66
|
+
"way to point this client at another host, by design.",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return override.endsWith("/") ? override : `${override}/`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isLoopback(value) {
|
|
73
|
+
// The prefix and the parsed host must agree: a prefix alone accepts a URL whose loopback
|
|
74
|
+
// address is only the userinfo in front of an `@` and whose real host is somewhere else.
|
|
75
|
+
if (!LOOPBACK.some((prefix) => value.startsWith(prefix))) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
let url;
|
|
79
|
+
try {
|
|
80
|
+
url = new URL(value);
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
return (
|
|
85
|
+
url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname) && !url.username && !url.password
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Node reports a refused connection to a name with two addresses as an AggregateError whose
|
|
90
|
+
// message is empty; its code is the useful part.
|
|
91
|
+
function reason(error) {
|
|
92
|
+
return error.message || error.code || String(error);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function request(url) {
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const client = url.protocol === "https:" ? https : http;
|
|
98
|
+
// identity, so the bytes hashed are the bytes published and never a CDN's compression.
|
|
99
|
+
const headers = { "User-Agent": USER_AGENT, "Accept-Encoding": "identity" };
|
|
100
|
+
const outgoing = client.get(url, { headers, timeout: TIMEOUT_MS }, resolve);
|
|
101
|
+
outgoing.on("timeout", () => {
|
|
102
|
+
outgoing.destroy(new Error(`no answer in ${TIMEOUT_MS / 1000} seconds`));
|
|
103
|
+
});
|
|
104
|
+
outgoing.on("error", reject);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* An open response, retrying only a 429 — our own rate limit asking for patience.
|
|
110
|
+
*
|
|
111
|
+
* The retry is here, around opening, because that is where a 429 arrives. A stream that
|
|
112
|
+
* fails halfway is not retried: this client's answer to a half-file is to delete it.
|
|
113
|
+
* Redirects are followed only while they stay on the same origin.
|
|
114
|
+
*/
|
|
115
|
+
async function respond(relative) {
|
|
116
|
+
const first = baseUrl() + relative.replace(/^\/+/, "");
|
|
117
|
+
for (const pause of [...BACKOFF_MS, null]) {
|
|
118
|
+
let url = new URL(first);
|
|
119
|
+
let response;
|
|
120
|
+
for (let hops = 0; ; hops += 1) {
|
|
121
|
+
try {
|
|
122
|
+
response = await request(url);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
throw new Unreachable(`${first} could not be read: ${reason(error)}`);
|
|
125
|
+
}
|
|
126
|
+
if (!REDIRECTS.has(response.statusCode) || !response.headers.location) {
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
response.resume();
|
|
130
|
+
const next = new URL(response.headers.location, url);
|
|
131
|
+
if (next.origin !== url.origin) {
|
|
132
|
+
throw new Refused(`${first} redirected off loremfile.dev, which is never followed`);
|
|
133
|
+
}
|
|
134
|
+
if (hops === MAX_REDIRECTS) {
|
|
135
|
+
throw new Unreachable(`${first} redirected more than ${MAX_REDIRECTS} times`);
|
|
136
|
+
}
|
|
137
|
+
url = next;
|
|
138
|
+
}
|
|
139
|
+
const status = response.statusCode;
|
|
140
|
+
if (status === 429 && pause !== null) {
|
|
141
|
+
response.resume();
|
|
142
|
+
await timing.backoff(pause);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (status < 200 || status >= 300) {
|
|
146
|
+
response.resume();
|
|
147
|
+
throw new Unreachable(`${first} answered ${status}`);
|
|
148
|
+
}
|
|
149
|
+
return response;
|
|
150
|
+
}
|
|
151
|
+
throw new Unreachable(`${first} is still answering 429`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The body in chunks, for fixtures — which run to 100 MB. A stream that breaks is
|
|
156
|
+
* `Unreachable`; whatever the caller does with each chunk fails as itself.
|
|
157
|
+
*/
|
|
158
|
+
async function* stream(relative) {
|
|
159
|
+
const response = await respond(relative);
|
|
160
|
+
const chunks = response[Symbol.asyncIterator]();
|
|
161
|
+
try {
|
|
162
|
+
for (;;) {
|
|
163
|
+
let next;
|
|
164
|
+
try {
|
|
165
|
+
next = await chunks.next();
|
|
166
|
+
} catch (error) {
|
|
167
|
+
throw new Unreachable(`${relative}: the download stopped: ${reason(error)}`);
|
|
168
|
+
}
|
|
169
|
+
if (next.done) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
yield next.value;
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
response.destroy();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The whole body at once. For the manifest, which is JSON and has to be parsed. */
|
|
180
|
+
async function fetchWhole(relative) {
|
|
181
|
+
const parts = [];
|
|
182
|
+
for await (const chunk of stream(relative)) {
|
|
183
|
+
parts.push(chunk);
|
|
184
|
+
}
|
|
185
|
+
return Buffer.concat(parts);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function manifest({ catalogVersion } = {}) {
|
|
189
|
+
let document;
|
|
190
|
+
try {
|
|
191
|
+
document = JSON.parse((await fetchWhole("manifest.json")).toString("utf8"));
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (error instanceof SyntaxError) {
|
|
194
|
+
throw new Unreachable(`the manifest is not JSON: ${error.message}`);
|
|
195
|
+
}
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
if (document === null || typeof document !== "object" || Array.isArray(document)) {
|
|
199
|
+
throw new Unreachable("the manifest is not a JSON object");
|
|
200
|
+
}
|
|
201
|
+
const published = String(document.catalog_version ?? "");
|
|
202
|
+
if (catalogVersion && published !== catalogVersion) {
|
|
203
|
+
throw new Refused(`loremfile.dev publishes catalog ${published}, not ${catalogVersion}`);
|
|
204
|
+
}
|
|
205
|
+
return document;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function active(document) {
|
|
209
|
+
return (document.fixtures ?? []).filter((entry) => (entry.status ?? "active") === "active");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The entries a request names, or `Refused` naming what does not exist. */
|
|
213
|
+
export function select(entries, { paths = [], formats = [] } = {}) {
|
|
214
|
+
const wantedPaths = new Set(paths);
|
|
215
|
+
const wantedFormats = new Set(formats);
|
|
216
|
+
if (wantedPaths.size === 0 && wantedFormats.size === 0) {
|
|
217
|
+
throw new Refused("name at least one path or format");
|
|
218
|
+
}
|
|
219
|
+
const byPath = new Map(entries.map((entry) => [entry.path, entry]));
|
|
220
|
+
const unknown = [...wantedPaths].filter((p) => !byPath.has(p)).sort();
|
|
221
|
+
if (unknown.length > 0) {
|
|
222
|
+
throw new Refused(`not published: ${unknown.join(", ")}`);
|
|
223
|
+
}
|
|
224
|
+
const publishedFormats = new Set(entries.map((entry) => entry.format));
|
|
225
|
+
const unknownFormats = [...wantedFormats].filter((f) => !publishedFormats.has(f)).sort();
|
|
226
|
+
if (unknownFormats.length > 0) {
|
|
227
|
+
throw new Refused(`no such format: ${unknownFormats.join(", ")}`);
|
|
228
|
+
}
|
|
229
|
+
return entries
|
|
230
|
+
.filter((entry) => wantedPaths.has(entry.path) || wantedFormats.has(entry.format))
|
|
231
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Where a fixture lands, refusing anything that would escape `dest`.
|
|
236
|
+
*
|
|
237
|
+
* The paths come from our own manifest, so this is not the day's most likely failure — but a
|
|
238
|
+
* client that writes where a downloaded document tells it to is the shape of problem this
|
|
239
|
+
* project publishes a fixture about (`edge/zip-directory-traversal-name.zip`). Backslashes
|
|
240
|
+
* count as separators, because on Windows they are.
|
|
241
|
+
*/
|
|
242
|
+
export function target(dest, fixturePath) {
|
|
243
|
+
const parts = fixturePath.split(/[\\/]/).filter((part) => part !== "" && part !== ".");
|
|
244
|
+
if (
|
|
245
|
+
fixturePath.startsWith("/") ||
|
|
246
|
+
path.win32.isAbsolute(fixturePath) ||
|
|
247
|
+
parts.includes("..") ||
|
|
248
|
+
parts.length === 0
|
|
249
|
+
) {
|
|
250
|
+
throw new Refused(`refusing ${JSON.stringify(fixturePath)}: not the shape of a fixture path`);
|
|
251
|
+
}
|
|
252
|
+
const root = path.resolve(dest);
|
|
253
|
+
const resolved = path.resolve(root, ...parts);
|
|
254
|
+
if (!resolved.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) {
|
|
255
|
+
throw new Refused(
|
|
256
|
+
`refusing ${JSON.stringify(fixturePath)}: it would be written outside ${dest}`,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
return resolved;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The wait between two downloads. */
|
|
263
|
+
export function pace() {
|
|
264
|
+
return timing.pace();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const GROUPED = new Intl.NumberFormat("en-US");
|
|
268
|
+
|
|
269
|
+
export function grouped(count) {
|
|
270
|
+
return GROUPED.format(count);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** What happened to one fixture. */
|
|
274
|
+
export class Result {
|
|
275
|
+
constructor(fixturePath, status, detail = "") {
|
|
276
|
+
this.path = fixturePath;
|
|
277
|
+
this.status = status; // written | skipped | ok | missing | changed
|
|
278
|
+
this.detail = detail;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
get ok() {
|
|
282
|
+
return ["written", "skipped", "ok"].includes(this.status);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Every byte of the chunk, or an error: a short write that went unnoticed would put a file
|
|
287
|
+
// whose hash was checked over bytes that never reached the disk at the published path.
|
|
288
|
+
async function writeAll(handle, chunk) {
|
|
289
|
+
let offset = 0;
|
|
290
|
+
while (offset < chunk.length) {
|
|
291
|
+
const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset);
|
|
292
|
+
if (bytesWritten === 0) {
|
|
293
|
+
throw new Error("the disk accepted no more bytes");
|
|
294
|
+
}
|
|
295
|
+
offset += bytesWritten;
|
|
296
|
+
}
|
|
297
|
+
return offset;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function exists(file) {
|
|
301
|
+
try {
|
|
302
|
+
await stat(file);
|
|
303
|
+
return true;
|
|
304
|
+
} catch {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Fetch one fixture, hashing as it arrives, and put it at its path only if it matches.
|
|
311
|
+
*
|
|
312
|
+
* The bytes go to a temporary file in the destination directory, not to memory and not to
|
|
313
|
+
* the system temporary directory: the first would cost 100 MB for the largest fixtures, and
|
|
314
|
+
* the second could be another filesystem, where the final move is a copy rather than a
|
|
315
|
+
* rename. A rename within one directory is atomic, so a reader of that directory sees either
|
|
316
|
+
* no file or the whole verified one — and the temporary file is removed on a mismatch, on an
|
|
317
|
+
* interrupted download, and on any other failure.
|
|
318
|
+
*/
|
|
319
|
+
export async function download(entry, dest, { force = false } = {}) {
|
|
320
|
+
const destination = target(dest, entry.path);
|
|
321
|
+
if (!force && (await exists(destination))) {
|
|
322
|
+
return new Result(entry.path, "skipped", "already here; --force overwrites");
|
|
323
|
+
}
|
|
324
|
+
const directory = path.dirname(destination);
|
|
325
|
+
await mkdir(directory, { recursive: true });
|
|
326
|
+
|
|
327
|
+
const partial = path.join(
|
|
328
|
+
directory,
|
|
329
|
+
`.${path.basename(destination)}.${randomBytes(6).toString("hex")}.part`,
|
|
330
|
+
);
|
|
331
|
+
const digest = createHash("sha256");
|
|
332
|
+
let written = 0;
|
|
333
|
+
const handle = await open(partial, "wx");
|
|
334
|
+
try {
|
|
335
|
+
try {
|
|
336
|
+
for await (const chunk of stream(entry.path)) {
|
|
337
|
+
digest.update(chunk);
|
|
338
|
+
written += await writeAll(handle, chunk);
|
|
339
|
+
}
|
|
340
|
+
} finally {
|
|
341
|
+
await handle.close();
|
|
342
|
+
}
|
|
343
|
+
const actual = digest.digest("hex");
|
|
344
|
+
if (actual !== entry.sha256) {
|
|
345
|
+
throw new Mismatch(
|
|
346
|
+
`${entry.path}: downloaded sha256 ${actual}, the manifest says ${entry.sha256}`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
await rename(partial, destination);
|
|
350
|
+
} finally {
|
|
351
|
+
// A no-op once the rename has happened, and the whole point otherwise.
|
|
352
|
+
await rm(partial, { force: true });
|
|
353
|
+
}
|
|
354
|
+
return new Result(entry.path, "written", `${grouped(written)} bytes`);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function hashFile(file) {
|
|
358
|
+
const digest = createHash("sha256");
|
|
359
|
+
for await (const chunk of createReadStream(file)) {
|
|
360
|
+
digest.update(chunk);
|
|
361
|
+
}
|
|
362
|
+
return digest.digest("hex");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function fileInfo(file) {
|
|
366
|
+
try {
|
|
367
|
+
const info = await stat(file);
|
|
368
|
+
return info.isFile() ? info : null;
|
|
369
|
+
} catch {
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Whether a fixture is on disk at all, without reading it. */
|
|
375
|
+
export async function held(entry, dest) {
|
|
376
|
+
return (await fileInfo(target(dest, entry.path))) !== null;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Check a fixture already on disk against the published manifest. */
|
|
380
|
+
export async function verify(entry, dest) {
|
|
381
|
+
const destination = target(dest, entry.path);
|
|
382
|
+
const info = await fileInfo(destination);
|
|
383
|
+
if (info === null) {
|
|
384
|
+
return new Result(entry.path, "missing", `not in ${dest}`);
|
|
385
|
+
}
|
|
386
|
+
const actual = await hashFile(destination);
|
|
387
|
+
if (actual !== entry.sha256) {
|
|
388
|
+
const expected = String(entry.sha256).slice(0, 12);
|
|
389
|
+
return new Result(entry.path, "changed", `sha256 ${actual.slice(0, 12)}, expected ${expected}`);
|
|
390
|
+
}
|
|
391
|
+
return new Result(entry.path, "ok", `${grouped(info.size)} bytes`);
|
|
392
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// `loremfile get | list | verify`, the same three commands as the Python client.
|
|
2
|
+
//
|
|
3
|
+
// node:util's parseArgs rather than a framework, because the package has no dependencies and
|
|
4
|
+
// this is three subcommands. Exit codes are the contract: 0 fine, 1 a file failed
|
|
5
|
+
// verification or is missing, 2 the request was wrong, 3 loremfile.dev could not be read.
|
|
6
|
+
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
|
|
10
|
+
import * as api from "./api.js";
|
|
11
|
+
|
|
12
|
+
export const OK = 0;
|
|
13
|
+
export const FAILED = 1;
|
|
14
|
+
export const REFUSED = 2;
|
|
15
|
+
export const UNREACHABLE = 3;
|
|
16
|
+
export const DEFAULT_DEST = "loremfile-fixtures";
|
|
17
|
+
|
|
18
|
+
export const VERSION = JSON.parse(
|
|
19
|
+
readFileSync(new URL("../package.json", import.meta.url), "utf8"),
|
|
20
|
+
).version;
|
|
21
|
+
|
|
22
|
+
const SHARED = {
|
|
23
|
+
json: { type: "boolean", help: "Print one JSON object." },
|
|
24
|
+
quiet: { type: "boolean", help: "Print nothing but failures." },
|
|
25
|
+
"catalog-version": {
|
|
26
|
+
type: "string",
|
|
27
|
+
value: "X.Y.Z",
|
|
28
|
+
help: "Refuse to run unless loremfile.dev publishes this catalog version.",
|
|
29
|
+
},
|
|
30
|
+
help: { type: "boolean", short: "h", help: "Show this help." },
|
|
31
|
+
};
|
|
32
|
+
const FORMAT = { type: "string", multiple: true, value: "FMT" };
|
|
33
|
+
const DEST = { type: "string", value: "DIR", help: `Default: ${DEFAULT_DEST}` };
|
|
34
|
+
|
|
35
|
+
/** Every option each command accepts. Exported so a test can read them off, not the source. */
|
|
36
|
+
export const COMMANDS = {
|
|
37
|
+
get: {
|
|
38
|
+
summary: "Download fixtures and verify them.",
|
|
39
|
+
positionals: "PATH… (e.g. pdf/minimal.pdf)",
|
|
40
|
+
options: {
|
|
41
|
+
format: { ...FORMAT, help: "Every published file of this format. Repeatable." },
|
|
42
|
+
dest: DEST,
|
|
43
|
+
force: { type: "boolean", help: "Overwrite files already there." },
|
|
44
|
+
"dry-run": { type: "boolean", help: "List what would be fetched." },
|
|
45
|
+
...SHARED,
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
list: {
|
|
49
|
+
summary: "What is published, without downloading.",
|
|
50
|
+
positionals: null,
|
|
51
|
+
options: {
|
|
52
|
+
format: { ...FORMAT, help: "Only this format. Repeatable." },
|
|
53
|
+
tag: { type: "string", multiple: true, value: "TAG", help: "Only this tag. Repeatable." },
|
|
54
|
+
"max-bytes": { type: "string", value: "N", help: "Only files of at most N bytes." },
|
|
55
|
+
...SHARED,
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
verify: {
|
|
59
|
+
summary: "Check files on disk against the manifest.",
|
|
60
|
+
positionals: "PATH…",
|
|
61
|
+
options: {
|
|
62
|
+
format: { ...FORMAT, help: "Every published file of this format. Repeatable." },
|
|
63
|
+
dest: DEST,
|
|
64
|
+
...SHARED,
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
class Usage extends Error {}
|
|
70
|
+
|
|
71
|
+
function usage() {
|
|
72
|
+
return [
|
|
73
|
+
`loremfile ${VERSION}`,
|
|
74
|
+
"Download CC0 sample files from loremfile.dev and check every byte.",
|
|
75
|
+
"",
|
|
76
|
+
"usage: loremfile {get,list,verify} [options]",
|
|
77
|
+
...Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(8)}${command.summary}`),
|
|
78
|
+
"",
|
|
79
|
+
"`loremfile COMMAND --help` lists a command's options.",
|
|
80
|
+
"Files come from loremfile.dev and nowhere else; there is no mirror option.",
|
|
81
|
+
"",
|
|
82
|
+
].join("\n");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function commandHelp(name) {
|
|
86
|
+
const command = COMMANDS[name];
|
|
87
|
+
const positionals = command.positionals ? ` ${command.positionals}` : "";
|
|
88
|
+
const lines = [`usage: loremfile ${name} [options]${positionals}`, command.summary, ""];
|
|
89
|
+
for (const [option, spec] of Object.entries(command.options)) {
|
|
90
|
+
const short = spec.short ? `-${spec.short}, ` : "";
|
|
91
|
+
const flag = `${short}--${option}${spec.value ? ` ${spec.value}` : ""}`;
|
|
92
|
+
lines.push(` ${flag.padEnd(28)}${spec.help ?? ""}`);
|
|
93
|
+
}
|
|
94
|
+
return `${lines.join("\n")}\n`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function parse(argv) {
|
|
98
|
+
const [name, ...rest] = argv;
|
|
99
|
+
if (name === undefined) {
|
|
100
|
+
throw new Usage("name a command: get, list or verify");
|
|
101
|
+
}
|
|
102
|
+
if (!Object.hasOwn(COMMANDS, name)) {
|
|
103
|
+
throw new Usage(`no such command: ${name}`);
|
|
104
|
+
}
|
|
105
|
+
const command = COMMANDS[name];
|
|
106
|
+
// parseArgs rejects a `short` or `multiple` key that is present but undefined, so only the
|
|
107
|
+
// keys a spec actually sets are passed on; `help` and `value` are for commandHelp alone.
|
|
108
|
+
const options = Object.fromEntries(
|
|
109
|
+
Object.entries(command.options).map(([option, { type, short, multiple }]) => [
|
|
110
|
+
option,
|
|
111
|
+
{ type, ...(short ? { short } : {}), ...(multiple ? { multiple } : {}) },
|
|
112
|
+
]),
|
|
113
|
+
);
|
|
114
|
+
const allowPositionals = command.positionals !== null;
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = parseArgs({ args: rest, options, allowPositionals, strict: true });
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (String(error.code).startsWith("ERR_PARSE_ARGS")) {
|
|
120
|
+
throw new Usage(error.message);
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
const values = parsed.values;
|
|
125
|
+
const args = {
|
|
126
|
+
command: name,
|
|
127
|
+
help: Boolean(values.help),
|
|
128
|
+
paths: parsed.positionals,
|
|
129
|
+
format: values.format ?? [],
|
|
130
|
+
tag: values.tag ?? [],
|
|
131
|
+
dest: values.dest ?? DEFAULT_DEST,
|
|
132
|
+
force: Boolean(values.force),
|
|
133
|
+
dryRun: Boolean(values["dry-run"]),
|
|
134
|
+
json: Boolean(values.json),
|
|
135
|
+
quiet: Boolean(values.quiet),
|
|
136
|
+
catalogVersion: values["catalog-version"],
|
|
137
|
+
maxBytes: null,
|
|
138
|
+
};
|
|
139
|
+
if (values["max-bytes"] !== undefined) {
|
|
140
|
+
const text = values["max-bytes"].trim();
|
|
141
|
+
if (!/^[+-]?\d+$/.test(text)) {
|
|
142
|
+
throw new Usage(`--max-bytes takes a whole number, not ${JSON.stringify(text)}`);
|
|
143
|
+
}
|
|
144
|
+
args.maxBytes = Number(text);
|
|
145
|
+
}
|
|
146
|
+
return args;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function emit(args, summary, results, io) {
|
|
150
|
+
if (args.json) {
|
|
151
|
+
const items = results.map(({ path, status, detail }) => ({ path, status, detail }));
|
|
152
|
+
io.out(`${JSON.stringify({ summary, items }, null, 2)}\n`);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
for (const result of results) {
|
|
156
|
+
if (!result.ok || !args.quiet) {
|
|
157
|
+
const detail = result.detail ? ` ${result.detail}` : "";
|
|
158
|
+
io.out(` ${result.status.padEnd(8)} ${result.path}${detail}\n`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!args.quiet) {
|
|
162
|
+
const pairs = Object.entries(summary).map(([key, value]) => `${key}=${value}`);
|
|
163
|
+
io.out(`${pairs.join(", ")}\n`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function runGet(args, io) {
|
|
168
|
+
const published = api.active(await api.manifest({ catalogVersion: args.catalogVersion }));
|
|
169
|
+
const entries = api.select(published, { paths: args.paths, formats: args.format });
|
|
170
|
+
if (args.dryRun) {
|
|
171
|
+
const total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
172
|
+
emit(
|
|
173
|
+
args,
|
|
174
|
+
{ files: entries.length, bytes: total, dest: args.dest, "dry-run": true },
|
|
175
|
+
entries.map((e) => new api.Result(e.path, "would fetch", `${api.grouped(e.bytes)} bytes`)),
|
|
176
|
+
io,
|
|
177
|
+
);
|
|
178
|
+
return OK;
|
|
179
|
+
}
|
|
180
|
+
const results = [];
|
|
181
|
+
for (const [index, entry] of entries.entries()) {
|
|
182
|
+
results.push(await api.download(entry, args.dest, { force: args.force }));
|
|
183
|
+
if (index + 1 < entries.length) {
|
|
184
|
+
await api.pace();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
emit(args, { files: results.length, dest: args.dest }, results, io);
|
|
188
|
+
return OK;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function runList(args, io) {
|
|
192
|
+
let entries = api.active(await api.manifest({ catalogVersion: args.catalogVersion }));
|
|
193
|
+
if (args.format.length > 0) {
|
|
194
|
+
entries = entries.filter((e) => args.format.includes(e.format));
|
|
195
|
+
}
|
|
196
|
+
if (args.tag.length > 0) {
|
|
197
|
+
entries = entries.filter((e) => (e.tags ?? []).some((tag) => args.tag.includes(tag)));
|
|
198
|
+
}
|
|
199
|
+
if (args.maxBytes !== null) {
|
|
200
|
+
entries = entries.filter((e) => e.bytes <= args.maxBytes);
|
|
201
|
+
}
|
|
202
|
+
const results = entries.map(
|
|
203
|
+
(e) => new api.Result(e.path, "listed", `${api.grouped(e.bytes)} bytes ${e.mime}`),
|
|
204
|
+
);
|
|
205
|
+
emit(args, { files: results.length }, results, io);
|
|
206
|
+
return OK;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function runVerify(args, io) {
|
|
210
|
+
let entries = api.active(await api.manifest({ catalogVersion: args.catalogVersion }));
|
|
211
|
+
if (args.paths.length > 0 || args.format.length > 0) {
|
|
212
|
+
entries = api.select(entries, { paths: args.paths, formats: args.format });
|
|
213
|
+
} else {
|
|
214
|
+
// Everything the destination actually holds, so `verify` alone checks a directory.
|
|
215
|
+
const held = [];
|
|
216
|
+
for (const entry of entries) {
|
|
217
|
+
if (await api.held(entry, args.dest)) {
|
|
218
|
+
held.push(entry);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
entries = held;
|
|
222
|
+
}
|
|
223
|
+
const results = [];
|
|
224
|
+
for (const entry of entries) {
|
|
225
|
+
results.push(await api.verify(entry, args.dest));
|
|
226
|
+
}
|
|
227
|
+
const failing = results.filter((r) => !r.ok);
|
|
228
|
+
emit(args, { checked: results.length, failing: failing.length }, results, io);
|
|
229
|
+
return failing.length > 0 ? FAILED : OK;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const RUNNERS = { get: runGet, list: runList, verify: runVerify };
|
|
233
|
+
|
|
234
|
+
const STDIO = {
|
|
235
|
+
out: (text) => process.stdout.write(text),
|
|
236
|
+
err: (text) => process.stderr.write(text),
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export async function main(argv, io = STDIO) {
|
|
240
|
+
if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "-h")) {
|
|
241
|
+
io.out(usage());
|
|
242
|
+
return OK;
|
|
243
|
+
}
|
|
244
|
+
if (argv.length === 1 && argv[0] === "--version") {
|
|
245
|
+
io.out(`loremfile ${VERSION}\n`);
|
|
246
|
+
return OK;
|
|
247
|
+
}
|
|
248
|
+
let args;
|
|
249
|
+
try {
|
|
250
|
+
args = parse(argv);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (error instanceof Usage) {
|
|
253
|
+
io.err(`loremfile: ${error.message}\n\n${usage()}`);
|
|
254
|
+
return REFUSED;
|
|
255
|
+
}
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
if (args.help) {
|
|
259
|
+
io.out(commandHelp(args.command));
|
|
260
|
+
return OK;
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
return await RUNNERS[args.command](args, io);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (error instanceof api.Refused) {
|
|
266
|
+
io.err(`loremfile: ${error.message}\n`);
|
|
267
|
+
return REFUSED;
|
|
268
|
+
}
|
|
269
|
+
if (error instanceof api.Mismatch) {
|
|
270
|
+
io.err(`loremfile: ${error.message}\n`);
|
|
271
|
+
return FAILED;
|
|
272
|
+
}
|
|
273
|
+
if (error instanceof api.Unreachable) {
|
|
274
|
+
io.err(`loremfile: ${error.message}\n`);
|
|
275
|
+
return UNREACHABLE;
|
|
276
|
+
}
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
}
|