Add evidence-backed investigation workflows

This commit is contained in:
morluto
2026-07-12 21:12:18 +00:00
parent 4110a4d717
commit 4ff4c11a00
178 changed files with 26320 additions and 1222 deletions
+86
View File
@@ -0,0 +1,86 @@
import { Buffer } from "node:buffer";
import { posix } from "node:path";
import {
ArtifactReaderFailure,
type ArtifactLimits,
} from "./ArtifactReader.js";
const DRIVE_OR_UNC = /^(?:[A-Za-z]:|\\|\/\/)/u;
/** Normalize an untrusted logical archive path without touching filesystem. */
export const normalizeArtifactPath = (
input: string,
limits: Pick<ArtifactLimits, "maxDepth" | "maxPathBytes">,
): string => {
if (
input.includes("\0") ||
input.includes("\\") ||
input.startsWith("/") ||
DRIVE_OR_UNC.test(input)
)
throw new ArtifactReaderFailure(
"path",
"Artifact path is absolute or unsafe",
);
const normalized = input.normalize("NFC").replace(/\/+$/u, "");
const parts = normalized.split("/");
if (
normalized.length === 0 ||
parts.some((part) => part === "" || part === "." || part === "..") ||
parts.length > limits.maxDepth ||
Buffer.byteLength(normalized, "utf8") > limits.maxPathBytes ||
posix.normalize(normalized) !== normalized
)
throw new ArtifactReaderFailure("path", "Artifact path is not normalized");
return normalized;
};
/** Reject exact, Unicode-normalized, case-folded, and prefix collisions. */
export class ArtifactPathRegistry {
readonly #root: PathTrieNode = { kind: undefined, children: new Map() };
readonly #folded = new Set<string>();
add(path: string, kind: "file" | "directory" | "symlink" | "slice"): void {
const folded = path.toLocaleLowerCase("en-US");
if (this.#folded.has(folded))
throw new ArtifactReaderFailure(
"path",
`Artifact path collision: ${path}`,
);
const parts = path.split("/");
let node = this.#root;
for (const [index, part] of parts.entries()) {
if (node.kind !== undefined && node.kind !== "directory")
throw new ArtifactReaderFailure(
"path",
`Artifact prefix conflict: ${path}`,
);
let child = node.children.get(part);
if (child === undefined) {
child = { kind: undefined, children: new Map() };
node.children.set(part, child);
}
node = child;
if (index === parts.length - 1) {
if (node.kind !== undefined)
throw new ArtifactReaderFailure(
"path",
`Artifact path collision: ${path}`,
);
if (kind !== "directory" && node.children.size > 0)
throw new ArtifactReaderFailure(
"path",
`Artifact prefix conflict: ${path}`,
);
}
}
node.kind = kind;
this.#folded.add(folded);
}
}
interface PathTrieNode {
kind: "file" | "directory" | "symlink" | "slice" | undefined;
readonly children: Map<string, PathTrieNode>;
}
+212
View File
@@ -0,0 +1,212 @@
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProvider,
type CapabilityDescriptor,
type ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
import {
ARTIFACT_TOOL_CONTRACTS,
artifactInventoryInputSchema,
artifactExtractionInputSchema,
type ArtifactToolName,
} from "../contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCapabilityUnavailableError,
ArtifactOperationError,
type AnalysisError,
} from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import {
ArtifactReaderFailure,
type ArtifactLimits,
} from "./ArtifactReader.js";
const IDENTITY: ProviderIdentity = Object.freeze({
id: "rea-artifact-graph",
name: "REA safe artifact graph provider",
version: "1",
});
/** Read-only inventory and transaction-owned extraction provider. */
export class ArtifactProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
ARTIFACT_TOOL_CONTRACTS.map((contract) =>
Object.freeze({
provider: IDENTITY,
operation: contract.name,
inputContractVersion: 1,
outputContractVersion: 1,
available: true as const,
reason: null,
pagination: "offset" as const,
exhaustive: false,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: contract.name === "extract_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limits: Object.freeze({
maxResults: 500,
maxPayloadBytes: 4 * 1024 * 1024,
timeoutMs: 120_000,
}),
limitations: Object.freeze([
"DMG and PKG child inventory requires a future native read-only adapter.",
"Nested containers are recorded but not recursively expanded implicitly.",
]),
}),
),
);
identity(): ProviderIdentity {
return IDENTITY;
}
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilities;
}
createClient(target: BinaryTarget): AnalysisClient {
return new ArtifactClient(target);
}
}
class ArtifactClient implements AnalysisClient {
constructor(private readonly target: BinaryTarget) {}
async execute(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
) {
if (operation === "health")
return ok(createAnalysisExecution(null, IDENTITY));
if (!isArtifactOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
"Operation is not implemented by artifact graph provider.",
),
);
try {
if (operation === "extract_artifact") {
const parsed = artifactExtractionInputSchema.parse(parameters);
const result = await extractArtifact(
{
inputPath: this.target.sourcePath ?? this.target.path,
inputFormat: this.target.format,
outputRoot: parsed.output_root,
occurrenceIds: parsed.occurrence_ids,
offset: parsed.offset,
limit: parsed.limit,
limits: limitsFrom(parsed),
},
options?.signal,
);
return ok(
createAnalysisExecution(result, IDENTITY, {
rawResult: null,
limitations: result.limitations,
subject: subjectFor(
this.target.sourcePath ?? this.target.path,
result.manifest,
),
locations: result.artifacts.items.map(
({ relative_path: path }) => ({
kind: "artifact-path" as const,
path,
}),
),
}),
);
}
const parsed = artifactInventoryInputSchema.parse(parameters);
const result = await inventoryArtifact(
this.target.sourcePath ?? this.target.path,
limitsFrom(parsed),
{
nodeOffset: parsed.node_offset,
nodeLimit: parsed.node_limit,
occurrenceOffset: parsed.occurrence_offset,
occurrenceLimit: parsed.occurrence_limit,
edgeOffset: parsed.edge_offset,
edgeLimit: parsed.edge_limit,
},
options?.signal,
);
return ok(
createAnalysisExecution(result, IDENTITY, {
rawResult: null,
limitations: result.limitations,
subject: subjectFor(
this.target.sourcePath ?? this.target.path,
result.manifest,
),
locations: result.occurrences.items.map(({ logical_path: path }) => ({
kind: "artifact-path" as const,
path,
})),
}),
);
} catch (cause: unknown) {
return err(translateFailure(operation, cause));
}
}
close(): Promise<void> {
return Promise.resolve();
}
}
const limitsFrom = (input: {
readonly max_entries: number;
readonly max_total_bytes: number;
readonly max_entry_bytes: number;
readonly max_compression_ratio: number;
readonly max_depth: number;
readonly max_path_bytes: number;
}): ArtifactLimits => ({
maxEntries: input.max_entries,
maxTotalBytes: input.max_total_bytes,
maxEntryBytes: input.max_entry_bytes,
maxCompressionRatio: input.max_compression_ratio,
maxDepth: input.max_depth,
maxPathBytes: input.max_path_bytes,
});
const isArtifactOperation = (
operation: AnalysisOperation,
): operation is ArtifactToolName =>
ARTIFACT_TOOL_CONTRACTS.some(({ name }) => name === operation);
const translateFailure = (
operation: ArtifactToolName,
cause: unknown,
): AnalysisError => {
if (cause instanceof ArtifactReaderFailure)
return new ArtifactOperationError(operation, cause.reason);
return new ArtifactOperationError(operation, "io");
};
const subjectFor = (
path: string,
manifest: {
readonly root_sha256: string;
readonly root_format: import("../domain/artifactGraph.js").ArtifactNode["format"];
},
) => ({
path,
sha256: manifest.root_sha256,
format: manifest.root_format,
});
+58
View File
@@ -0,0 +1,58 @@
import type { Readable } from "node:stream";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
export interface ArtifactEntry {
readonly path: string;
readonly kind: "file" | "directory" | "symlink" | "slice";
readonly declaredSize: number | null;
readonly compressedSize: number | null;
readonly executable: boolean;
readonly encrypted: boolean;
readonly byteOffset: number | null;
readonly declaredSha256: string | null;
readonly limitations: readonly string[];
readonly adapterKey: string;
/** Filesystem identity captured during traversal, when supplied by an adapter. */
readonly sourceIdentity?: {
readonly device: number;
readonly inode: number;
};
}
/** Read-only adapter over one directory, archive, or virtual container. */
export interface ArtifactReader {
readonly format: "directory" | "zip" | "ipa" | "apk" | "asar" | "file";
entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry>;
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable>;
provenance(): readonly ArtifactCommand[];
close(): Promise<void>;
}
/** Hard traversal limits shared by every reader and extraction transaction. */
export interface ArtifactLimits {
readonly maxEntries: number;
readonly maxTotalBytes: number;
readonly maxEntryBytes: number;
readonly maxCompressionRatio: number;
readonly maxDepth: number;
readonly maxPathBytes: number;
}
/** Typed adapter failure translated at provider boundary. */
export class ArtifactReaderFailure extends Error {
constructor(
readonly reason:
| "cancelled"
| "format"
| "integrity"
| "limit"
| "path"
| "unavailable",
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = "ArtifactReaderFailure";
}
}
+80
View File
@@ -0,0 +1,80 @@
import { Readable } from "node:stream";
import { extractFile, listPackage, statFile } from "@electron/asar";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
/** Official Electron ASAR adapter. Individual files remain caller-bounded. */
export class AsarArtifactReader implements ArtifactReader {
readonly format = "asar" as const;
constructor(private readonly path: string) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
const paths = listPackage(this.path, { isPack: false }).sort(
(left, right) => left.localeCompare(right, "en"),
);
for (const listed of paths) {
abortIfNeeded(signal);
const path = listed.replace(/^\/+|\/+$/gu, "");
if (path.length === 0) continue;
const metadata = statFile(this.path, path, false);
const kind =
"files" in metadata
? "directory"
: "link" in metadata
? "symlink"
: "file";
yield {
path,
kind,
declaredSize: "size" in metadata ? metadata.size : null,
compressedSize: null,
executable: "executable" in metadata && metadata.executable,
encrypted: false,
byteOffset: null,
declaredSha256:
"integrity" in metadata &&
metadata.integrity.algorithm === "SHA256" &&
/^[a-f0-9]{64}$/u.test(metadata.integrity.hash)
? metadata.integrity.hash
: null,
limitations:
kind === "symlink"
? ["ASAR symlink target was not followed or disclosed."]
: [
"Official ASAR extraction buffers each individually bounded file.",
],
adapterKey: path,
};
}
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
abortIfNeeded(signal);
if (entry.kind !== "file")
return Promise.reject(
new ArtifactReaderFailure("format", "ASAR entry is not a regular file"),
);
return Promise.resolve(
Readable.from(extractFile(this.path, entry.adapterKey, false)),
);
}
close(): Promise<void> {
return Promise.resolve();
}
provenance(): readonly [] {
return [];
}
}
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
};
+139
View File
@@ -0,0 +1,139 @@
import { constants } from "node:fs";
import { lstat, open, opendir, realpath } from "node:fs/promises";
import { isAbsolute, join, relative, sep } from "node:path";
import type { Readable } from "node:stream";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
/** Deterministic, non-symlink-following directory reader. */
export class DirectoryArtifactReader implements ArtifactReader {
readonly format = "directory" as const;
readonly #rootPromise: Promise<string>;
constructor(root: string) {
this.#rootPromise = realpath(root);
}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
const root = await this.#rootPromise;
const pending = [root];
while (pending.length > 0) {
abortIfNeeded(signal);
const directory = pending.pop();
if (directory === undefined) break;
await assertContainedDirectory(root, directory);
const children: string[] = [];
const handle = await opendir(directory);
try {
for await (const child of handle) children.push(child.name);
} finally {
await handle.close().catch(() => undefined);
}
await assertContainedDirectory(root, directory);
children.sort((left, right) => left.localeCompare(right, "en"));
const directories: string[] = [];
for (const name of children) {
abortIfNeeded(signal);
const absolute = join(directory, name);
const metadata = await lstat(absolute);
const path = relative(root, absolute).split(sep).join("/");
const kind = metadata.isSymbolicLink()
? "symlink"
: metadata.isDirectory()
? "directory"
: metadata.isFile()
? "file"
: undefined;
if (kind === undefined) continue;
if (kind === "directory") directories.push(absolute);
yield {
path,
kind,
declaredSize: kind === "file" ? metadata.size : null,
compressedSize: null,
executable: (metadata.mode & 0o111) !== 0,
encrypted: false,
byteOffset: null,
declaredSha256: null,
limitations:
kind === "symlink"
? ["Symlink target was not followed or disclosed."]
: [],
adapterKey: absolute,
...(kind === "file"
? { sourceIdentity: { device: metadata.dev, inode: metadata.ino } }
: {}),
};
}
directories.reverse();
pending.push(...directories);
}
}
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
abortIfNeeded(signal);
if (entry.kind !== "file")
throw new ArtifactReaderFailure(
"format",
"Only regular files can be opened",
);
const handle = await open(
entry.adapterKey,
constants.O_RDONLY | constants.O_NOFOLLOW,
);
const observed = await handle.stat();
if (
!observed.isFile() ||
entry.sourceIdentity === undefined ||
observed.dev !== entry.sourceIdentity.device ||
observed.ino !== entry.sourceIdentity.inode
) {
await handle.close();
throw new ArtifactReaderFailure(
"integrity",
`Directory entry changed before open: ${entry.path}`,
);
}
return handle.createReadStream({ autoClose: true });
}
close(): Promise<void> {
return Promise.resolve();
}
provenance(): readonly [] {
return [];
}
}
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact traversal cancelled",
);
};
const assertContainedDirectory = async (
root: string,
directory: string,
): Promise<void> => {
const canonical = await realpath(directory);
const fromRoot = relative(root, canonical);
const metadata = await lstat(directory);
if (
metadata.isSymbolicLink() ||
!metadata.isDirectory() ||
fromRoot === ".." ||
fromRoot.startsWith(`..${sep}`) ||
isAbsolute(fromRoot)
)
throw new ArtifactReaderFailure(
"path",
"Directory traversal escaped or changed its artifact root",
);
};
+102
View File
@@ -0,0 +1,102 @@
import { createReadStream } from "node:fs";
import type { Readable } from "node:stream";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
import {
XcrunCommandRunner,
type NativeCommandRunner,
} from "../native/CommandRunner.js";
import { parseLipoArchitectures } from "../native/parsers/lipo.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
export class MachOSliceArtifactReader implements ArtifactReader {
readonly format = "file" as const;
#command: ArtifactCommand | undefined;
constructor(
private readonly path: string,
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
const captured = await this.runner.run(
"lipo",
["-detailed_info", this.path],
{
...(signal === undefined ? {} : { signal }),
timeoutMs: 30_000,
maxOutputBytes: 4 * 1024 * 1024,
},
);
if (!captured.ok)
throw new ArtifactReaderFailure(
captured.error.reason === "cancelled" ? "cancelled" : "unavailable",
"lipo could not enumerate universal Mach-O slices",
{ cause: captured.error },
);
this.#command = {
tool: captured.value.tool,
arguments: ["-detailed_info", "$ARTIFACT"],
tool_version: captured.value.toolVersion,
executable_sha256: captured.value.executableSha256,
exit_code: captured.value.exitCode,
effects: ["read"],
};
for (const architecture of parseLipoArchitectures(captured.value.stdout)) {
if (architecture.file_offset === null || architecture.size === null)
throw new ArtifactReaderFailure(
"integrity",
"lipo omitted a universal slice byte range",
);
yield {
path: `slices/${architecture.name}`,
kind: "slice",
declaredSize: architecture.size,
compressedSize: null,
executable: true,
encrypted: false,
byteOffset: architecture.file_offset,
declaredSha256: null,
limitations: [],
adapterKey: `${String(architecture.file_offset)}:${String(architecture.size)}`,
};
}
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
if (signal?.aborted === true)
return Promise.reject(
new ArtifactReaderFailure("cancelled", "Mach-O slice read cancelled"),
);
const [offsetText, sizeText] = entry.adapterKey.split(":");
const offset = Number(offsetText);
const size = Number(sizeText);
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(size) ||
size <= 0
)
return Promise.reject(
new ArtifactReaderFailure(
"integrity",
"Invalid Mach-O slice byte range",
),
);
return Promise.resolve(
createReadStream(this.path, { start: offset, end: offset + size - 1 }),
);
}
provenance(): readonly ArtifactCommand[] {
return this.#command === undefined ? [] : [this.#command];
}
close(): Promise<void> {
return Promise.resolve();
}
}
+321
View File
@@ -0,0 +1,321 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { lstat, mkdir, open, realpath, rm } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
import type { Readable } from "node:stream";
import { streamChunkToBuffer } from "./StreamBytes.js";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "./ArtifactPaths.js";
import {
ArtifactReaderFailure,
type ArtifactLimits,
} from "./ArtifactReader.js";
/** One file durably written to a transaction-owned output tree. */
export interface SafeOutputFile {
readonly relativePath: string;
readonly sha256: string;
readonly bytesWritten: number;
}
/** Cleanup facts established while rolling back an uncommitted tree. */
export interface SafeOutputCleanup {
readonly attempted: boolean;
readonly verified: boolean;
readonly residualPaths: readonly string[];
}
/** Transactional, symlink-resistant materialization beneath an absent path. */
export class SafeOutputTree {
readonly #registry = new ArtifactPathRegistry();
readonly #limits: ArtifactLimits;
readonly #outputRoot: string;
readonly #stagingRoot: string;
#totalBytes = 0;
#published = false;
#cleanup: SafeOutputCleanup = {
attempted: false,
verified: false,
residualPaths: [],
};
private constructor(
outputRoot: string,
stagingRoot: string,
limits: ArtifactLimits,
) {
this.#outputRoot = outputRoot;
this.#stagingRoot = stagingRoot;
this.#limits = limits;
}
/** Exclusively create the absent destination as this transaction's owned tree. */
static async create(
outputRoot: string,
limits: ArtifactLimits,
): Promise<SafeOutputTree> {
if (!isAbsolute(outputRoot))
throw new ArtifactReaderFailure(
"path",
"Extraction output root must be absolute",
);
const requested = resolve(outputRoot);
const name = basename(requested);
if (name === "." || name === "..")
throw new ArtifactReaderFailure("path", "Invalid extraction output root");
const parent = await realpath(dirname(requested)).catch(
(cause: unknown) => {
throw new ArtifactReaderFailure(
"unavailable",
"Extraction output parent is unavailable",
{ cause },
);
},
);
const canonicalOutput = join(parent, name);
await mkdir(canonicalOutput, { mode: 0o700 }).catch((cause: unknown) => {
if (isAlreadyExists(cause))
throw new ArtifactReaderFailure(
"path",
"Extraction output root already exists",
{ cause },
);
throw cause;
});
try {
const stagingHandle = await open(
canonicalOutput,
constants.O_RDONLY | constants.O_DIRECTORY,
);
try {
await stagingHandle.chmod(0o700);
} finally {
await stagingHandle.close();
}
return new SafeOutputTree(canonicalOutput, canonicalOutput, limits);
} catch (cause: unknown) {
await rm(canonicalOutput, { recursive: true, force: true });
throw cause;
}
}
get outputRoot(): string {
return this.#outputRoot;
}
get cleanup(): SafeOutputCleanup {
return this.#cleanup;
}
/** Stream one selected regular file with exact byte and digest verification. */
async write(
relativePath: string,
source: Readable,
expectedSha256: string,
signal?: AbortSignal,
): Promise<SafeOutputFile> {
this.#assertWritable();
const path = normalizeArtifactPath(relativePath, this.#limits);
this.#registry.add(path, "file");
const destination = await this.#prepareParent(path);
const handle = await open(
destination,
constants.O_CREAT |
constants.O_EXCL |
constants.O_WRONLY |
constants.O_NOFOLLOW,
0o600,
).catch((cause: unknown) => {
throw new ArtifactReaderFailure(
"path",
`Could not exclusively create extraction path: ${path}`,
{ cause },
);
});
const hash = createHash("sha256");
let bytes = 0;
try {
for await (const raw of source) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > this.#limits.maxEntryBytes)
throw new ArtifactReaderFailure(
"limit",
`Observed entry bytes exceed limit: ${path}`,
);
if (this.#totalBytes + bytes > this.#limits.maxTotalBytes)
throw new ArtifactReaderFailure(
"limit",
"Observed extraction bytes exceed cumulative limit",
);
hash.update(chunk);
await writeAll(handle, chunk);
}
const sha256 = hash.digest("hex");
if (sha256 !== expectedSha256)
throw new ArtifactReaderFailure(
"integrity",
`Extracted content disagrees with inventory: ${path}`,
);
await handle.sync();
await handle.close();
const readback = await hashFile(destination, bytes, signal);
if (readback.sha256 !== sha256 || readback.bytes !== bytes)
throw new ArtifactReaderFailure(
"integrity",
`Durable readback verification failed: ${path}`,
);
this.#totalBytes += bytes;
return { relativePath: path, sha256, bytesWritten: bytes };
} catch (cause: unknown) {
await handle.close().catch(() => undefined);
throw cause;
}
}
/** Durably commit the exclusively-created output tree. */
async commit(): Promise<void> {
this.#assertWritable();
const parent = await open(
dirname(this.#outputRoot),
constants.O_RDONLY | constants.O_DIRECTORY,
);
const staging = await open(
this.#stagingRoot,
constants.O_RDONLY | constants.O_DIRECTORY,
);
try {
await staging.sync();
await parent.sync();
this.#published = true;
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"path",
"Could not durably commit extraction output",
{ cause },
);
} finally {
await Promise.allSettled([parent.close(), staging.close()]);
}
}
/** Remove only this transaction's uncommitted tree and verify absence. */
async rollback(): Promise<SafeOutputCleanup> {
if (this.#published) return this.#cleanup;
await rm(this.#stagingRoot, { recursive: true, force: true });
const absent = await isAbsent(this.#stagingRoot);
this.#cleanup = {
attempted: true,
verified: absent,
residualPaths: absent ? [] : [basename(this.#stagingRoot)],
};
if (!absent)
throw new ArtifactReaderFailure(
"integrity",
"Extraction output cleanup could not be verified",
);
return this.#cleanup;
}
async #prepareParent(relativePath: string): Promise<string> {
const parts = relativePath.split("/");
const fileName = parts.pop();
if (fileName === undefined)
throw new ArtifactReaderFailure("path", "Invalid extraction path");
let current = this.#stagingRoot;
for (const part of parts) {
current = join(current, part);
await mkdir(current, { mode: 0o700 }).catch((cause: unknown) => {
if (!isAlreadyExists(cause)) throw cause;
});
const metadata = await lstat(current);
if (!metadata.isDirectory() || metadata.isSymbolicLink())
throw new ArtifactReaderFailure(
"path",
`Unsafe extraction parent: ${relativePath}`,
);
}
return join(current, fileName);
}
#assertWritable(): void {
if (this.#published)
throw new ArtifactReaderFailure(
"integrity",
"Extraction tree is already committed",
);
}
}
const hashFile = async (
path: string,
maximum: number,
signal?: AbortSignal,
): Promise<{ readonly sha256: string; readonly bytes: number }> => {
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
const hash = createHash("sha256");
let bytes = 0;
try {
for await (const raw of handle.createReadStream({ autoClose: false })) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > maximum)
throw new ArtifactReaderFailure(
"integrity",
"Readback exceeded the bytes written",
);
hash.update(chunk);
}
} finally {
await handle.close();
}
return { sha256: hash.digest("hex"), bytes };
};
const writeAll = async (
handle: Awaited<ReturnType<typeof open>>,
chunk: Buffer,
): Promise<void> => {
let offset = 0;
while (offset < chunk.length) {
const { bytesWritten } = await handle.write(
chunk,
offset,
chunk.length - offset,
);
if (bytesWritten === 0)
throw new ArtifactReaderFailure(
"unavailable",
"Extraction output stopped accepting bytes",
);
offset += bytesWritten;
}
};
const isAbsent = async (path: string): Promise<boolean> =>
lstat(path).then(
() => false,
(cause: unknown) => {
if (isNotFound(cause)) return true;
throw cause;
},
);
const isNotFound = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const isAlreadyExists = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact extraction cancelled",
);
};
+7
View File
@@ -0,0 +1,7 @@
/** Parse a Node readable chunk without unchecked coercion. */
export const streamChunkToBuffer = (value: unknown): Buffer => {
if (Buffer.isBuffer(value)) return value;
if (value instanceof Uint8Array) return Buffer.from(value);
if (typeof value === "string") return Buffer.from(value);
throw new TypeError("Readable stream emitted a non-byte chunk");
};
+138
View File
@@ -0,0 +1,138 @@
import { open, type FileHandle } from "node:fs/promises";
import { PassThrough, type Readable } from "node:stream";
import { once } from "node:events";
import { Reader, ZipReader, type Entry, type FileEntry } from "@zip.js/zip.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "./ArtifactReader.js";
class NodeFileReader extends Reader<string> {
#handle: FileHandle | undefined;
constructor(private readonly path: string) {
super(path);
}
override async init(): Promise<void> {
this.#handle = await open(this.path, "r");
this.size = (await this.#handle.stat()).size;
}
override async readUint8Array(
index: number,
length: number,
): Promise<Uint8Array> {
const handle = this.#handle;
if (handle === undefined) throw new Error("ZIP reader is not initialized");
const bytes = Buffer.alloc(Math.min(length, this.size - index));
const read = await handle.read(bytes, 0, bytes.length, index);
return bytes.subarray(0, read.bytesRead);
}
async closeHandle(): Promise<void> {
await this.#handle?.close();
this.#handle = undefined;
}
}
/** Lazy Zip64-capable reader with CRC and overlap verification on every read. */
export class ZipArtifactReader implements ArtifactReader {
readonly format: "zip" | "ipa" | "apk";
readonly #source: NodeFileReader;
readonly #reader: ZipReader<string>;
readonly #entries = new Map<string, Entry>();
constructor(path: string, format: "zip" | "ipa" | "apk") {
this.format = format;
this.#source = new NodeFileReader(path);
this.#reader = new ZipReader(this.#source, {
checkSignature: true,
checkOverlappingEntry: true,
});
}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
for await (const entry of this.#reader.getEntriesGenerator()) {
abortIfNeeded(signal);
this.#entries.set(entry.filename, entry);
const symlink = isSymlink(entry);
yield {
path: entry.filename,
kind: entry.directory ? "directory" : symlink ? "symlink" : "file",
declaredSize: entry.directory ? null : entry.uncompressedSize,
compressedSize: entry.directory ? null : entry.compressedSize,
executable: entry.executable,
encrypted: entry.encrypted,
byteOffset: null,
declaredSha256: null,
limitations: symlink ? ["Archive symlink target was not read."] : [],
adapterKey: entry.filename,
};
}
}
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
abortIfNeeded(signal);
const stored = this.#entries.get(entry.adapterKey);
if (stored === undefined || stored.directory || isSymlink(stored))
return Promise.reject(
new ArtifactReaderFailure("format", "ZIP entry is not a regular file"),
);
if (stored.encrypted)
return Promise.reject(
new ArtifactReaderFailure(
"unavailable",
"Encrypted ZIP entry is unsupported",
),
);
return Promise.resolve(extractStream(stored, signal));
}
async close(): Promise<void> {
await this.#reader.close().catch(() => undefined);
await this.#source.closeHandle();
}
provenance(): readonly [] {
return [];
}
}
const extractStream = (entry: FileEntry, signal?: AbortSignal): Readable => {
const output = new PassThrough();
const writable = new WritableStream<Uint8Array>({
write: async (chunk) => {
abortIfNeeded(signal);
if (!output.write(Buffer.from(chunk))) await once(output, "drain");
},
close: () => {
output.end();
},
abort: (reason) => {
output.destroy(toError(reason));
},
});
void entry
.getData(writable, {
checkSignature: true,
checkOverlappingEntry: true,
onprogress: () => abortIfNeeded(signal),
})
.catch((cause: unknown) => output.destroy(toError(cause)));
return output;
};
const isSymlink = (entry: Entry): boolean =>
entry.unixMode !== undefined && (entry.unixMode & 0o170000) === 0o120000;
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure("cancelled", "ZIP operation cancelled");
};
const toError = (cause: unknown): Error =>
cause instanceof Error ? cause : new Error("ZIP extraction failed");