Files
reverse-engineering-anything/src/resources/ZipArtifactReader.ts
T
Adolanium 996ab6e2ae fix(zip): bound the member count of a ZIP inventory (#14997)
* fix(limits): admit a ZIP member count on reader limits

artifact.member_count now resolves artifact_limits.zip.member_count. Recorded Evidence from before this group may omit zip.

* fix(zip): refuse a central directory past the member count

Count every central-directory record before retaining it. The refusal omits required_value because later records stay unread.

* test(zip): cover a central directory past the member count

Three empty members at a count of two refuse through the reader and through the zip format reader.

* docs(limits): name zip.member_count on the member-count setting

The existing REA_ARTIFACT_MEMBER_COUNT seed already supplies that default.

* test(artifacts): select the ZIP member count with the explicit fields

The acceptance case ignores an invalid artifact.member_count seed only when every backed field is selected. zip.member_count is one of those fields.

* fix(schemas): record the ZIP member-count input summaries

extract_artifact and inspect_artifact changed their input compact schema when zip.member_count was advertised.

* fix(zip): keep member count on Flutter, Playwright, and SAZ

Those readers omitted the session count and described the refusal as a byte budget. They now admit artifact.member_count and report the count.

* test(zip): cover member-count refusals outside artifact inventory

A two-member archive at a session count of one stays a count for Flutter, Playwright traces, and SAZ. One member still passes that cap.

* docs(limits): name the ZIP consumers of artifact.member_count

Flutter APK inventory, Playwright trace import, and SAZ decoding use the session count and report it as a count.

* fix(capture): read the fixed-limit boundary from the ceiling

CaptureFormatError keeps that boundary on ceiling. The SAZ reply read cause.boundary, so a fixed-limit reply omitted the field the parent requires.

* fix(limits): recover ZIP member count through the session setting

Flutter, Playwright, and SAZ have no artifact_limits argument. The refusal names artifact.member_count, leaves parameter unset, and tells the caller to raise that setting. sessionSettingConstraint owns the error next to the other resource refusals.

* fix(android): keep a partial JNI report at the ZIP member count

readAndroidJniLibraries already returns a partial inventory when its entry allowance stops the scan. The session member count is that same stop. The reader takes artifact.member_count, and the report names the unexamined remainder instead of aborting the inspection.

* fix(zip): resolve the member count from the selected environment

ZIP admission and its refusal use the launch environment selected for the runtime. Only SAZ sends that count to the capture decoder.

* fix(zip): drop the unused ZipReaderLimits export

Knip reports the type because no caller imports it. ZIP limits stay on the schema.

* fix(playwright): return an invalid member-count seed as a result

The trace catch uses the count captured before the failure. A configuration error stays a Result and keeps the archive hash.

* fix(jni): name the member count on a partial library scan

The partial report keeps the count that stopped the scan and the recovery for artifact.member_count.

* fix(settings): register artifact.member_count for its ZIP consumers

Scoped inspection of the Flutter, Playwright, capture, and JNI operations includes the setting.

* test(artifacts): parse Evidence that omits the audit-log policy

The merged reader-limit schema still accepts a record that omits the Kubernetes audit-log policy.
2026-11-29 13:08:56 -05:00

770 lines
27 KiB
TypeScript

import {
malformedInput,
ParseFailureError,
unsupportedInput,
} from "../domain/parseFailure.js";
import { OwnerCancellation } from "../domain/analysisErrorCore.js";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import {
ArtifactEntryContentUnavailable,
ArtifactReaderFailure,
copyArtifactEntry,
malformedArtifact,
sameArtifactEntry,
type ArtifactEntry,
type ArtifactFixedLimit,
type ArtifactReader,
type ArtifactReaderTraversal,
type ArtifactTraversalOptions,
} from "./ArtifactReader.js";
import { ArtifactFileSource } from "./ArtifactFileSource.js";
import { DEFAULT_ZIP_READER_LIMITS } from "../domain/artifactReaderLimits.js";
import { artifactReaderLimitFailure } from "./ArtifactReaderLimits.js";
import {
currentDirectoryPrefixLimitation,
withoutCurrentDirectoryPrefix,
} from "./ArtifactPaths.js";
import type { FileHandle } from "node:fs/promises";
import { compose, Duplex, PassThrough, type Readable } from "node:stream";
import { once } from "node:events";
import { constants, createZstdDecompress } from "node:zlib";
import {
ERR_AMBIGUOUS_ARCHIVE,
ERR_BAD_FORMAT,
ERR_CENTRAL_DIRECTORY_NOT_FOUND,
ERR_ENCRYPTED_CENTRAL_DIRECTORY,
ERR_ENTRY_DATA_OUT_OF_BOUNDS,
ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
ERR_EOCDR_NOT_FOUND,
ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
ERR_INVALID_COMPRESSED_DATA,
ERR_INVALID_CRC32,
ERR_INVALID_UNCOMPRESSED_SIZE,
ERR_LOCAL_FILE_HEADER_NOT_FOUND,
ERR_OVERLAPPING_ENTRY,
ERR_SPLIT_ZIP_FILE,
ERR_UNSUPPORTED_COMPRESSION,
ERR_UNSUPPORTED_ENCRYPTION,
ERR_UNSUPPORTED_UINT64,
Reader,
registerCodec,
ZipReader,
type DecompressionStreamOptions,
type Entry,
type FileEntry,
type ZipReaderConstructorOptions,
} from "@zip.js/zip.js";
import {
accountZipMemberRegion,
type ZipLocalRecord,
type ZipMemberRegionAccount,
} from "../domain/zip/zipMemberRegion.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import { strictUtf8Decoder } from "../domain/strictUtf8.js";
import { decodeZipCp437 } from "../domain/zip/zipEntryText.js";
import { invariantViolation } from "../domain/internalInvariant.js";
import {
ZstandardFramingError,
zstandardFrameChunks,
} from "../domain/compression/zstandardFrameChunks.js";
const ZIP_UTF8_DECODER = strictUtf8Decoder("preserve");
/** Fixed method-93 decoder window: 2^27 bytes, matching the ELF/GPU decoders. */
const ZIP_ZSTANDARD_WINDOW_LOG_MAX = 27;
const ZIP_ZSTANDARD_WINDOW_ALLOWANCE = `${String(2 ** (ZIP_ZSTANDARD_WINDOW_LOG_MAX - 20))} MiB`;
/** A frame above the window cap is a deliberate resource refusal, not damage. */
const ZIP_ZSTANDARD_WINDOW_LIMIT = `ZIP Zstandard member requires a decoder window above REA's fixed ${ZIP_ZSTANDARD_WINDOW_ALLOWANCE} allowance; the archive is not necessarily corrupt.`;
/** The fixed method-93 decoder window ceiling, with the request change that fits it. */
export const ZIP_ZSTANDARD_WINDOW_CEILING: ArtifactFixedLimit = {
name: "The ZIP Zstandard decoder window allowance",
kind: "parser",
limit: 2 ** ZIP_ZSTANDARD_WINDOW_LOG_MAX,
unit: "bytes",
narrowing: `Recompress the member with a window of at most ${ZIP_ZSTANDARD_WINDOW_ALLOWANCE}, or decompress it with a tool that admits larger windows, then retry.`,
};
/** Keep zip.js's framing, CRC, size checks and backpressure for method 93. */
class ZipZstandardDecompressionStream {
readonly readable;
readonly writable;
constructor(_format: string, options?: DecompressionStreamOptions) {
const stream = Duplex.toWeb(
compose(
new PassThrough(),
zstandardFrameChunks,
createZstdDecompress({
chunkSize: options?.chunkSize,
params: {
[constants.ZSTD_d_windowLogMax]: ZIP_ZSTANDARD_WINDOW_LOG_MAX,
},
}),
),
);
this.readable = stream.readable;
this.writable = stream.writable;
}
}
// zip.js owns a process-local codec registry. Module initialization registers
// this decoder once; no codecURI means the native Node stream stays in-process.
registerCodec({
compressionMethod: 93,
format: "rea-zip-zstd",
DecompressionStream: ZipZstandardDecompressionStream,
});
/** zip.js reader options: CRC and overlap checks, and names decoded as REA reads them. */
export const ZIP_READER_OPTIONS = {
checkSignature: true,
checkOverlappingEntry: true,
// Unflagged names use the ZIP legacy encoding (CP437); the UTF-8 flag
// and validated Unicode Path extra fields remain authoritative.
filenameEncoding: "cp437",
// REA applies its own provider-neutral path validation in scanReader and
// must preserve that typed failure instead of zip.js rejecting first.
filenameValidation: "tolerant",
} as const satisfies ZipReaderConstructorOptions;
class NodeFileReader extends Reader<string> {
#handle: FileHandle | undefined;
readonly #source: ArtifactFileSource;
#initPromise: Promise<void> | undefined;
constructor(
private readonly path: string,
private readonly maximumReadBytes?: number,
admitted?: StableRegularFileDescriptor,
) {
super(path);
this.#source = new ArtifactFileSource(path, "ZIP", admitted);
}
override init(): Promise<void> {
this.#initPromise ??= this.#initialize();
return this.#initPromise;
}
async #initialize(): Promise<void> {
const source = await this.#source.read();
this.#handle = source.handle;
this.size = source.initial.size;
}
async verify(): Promise<void> {
await this.#source.read();
}
override async readUint8Array(
index: number,
length: number,
): Promise<Uint8Array> {
await this.verify();
const handle = this.#handle;
if (handle === undefined)
throw invariantViolation("ZIP reader is not initialized");
const readBytes = Math.min(length, this.size - index);
// A central-directory offset can point past EOF. Type that malformed ZIP
// read before a negative size reaches Buffer.alloc and becomes an I/O error.
if (readBytes < 0)
throw malformedArtifact(
"zip",
`ZIP archive is malformed: read at ${index} extends beyond the ${this.size}-byte archive`,
{ offset: index },
);
if (
this.maximumReadBytes !== undefined &&
readBytes > this.maximumReadBytes
)
throw new ArtifactReaderFailure(
"limit",
`ZIP metadata read requires ${readBytes} bytes, exceeding the ${this.maximumReadBytes}-byte read budget`,
);
const bytes = await readFileHandleRange(handle, index, readBytes);
if (bytes.length !== readBytes)
throw new ArtifactReaderFailure(
"integrity",
`ZIP source ended before its admitted extent: ${this.path}`,
{ integrityCheck: "read-coverage" },
);
await this.verify();
return bytes;
}
async closeHandle(): Promise<void> {
await this.#initPromise?.catch(() => undefined);
await this.#source.close();
this.#handle = undefined;
}
}
/** Lazy Zip64-capable reader with CRC and overlap verification on every read. */
export class ZipArtifactReader implements ArtifactReader {
readonly format: ZipPackageFormat;
readonly #source: NodeFileReader;
readonly #reader: ZipReader<string>;
readonly #streams = new Map<Readable, Promise<void>>();
readonly #enumerations = new Set<AsyncGenerator<Entry, void>>();
/** Running traversal steps, including the final accounting pass, that close joins. */
readonly #traversalSteps = new Set<Promise<unknown>>();
#closing = false;
#closePromise: Promise<void> | undefined;
readonly #entries = new Map<
string,
{ readonly source: Entry; readonly metadata: ArtifactEntry }
>();
/** Central-directory records this archive may retain. */
readonly #memberCount: number;
/** Optionally bound each metadata read before allocating its backing buffer. */
constructor(
path: string,
format: ZipPackageFormat,
maximumMetadataReadBytes?: number,
admitted?: StableRegularFileDescriptor,
private readonly expandedBytes?: number,
memberCount?: number,
) {
this.format = format;
this.#memberCount = memberCount ?? DEFAULT_ZIP_READER_LIMITS.member_count;
this.#source = new NodeFileReader(path, maximumMetadataReadBytes, admitted);
this.#reader = new ZipReader(this.#source, ZIP_READER_OPTIONS);
}
entries(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncIterable<ArtifactEntry> {
const traversal = this.#enumerate(signal, options);
const steps = this.#traversalSteps;
// Close joins a running step without ending the traversal, so the
// caller's next step still observes the close instead of completion.
const step = <T>(running: Promise<T>): Promise<T> => {
steps.add(running);
const settled = () => {
steps.delete(running);
};
running.then(settled, settled);
return running;
};
const iterator: AsyncIterator<ArtifactEntry, void> = {
next: () => step(traversal.next()),
return: (value) => step(traversal.return(value)),
throw: (cause: unknown) => step(traversal.throw(cause)),
};
return { [Symbol.asyncIterator]: () => iterator };
}
async *#enumerate(
signal?: AbortSignal,
options?: ArtifactTraversalOptions,
): AsyncGenerator<ArtifactEntry, void> {
this.#assertOpen(signal);
let index = 0;
// A traversal owns its accounting, including overlapping or repeated passes.
let declaredFileBytes = 0n;
let prefixedMembers = 0;
// Every directory record, listed or not, claims its local entry's bytes.
const records: ZipLocalRecord[] = [];
const enumeration = typedZipFailures(
this.#reader.getEntriesGenerator({ decodeText: decodeZipEntryText }),
);
this.#enumerations.add(enumeration);
try {
for await (const entry of enumeration) {
await this.#source.verify();
this.#assertOpen(signal);
// Later records are unmeasured, so this refusal names no required_value.
if (records.length >= this.#memberCount)
throw artifactReaderLimitFailure(
"artifact_limits.zip.member_count",
this.#memberCount,
"count",
);
records.push({
offset: entry.offset,
compressedSize: entry.compressedSize,
uncompressedSize: entry.uncompressedSize,
crc32: entry.crc32,
zip64: entry.zip64,
dataDescriptor: entry.bitFlag?.dataDescriptor ?? false,
});
// ZIP member identity is its directory occurrence, not its filename.
// Logical path uniqueness belongs to the artifact inventory boundary.
const metadata = projectZipEntry(entry, index++);
if (metadata === undefined) continue;
if (metadata.sourcePath !== undefined) prefixedMembers += 1;
// zip.js enforces each member's declared output size, so this sum bounds streamed work.
if (
metadata.kind === "file" &&
!metadata.encrypted &&
metadata.declaredSize !== null &&
Number.isSafeInteger(metadata.declaredSize) &&
metadata.declaredSize >= 0
) {
declaredFileBytes += BigInt(metadata.declaredSize);
const budget =
this.expandedBytes ??
artifactExpansionBudgetBytes(this.#source.size);
if (declaredFileBytes > BigInt(budget))
throw artifactReaderLimitFailure(
"artifact_limits.expanded_bytes",
budget,
"bytes",
declaredFileBytes,
);
}
const stored = this.#entries.get(metadata.adapterKey);
if (
stored !== undefined &&
!sameArtifactEntry(metadata, stored.metadata)
)
throw new ArtifactReaderFailure(
"integrity",
`ZIP member identity changed during enumeration: ${entry.filename}`,
{ integrityCheck: "entry-metadata" },
);
if (stored === undefined)
this.#entries.set(metadata.adapterKey, {
source: entry,
metadata: copyArtifactEntry(metadata),
});
yield metadata;
}
this.#assertOpen(signal);
// The listing comes from the central directory; local entries it does
// not reference are only visible as bytes no record accounts for.
const directoryOffset = this.#reader.directoryOffset;
const account =
directoryOffset === undefined
? undefined
: await accountZipMemberRegion(
records,
directoryOffset,
(at, length) => this.#source.readUint8Array(at, length),
);
this.#assertOpen(signal);
await this.#source.verify();
this.#assertOpen(signal);
options?.onCoverage?.(zipListingCoverage(account, prefixedMembers));
} finally {
this.#enumerations.delete(enumeration);
await enumeration.return();
}
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
this.#assertOpen(signal);
const stored = this.#entries.get(entry.adapterKey);
if (stored === undefined || !sameArtifactEntry(entry, stored.metadata))
return Promise.reject(
new ArtifactReaderFailure(
"integrity",
"ZIP entry metadata does not match this reader's inventory",
{
integrityCheck:
stored === undefined ? "foreign-entry" : "entry-metadata",
},
),
);
const source = stored.source;
if (source.directory || source.symlink)
return Promise.reject(
new ArtifactReaderFailure("path", "ZIP entry is not a regular file"),
);
if (source.encrypted)
return Promise.reject(
new ArtifactReaderFailure(
"unavailable",
"Encrypted ZIP entry is unsupported",
),
);
const { output, completion } = extractStream(
source,
() => this.#source.verify(),
signal,
);
this.#streams.set(output, completion);
// Producer completion can precede consumption of a small buffered member.
// Retain the output until both it and its producer have finished.
output.once("close", () => {
void completion.then(() => this.#streams.delete(output));
});
return Promise.resolve(output);
}
close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#close().finally(() => {
// A failed descriptor close retains its owner for a later retry.
this.#closePromise = undefined;
});
return this.#closePromise;
}
async #close(): Promise<void> {
for (const output of this.#streams.keys())
output.destroy(
new ArtifactReaderFailure("unavailable", "ZIP reader closed"),
);
// A joined traversal step reports its own failure to its caller.
const [outcomes] = await Promise.all([
Promise.allSettled([
...this.#streams.values(),
...Array.from(this.#enumerations, (enumeration) =>
enumeration.return(),
),
]),
Promise.allSettled(this.#traversalSteps),
]);
this.#enumerations.clear();
// best-effort cleanup: zip-reader close must not mask prior extraction state.
await this.#reader.close().catch(() => undefined);
const failures = outcomes.flatMap((outcome) =>
outcome.status === "rejected" ? [outcome.reason as unknown] : [],
);
try {
await this.#source.closeHandle();
this.#entries.clear();
} catch (cause: unknown) {
failures.push(cause);
}
if (failures.length === 1) throw failures[0];
if (failures.length > 1)
throw new AggregateError(failures, "ZIP reader cleanup failed");
}
#assertOpen(signal?: AbortSignal): void {
assertArtifactReadActive(signal);
if (this.#closing)
throw new ArtifactReaderFailure("unavailable", "ZIP reader is closed");
}
provenance(): readonly [] {
return [];
}
}
/** Coverage of a central-directory listing, given the member region's byte account. */
export const zipListingCoverage = (
account: ZipMemberRegionAccount | undefined,
/** Listed members whose leading `./` the logical path omits. */
prefixedMembers = 0,
): ArtifactReaderTraversal => {
const prefixed =
prefixedMembers === 0
? []
: [currentDirectoryPrefixLimitation("ZIP", prefixedMembers)];
if (account === undefined)
return {
status: "unknown",
limitations: [
"ZIP central directory offset was not established; bytes outside the listed members were not accounted for.",
...prefixed,
],
};
// Coverage follows the byte account alone; a normalized name is not a gap.
const gaps = [
...(account.unaccountedRanges === 0
? []
: [
`ZIP central directory does not account for ${String(account.unaccountedBytes)} byte(s) in ${String(account.unaccountedRanges)} range(s) before it, first at offset ${String(account.firstUnaccountedOffset)}; local entries it does not list may exist there.`,
]),
...(account.unlocatedHeaders === 0
? []
: [
`${String(account.unlocatedHeaders)} ZIP central directory record(s) point at no local file header; the bytes they claim were not accounted for.`,
]),
...(account.unverifiedExtents === 0
? []
: [
`${String(account.unverifiedExtents)} ZIP central directory record(s) have payload extents that conflict with or cannot be established from their local headers or required data descriptors; those claims were not used to establish complete coverage.`,
]),
];
return {
status: gaps.length === 0 ? "complete" : "unknown",
limitations: [...gaps, ...prefixed],
};
};
const projectZipEntry = (
entry: Entry,
index: number,
): ArtifactEntry | undefined => {
const kind = entry.symlink
? "symlink"
: entry.directory
? "directory"
: "file";
const sourcePath = zipEntryPath(entry);
const path = withoutCurrentDirectoryPrefix(sourcePath);
// Root directory markers carry no inventory occurrence. A file with this
// spelling is still passed to the shared path validator and rejected there.
if (kind === "directory" && (path === "" || path === ".")) return undefined;
return {
path,
...(path === sourcePath ? {} : { sourcePath }),
kind,
declaredSize: kind === "directory" ? null : entry.uncompressedSize,
compressedSize: kind === "directory" ? null : entry.compressedSize,
executable: entry.executable,
encrypted: entry.encrypted,
byteOffset: null,
declaredIntegrity: null,
unpacked: false,
limitations: [
...(kind === "symlink" ? ["Archive symlink target was not read."] : []),
...zipEntryNameLimitations(entry),
],
adapterKey: `zip-entry:${index}`,
};
};
/** Preserve source bytes when an unflagged legacy name may use another code page. */
export const zipEntryNameLimitations = (entry: Entry): readonly string[] => {
if (entry.filenameUTF8 || entry.extraFieldUnicodePath?.valid === true)
return [];
const bytes = entry.rawFilename;
if (!bytes.some((byte) => byte >= 0x80)) return [];
const hex = Buffer.from(bytes).toString("hex");
return [
`ZIP name uses CP437 fallback; source encoding unverified; raw hex: ${hex}.`,
];
};
/** Decode an entry name as zip.js reports it: strict UTF-8 when flagged, CP437 otherwise. */
export const decodeZipEntryText = (
bytes: Uint8Array,
encoding: string,
type: "filename" | "comment",
): string | undefined => {
if (type !== "filename") return undefined;
if (encoding === "utf-8")
return decodeStrictZipUtf8(bytes, "ZIP filename is not valid UTF-8");
return encoding === "cp437" ? decodeZipCp437(bytes) : undefined;
};
/** An entry's name, from a valid Unicode Path extra field when it has one. */
export const zipEntryPath = (entry: Entry): string => {
const field = entry.extraFieldUnicodePath;
if (field?.valid !== true) return entry.filename;
return decodeStrictZipUtf8(
field.data.subarray(5),
"ZIP Unicode Path extra field is not valid UTF-8",
);
};
const decodeStrictZipUtf8 = (bytes: Uint8Array, message: string): string => {
try {
// Keep the adapter's path semantics aligned with zip.js's default decoder:
// a leading U+FEFF is part of a member name, not a transport signature.
return ZIP_UTF8_DECODER.decode(bytes);
} catch (cause: unknown) {
throw malformedArtifact("zip", message, { cause, field: "name" });
}
};
const extractStream = (
entry: FileEntry,
verifySource: () => Promise<void>,
signal?: AbortSignal,
): { readonly output: Readable; readonly completion: Promise<void> } => {
const output = new PassThrough();
// Reader retirement can precede a caller attaching its own error listener.
output.on("error", () => undefined);
const controller = new AbortController();
const onAbort = (): void => {
controller.abort(signal?.reason);
// AbortSignal listeners dispatch synchronously, so this destroy wins the race
// against `getData` rejecting with its own AbortError. That ordering is what
// keeps the caller-visible failure typed as `cancelled`.
output.destroy(
new ArtifactReaderFailure("cancelled", "ZIP operation cancelled", {
cause: signal?.reason,
}),
);
};
signal?.addEventListener("abort", onAbort, { once: true });
// A closed output cancels its producer; the reader separately awaits getData
// settlement before releasing the source descriptor.
output.once("close", () => {
signal?.removeEventListener("abort", onAbort);
controller.abort(OwnerCancellation.noLongerNeeded);
});
const writable = new WritableStream<Uint8Array>({
write: async (chunk) => {
assertArtifactReadActive(signal);
// The stream owns this copy for as long as downstream retains it.
if (!output.write(Buffer.from(chunk)))
await once(output, "drain", { signal: controller.signal });
},
// Sink closure can precede getData's final validation or rejection.
// The producer's successful settlement owns consumer-visible EOF below.
abort: (reason) => {
output.destroy(toError(typedZipFailure(reason, entry.compressionMethod)));
},
});
const completion = verifySource()
.then(() =>
entry.getData(writable, {
signal: controller.signal,
checkSignature: true,
checkOverlappingEntry: true,
onprogress: () => assertArtifactReadActive(signal),
}),
)
.then(async () => {
await verifySource();
assertArtifactReadActive(signal);
output.end();
})
.catch((cause: unknown) => {
output.destroy(toError(typedZipFailure(cause, entry.compressionMethod)));
});
return { output, completion };
};
/** zip.js reports archive faults as plain errors identified by message. */
const ZIP_FAILURE_REASONS: ReadonlyMap<string, "malformed" | "unavailable"> =
new Map([
...[
ERR_AMBIGUOUS_ARCHIVE,
ERR_BAD_FORMAT,
ERR_CENTRAL_DIRECTORY_NOT_FOUND,
ERR_ENTRY_DATA_OUT_OF_BOUNDS,
ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
ERR_EOCDR_NOT_FOUND,
ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
ERR_INVALID_COMPRESSED_DATA,
ERR_INVALID_CRC32,
ERR_INVALID_UNCOMPRESSED_SIZE,
ERR_LOCAL_FILE_HEADER_NOT_FOUND,
ERR_OVERLAPPING_ENTRY,
ERR_UNSUPPORTED_UINT64,
].map((message) => [message, "malformed"] as const),
...[
ERR_ENCRYPTED_CENTRAL_DIRECTORY,
ERR_SPLIT_ZIP_FILE,
ERR_UNSUPPORTED_COMPRESSION,
ERR_UNSUPPORTED_ENCRYPTION,
].map((message) => [message, "unavailable"] as const),
]);
/** Type a zip.js archive fault so consumers do not report it as file I/O. */
const typedZipFailure = (
cause: unknown,
compressionMethod?: number,
): unknown => {
if (!(cause instanceof Error) || cause instanceof ArtifactReaderFailure)
return cause;
// zip.js refuses a member's method before reading its data, so only that
// member's content is unreadable. The central directory still lists every
// entry, so entry coverage is unchanged, as for an encrypted member; the
// occurrence limitation carries the content gap.
if (
compressionMethod !== undefined &&
cause.message === ERR_UNSUPPORTED_COMPRESSION
)
return new ArtifactEntryContentUnavailable(
`ZIP archive uses an unsupported feature: ${cause.message} (method ${String(compressionMethod)})`,
`ZIP member compression method ${String(compressionMethod)} is unsupported; no content hash or child artifact was produced.`,
{ cause },
);
// Only method 93 uses Node's native Zstandard decoder. Do not classify
// cancellation or an unrelated codec/runtime error as malformed ZIP data.
const codecCause =
compressionMethod === 93 &&
cause.message === ERR_INVALID_COMPRESSED_DATA &&
cause.cause instanceof Error
? cause.cause
: cause;
const code = "code" in codecCause ? codecCause.code : undefined;
if (compressionMethod === 93 && code === "ZSTD_error_dictionary_wrong")
return new ArtifactReaderFailure(
"unavailable",
"ZIP archive uses an unsupported Zstandard dictionary",
{ cause: codecCause },
);
if (
compressionMethod === 93 &&
code === "ZSTD_error_frameParameter_windowTooLarge"
)
return new ArtifactReaderFailure("limit", ZIP_ZSTANDARD_WINDOW_LIMIT, {
cause: codecCause,
boundary: "memory",
fixedAllowance: ZIP_ZSTANDARD_WINDOW_CEILING,
});
const invalidZstandard =
compressionMethod === 93 &&
(codecCause instanceof ZstandardFramingError ||
code === "ZSTD_error_prefix_unknown" ||
code === "ZSTD_error_checksum_wrong" ||
code === "ZSTD_error_corruption_detected" ||
code === "ZSTD_error_dictionary_corrupted" ||
code === "ZSTD_error_frameParameter_unsupported" ||
code === "Z_BUF_ERROR");
const reason =
ZIP_FAILURE_REASONS.get(cause.message) ??
(invalidZstandard ? "malformed" : undefined);
if (reason === undefined) return cause;
const failureCause = invalidZstandard ? codecCause : cause;
return reason === "malformed"
? malformedArtifact(
"zip",
`ZIP archive is malformed: ${invalidZstandard ? ERR_INVALID_COMPRESSED_DATA : cause.message}`,
{ cause: failureCause },
)
: new ArtifactReaderFailure(
reason,
`ZIP archive uses an unsupported feature: ${cause.message}`,
{ cause: failureCause },
);
};
/** Preserve reader failures and attach the package format to newly classified ZIP faults. */
export const throwZipPackageFailure = (
cause: unknown,
format: string,
packageName: string,
compressionMethod?: number,
): never => {
if (
cause instanceof ArtifactReaderFailure ||
cause instanceof ParseFailureError
)
throw cause;
const typed = typedZipFailure(cause, compressionMethod);
if (!(typed instanceof ArtifactReaderFailure)) throw cause;
if (typed.reason === "limit") throw typed;
if (typed.reason === "unavailable")
throw unsupportedInput(
format,
`${packageName} ZIP uses an unsupported layout: ${typed.message}`,
{ cause: typed },
);
if (typed.parseFailure !== undefined)
throw malformedInput(format, typed.message, { cause: typed });
throw cause;
};
async function* typedZipFailures<T>(
source: AsyncIterable<T>,
): AsyncGenerator<T, void> {
try {
yield* source;
} catch (cause: unknown) {
throw typedZipFailure(cause);
}
}
const toError = (cause: unknown): Error =>
cause instanceof Error ? cause : new Error("ZIP extraction failed");