@stigmer/artifact-fetch 0.0.0-stage → 0.1.1

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/retry.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The download retry contract every artifact fetch runs under.
3
+ *
4
+ * A connection that resets before or during the body, a 5xx or a 429 is tried
5
+ * again with a doubling wait, so a network blip does not fail a first
6
+ * `stigmer up`, a CI lane, an image build or a person's first Claude turn. Any
7
+ * other HTTP status is an answer and fails at once. The body is read inside
8
+ * the attempt, so a connection that drops after the headers is as transient as
9
+ * one that never connects. An abort is never retried: the caller asked to
10
+ * stop.
11
+ */
12
+ import { setTimeout as delay } from "node:timers/promises";
13
+ import { ArtifactFetchError } from "./errors.js";
14
+ /** Attempts per download before a transient failure is reported. */
15
+ export const DOWNLOAD_ATTEMPTS = 4;
16
+ /** The wait before the second attempt; it doubles before each later one (1 s, 2 s, 4 s). */
17
+ export const DOWNLOAD_RETRY_BASE_DELAY_MS = 1_000;
18
+ /** The process's network, with either half replaced (tests). */
19
+ export function network(overrides = {}) {
20
+ return { fetch: overrides.fetchImpl ?? fetch, sleep: overrides.sleep ?? ((ms) => delay(ms)) };
21
+ }
22
+ /**
23
+ * One download of `url`, retried by the contract above, with `read` consuming
24
+ * the response inside each attempt. `label` names the artifact in the error.
25
+ * `signal`, when given, is passed to the fetch; once it aborts, its reason is
26
+ * thrown as is, never retried and never wrapped.
27
+ */
28
+ export async function fetchWithRetry(net, url, label, read, signal) {
29
+ let lastFailure = "";
30
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
31
+ if (attempt > 1)
32
+ await net.sleep(DOWNLOAD_RETRY_BASE_DELAY_MS * 2 ** (attempt - 2));
33
+ signal?.throwIfAborted();
34
+ let res;
35
+ try {
36
+ res = await net.fetch(url, signal === undefined ? undefined : { signal });
37
+ }
38
+ catch (err) {
39
+ signal?.throwIfAborted();
40
+ lastFailure = describeFailure(err);
41
+ continue;
42
+ }
43
+ if (!res.ok) {
44
+ if (!isTransientStatus(res.status)) {
45
+ throw new ArtifactFetchError(`failed to download ${label}: HTTP ${res.status} from ${url}`);
46
+ }
47
+ lastFailure = `HTTP ${res.status}`;
48
+ continue;
49
+ }
50
+ try {
51
+ return await read(res);
52
+ }
53
+ catch (err) {
54
+ signal?.throwIfAborted();
55
+ if (err instanceof ArtifactFetchError)
56
+ throw err;
57
+ lastFailure = describeFailure(err);
58
+ }
59
+ }
60
+ throw new ArtifactFetchError(`failed to download ${label} from ${url} after ${DOWNLOAD_ATTEMPTS} attempts: ${lastFailure}`, [
61
+ "check the network connection, then run the command again",
62
+ ]);
63
+ }
64
+ // A server error or a rate limit may clear on its own; any other status will not.
65
+ function isTransientStatus(status) {
66
+ return status >= 500 || status === 429;
67
+ }
68
+ /** An error as one line, with Node fetch's socket error behind "fetch failed" appended. */
69
+ export function describeFailure(err) {
70
+ if (!(err instanceof Error))
71
+ return String(err);
72
+ return err.cause instanceof Error ? `${err.message}: ${err.cause.message}` : err.message;
73
+ }
74
+ //# sourceMappingURL=retry.js.map
package/retry.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["src/retry.ts"],"names":[],"mappings":"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"}
package/src/digest.ts ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The digests an artifact is checked against before a byte of it is used.
3
+ *
4
+ * Two publishers, two forms, one comparison: a release's `sha256sum`-format
5
+ * checksum file (Temporal's `checksums.txt`) records lowercase sha256 hex per
6
+ * asset, and npm records a package tarball's Subresource Integrity string
7
+ * (`sha512-<base64>`) in the registry and in every lockfile. Both parse to an
8
+ * {@link ExpectedDigest}, the algorithm and the raw digest bytes, so a
9
+ * download is hashed once while it streams and compared by bytes.
10
+ */
11
+
12
+ import { createHash } from "node:crypto";
13
+
14
+ /** The hash algorithms an expected digest may name; SHA-1, which old npm lockfiles carry, is refused. */
15
+ export type DigestAlgorithm = "sha256" | "sha384" | "sha512";
16
+
17
+ /** What an artifact's bytes must hash to. */
18
+ export interface ExpectedDigest {
19
+ readonly algorithm: DigestAlgorithm;
20
+ readonly digest: Buffer;
21
+ }
22
+
23
+ /** Lowercase hex sha256 of `bytes`. */
24
+ export function sha256Hex(bytes: Uint8Array): string {
25
+ return createHash("sha256").update(bytes).digest("hex");
26
+ }
27
+
28
+ /**
29
+ * The sha256 a `shasum`/`sha256sum`-format file records for `filename`, lowercase
30
+ * hex, or "" when the file has no entry for it. Each line is "<hex> <filename>";
31
+ * `sha256sum -b` writes the filename with a leading "*" (binary mode), which is
32
+ * not part of the name. A release-wide file lists every asset, so the match is
33
+ * by filename, never by position.
34
+ */
35
+ export function parseShasum(content: string, filename: string): string {
36
+ for (const line of content.split("\n")) {
37
+ const [hex, name] = line.trim().split(/\s+/, 2);
38
+ if (hex === undefined || name === undefined) continue;
39
+ if (name.replace(/^\*/, "") === filename) return hex.toLowerCase();
40
+ }
41
+ return "";
42
+ }
43
+
44
+ const STRENGTH: Record<DigestAlgorithm, number> = { sha256: 1, sha384: 2, sha512: 3 };
45
+
46
+ /**
47
+ * The strongest digest an SRI string names (`sha512-<base64>`, possibly several
48
+ * space-separated, as the W3C form allows). Throws when it names none this
49
+ * library accepts: an integrity it cannot check is not a pin.
50
+ */
51
+ export function parseIntegrity(sri: string): ExpectedDigest {
52
+ let best: ExpectedDigest | undefined;
53
+ for (const token of sri.trim().split(/\s+/)) {
54
+ const dash = token.indexOf("-");
55
+ if (dash <= 0) continue;
56
+ const algorithm = token.slice(0, dash);
57
+ if (!Object.hasOwn(STRENGTH, algorithm)) continue;
58
+ // An SRI token may carry options after a `?`; the digest ends there.
59
+ const options = token.indexOf("?", dash);
60
+ const digest = Buffer.from(token.slice(dash + 1, options === -1 ? undefined : options), "base64");
61
+ const candidate = { algorithm: algorithm as DigestAlgorithm, digest };
62
+ if (digest.length > 0 && (best === undefined || STRENGTH[candidate.algorithm] > STRENGTH[best.algorithm])) best = candidate;
63
+ }
64
+ if (best === undefined) throw new Error(`integrity "${sri}" names no sha256, sha384 or sha512 digest`);
65
+ return best;
66
+ }
67
+
68
+ /** The expected digest a sha256 hex string (a checksum file's line) names. */
69
+ export function sha256Digest(hex: string): ExpectedDigest {
70
+ return { algorithm: "sha256", digest: Buffer.from(hex, "hex") };
71
+ }
72
+
73
+ /** A digest as its publisher writes it: hex for sha256, SRI for the others. */
74
+ export function formatDigest(expected: ExpectedDigest): string {
75
+ return expected.algorithm === "sha256" ? expected.digest.toString("hex") : `${expected.algorithm}-${expected.digest.toString("base64")}`;
76
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * A verified download streamed to a file.
3
+ *
4
+ * The response body is written to `dest` while it is hashed, so an artifact
5
+ * of any size costs one buffer of memory, and the file is only handed back
6
+ * once the whole body matched its expected digest. A mismatch is an answer,
7
+ * not a blip: the file is removed and the download is refused without a
8
+ * retry. Every other failure (the retry contract in `retry.ts` given up, an
9
+ * abort) also removes the file, so `dest` exists afterwards exactly when it
10
+ * holds the verified bytes.
11
+ */
12
+
13
+ import { createHash } from "node:crypto";
14
+ import { open, rm } from "node:fs/promises";
15
+ import { ArtifactFetchError } from "./errors.js";
16
+ import { formatDigest, type ExpectedDigest } from "./digest.js";
17
+ import { fetchWithRetry, network } from "./retry.js";
18
+
19
+ export interface DownloadToFileOptions {
20
+ /** The artifact's URL. */
21
+ readonly url: string;
22
+ /** The file the verified bytes are written to; replaced when it exists. */
23
+ readonly dest: string;
24
+ /** What the whole body must hash to. */
25
+ readonly expected: ExpectedDigest;
26
+ /** The artifact's name in errors ("Claude engine", "Temporal CLI"). */
27
+ readonly label: string;
28
+ /** Stops the download; the file is removed and the signal's reason thrown. */
29
+ readonly signal?: AbortSignal;
30
+ /** Called after every chunk with the bytes received so far in this attempt and the advertised length, when the server sent one. */
31
+ readonly onProgress?: (received: number, total: number | undefined) => void;
32
+ /** Override the fetch implementation (tests). */
33
+ readonly fetchImpl?: typeof fetch;
34
+ /** Override the wait between download attempts (tests). */
35
+ readonly sleep?: (ms: number) => Promise<void>;
36
+ }
37
+
38
+ /** Download `url` to `dest`, verified against `expected`; resolves with the byte count. */
39
+ export async function downloadToFile(options: DownloadToFileOptions): Promise<{ readonly bytes: number }> {
40
+ const net = network({ fetchImpl: options.fetchImpl, sleep: options.sleep });
41
+ try {
42
+ const { bytes, actual } = await fetchWithRetry(net, options.url, options.label, (res) => writeBody(res, options), options.signal);
43
+ if (!actual.equals(options.expected.digest)) {
44
+ throw new ArtifactFetchError(`${options.label} checksum mismatch — refusing to use the download`, [
45
+ `expected: ${formatDigest(options.expected)}`,
46
+ `actual: ${formatDigest({ algorithm: options.expected.algorithm, digest: actual })}`,
47
+ `archive: ${options.url}`,
48
+ ]);
49
+ }
50
+ return { bytes };
51
+ } catch (err) {
52
+ await rm(options.dest, { force: true });
53
+ throw err;
54
+ }
55
+ }
56
+
57
+ // One attempt's body: truncate the file, then hash and write each chunk in
58
+ // order. A body that ends early throws, and the retry contract decides.
59
+ async function writeBody(res: Response, options: DownloadToFileOptions): Promise<{ bytes: number; actual: Buffer }> {
60
+ if (res.body === null) throw new Error("the response has no body");
61
+ // A length names the bytes on the wire; fetch decodes a content-encoding
62
+ // before the body reaches here, so only an unencoded length counts.
63
+ const advertised = res.headers.get("content-encoding") === null ? Number(res.headers.get("content-length")) : Number.NaN;
64
+ const total = Number.isFinite(advertised) && advertised > 0 ? advertised : undefined;
65
+ const hash = createHash(options.expected.algorithm);
66
+ const file = await open(options.dest, "w", 0o644);
67
+ let bytes = 0;
68
+ try {
69
+ for await (const chunk of res.body) {
70
+ hash.update(chunk);
71
+ await file.write(chunk);
72
+ bytes += chunk.byteLength;
73
+ options.onProgress?.(bytes, total);
74
+ }
75
+ } finally {
76
+ await file.close();
77
+ }
78
+ if (total !== undefined && bytes !== total) throw new Error(`the body ended after ${bytes} of ${total} bytes`);
79
+ return { bytes, actual: hash.digest() };
80
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The one error this library throws for a fetch that did not produce a
3
+ * verified artifact: a persistent network failure, an HTTP status that is an
4
+ * answer, a digest mismatch, or an archive that breaks the extraction rules.
5
+ * `message` says what failed and `details` the facts behind it (the URL, the
6
+ * expected and actual digest, what to do), one line each, so a consumer
7
+ * renders its own surface (the CLI's exit error, the runner's turn failure)
8
+ * without parsing the message.
9
+ */
10
+ export class ArtifactFetchError extends Error {
11
+ readonly details: readonly string[];
12
+
13
+ constructor(message: string, details: readonly string[] = []) {
14
+ super(message);
15
+ this.name = "ArtifactFetchError";
16
+ this.details = details;
17
+ }
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ export { ArtifactFetchError } from "./errors.js";
2
+ export { DOWNLOAD_ATTEMPTS, DOWNLOAD_RETRY_BASE_DELAY_MS, describeFailure, fetchWithRetry, network, type Network } from "./retry.js";
3
+ export {
4
+ formatDigest,
5
+ parseIntegrity,
6
+ parseShasum,
7
+ sha256Digest,
8
+ sha256Hex,
9
+ type DigestAlgorithm,
10
+ type ExpectedDigest,
11
+ } from "./digest.js";
12
+ export { downloadToFile, type DownloadToFileOptions } from "./download.js";
13
+ export {
14
+ TAR_BLOCK,
15
+ extractPackageTarball,
16
+ extractTarEntry,
17
+ parseTarHeader,
18
+ readTar,
19
+ type ExtractPackageOptions,
20
+ type TarEntry,
21
+ type TarEntryKind,
22
+ type TarHeader,
23
+ } from "./tar.js";
package/src/retry.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The download retry contract every artifact fetch runs under.
3
+ *
4
+ * A connection that resets before or during the body, a 5xx or a 429 is tried
5
+ * again with a doubling wait, so a network blip does not fail a first
6
+ * `stigmer up`, a CI lane, an image build or a person's first Claude turn. Any
7
+ * other HTTP status is an answer and fails at once. The body is read inside
8
+ * the attempt, so a connection that drops after the headers is as transient as
9
+ * one that never connects. An abort is never retried: the caller asked to
10
+ * stop.
11
+ */
12
+
13
+ import { setTimeout as delay } from "node:timers/promises";
14
+ import { ArtifactFetchError } from "./errors.js";
15
+
16
+ /** Attempts per download before a transient failure is reported. */
17
+ export const DOWNLOAD_ATTEMPTS = 4;
18
+
19
+ /** The wait before the second attempt; it doubles before each later one (1 s, 2 s, 4 s). */
20
+ export const DOWNLOAD_RETRY_BASE_DELAY_MS = 1_000;
21
+
22
+ /** The network a download runs over: the fetch it calls and the wait between attempts. */
23
+ export interface Network {
24
+ readonly fetch: typeof fetch;
25
+ readonly sleep: (ms: number) => Promise<void>;
26
+ }
27
+
28
+ /** The process's network, with either half replaced (tests). */
29
+ export function network(overrides: { readonly fetchImpl?: typeof fetch; readonly sleep?: (ms: number) => Promise<void> } = {}): Network {
30
+ return { fetch: overrides.fetchImpl ?? fetch, sleep: overrides.sleep ?? ((ms) => delay(ms)) };
31
+ }
32
+
33
+ /**
34
+ * One download of `url`, retried by the contract above, with `read` consuming
35
+ * the response inside each attempt. `label` names the artifact in the error.
36
+ * `signal`, when given, is passed to the fetch; once it aborts, its reason is
37
+ * thrown as is, never retried and never wrapped.
38
+ */
39
+ export async function fetchWithRetry<T>(
40
+ net: Network,
41
+ url: string,
42
+ label: string,
43
+ read: (res: Response) => Promise<T>,
44
+ signal?: AbortSignal,
45
+ ): Promise<T> {
46
+ let lastFailure = "";
47
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
48
+ if (attempt > 1) await net.sleep(DOWNLOAD_RETRY_BASE_DELAY_MS * 2 ** (attempt - 2));
49
+ signal?.throwIfAborted();
50
+
51
+ let res: Response;
52
+ try {
53
+ res = await net.fetch(url, signal === undefined ? undefined : { signal });
54
+ } catch (err) {
55
+ signal?.throwIfAborted();
56
+ lastFailure = describeFailure(err);
57
+ continue;
58
+ }
59
+ if (!res.ok) {
60
+ if (!isTransientStatus(res.status)) {
61
+ throw new ArtifactFetchError(`failed to download ${label}: HTTP ${res.status} from ${url}`);
62
+ }
63
+ lastFailure = `HTTP ${res.status}`;
64
+ continue;
65
+ }
66
+ try {
67
+ return await read(res);
68
+ } catch (err) {
69
+ signal?.throwIfAborted();
70
+ if (err instanceof ArtifactFetchError) throw err;
71
+ lastFailure = describeFailure(err);
72
+ }
73
+ }
74
+ throw new ArtifactFetchError(`failed to download ${label} from ${url} after ${DOWNLOAD_ATTEMPTS} attempts: ${lastFailure}`, [
75
+ "check the network connection, then run the command again",
76
+ ]);
77
+ }
78
+
79
+ // A server error or a rate limit may clear on its own; any other status will not.
80
+ function isTransientStatus(status: number): boolean {
81
+ return status >= 500 || status === 429;
82
+ }
83
+
84
+ /** An error as one line, with Node fetch's socket error behind "fetch failed" appended. */
85
+ export function describeFailure(err: unknown): string {
86
+ if (!(err instanceof Error)) return String(err);
87
+ return err.cause instanceof Error ? `${err.message}: ${err.cause.message}` : err.message;
88
+ }
package/src/tar.ts ADDED
@@ -0,0 +1,290 @@
1
+ /**
2
+ * One minimal POSIX/ustar reader, two uses.
3
+ *
4
+ * {@link parseTarHeader} reads a 512-byte header block: the name (with the
5
+ * ustar prefix), the octal mode and size, the type flag, and whether the
6
+ * header's checksum holds. Everything else here walks archives with it:
7
+ *
8
+ * - {@link extractTarEntry} returns one regular file by basename from an
9
+ * uncompressed archive in memory (a release's single binary, such as the
10
+ * Temporal CLI);
11
+ * - {@link readTar} walks an archive as it streams, entry by entry, and
12
+ * {@link extractPackageTarball} uses it to unpack a whole npm package from
13
+ * a `.tgz` on disk under strict rules: every entry a regular file under the
14
+ * prefix npm packs with (`package/`), no absolute path, no `.` or `..`
15
+ * segment, no duplicate, a valid header checksum. Any other entry refuses
16
+ * the archive, links and pax headers included, so a package can never
17
+ * write outside the directory it is unpacked into. npm packs regular files
18
+ * only, so a published package passes.
19
+ *
20
+ * No native `tar` and no dependency: the CLI's base install stays lean, and
21
+ * the runner bundles this into its single file.
22
+ */
23
+
24
+ import { createReadStream } from "node:fs";
25
+ import { mkdir, open } from "node:fs/promises";
26
+ import { dirname, isAbsolute, join, sep } from "node:path";
27
+ import { pipeline } from "node:stream/promises";
28
+ import { createGunzip } from "node:zlib";
29
+ import { ArtifactFetchError } from "./errors.js";
30
+
31
+ /** A tar block: headers and data are padded to it. */
32
+ export const TAR_BLOCK = 512;
33
+
34
+ /** What an entry is, from its type flag. */
35
+ export type TarEntryKind = "file" | "directory" | "symlink" | "hardlink" | "pax" | "other";
36
+
37
+ /** One header block, read. */
38
+ export interface TarHeader {
39
+ /** The entry's path: the ustar prefix and name joined, as the archive spells it. */
40
+ readonly name: string;
41
+ /** Permission bits from the header (octal), 0 when unreadable. */
42
+ readonly mode: number;
43
+ /** The data's length in bytes; `NaN` when the size field is not octal. */
44
+ readonly size: number;
45
+ readonly kind: TarEntryKind;
46
+ /** The raw type flag character. */
47
+ readonly typeFlag: string;
48
+ /** Whether the header's stored checksum equals its computed one. */
49
+ readonly checksumValid: boolean;
50
+ }
51
+
52
+ /** The header in `block`, or `null` for a zero block, which marks the end of an archive. */
53
+ export function parseTarHeader(block: Uint8Array): TarHeader | null {
54
+ if (block.every((byte) => byte === 0)) return null;
55
+ const name = readCString(block, 0, 100);
56
+ const magic = readCString(block, 257, 6);
57
+ const prefix = magic.startsWith("ustar") ? readCString(block, 345, 155) : "";
58
+ const typeFlag = String.fromCharCode(block[156] ?? 0);
59
+ return {
60
+ name: prefix === "" ? name : `${prefix}/${name}`,
61
+ mode: readOctal(block, 100, 8) || 0,
62
+ size: readOctal(block, 124, 12),
63
+ kind: kindOf(typeFlag),
64
+ typeFlag,
65
+ checksumValid: readOctal(block, 148, 8) === headerChecksum(block),
66
+ };
67
+ }
68
+
69
+ function kindOf(typeFlag: string): TarEntryKind {
70
+ switch (typeFlag) {
71
+ case "0":
72
+ case "\0":
73
+ case "7":
74
+ return "file";
75
+ case "5":
76
+ return "directory";
77
+ case "2":
78
+ return "symlink";
79
+ case "1":
80
+ return "hardlink";
81
+ case "x":
82
+ case "g":
83
+ return "pax";
84
+ default:
85
+ return "other";
86
+ }
87
+ }
88
+
89
+ // The unsigned sum of the header's bytes with the checksum field read as spaces.
90
+ function headerChecksum(block: Uint8Array): number {
91
+ let sum = 0;
92
+ for (let i = 0; i < TAR_BLOCK; i++) sum += i >= 148 && i < 156 ? 0x20 : (block[i] ?? 0);
93
+ return sum;
94
+ }
95
+
96
+ function readOctal(block: Uint8Array, start: number, length: number): number {
97
+ const text = readCString(block, start, length).trim();
98
+ if (text === "") return 0;
99
+ return /^[0-7]+$/.test(text) ? Number.parseInt(text, 8) : Number.NaN;
100
+ }
101
+
102
+ function readCString(block: Uint8Array, start: number, length: number): string {
103
+ let end = start;
104
+ const limit = start + length;
105
+ while (end < limit && block[end] !== 0) end += 1;
106
+ return Buffer.from(block.subarray(start, end)).toString("utf8");
107
+ }
108
+
109
+ function padded(size: number): number {
110
+ return Math.ceil(size / TAR_BLOCK) * TAR_BLOCK;
111
+ }
112
+
113
+ /**
114
+ * Extract a single regular-file entry whose basename matches `name` from an
115
+ * (uncompressed) tar buffer, or `null` when there is none.
116
+ */
117
+ export function extractTarEntry(buf: Uint8Array, name: string): Uint8Array | null {
118
+ let offset = 0;
119
+ while (offset + TAR_BLOCK <= buf.length) {
120
+ const header = parseTarHeader(buf.subarray(offset, offset + TAR_BLOCK));
121
+ if (header === null) break;
122
+ const size = Number.isNaN(header.size) ? 0 : header.size;
123
+ const dataStart = offset + TAR_BLOCK;
124
+ if (header.kind === "file" && basename(header.name) === name) return buf.subarray(dataStart, dataStart + size);
125
+ offset = dataStart + padded(size);
126
+ }
127
+ return null;
128
+ }
129
+
130
+ function basename(path: string): string {
131
+ const parts = path.split("/");
132
+ return parts[parts.length - 1] ?? path;
133
+ }
134
+
135
+ /** One entry of a streamed archive: its header, and its data, readable once before the walk moves on. */
136
+ export interface TarEntry {
137
+ readonly header: TarHeader;
138
+ /** The entry's bytes in order; an entry whose data is not read is skipped. */
139
+ data(): AsyncGenerator<Uint8Array>;
140
+ }
141
+
142
+ /**
143
+ * The entries of an uncompressed tar stream, in order. Each entry's data must
144
+ * be read (or left) before the next entry is requested. Ends at the archive's
145
+ * zero block, draining what follows; throws on a stream that ends inside a
146
+ * header or an entry's data, and on a size field that is not octal.
147
+ */
148
+ export async function* readTar(source: AsyncIterable<Uint8Array>): AsyncGenerator<TarEntry> {
149
+ const reader = new ByteReader(source);
150
+ for (;;) {
151
+ const block = await reader.readExact(TAR_BLOCK);
152
+ if (block === null) throw new Error("the archive ends without its end-of-archive block");
153
+ const header = parseTarHeader(block);
154
+ if (header === null) {
155
+ await reader.drain();
156
+ return;
157
+ }
158
+ if (Number.isNaN(header.size)) throw new Error(`entry ${header.name} has a size field that is not octal`);
159
+ let remaining = header.size;
160
+ yield {
161
+ header,
162
+ async *data() {
163
+ while (remaining > 0) {
164
+ const chunk = await reader.readUpTo(remaining);
165
+ if (chunk === null) throw new Error(`the archive ends inside ${header.name}`);
166
+ remaining -= chunk.byteLength;
167
+ yield chunk;
168
+ }
169
+ },
170
+ };
171
+ if (!(await reader.skip(remaining + padded(header.size) - header.size))) {
172
+ throw new Error(`the archive ends inside ${header.name}`);
173
+ }
174
+ }
175
+ }
176
+
177
+ // Exact and bounded reads over an async byte stream, holding at most one
178
+ // chunk beyond what was asked.
179
+ class ByteReader {
180
+ private readonly iterator: AsyncIterator<Uint8Array>;
181
+ private pending: Uint8Array = new Uint8Array(0);
182
+
183
+ constructor(source: AsyncIterable<Uint8Array>) {
184
+ this.iterator = source[Symbol.asyncIterator]();
185
+ }
186
+
187
+ /** Exactly `n` bytes, or `null` when the stream ends first. */
188
+ async readExact(n: number): Promise<Uint8Array | null> {
189
+ const parts: Uint8Array[] = [];
190
+ let have = 0;
191
+ while (have < n) {
192
+ const chunk = await this.readUpTo(n - have);
193
+ if (chunk === null) return null;
194
+ parts.push(chunk);
195
+ have += chunk.byteLength;
196
+ }
197
+ return parts.length === 1 ? (parts[0] as Uint8Array) : Buffer.concat(parts);
198
+ }
199
+
200
+ /** Between 1 and `n` bytes, or `null` at the end of the stream. */
201
+ async readUpTo(n: number): Promise<Uint8Array | null> {
202
+ while (this.pending.byteLength === 0) {
203
+ const next = await this.iterator.next();
204
+ if (next.done === true) return null;
205
+ this.pending = next.value;
206
+ }
207
+ const take = this.pending.subarray(0, Math.min(n, this.pending.byteLength));
208
+ this.pending = this.pending.subarray(take.byteLength);
209
+ return take;
210
+ }
211
+
212
+ /** Discards `n` bytes; false when the stream ends first. */
213
+ async skip(n: number): Promise<boolean> {
214
+ let left = n;
215
+ while (left > 0) {
216
+ const chunk = await this.readUpTo(left);
217
+ if (chunk === null) return false;
218
+ left -= chunk.byteLength;
219
+ }
220
+ return true;
221
+ }
222
+
223
+ /** Reads the stream to its end. */
224
+ async drain(): Promise<void> {
225
+ this.pending = new Uint8Array(0);
226
+ for (;;) {
227
+ const next = await this.iterator.next();
228
+ if (next.done === true) return;
229
+ }
230
+ }
231
+ }
232
+
233
+ export interface ExtractPackageOptions {
234
+ /** The prefix every entry must carry, stripped on the way out; npm packs under `package/`. */
235
+ readonly prefix: string;
236
+ /** The archive's name in errors. */
237
+ readonly label: string;
238
+ /** Stops the extraction; the signal's reason is thrown. */
239
+ readonly signal?: AbortSignal;
240
+ }
241
+
242
+ /**
243
+ * Unpack the gzipped tar at `archivePath` into `destDir` under the rules in
244
+ * the module header; resolves with the number of files written. `destDir`
245
+ * should be new and empty: a file that already exists there refuses the
246
+ * archive rather than be replaced. Each file keeps its archived permission
247
+ * bits, less set-id, sticky and group or other write.
248
+ */
249
+ export async function extractPackageTarball(archivePath: string, destDir: string, options: ExtractPackageOptions): Promise<{ readonly files: number }> {
250
+ let files = 0;
251
+ const refuse = (reason: string): never => {
252
+ throw new ArtifactFetchError(`${options.label} archive refused: ${reason}`, [`archive: ${archivePath}`]);
253
+ };
254
+ await pipeline(
255
+ createReadStream(archivePath),
256
+ createGunzip(),
257
+ async (source: AsyncIterable<Uint8Array>) => {
258
+ for await (const entry of readTar(source)) {
259
+ const { header } = entry;
260
+ if (!header.checksumValid) refuse(`entry ${JSON.stringify(header.name)} has a corrupt header`);
261
+ if (header.kind !== "file") refuse(`entry ${JSON.stringify(header.name)} is a ${header.kind}, and only regular files are accepted`);
262
+ const target = join(destDir, packagePath(header.name, options.prefix, refuse));
263
+ await mkdir(dirname(target), { recursive: true });
264
+ const file = await open(target, "wx", 0o600).catch((err: unknown) =>
265
+ refuse(`entry ${JSON.stringify(header.name)} could not be created (${err instanceof Error ? err.message : String(err)})`),
266
+ );
267
+ try {
268
+ for await (const chunk of entry.data()) await file.write(chunk);
269
+ await file.chmod(header.mode & 0o755);
270
+ } finally {
271
+ await file.close();
272
+ }
273
+ files += 1;
274
+ }
275
+ },
276
+ options.signal === undefined ? {} : { signal: options.signal },
277
+ );
278
+ return { files };
279
+ }
280
+
281
+ // The path an entry writes to, relative to the destination, or a refusal.
282
+ function packagePath(name: string, prefix: string, refuse: (reason: string) => never): string {
283
+ const quoted = JSON.stringify(name);
284
+ if (!name.startsWith(prefix)) refuse(`entry ${quoted} is not under ${prefix}`);
285
+ const rel = name.slice(prefix.length);
286
+ if (rel === "" || isAbsolute(rel) || rel.includes("\\") || rel.includes("\0")) refuse(`entry ${quoted} is not a plain relative path`);
287
+ // With no absolute start and no empty, . or .. segment, the path cannot leave the package.
288
+ if (rel.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) refuse(`entry ${quoted} has an empty, . or .. segment`);
289
+ return rel.split("/").join(sep);
290
+ }