chore: merge main into feat/dylib-resolution
Resolve conflicts against main: - README.md: take main's simplified English README, which no longer has the tool-family table. - README_ja.md: take main's reworded table and count trace_dylib_resolution in the artifact graph row (5 -> 6). - Skill: the references gain the trace_dylib_resolution paragraph, so the version moves to 29 (main already uses 28). - Regenerate the product catalog, conformance manifest, skill digest and package metadata (135 tools). The MCP tool catalog is now built rather than committed (#997), so it is removed here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,8 +10,8 @@ import {
|
||||
import { inspectBundleKeyedArchive } from "./apple/KeyedArchiveReader.js";
|
||||
import { traceDylibResolution } from "./apple/DylibResolutionReader.js";
|
||||
import { basename, dirname } from "node:path";
|
||||
import { inventoryArtifact } from "../application/ArtifactInventory.js";
|
||||
import { extractArtifact } from "../application/ArtifactExtraction.js";
|
||||
import { inventoryArtifact } from "./inventory/ArtifactInventory.js";
|
||||
import { extractArtifact } from "./extraction/ArtifactExtraction.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "./apple/InterfaceBuilderAnalysis.js";
|
||||
import { analyzeAppleAssetCatalogs } from "./apple/AppleAssetCatalogAnalysis.js";
|
||||
import {
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
} from "./ArtifactProviderMetadata.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createArtifactInspection } from "../domain/artifactInspection.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "../application/ArtifactInventory/policy.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "./inventory/policy.js";
|
||||
|
||||
/** Read-only inventory and exclusively owned extraction provider. */
|
||||
export class ArtifactProvider implements AnalysisProvider {
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { sep } from "node:path";
|
||||
import { constants, createReadStream, type Stats } from "node:fs";
|
||||
import { lstat, open, realpath, type FileHandle } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { extractFile, listPackage, statFile, uncache } from "@electron/asar";
|
||||
import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
|
||||
|
||||
/**
|
||||
* Official Electron ASAR adapter. Individual files remain caller-bounded.
|
||||
* Official Electron ASAR adapter with range-streamed member reads.
|
||||
*
|
||||
* An entry marked `unpacked` is metadata, not an integrity exemption: Electron
|
||||
* stores its bytes beside the archive in `<archive>.unpacked`, and callers must
|
||||
@@ -19,17 +21,33 @@ import {
|
||||
*/
|
||||
export class AsarArtifactReader implements ArtifactReader {
|
||||
readonly format = "asar" as const;
|
||||
#archiveSize: number | undefined;
|
||||
#headerSize: number | undefined;
|
||||
readonly #entries = new Map<string, AsarEntryState>();
|
||||
|
||||
constructor(private readonly path: string) {}
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
private readonly openUnpackedFile: OpenAsarUnpackedFile = open,
|
||||
) {}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let paths: string[];
|
||||
try {
|
||||
// ASAR caches headers by path even after the archive has been replaced.
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
uncache(this.path);
|
||||
paths = listPackage(this.path, { isPack: false }).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
);
|
||||
this.#headerSize = getRawHeader(this.path).headerSize;
|
||||
const archiveMetadata = await lstat(this.path);
|
||||
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"ASAR container is not a regular file",
|
||||
);
|
||||
this.#archiveSize = archiveMetadata.size;
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, "inventory", cause);
|
||||
}
|
||||
@@ -56,7 +74,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
: "link" in metadata
|
||||
? "symlink"
|
||||
: "file";
|
||||
yield {
|
||||
const entry: ArtifactEntry = {
|
||||
path,
|
||||
kind,
|
||||
declaredSize: "size" in metadata ? metadata.size : null,
|
||||
@@ -74,42 +92,121 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
limitations:
|
||||
kind === "symlink"
|
||||
? ["ASAR symlink target was not followed or disclosed."]
|
||||
: [
|
||||
"Official ASAR extraction buffers each individually bounded file.",
|
||||
],
|
||||
: [],
|
||||
adapterKey: providerPath,
|
||||
};
|
||||
if (kind === "file" && isAsarFileMetadata(metadata))
|
||||
this.#entries.set(providerPath, {
|
||||
metadata,
|
||||
entry: copyArtifactEntry(entry),
|
||||
});
|
||||
yield entry;
|
||||
}
|
||||
}
|
||||
|
||||
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
async 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"),
|
||||
const state = this.#entries.get(entry.adapterKey);
|
||||
if (state === undefined && entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"ASAR entry is not a regular file",
|
||||
);
|
||||
if (state === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry was not produced by this reader: ${entry.path}`,
|
||||
);
|
||||
if (!sameArtifactEntry(entry, state.entry))
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry metadata changed since inventory: ${state.entry.path}`,
|
||||
);
|
||||
const { metadata } = state;
|
||||
const producedEntry = state.entry;
|
||||
if (producedEntry.unpacked) {
|
||||
const handle = await this.#openUnpackedEntry(producedEntry);
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
abortIfNeeded(signal);
|
||||
if (!observed.isFile())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${producedEntry.path}`,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw asarFailure(this.path, `read ${producedEntry.path}`, cause);
|
||||
}
|
||||
const source = handle.createReadStream({
|
||||
start: 0,
|
||||
autoClose: true,
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
undefined,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
const archiveSize = this.#archiveSize;
|
||||
const headerSize = this.#headerSize;
|
||||
const offset =
|
||||
metadata.offset === undefined
|
||||
? undefined
|
||||
: parseArchiveOffset(metadata.offset);
|
||||
const start =
|
||||
offset === undefined || headerSize === undefined
|
||||
? undefined
|
||||
: 8 + headerSize + offset;
|
||||
if (
|
||||
archiveSize === undefined ||
|
||||
start === undefined ||
|
||||
!Number.isSafeInteger(start) ||
|
||||
metadata.size < 0 ||
|
||||
!Number.isSafeInteger(metadata.size) ||
|
||||
start > archiveSize ||
|
||||
metadata.size > archiveSize - start
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`ASAR entry range is outside its container: ${producedEntry.path}`,
|
||||
);
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
return Promise.resolve(
|
||||
Readable.from(extractFile(this.path, entry.adapterKey, false)),
|
||||
const openedHandle = await open(
|
||||
this.path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
handle = openedHandle;
|
||||
const observed = await openedHandle.stat();
|
||||
abortIfNeeded(signal);
|
||||
if (!observed.isFile() || observed.size !== archiveSize)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before read: ${producedEntry.path}`,
|
||||
);
|
||||
if (metadata.size === 0) {
|
||||
await closeAsarHandle(() => openedHandle.close(), signal);
|
||||
handle = undefined;
|
||||
return Readable.from([]);
|
||||
}
|
||||
const source = openedHandle.createReadStream({
|
||||
start,
|
||||
end: start + metadata.size - 1,
|
||||
autoClose: true,
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
metadata.size,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
return Promise.reject(
|
||||
new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
),
|
||||
);
|
||||
return Promise.reject(
|
||||
asarFailure(this.path, `read ${entry.path}`, cause),
|
||||
);
|
||||
await handle?.close().catch(() => undefined);
|
||||
throw asarFailure(this.path, `read ${producedEntry.path}`, cause);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,14 +218,154 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
|
||||
close(): Promise<void> {
|
||||
uncache(this.path);
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
provenance(): readonly [] {
|
||||
return [];
|
||||
}
|
||||
|
||||
async #openUnpackedEntry(entry: ArtifactEntry): Promise<UnpackedFileHandle> {
|
||||
const unpackedRoot = `${this.path}.unpacked`;
|
||||
try {
|
||||
const rootMetadata = await lstat(unpackedRoot);
|
||||
if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"ASAR unpacked companion is not a regular directory",
|
||||
);
|
||||
const canonicalRoot = await realpath(unpackedRoot);
|
||||
const candidate = join(unpackedRoot, entry.adapterKey);
|
||||
const canonical = await realpath(candidate);
|
||||
const relativePath = relative(canonicalRoot, canonical);
|
||||
if (
|
||||
relativePath === ".." ||
|
||||
relativePath.startsWith(`..${sep}`) ||
|
||||
isAbsolute(relativePath)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry escaped its companion directory: ${entry.path}`,
|
||||
);
|
||||
const pathMetadata = await lstat(candidate);
|
||||
if (!pathMetadata.isFile() || pathMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${entry.path}`,
|
||||
);
|
||||
const handle = await this.openUnpackedFile(
|
||||
canonical,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
const openedMetadata = await handle
|
||||
.stat()
|
||||
.catch(async (cause: unknown) => {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
});
|
||||
if (
|
||||
!openedMetadata.isFile() ||
|
||||
openedMetadata.dev !== pathMetadata.dev ||
|
||||
openedMetadata.ino !== pathMetadata.ino
|
||||
) {
|
||||
await handle.close();
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR unpacked entry changed before read: ${entry.path}`,
|
||||
{},
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return handle;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
throw asarFailure(this.path, `read ${entry.path}`, cause);
|
||||
}
|
||||
}
|
||||
|
||||
#resetArchiveState(): void {
|
||||
this.#archiveSize = undefined;
|
||||
this.#headerSize = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
type AsarFileMetadata = Extract<ReturnType<typeof statFile>, { size: number }>;
|
||||
type AsarEntryState = {
|
||||
readonly metadata: AsarFileMetadata;
|
||||
readonly entry: ArtifactEntry;
|
||||
};
|
||||
type UnpackedFileHandle = {
|
||||
stat(): Promise<Stats>;
|
||||
close(): Promise<void>;
|
||||
createReadStream: FileHandle["createReadStream"];
|
||||
};
|
||||
type OpenAsarUnpackedFile = (
|
||||
path: string,
|
||||
flags: number,
|
||||
) => Promise<UnpackedFileHandle>;
|
||||
|
||||
const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
|
||||
...entry,
|
||||
limitations: [...entry.limitations],
|
||||
...(entry.sourceIdentity === undefined
|
||||
? {}
|
||||
: { sourceIdentity: { ...entry.sourceIdentity } }),
|
||||
});
|
||||
|
||||
const sameArtifactEntry = (
|
||||
entry: ArtifactEntry,
|
||||
produced: ArtifactEntry,
|
||||
): boolean =>
|
||||
entry.path === produced.path &&
|
||||
entry.kind === produced.kind &&
|
||||
entry.declaredSize === produced.declaredSize &&
|
||||
entry.compressedSize === produced.compressedSize &&
|
||||
entry.executable === produced.executable &&
|
||||
entry.encrypted === produced.encrypted &&
|
||||
entry.byteOffset === produced.byteOffset &&
|
||||
entry.declaredSha256 === produced.declaredSha256 &&
|
||||
entry.unpacked === produced.unpacked &&
|
||||
entry.adapterKey === produced.adapterKey &&
|
||||
entry.limitations.length === produced.limitations.length &&
|
||||
entry.limitations.every(
|
||||
(limitation, index) => limitation === produced.limitations[index],
|
||||
) &&
|
||||
entry.sourceIdentity?.device === produced.sourceIdentity?.device &&
|
||||
entry.sourceIdentity?.inode === produced.sourceIdentity?.inode;
|
||||
|
||||
const isAsarFileMetadata = (
|
||||
metadata: ReturnType<typeof statFile>,
|
||||
): metadata is AsarFileMetadata =>
|
||||
"size" in metadata &&
|
||||
typeof metadata.size === "number" &&
|
||||
!("files" in metadata) &&
|
||||
!("link" in metadata);
|
||||
|
||||
const parseArchiveOffset = (value: string): number | undefined => {
|
||||
if (!/^(?:0|[1-9][0-9]*)$/u.test(value)) return undefined;
|
||||
const offset = Number(value);
|
||||
return Number.isSafeInteger(offset) ? offset : undefined;
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
/** Close an ASAR file handle before honoring cancellation of an empty member. */
|
||||
export const closeAsarHandle = async (
|
||||
close: () => Promise<void>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
await close();
|
||||
abortIfNeeded(signal);
|
||||
};
|
||||
|
||||
/** Validate and contextualize bytes read from one ASAR member source. */
|
||||
export const readValidatedAsarEntry = (
|
||||
source: Readable,
|
||||
expectedBytes: number | undefined,
|
||||
entryPath: string,
|
||||
archivePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Readable => {
|
||||
const output = Readable.from(
|
||||
(async function* () {
|
||||
let observedBytes = 0;
|
||||
const iterator = source[Symbol.asyncIterator]();
|
||||
try {
|
||||
while (true) {
|
||||
abortIfNeeded(signal);
|
||||
const next = await iterator.next();
|
||||
if (next.done) break;
|
||||
const chunk: unknown = next.value;
|
||||
if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`ASAR entry did not return bytes: ${entryPath}`,
|
||||
);
|
||||
observedBytes += Buffer.isBuffer(chunk)
|
||||
? chunk.length
|
||||
: chunk.byteLength;
|
||||
if (expectedBytes !== undefined && observedBytes > expectedBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry exceeded its declared size: ${entryPath}`,
|
||||
);
|
||||
yield chunk;
|
||||
}
|
||||
if (expectedBytes !== undefined && observedBytes !== expectedBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry size disagrees with its header: ${entryPath}`,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(archivePath, `read ${entryPath}`, cause);
|
||||
} finally {
|
||||
try {
|
||||
await iterator.return?.();
|
||||
} catch {
|
||||
// Preserve the read failure; source destruction below owns cleanup.
|
||||
}
|
||||
if (!source.destroyed) source.destroy();
|
||||
}
|
||||
})(),
|
||||
);
|
||||
const closeSource = (): void => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
if (!source.destroyed) source.destroy();
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
closeSource();
|
||||
output.destroy(
|
||||
new ArtifactReaderFailure("cancelled", "ASAR operation cancelled"),
|
||||
);
|
||||
};
|
||||
output.once("close", closeSource);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
return output;
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
|
||||
};
|
||||
|
||||
const asarFailure = (
|
||||
path: string,
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
if (isFilesystemFailure(cause))
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} ASAR at ${path}: ${cause.message}`,
|
||||
{ cause },
|
||||
);
|
||||
return new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Malformed ASAR during ${operation}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const isFilesystemFailure = (
|
||||
cause: unknown,
|
||||
): cause is NodeJS.ErrnoException & Error =>
|
||||
cause instanceof Error &&
|
||||
"errno" in cause &&
|
||||
typeof cause.errno === "number" &&
|
||||
"syscall" in cause &&
|
||||
typeof cause.syscall === "string";
|
||||
@@ -13,34 +13,48 @@ import {
|
||||
export class DirectoryArtifactReader implements ArtifactReader {
|
||||
readonly format = "directory" as const;
|
||||
readonly #rootPromise: Promise<string>;
|
||||
readonly #rootPath: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.#rootPath = root;
|
||||
this.#rootPromise = realpath(root);
|
||||
}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#rootPromise;
|
||||
const root = await this.#rootPromise.catch((cause: unknown) => {
|
||||
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
|
||||
});
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
abortIfNeeded(signal);
|
||||
const directory = pending.pop();
|
||||
if (directory === undefined) break;
|
||||
await assertContainedDirectory(root, directory);
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory),
|
||||
);
|
||||
const children: string[] = [];
|
||||
const handle = await opendir(directory);
|
||||
const handle = await opendir(directory).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open directory", directory, cause);
|
||||
});
|
||||
try {
|
||||
for await (const child of handle) children.push(child.name);
|
||||
} catch (cause: unknown) {
|
||||
throw directoryIoFailure("read directory", directory, cause);
|
||||
} finally {
|
||||
// best-effort cleanup: directory-handle close must not mask traversal.
|
||||
await handle.close().catch(() => undefined);
|
||||
}
|
||||
await assertContainedDirectory(root, directory);
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
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 metadata = await lstat(absolute).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("inspect entry", absolute, cause);
|
||||
});
|
||||
const path = relative(root, absolute).split(sep).join("/");
|
||||
const kind = metadata.isSymbolicLink()
|
||||
? "symlink"
|
||||
@@ -86,9 +100,17 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
const handle = await open(
|
||||
entry.adapterKey,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open entry", entry.adapterKey, cause);
|
||||
});
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
const observed = await handle.stat().catch((cause: unknown) => {
|
||||
throw directoryIoFailure(
|
||||
"inspect opened entry",
|
||||
entry.adapterKey,
|
||||
cause,
|
||||
);
|
||||
});
|
||||
if (
|
||||
!observed.isFile() ||
|
||||
entry.sourceIdentity === undefined ||
|
||||
@@ -117,6 +139,38 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
const directoryIoFailure = (
|
||||
operation: string,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
const code =
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? ` (${cause.code})`
|
||||
: "";
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} at ${path}${code}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const withDirectoryIoContext = async <T>(
|
||||
operation: string,
|
||||
path: string,
|
||||
action: () => Promise<T>,
|
||||
): Promise<T> => {
|
||||
try {
|
||||
return await action();
|
||||
} catch (cause: unknown) {
|
||||
throw directoryIoFailure(operation, path, cause);
|
||||
}
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
|
||||
@@ -37,13 +37,18 @@ export interface NativeDmgHost {
|
||||
arguments_: readonly string[],
|
||||
signal?: AbortSignal,
|
||||
options?: { readonly timeoutMs: number },
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: number }>;
|
||||
): Promise<{
|
||||
readonly stdout: string;
|
||||
readonly stderr?: string;
|
||||
readonly exitCode: number;
|
||||
readonly cause?: unknown;
|
||||
}>;
|
||||
}
|
||||
|
||||
const systemHost: NativeDmgHost = {
|
||||
async run(arguments_, signal, options) {
|
||||
try {
|
||||
const { stdout } = await execFileOutput(
|
||||
const { stdout, stderr } = await execFileOutput(
|
||||
"/usr/bin/hdiutil",
|
||||
[...arguments_],
|
||||
{
|
||||
@@ -51,13 +56,23 @@ const systemHost: NativeDmgHost = {
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
},
|
||||
);
|
||||
return { stdout, exitCode: 0 };
|
||||
return { stdout, stderr, exitCode: 0 };
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled");
|
||||
throw new ArtifactReaderFailure("format", "hdiutil rejected the DMG", {
|
||||
cause,
|
||||
});
|
||||
const exitCode = processExitCode(cause);
|
||||
if (exitCode !== undefined)
|
||||
return {
|
||||
stdout: processOutput(cause, "stdout"),
|
||||
stderr: processOutput(cause, "stderr"),
|
||||
exitCode,
|
||||
cause,
|
||||
};
|
||||
throw new ArtifactReaderFailure(
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -250,15 +265,157 @@ const runChecked = async (
|
||||
signal?: AbortSignal,
|
||||
options?: { readonly timeoutMs: number },
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: 0 }> => {
|
||||
const result = await host.run(arguments_, signal, options);
|
||||
if (result.exitCode !== 0)
|
||||
let result: Awaited<ReturnType<NativeDmgHost["run"]>>;
|
||||
try {
|
||||
result = await host.run(arguments_, signal, options);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled", {
|
||||
cause,
|
||||
});
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed with a non-zero exit code`,
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(
|
||||
cause,
|
||||
arguments_,
|
||||
)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (result.exitCode !== 0) {
|
||||
const failure = {
|
||||
command: "/usr/bin/hdiutil",
|
||||
exitCode: result.exitCode,
|
||||
...(result.cause === undefined
|
||||
? {}
|
||||
: { code: processExitCode(result.cause) }),
|
||||
stdout: result.stdout,
|
||||
...(result.stderr === undefined ? {} : { stderr: result.stderr }),
|
||||
};
|
||||
const reason = commandFailureReason(failure, arguments_[0]);
|
||||
const details = describeCommandFailure(failure, arguments_);
|
||||
const unknownVerifyFailure =
|
||||
arguments_[0] === "verify" && reason === "unavailable";
|
||||
throw new ArtifactReaderFailure(
|
||||
reason,
|
||||
unknownVerifyFailure
|
||||
? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}`
|
||||
: `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`,
|
||||
result.cause === undefined ? undefined : { cause: result.cause },
|
||||
);
|
||||
}
|
||||
return { stdout: result.stdout, exitCode: 0 };
|
||||
};
|
||||
|
||||
const describeCommandFailure = (
|
||||
cause: unknown,
|
||||
arguments_: readonly string[],
|
||||
): string => {
|
||||
const fields: Record<string, string | number | readonly string[]> = {
|
||||
command: "/usr/bin/hdiutil",
|
||||
arguments: [...arguments_],
|
||||
};
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
for (const key of [
|
||||
"code",
|
||||
"exitCode",
|
||||
"errno",
|
||||
"syscall",
|
||||
"signal",
|
||||
"stdout",
|
||||
"stderr",
|
||||
] as const) {
|
||||
const value = Reflect.get(cause, key);
|
||||
if (typeof value === "string" || typeof value === "number")
|
||||
fields[key] = value;
|
||||
}
|
||||
const code = Reflect.get(cause, "code");
|
||||
if (typeof code === "number") fields.exitCode = code;
|
||||
}
|
||||
if (cause instanceof ArtifactReaderFailure) fields.message = cause.message;
|
||||
else if (cause instanceof Error) fields.message = cause.message;
|
||||
return JSON.stringify(fields);
|
||||
};
|
||||
|
||||
const processExitCode = (cause: unknown): number | undefined => {
|
||||
if (typeof cause !== "object" || cause === null) return undefined;
|
||||
const exitCode = Reflect.get(cause, "exitCode");
|
||||
if (typeof exitCode === "number") return exitCode;
|
||||
const code = Reflect.get(cause, "code");
|
||||
return typeof code === "number" ? code : undefined;
|
||||
};
|
||||
|
||||
const processOutput = (cause: unknown, field: "stdout" | "stderr"): string => {
|
||||
if (typeof cause !== "object" || cause === null) return "";
|
||||
const value = Reflect.get(cause, field);
|
||||
return typeof value === "string" ? value : "";
|
||||
};
|
||||
|
||||
const commandFailureReason = (
|
||||
cause: unknown,
|
||||
operation: string | undefined,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
if (typeof cause !== "object" || cause === null) return "unavailable";
|
||||
const code = Reflect.get(cause, "code");
|
||||
const exitCode = Reflect.get(cause, "exitCode");
|
||||
if (typeof code === "number" || typeof exitCode === "number")
|
||||
return operation === "verify" ? verifyFailureReason(cause) : "unavailable";
|
||||
if (code === "ENOENT") {
|
||||
const syscall = Reflect.get(cause, "syscall");
|
||||
return typeof syscall === "string" && syscall.startsWith("spawn")
|
||||
? "unavailable"
|
||||
: "io";
|
||||
}
|
||||
if (
|
||||
code === "EACCES" ||
|
||||
code === "EPERM" ||
|
||||
code === "EIO" ||
|
||||
code === "ENOTDIR" ||
|
||||
code === "EISDIR" ||
|
||||
code === "ENODEV" ||
|
||||
code === "EROFS" ||
|
||||
code === "EMFILE" ||
|
||||
code === "ENFILE"
|
||||
)
|
||||
return "io";
|
||||
return "unavailable";
|
||||
};
|
||||
|
||||
const verifyFailureReason = (
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
const diagnostic = verifyFailureDiagnostic(
|
||||
processOutput(cause, "stdout"),
|
||||
processOutput(cause, "stderr"),
|
||||
);
|
||||
switch (diagnostic) {
|
||||
case "image not recognized":
|
||||
return "format";
|
||||
case "invalid checksum":
|
||||
case "image data corrupted":
|
||||
return "integrity";
|
||||
case "No such file or directory":
|
||||
case "Permission denied":
|
||||
case "Input/output error":
|
||||
return "io";
|
||||
default:
|
||||
return "unavailable";
|
||||
}
|
||||
};
|
||||
|
||||
const verifyFailureDiagnostic = (
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
): string | undefined => {
|
||||
const prefix = "hdiutil: verify failed - ";
|
||||
return `${stdout}\n${stderr}`
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.startsWith(prefix))
|
||||
?.slice(prefix.length);
|
||||
};
|
||||
|
||||
const command = (
|
||||
arguments_: readonly string[],
|
||||
effects: ArtifactCommand["effects"],
|
||||
|
||||
@@ -53,6 +53,9 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
this.#reader = new ZipReader(this.#source, {
|
||||
checkSignature: true,
|
||||
checkOverlappingEntry: true,
|
||||
// REA applies its own provider-neutral path validation in scanReader and
|
||||
// must preserve that typed failure instead of zip.js rejecting first.
|
||||
filenameValidation: "tolerant",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "../ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
type ArtifactExtractionResult,
|
||||
type ArtifactGraphManifest,
|
||||
type ArtifactNode,
|
||||
type ArtifactOccurrence,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
|
||||
|
||||
/** Local extraction input with the output root chosen by the adapter. */
|
||||
export interface ArtifactExtractionInput {
|
||||
readonly inputPath: string;
|
||||
readonly inputFormat: BinaryTarget["format"];
|
||||
readonly outputRoot: string;
|
||||
}
|
||||
|
||||
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
|
||||
export const extractArtifact = async (
|
||||
input: ArtifactExtractionInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactExtractionResult> => {
|
||||
const sourcePath = await realpath(input.inputPath);
|
||||
const snapshot = await scanArtifactInventory(sourcePath, {
|
||||
signal,
|
||||
});
|
||||
const selectedOccurrences = snapshot.occurrences.filter(
|
||||
(occurrence) =>
|
||||
(occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
|
||||
occurrence.logical_path !== ".",
|
||||
);
|
||||
const selectedIds = new Set(
|
||||
selectedOccurrences.map(({ occurrence_id: id }) => id),
|
||||
);
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const neededNodes = new Set<string>();
|
||||
collectOccurrences(
|
||||
snapshot.occurrences,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
);
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
collectNodes(snapshot.nodes, neededNodes, nodes);
|
||||
const inventory: LoadedInventory = {
|
||||
manifest: snapshot.manifest,
|
||||
occurrences,
|
||||
nodes,
|
||||
};
|
||||
const selected = selectedOccurrences.map((occurrence) => {
|
||||
if (
|
||||
(occurrence.entry_kind !== "file" && occurrence.entry_kind !== "slice") ||
|
||||
occurrence.artifact_id === null ||
|
||||
occurrence.encrypted ||
|
||||
occurrence.logical_path === "."
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Selected occurrence is not an extractable regular child file: ${occurrence.occurrence_id}`,
|
||||
);
|
||||
const node = inventory.nodes.get(occurrence.artifact_id);
|
||||
if (node === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Selected occurrence has no inventory node: ${occurrence.occurrence_id}`,
|
||||
);
|
||||
return { occurrence, node };
|
||||
});
|
||||
return materializeSelection({
|
||||
input,
|
||||
sourcePath,
|
||||
inventory,
|
||||
selected,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
interface SelectedOccurrence {
|
||||
readonly occurrence: ArtifactOccurrence;
|
||||
readonly node: ArtifactNode;
|
||||
}
|
||||
|
||||
interface ExtractedOccurrence {
|
||||
readonly artifact_id: string;
|
||||
readonly relative_path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes_written: number;
|
||||
readonly created: true;
|
||||
}
|
||||
|
||||
const materializeSelection = async ({
|
||||
input,
|
||||
sourcePath,
|
||||
inventory,
|
||||
selected,
|
||||
signal,
|
||||
}: {
|
||||
readonly input: ArtifactExtractionInput;
|
||||
readonly sourcePath: string;
|
||||
readonly inventory: LoadedInventory;
|
||||
readonly selected: readonly SelectedOccurrence[];
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<ArtifactExtractionResult> => {
|
||||
const byPath = new Map(
|
||||
selected.map((item) => [item.occurrence.logical_path, item]),
|
||||
);
|
||||
const reader = await createReader(sourcePath, input.inputFormat);
|
||||
const output = await SafeOutputTree.create(input.outputRoot);
|
||||
let readerClosed = false;
|
||||
const extracted: ExtractedOccurrence[] = [];
|
||||
try {
|
||||
const materialized: SelectedOccurrence[] = [];
|
||||
const registry = new ArtifactPathRegistry();
|
||||
for await (const entry of reader.entries(signal)) {
|
||||
const path = normalizeArtifactPath(entry.path);
|
||||
registry.add(path, entry.kind);
|
||||
const selectedItem = byPath.get(path);
|
||||
if (selectedItem === undefined) {
|
||||
if (entry.kind === "file" || entry.kind === "slice")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Regular artifact entry is missing from inventory: ${path}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
preflight(entry);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const written = await output.write(
|
||||
path,
|
||||
stream,
|
||||
selectedItem.node.sha256,
|
||||
signal,
|
||||
);
|
||||
extracted.push({
|
||||
artifact_id: selectedItem.node.artifact_id,
|
||||
relative_path: written.relativePath,
|
||||
sha256: written.sha256,
|
||||
bytes_written: written.bytesWritten,
|
||||
created: true,
|
||||
});
|
||||
materialized.push(selectedItem);
|
||||
}
|
||||
await reader.close();
|
||||
readerClosed = true;
|
||||
extracted.sort((left, right) =>
|
||||
left.relative_path.localeCompare(right.relative_path, "en"),
|
||||
);
|
||||
const result = createExtractionResult(
|
||||
input,
|
||||
inventory,
|
||||
materialized,
|
||||
extracted,
|
||||
);
|
||||
await output.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (!readerClosed)
|
||||
await reader.close().catch((cause: unknown) => {
|
||||
// best-effort cleanup: reader close must not mask the extraction failure.
|
||||
void cause;
|
||||
});
|
||||
await output.rollback();
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const createExtractionResult = (
|
||||
input: ArtifactExtractionInput,
|
||||
inventory: LoadedInventory,
|
||||
selected: readonly SelectedOccurrence[],
|
||||
extracted: readonly ExtractedOccurrence[],
|
||||
): ArtifactExtractionResult => {
|
||||
const extractionSemantic = {
|
||||
source_manifest_id: inventory.manifest.manifest_id,
|
||||
selected_occurrence_ids: selected
|
||||
.map(({ occurrence }) => occurrence.occurrence_id)
|
||||
.sort((left, right) => left.localeCompare(right)),
|
||||
files_sha256: canonicalDigest(extracted, "Artifact"),
|
||||
output_root_alias: "$OUTPUT_ROOT" as const,
|
||||
};
|
||||
return artifactExtractionResultSchema.parse({
|
||||
manifest: inventory.manifest,
|
||||
extraction_manifest: {
|
||||
...extractionSemantic,
|
||||
extraction_id: `aex_${canonicalDigest(extractionSemantic, "Artifact")}`,
|
||||
},
|
||||
output_root: input.outputRoot,
|
||||
artifacts: extracted,
|
||||
containment_verified: true,
|
||||
cleanup: { attempted: false, verified: true, residual_paths: [] },
|
||||
provenance: [],
|
||||
limitations: [
|
||||
"All regular files in the active artifact were materialized; nested archive contents remain represented by their containing file.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
interface LoadedInventory {
|
||||
readonly manifest: ArtifactGraphManifest;
|
||||
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
|
||||
readonly nodes: ReadonlyMap<string, ArtifactNode>;
|
||||
}
|
||||
|
||||
const collectOccurrences = (
|
||||
items: readonly ArtifactOccurrence[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactOccurrence>,
|
||||
neededNodes: Set<string>,
|
||||
): void => {
|
||||
for (const item of items) {
|
||||
if (!selected.has(item.occurrence_id)) continue;
|
||||
output.set(item.occurrence_id, item);
|
||||
if (item.artifact_id !== null) neededNodes.add(item.artifact_id);
|
||||
}
|
||||
};
|
||||
|
||||
const collectNodes = (
|
||||
items: readonly ArtifactNode[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactNode>,
|
||||
): void => {
|
||||
for (const item of items)
|
||||
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
|
||||
};
|
||||
|
||||
const createReader = async (
|
||||
path: string,
|
||||
format: BinaryTarget["format"],
|
||||
): Promise<ArtifactReader> => {
|
||||
if ((await lstat(path)).isDirectory())
|
||||
return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (
|
||||
format === "ipa" ||
|
||||
format === "apk" ||
|
||||
format === "msix" ||
|
||||
format === "appx" ||
|
||||
format === "zip"
|
||||
)
|
||||
return new ZipArtifactReader(path, format);
|
||||
if (format === "mach-o") return new MachOSliceArtifactReader(path);
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`Artifact format has no extraction reader: ${format}`,
|
||||
);
|
||||
};
|
||||
|
||||
const preflight = (entry: ArtifactEntry): void => {
|
||||
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Selected artifact entry cannot be read: ${entry.path}`,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
|
||||
|
||||
it("breaks locale-collation ties deterministically by code unit", () => {
|
||||
const names = ["a\u200d.txt", "a.txt", "a\u200b.txt", "a\u200c.txt"];
|
||||
expect("a\u200d.txt".localeCompare("a.txt")).toBe(0);
|
||||
expect(names.sort(compareDirectoryChildNames)).toEqual([
|
||||
"a.txt",
|
||||
"a\u200b.txt",
|
||||
"a\u200c.txt",
|
||||
"a\u200d.txt",
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,369 @@
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import type { ArtifactEntry } from "../ArtifactReader.js";
|
||||
import type {
|
||||
ArtifactCommand,
|
||||
ArtifactEdge,
|
||||
ArtifactNode,
|
||||
ArtifactOccurrence,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import { zipPackageFormatForPath } from "../../domain/zipPackageFormat.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
|
||||
|
||||
/** Mutable internal occurrence used until root-bound IDs are known. */
|
||||
export interface MutableOccurrence {
|
||||
occurrence_id: string;
|
||||
artifact_id: string | null;
|
||||
parent_occurrence_id: string | null;
|
||||
logical_path: string;
|
||||
entry_kind: ArtifactOccurrence["entry_kind"];
|
||||
declared_size: number | null;
|
||||
compressed_size: number | null;
|
||||
executable: boolean;
|
||||
encrypted: boolean;
|
||||
hash_status: ArtifactOccurrence["hash_status"];
|
||||
source_location: ArtifactOccurrence["source_location"];
|
||||
limitations: string[];
|
||||
}
|
||||
|
||||
/** Index the first occurrence for each canonical logical path. */
|
||||
export const indexOccurrencesByPath = (
|
||||
occurrences: readonly MutableOccurrence[],
|
||||
): ReadonlyMap<string, MutableOccurrence> => {
|
||||
const byPath = new Map<string, MutableOccurrence>();
|
||||
for (const occurrence of occurrences)
|
||||
if (!byPath.has(occurrence.logical_path))
|
||||
byPath.set(occurrence.logical_path, occurrence);
|
||||
return byPath;
|
||||
};
|
||||
|
||||
export const createOccurrence = (
|
||||
entry: ArtifactEntry,
|
||||
path: string,
|
||||
parent: string | null,
|
||||
): MutableOccurrence => ({
|
||||
occurrence_id: `occ_${canonicalDigest({ path, kind: entry.kind }, "Artifact")}`,
|
||||
artifact_id: null,
|
||||
parent_occurrence_id: parent,
|
||||
logical_path: path,
|
||||
entry_kind: entry.kind,
|
||||
declared_size: entry.declaredSize,
|
||||
compressed_size: entry.compressedSize,
|
||||
executable: entry.executable,
|
||||
encrypted: entry.encrypted,
|
||||
hash_status: entry.encrypted ? "unavailable" : "not-hashed",
|
||||
source_location:
|
||||
entry.byteOffset === null || entry.declaredSize === null
|
||||
? null
|
||||
: { offset: entry.byteOffset, length: entry.declaredSize },
|
||||
limitations: [...entry.limitations],
|
||||
});
|
||||
|
||||
/** Preserve collation order and break distinct-name ties by UTF-16 code units. */
|
||||
export const compareDirectoryChildNames = (
|
||||
left: string,
|
||||
right: string,
|
||||
): number => {
|
||||
const collated = left.localeCompare(right);
|
||||
if (collated !== 0) return collated;
|
||||
if (left < right) return -1;
|
||||
return left > right ? 1 : 0;
|
||||
};
|
||||
|
||||
export const materializeDirectoryNodes = (
|
||||
occurrences: MutableOccurrence[],
|
||||
nodes: Map<string, ArtifactNode>,
|
||||
): void => {
|
||||
const directories = occurrences
|
||||
.filter(({ entry_kind: kind }) => kind === "directory")
|
||||
.sort(
|
||||
(left, right) => depth(right.logical_path) - depth(left.logical_path),
|
||||
);
|
||||
const childrenByParent = new Map<string, MutableOccurrence[]>();
|
||||
for (const occurrence of occurrences) {
|
||||
if (occurrence.parent_occurrence_id === null) continue;
|
||||
const children = childrenByParent.get(occurrence.parent_occurrence_id);
|
||||
if (children === undefined)
|
||||
childrenByParent.set(occurrence.parent_occurrence_id, [occurrence]);
|
||||
else children.push(occurrence);
|
||||
}
|
||||
for (const directory of directories) {
|
||||
const children = (childrenByParent.get(directory.occurrence_id) ?? [])
|
||||
.map(({ logical_path, artifact_id, entry_kind }) => ({
|
||||
// Intermediate directory entries may be absent from an archive.
|
||||
name: logical_path.slice(directory.logical_path.length + 1),
|
||||
artifact_id,
|
||||
entry_kind,
|
||||
}))
|
||||
.sort((left, right) => compareDirectoryChildNames(left.name, right.name));
|
||||
const node = createArtifactNode({
|
||||
sha256: canonicalDigest({ kind: "directory", children }, "Artifact"),
|
||||
size: 0,
|
||||
kind: directory.logical_path.toLowerCase().endsWith(".framework")
|
||||
? "framework"
|
||||
: "container",
|
||||
format: "directory",
|
||||
executable: false,
|
||||
contentState: "virtual",
|
||||
});
|
||||
const existing = nodes.get(node.artifact_id);
|
||||
nodes.set(
|
||||
node.artifact_id,
|
||||
existing?.kind === "framework" ? existing : node,
|
||||
);
|
||||
directory.artifact_id = node.artifact_id;
|
||||
directory.hash_status = "verified";
|
||||
}
|
||||
};
|
||||
|
||||
export const createRootNode = (input: {
|
||||
readonly path: string;
|
||||
readonly format: ArtifactNode["format"];
|
||||
readonly directory: boolean;
|
||||
readonly digest: { readonly sha256: string; readonly bytes: number } | null;
|
||||
readonly occurrences: readonly MutableOccurrence[];
|
||||
}): ArtifactNode =>
|
||||
createArtifactNode({
|
||||
sha256:
|
||||
input.digest?.sha256 ??
|
||||
canonicalDigest(
|
||||
{
|
||||
kind: "directory-root",
|
||||
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
|
||||
logical_path,
|
||||
artifact_id,
|
||||
})),
|
||||
},
|
||||
"Artifact",
|
||||
),
|
||||
size: input.digest?.bytes ?? 0,
|
||||
kind:
|
||||
input.directory ||
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(
|
||||
input.format,
|
||||
)
|
||||
? "container"
|
||||
: input.format === "dos-mz"
|
||||
? "executable"
|
||||
: classifyArtifactPath(input.path).kind,
|
||||
format: input.format,
|
||||
executable: false,
|
||||
contentState: "materialized",
|
||||
});
|
||||
|
||||
export const createArtifactNode = (input: {
|
||||
readonly sha256: string;
|
||||
readonly size: number;
|
||||
readonly kind: ArtifactNode["kind"];
|
||||
readonly format: ArtifactNode["format"];
|
||||
readonly executable: boolean;
|
||||
readonly contentState: ArtifactNode["content_state"];
|
||||
readonly limitations?: readonly string[];
|
||||
}): ArtifactNode => ({
|
||||
artifact_id: `art_${canonicalDigest({ sha256: input.sha256 }, "Artifact")}`,
|
||||
kind: input.kind,
|
||||
format: input.format,
|
||||
sha256: input.sha256,
|
||||
size: input.size,
|
||||
media_type: null,
|
||||
architecture: null,
|
||||
executable: input.executable,
|
||||
content_state: input.contentState,
|
||||
limitations: [...(input.limitations ?? [])],
|
||||
});
|
||||
|
||||
export const rootOccurrenceFor = (
|
||||
node: ArtifactNode,
|
||||
declaredSize: number,
|
||||
): MutableOccurrence => ({
|
||||
occurrence_id: `occ_${canonicalDigest({ root: node.artifact_id }, "Artifact")}`,
|
||||
artifact_id: node.artifact_id,
|
||||
parent_occurrence_id: null,
|
||||
logical_path: ".",
|
||||
entry_kind: node.format === "directory" ? "directory" : "file",
|
||||
declared_size: declaredSize,
|
||||
compressed_size: null,
|
||||
executable: node.executable,
|
||||
encrypted: false,
|
||||
hash_status: "verified",
|
||||
source_location: null,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
export const rekeyOccurrences = (
|
||||
rootArtifactId: string,
|
||||
occurrences: MutableOccurrence[],
|
||||
): void => {
|
||||
const replacements = new Map<string, string>();
|
||||
for (const occurrence of occurrences)
|
||||
replacements.set(
|
||||
occurrence.occurrence_id,
|
||||
`occ_${canonicalDigest(
|
||||
{
|
||||
root_artifact_id: rootArtifactId,
|
||||
logical_path: occurrence.logical_path,
|
||||
entry_kind: occurrence.entry_kind,
|
||||
},
|
||||
"Artifact",
|
||||
)}`,
|
||||
);
|
||||
for (const occurrence of occurrences) {
|
||||
occurrence.occurrence_id =
|
||||
replacements.get(occurrence.occurrence_id) ?? occurrence.occurrence_id;
|
||||
if (occurrence.parent_occurrence_id !== null)
|
||||
occurrence.parent_occurrence_id =
|
||||
replacements.get(occurrence.parent_occurrence_id) ??
|
||||
occurrence.parent_occurrence_id;
|
||||
}
|
||||
};
|
||||
|
||||
export const createArtifactEdges = (
|
||||
rootArtifactId: string,
|
||||
occurrences: MutableOccurrence[],
|
||||
producer?: ArtifactCommand,
|
||||
): ArtifactEdge[] => {
|
||||
const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));
|
||||
const byPath = indexOccurrencesByPath(occurrences);
|
||||
const edges: ArtifactEdge[] = [];
|
||||
for (const occurrence of occurrences) {
|
||||
if (
|
||||
occurrence.parent_occurrence_id === null ||
|
||||
occurrence.artifact_id === null
|
||||
)
|
||||
continue;
|
||||
const mappedSource = occurrence.logical_path.toLowerCase().endsWith(".map")
|
||||
? byPath.get(occurrence.logical_path.slice(0, -".map".length))
|
||||
: undefined;
|
||||
const parentArtifactId =
|
||||
mappedSource?.artifact_id ??
|
||||
byId.get(occurrence.parent_occurrence_id)?.artifact_id ??
|
||||
rootArtifactId;
|
||||
const semantic = {
|
||||
parent_artifact_id: parentArtifactId,
|
||||
child_artifact_id: occurrence.artifact_id,
|
||||
relation:
|
||||
occurrence.entry_kind === "slice"
|
||||
? ("slice-of" as const)
|
||||
: relationFor(occurrence.logical_path),
|
||||
occurrence_id: occurrence.occurrence_id,
|
||||
logical_path: occurrence.logical_path,
|
||||
};
|
||||
edges.push({
|
||||
edge_id: `edge_${canonicalDigest(semantic, "Artifact")}`,
|
||||
...semantic,
|
||||
producer: occurrence.entry_kind === "slice" ? (producer ?? null) : null,
|
||||
ordinal: edges.length,
|
||||
});
|
||||
}
|
||||
return edges;
|
||||
};
|
||||
|
||||
export const nearestParent = (
|
||||
path: string,
|
||||
occurrences: ReadonlyMap<string, MutableOccurrence>,
|
||||
expandedContainerIds: ReadonlySet<string>,
|
||||
): MutableOccurrence | undefined => {
|
||||
const parts = path.split("/");
|
||||
while (parts.length > 1) {
|
||||
parts.pop();
|
||||
const candidate = occurrences.get(parts.join("/"));
|
||||
if (
|
||||
candidate !== undefined &&
|
||||
(candidate.entry_kind === "directory" ||
|
||||
expandedContainerIds.has(candidate.occurrence_id))
|
||||
)
|
||||
return candidate;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const classifyArtifactPath = (
|
||||
path: string,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.endsWith(".map"))
|
||||
return { kind: "source-map", format: "source-map" };
|
||||
if (/\.(?:m?js|cjs)$/u.test(lower))
|
||||
return { kind: "javascript", format: "javascript-bundle" };
|
||||
if (lower.endsWith(".asar")) return { kind: "container", format: "asar" };
|
||||
const archiveFormat = zipPackageFormatForPath(lower);
|
||||
if (archiveFormat !== undefined)
|
||||
return { kind: "container", format: archiveFormat };
|
||||
if (/\.framework(?:\/|$)/u.test(lower))
|
||||
return { kind: "framework", format: "file" };
|
||||
if (/\.(?:node|dylib|so)$/u.test(lower))
|
||||
return {
|
||||
kind: lower.endsWith(".node") ? "native-addon" : "dynamic-library",
|
||||
format: "file",
|
||||
};
|
||||
if (lower.endsWith(".plist")) return { kind: "plist", format: "plist" };
|
||||
if (lower.endsWith(".entitlements"))
|
||||
return { kind: "entitlements", format: "entitlements" };
|
||||
return { kind: "resource", format: "file" };
|
||||
};
|
||||
|
||||
/** Classify executable formats from bytes while retaining path-specific roles. */
|
||||
export const classifyArtifactContent = (
|
||||
path: string,
|
||||
prefix: Buffer,
|
||||
fileSize = prefix.length,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const byPath = classifyArtifactPath(path);
|
||||
if (prefix.length >= 4) {
|
||||
const magic = prefix.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
|
||||
return {
|
||||
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
|
||||
format: "mach-o-universal",
|
||||
};
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
|
||||
return {
|
||||
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
|
||||
? byPath.kind
|
||||
: "executable",
|
||||
format: "mach-o",
|
||||
};
|
||||
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
|
||||
return {
|
||||
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
|
||||
? byPath.kind
|
||||
: "executable",
|
||||
format: "elf",
|
||||
};
|
||||
}
|
||||
if (prefix.length >= 2 && prefix[0] === 0x4d && prefix[1] === 0x5a) {
|
||||
if (
|
||||
!Number.isSafeInteger(fileSize) ||
|
||||
fileSize < prefix.length ||
|
||||
prefix.length < Math.min(fileSize, 64)
|
||||
)
|
||||
return { kind: "unknown", format: "unknown" };
|
||||
const windowsOffset = mzWindowsHeaderOffset(prefix);
|
||||
if (windowsOffset !== null) {
|
||||
if (
|
||||
windowsOffset >= 64 &&
|
||||
windowsOffset <= prefix.length - 4 &&
|
||||
prefix
|
||||
.subarray(windowsOffset, windowsOffset + 4)
|
||||
.equals(Buffer.from([0x50, 0x45, 0, 0]))
|
||||
)
|
||||
return {
|
||||
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
|
||||
format: "pe",
|
||||
};
|
||||
} else if (parseDosMzHeader(prefix, fileSize).ok) {
|
||||
return { kind: "executable", format: "dos-mz" };
|
||||
}
|
||||
// Missing bounded evidence and malformed MZ bytes both remain unclassified.
|
||||
return { kind: "unknown", format: "unknown" };
|
||||
}
|
||||
return byPath;
|
||||
};
|
||||
|
||||
const relationFor = (path: string): ArtifactEdge["relation"] => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.endsWith(".map")) return "maps-source";
|
||||
if (lower.includes(".framework/")) return "embeds";
|
||||
return "contains";
|
||||
};
|
||||
|
||||
const depth = (path: string): number => path.split("/").length;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import { abortIfNeeded } from "../ArtifactHash.js";
|
||||
import { scanCanonicalArtifactInventory } from "./scanCanonical.js";
|
||||
import type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
} from "./types.js";
|
||||
|
||||
export { scanCanonicalArtifactInventory } from "./scanCanonical.js";
|
||||
|
||||
export type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
} from "./types.js";
|
||||
|
||||
/** Inventory one local artifact and return every graph collection inline. */
|
||||
export const inventoryArtifact = async (
|
||||
inputPath: string,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly integrity?: ArtifactIntegrityPolicy;
|
||||
} = {},
|
||||
): Promise<ArtifactInventoryResult> => {
|
||||
const snapshot = await scanArtifactInventory(inputPath, options);
|
||||
return artifactInventoryResultSchema.parse(snapshot);
|
||||
};
|
||||
|
||||
/** Scan an artifact once and retain the complete immutable graph for projection. */
|
||||
export const scanArtifactInventory = async (
|
||||
inputPath: string,
|
||||
options: ArtifactInventoryOptions = {},
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
abortIfNeeded(options.signal);
|
||||
const path = await realpath(inputPath);
|
||||
return scanCanonicalArtifactInventory(path, options);
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { open } from "node:fs/promises";
|
||||
|
||||
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
|
||||
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
zipPackageFormatForPath,
|
||||
} from "../../domain/zipPackageFormat.js";
|
||||
|
||||
const classifyContainerExtension = (
|
||||
path: string,
|
||||
): ArtifactNode["format"] | undefined => {
|
||||
const lower = path.toLowerCase();
|
||||
const zipPackage = zipPackageFormatForPath(lower);
|
||||
if (zipPackage !== undefined) return zipPackage;
|
||||
for (const format of ["asar", "dmg", "pkg"] as const)
|
||||
if (lower.endsWith(`.${format}`)) return format;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const classifyRoot = async (
|
||||
path: string,
|
||||
directory: boolean,
|
||||
): Promise<ArtifactNode["format"]> => {
|
||||
if (directory) return "directory";
|
||||
const extensionFormat = classifyContainerExtension(path);
|
||||
if (extensionFormat !== undefined) return extensionFormat;
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
const prefix = magic.subarray(0, observed.bytesRead);
|
||||
if (hasZipSignature(prefix)) return "zip";
|
||||
return classifyArtifactContent(path, prefix, (await handle.stat()).size)
|
||||
.format;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ArtifactIntegrityPolicy } from "./types.js";
|
||||
|
||||
/** Parsed caller intent for integrity mismatch handling. */
|
||||
export type ArtifactIntegrityIntent =
|
||||
| { readonly mode: "fail" }
|
||||
| { readonly mode: "record-and-continue" };
|
||||
|
||||
/** Preserve the explicit integrity admission choice without changing verification. */
|
||||
export const resolveArtifactIntegrityPolicy = (
|
||||
intent: ArtifactIntegrityIntent,
|
||||
): ArtifactIntegrityPolicy => intent;
|
||||
@@ -0,0 +1,49 @@
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import type { ArtifactReader } from "../ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
|
||||
export const createReader = async (
|
||||
path: string,
|
||||
format: ArtifactNode["format"],
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactReader | undefined> => {
|
||||
switch (format) {
|
||||
case "directory":
|
||||
return new DirectoryArtifactReader(path);
|
||||
case "zip":
|
||||
case "ipa":
|
||||
case "apk":
|
||||
case "msix":
|
||||
case "appx":
|
||||
return new ZipArtifactReader(path, format);
|
||||
case "asar":
|
||||
return new AsarArtifactReader(path);
|
||||
case "mach-o-universal":
|
||||
return process.platform === "darwin"
|
||||
? new MachOSliceArtifactReader(path)
|
||||
: undefined;
|
||||
case "dmg":
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
return NativeDmgArtifactReader.create(path, signal);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const inventoryLimitations = (
|
||||
format: ArtifactNode["format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
): string[] => {
|
||||
if (reader !== undefined) return [];
|
||||
if (format === "dmg" || format === "pkg")
|
||||
return [
|
||||
`${format.toUpperCase()} root hash is observed; child inventory requires a native macOS adapter.`,
|
||||
];
|
||||
if (format === "mach-o-universal" && process.platform !== "darwin")
|
||||
return ["Universal Mach-O slices require the native macOS lipo adapter."];
|
||||
return ["Artifact has no child container entries."];
|
||||
};
|
||||
@@ -0,0 +1,271 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import type { Stats } from "node:fs";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactReader,
|
||||
} from "../ArtifactReader.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
type ArtifactNode,
|
||||
type IntegrityContradiction,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
createArtifactEdges,
|
||||
createRootNode,
|
||||
indexOccurrencesByPath,
|
||||
materializeDirectoryNodes,
|
||||
rekeyOccurrences,
|
||||
rootOccurrenceFor,
|
||||
type MutableOccurrence,
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import { classifyRoot } from "./classify.js";
|
||||
import { hashReadable, type HashResult } from "../ArtifactHash.js";
|
||||
import { createReader, inventoryLimitations } from "./reader.js";
|
||||
import {
|
||||
scanReader,
|
||||
type PendingIntegrityContradiction,
|
||||
} from "./scanReader.js";
|
||||
import {
|
||||
STRICT_INTEGRITY_POLICY,
|
||||
type ArtifactInventoryOptions,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./types.js";
|
||||
|
||||
export const scanCanonicalArtifactInventory = async (
|
||||
path: string,
|
||||
options: ArtifactInventoryOptions = {},
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
|
||||
const metadata = await lstat(path);
|
||||
const rootFormat = await classifyRoot(path, metadata.isDirectory());
|
||||
const rootDigest = metadata.isDirectory()
|
||||
? null
|
||||
: await hashReadable(createReadStream(path), options.signal);
|
||||
const reader = await createReader(path, rootFormat, options.signal);
|
||||
|
||||
try {
|
||||
const { nodes, occurrences, pendingContradictions } = await scanReader(
|
||||
reader,
|
||||
options.signal,
|
||||
integrity,
|
||||
);
|
||||
return await buildInventorySnapshot({
|
||||
path,
|
||||
metadata,
|
||||
rootFormat,
|
||||
rootDigest,
|
||||
reader,
|
||||
signal: options.signal,
|
||||
nodes,
|
||||
occurrences,
|
||||
pendingContradictions,
|
||||
});
|
||||
} finally {
|
||||
await reader?.close();
|
||||
}
|
||||
};
|
||||
|
||||
interface SnapshotBuildInput {
|
||||
readonly path: string;
|
||||
readonly metadata: Stats;
|
||||
readonly rootFormat: ArtifactNode["format"];
|
||||
readonly rootDigest: HashResult | null;
|
||||
readonly reader: ArtifactReader | undefined;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
readonly occurrences: MutableOccurrence[];
|
||||
readonly pendingContradictions: PendingIntegrityContradiction[];
|
||||
}
|
||||
|
||||
const buildInventorySnapshot = async (
|
||||
input: SnapshotBuildInput,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const { path, metadata, rootFormat, rootDigest, reader, signal } = input;
|
||||
materializeDirectoryNodes(input.occurrences, input.nodes);
|
||||
const rootNode = createRootNode({
|
||||
path,
|
||||
format: rootFormat,
|
||||
directory: metadata.isDirectory(),
|
||||
digest: rootDigest,
|
||||
occurrences: input.occurrences,
|
||||
});
|
||||
input.nodes.set(rootNode.artifact_id, rootNode);
|
||||
rekeyOccurrences(rootNode.artifact_id, input.occurrences);
|
||||
const rootOccurrence = rootOccurrenceFor(rootNode, metadata.size);
|
||||
for (const occurrence of input.occurrences)
|
||||
if (occurrence.parent_occurrence_id === null)
|
||||
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
|
||||
input.occurrences.unshift(rootOccurrence);
|
||||
|
||||
const occurrenceById = new Map(
|
||||
input.occurrences.map((occurrence) => [
|
||||
occurrence.occurrence_id,
|
||||
occurrence,
|
||||
]),
|
||||
);
|
||||
const occurrenceByPath = indexOccurrencesByPath(input.occurrences);
|
||||
const integrityContradictions = buildIntegrityContradictions(
|
||||
input.pendingContradictions,
|
||||
occurrenceByPath,
|
||||
occurrenceById,
|
||||
rootNode,
|
||||
);
|
||||
const edges = createArtifactEdges(
|
||||
rootNode.artifact_id,
|
||||
input.occurrences,
|
||||
reader?.provenance()[0],
|
||||
);
|
||||
const orderedNodes = sortNodes([...input.nodes.values()]);
|
||||
const orderedOccurrences = sortOccurrences(input.occurrences);
|
||||
const orderedEdges = sortEdges(edges);
|
||||
|
||||
await verifyRootDigest(path, rootDigest, signal);
|
||||
|
||||
const graphSha256 = canonicalDigest(
|
||||
{
|
||||
nodes: orderedNodes,
|
||||
occurrences: orderedOccurrences,
|
||||
edges: orderedEdges,
|
||||
integrity_contradictions: integrityContradictions,
|
||||
},
|
||||
"Artifact",
|
||||
);
|
||||
const manifest = buildManifest({
|
||||
rootNode,
|
||||
graphSha256,
|
||||
orderedNodes,
|
||||
orderedOccurrences,
|
||||
orderedEdges,
|
||||
});
|
||||
return {
|
||||
manifest,
|
||||
nodes: orderedNodes,
|
||||
occurrences: orderedOccurrences,
|
||||
edges: orderedEdges,
|
||||
provenance: reader?.provenance() ?? [],
|
||||
integrity_contradictions: integrityContradictions,
|
||||
limitations: buildLimitations(rootFormat, reader, integrityContradictions),
|
||||
};
|
||||
};
|
||||
|
||||
const buildIntegrityContradictions = (
|
||||
pending: readonly PendingIntegrityContradiction[],
|
||||
occurrenceByPath: ReadonlyMap<string, MutableOccurrence>,
|
||||
occurrenceById: ReadonlyMap<string, MutableOccurrence>,
|
||||
rootNode: ArtifactNode,
|
||||
): IntegrityContradiction[] =>
|
||||
pending.map((contradiction): IntegrityContradiction => {
|
||||
const occurrence = occurrenceByPath.get(contradiction.logicalPath);
|
||||
if (occurrence === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Integrity contradiction lost its graph occurrence",
|
||||
);
|
||||
const parent =
|
||||
occurrence.parent_occurrence_id === null
|
||||
? undefined
|
||||
: occurrenceById.get(occurrence.parent_occurrence_id);
|
||||
const parentArtifactId = parent?.artifact_id ?? rootNode.artifact_id;
|
||||
return {
|
||||
contradiction_id: `ic_${canonicalDigest(
|
||||
{
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
logical_path: contradiction.logicalPath,
|
||||
declared_sha256: contradiction.declaredSha256,
|
||||
observed_sha256: contradiction.observedSha256,
|
||||
},
|
||||
"Artifact",
|
||||
)}`,
|
||||
occurrence_id: occurrence.occurrence_id,
|
||||
parent_artifact_id: parentArtifactId,
|
||||
logical_path: contradiction.logicalPath,
|
||||
declared_sha256: contradiction.declaredSha256,
|
||||
observed_sha256: contradiction.observedSha256,
|
||||
entry_kind: contradiction.entryKind,
|
||||
unpacked: contradiction.unpacked,
|
||||
trust: "observed-untrusted",
|
||||
provenance: "container-integrity-metadata-versus-observed-bytes",
|
||||
limitations: [
|
||||
"Observed bytes contradict declared integrity metadata and cannot support equivalence.",
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
const verifyRootDigest = async (
|
||||
path: string,
|
||||
rootDigest: HashResult | null,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<void> => {
|
||||
if (rootDigest === null) return;
|
||||
const verified = await hashReadable(createReadStream(path), signal);
|
||||
if (
|
||||
verified.sha256 !== rootDigest.sha256 ||
|
||||
verified.bytes !== rootDigest.bytes
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Root artifact changed during inventory",
|
||||
);
|
||||
};
|
||||
|
||||
const sortNodes = (nodes: ArtifactNode[]): ArtifactNode[] =>
|
||||
nodes.sort((left, right) =>
|
||||
left.artifact_id.localeCompare(right.artifact_id),
|
||||
);
|
||||
|
||||
const sortOccurrences = (
|
||||
occurrences: MutableOccurrence[],
|
||||
): MutableOccurrence[] =>
|
||||
occurrences.sort((left, right) =>
|
||||
left.logical_path.localeCompare(right.logical_path, "en"),
|
||||
);
|
||||
|
||||
const sortEdges = <T extends { edge_id: string }>(edges: T[]): T[] =>
|
||||
edges.sort((left, right) => left.edge_id.localeCompare(right.edge_id));
|
||||
|
||||
const buildManifest = ({
|
||||
rootNode,
|
||||
graphSha256,
|
||||
orderedNodes,
|
||||
orderedOccurrences,
|
||||
orderedEdges,
|
||||
}: {
|
||||
readonly rootNode: ArtifactNode;
|
||||
readonly graphSha256: string;
|
||||
readonly orderedNodes: readonly ArtifactNode[];
|
||||
readonly orderedOccurrences: readonly unknown[];
|
||||
readonly orderedEdges: readonly { edge_id: string }[];
|
||||
}): ArtifactInventoryResult["manifest"] =>
|
||||
artifactInventoryResultSchema.shape.manifest.parse({
|
||||
manifest_id: `agm_${canonicalDigest(
|
||||
{
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
graph_sha256: graphSha256,
|
||||
},
|
||||
"Artifact",
|
||||
)}`,
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
root_sha256: rootNode.sha256,
|
||||
root_format: rootNode.format,
|
||||
graph_sha256: graphSha256,
|
||||
node_count: orderedNodes.length,
|
||||
occurrence_count: orderedOccurrences.length,
|
||||
edge_count: orderedEdges.length,
|
||||
});
|
||||
|
||||
const buildLimitations = (
|
||||
rootFormat: ArtifactNode["format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
integrityContradictions: readonly IntegrityContradiction[],
|
||||
): string[] => [
|
||||
...inventoryLimitations(rootFormat, reader),
|
||||
...(integrityContradictions.length === 0
|
||||
? []
|
||||
: [
|
||||
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
|
||||
]),
|
||||
];
|
||||
@@ -0,0 +1,254 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "../ArtifactReader.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
classifyArtifactContent,
|
||||
createArtifactNode,
|
||||
createOccurrence,
|
||||
nearestParent,
|
||||
type MutableOccurrence,
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
import {
|
||||
STRICT_INTEGRITY_POLICY,
|
||||
type ArtifactIntegrityPolicy,
|
||||
} from "./types.js";
|
||||
import { hashReadable } from "../ArtifactHash.js";
|
||||
|
||||
export interface PendingIntegrityContradiction {
|
||||
readonly logicalPath: string;
|
||||
readonly declaredSha256: string;
|
||||
readonly observedSha256: string;
|
||||
readonly entryKind: "file" | "slice";
|
||||
readonly unpacked: boolean;
|
||||
}
|
||||
|
||||
const UNAVAILABLE_UNPACKED_LIMITATION =
|
||||
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.";
|
||||
|
||||
const emptyScan = (): {
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
readonly occurrences: MutableOccurrence[];
|
||||
readonly pendingContradictions: PendingIntegrityContradiction[];
|
||||
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
|
||||
|
||||
interface ScanContext {
|
||||
readonly reader: ArtifactReader;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly integrity: ArtifactIntegrityPolicy;
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
readonly occurrences: MutableOccurrence[];
|
||||
readonly pendingContradictions: PendingIntegrityContradiction[];
|
||||
readonly occurrenceByPath: Map<string, MutableOccurrence>;
|
||||
readonly registry: ArtifactPathRegistry;
|
||||
readonly expandedContainerIds: Set<string>;
|
||||
}
|
||||
|
||||
export const scanReader = async (
|
||||
reader: ArtifactReader | undefined,
|
||||
signal?: AbortSignal,
|
||||
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
|
||||
): Promise<{
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
readonly occurrences: MutableOccurrence[];
|
||||
readonly pendingContradictions: PendingIntegrityContradiction[];
|
||||
}> => {
|
||||
const { nodes, occurrences, pendingContradictions } = emptyScan();
|
||||
if (reader === undefined)
|
||||
return { nodes, occurrences, pendingContradictions };
|
||||
const context: ScanContext = {
|
||||
reader,
|
||||
signal,
|
||||
integrity,
|
||||
nodes,
|
||||
occurrences,
|
||||
pendingContradictions,
|
||||
occurrenceByPath: new Map<string, MutableOccurrence>(),
|
||||
registry: new ArtifactPathRegistry(),
|
||||
expandedContainerIds: new Set<string>(),
|
||||
};
|
||||
await visitArtifactEntries(context, reader, "");
|
||||
// Archive directories may appear after their children. Resolve containment
|
||||
// against the complete index before directory identities are materialized.
|
||||
for (const occurrence of occurrences)
|
||||
occurrence.parent_occurrence_id =
|
||||
nearestParent(
|
||||
occurrence.logical_path,
|
||||
context.occurrenceByPath,
|
||||
context.expandedContainerIds,
|
||||
)?.occurrence_id ?? null;
|
||||
return { nodes, occurrences, pendingContradictions };
|
||||
};
|
||||
|
||||
const visitArtifactEntries = async (
|
||||
context: ScanContext,
|
||||
currentReader: ArtifactReader,
|
||||
prefix: string,
|
||||
): Promise<void> => {
|
||||
const stack: Array<{
|
||||
readonly reader: ArtifactReader;
|
||||
readonly prefix: string;
|
||||
readonly iterator: AsyncIterator<ArtifactEntry>;
|
||||
readonly owned: boolean;
|
||||
}> = [
|
||||
{
|
||||
reader: currentReader,
|
||||
prefix,
|
||||
iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](),
|
||||
owned: false,
|
||||
},
|
||||
];
|
||||
try {
|
||||
while (stack.length > 0) {
|
||||
const frame = stack.at(-1);
|
||||
if (frame === undefined) break;
|
||||
const next = await frame.iterator.next();
|
||||
if (next.done) {
|
||||
stack.pop();
|
||||
if (frame.owned) await frame.reader.close();
|
||||
continue;
|
||||
}
|
||||
const entry = next.value;
|
||||
const logicalPath = normalizeArtifactPath(
|
||||
frame.prefix.length === 0
|
||||
? entry.path
|
||||
: `${frame.prefix}/${entry.path}`,
|
||||
);
|
||||
const expandableAsar = isExpandableAsar(entry, logicalPath);
|
||||
context.registry.add(
|
||||
logicalPath,
|
||||
expandableAsar ? "directory" : entry.kind,
|
||||
);
|
||||
const occurrence = createOccurrence(entry, logicalPath, null);
|
||||
let digested:
|
||||
| { readonly node: ArtifactNode; readonly mismatched: boolean }
|
||||
| undefined;
|
||||
try {
|
||||
digested = await digestArtifactEntry(
|
||||
context,
|
||||
frame.reader,
|
||||
entry,
|
||||
logicalPath,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (!isUnavailableUnpackedEntry(cause, entry)) throw cause;
|
||||
occurrence.hash_status = "unavailable";
|
||||
occurrence.limitations.push(UNAVAILABLE_UNPACKED_LIMITATION);
|
||||
}
|
||||
if (digested !== undefined) {
|
||||
context.nodes.set(digested.node.artifact_id, digested.node);
|
||||
occurrence.artifact_id = digested.node.artifact_id;
|
||||
occurrence.hash_status = digested.mismatched
|
||||
? "mismatched"
|
||||
: "verified";
|
||||
if (digested.mismatched)
|
||||
occurrence.limitations.push(
|
||||
"Declared integrity metadata contradicts observed bytes.",
|
||||
);
|
||||
}
|
||||
context.occurrences.push(occurrence);
|
||||
context.occurrenceByPath.set(logicalPath, occurrence);
|
||||
if (expandableAsar && digested?.mismatched !== true) {
|
||||
const nested = new AsarArtifactReader(entry.adapterKey);
|
||||
// Only traversed containers can own members, not opaque ASAR-named files.
|
||||
context.expandedContainerIds.add(occurrence.occurrence_id);
|
||||
stack.push({
|
||||
reader: nested,
|
||||
prefix: logicalPath,
|
||||
iterator: nested.entries(context.signal)[Symbol.asyncIterator](),
|
||||
owned: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled(
|
||||
stack
|
||||
.filter(({ owned }) => owned)
|
||||
.map(async ({ reader, iterator }) => {
|
||||
await iterator.return?.();
|
||||
await reader.close();
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const digestArtifactEntry = async (
|
||||
context: ScanContext,
|
||||
currentReader: ArtifactReader,
|
||||
entry: ArtifactEntry,
|
||||
logicalPath: string,
|
||||
): Promise<
|
||||
{ readonly node: ArtifactNode; readonly mismatched: boolean } | undefined
|
||||
> => {
|
||||
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
|
||||
return undefined;
|
||||
const digest = await hashReadable(
|
||||
await currentReader.open(entry, context.signal),
|
||||
context.signal,
|
||||
);
|
||||
const mismatched =
|
||||
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
|
||||
if (mismatched && entry.declaredSha256 !== null) {
|
||||
if (context.integrity.mode === "fail")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
|
||||
undefined,
|
||||
{
|
||||
logicalPath,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: digest.sha256,
|
||||
unpacked: entry.unpacked,
|
||||
},
|
||||
);
|
||||
context.pendingContradictions.push({
|
||||
logicalPath,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
observedSha256: digest.sha256,
|
||||
entryKind: entry.kind,
|
||||
unpacked: entry.unpacked,
|
||||
});
|
||||
}
|
||||
const classified =
|
||||
entry.kind === "slice"
|
||||
? ({ kind: "universal-slice", format: "mach-o" } as const)
|
||||
: classifyArtifactContent(logicalPath, digest.prefix, digest.bytes);
|
||||
return {
|
||||
node: createArtifactNode({
|
||||
sha256: digest.sha256,
|
||||
size: digest.bytes,
|
||||
kind: classified.kind,
|
||||
format: classified.format,
|
||||
executable: entry.executable,
|
||||
contentState: "embedded",
|
||||
limitations: mismatched
|
||||
? [
|
||||
"Observed content contradicts declared integrity metadata and is untrusted.",
|
||||
]
|
||||
: [],
|
||||
}),
|
||||
mismatched,
|
||||
};
|
||||
};
|
||||
|
||||
const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
|
||||
entry.kind === "file" &&
|
||||
logicalPath.toLowerCase().endsWith(".asar") &&
|
||||
isAbsolute(entry.adapterKey);
|
||||
|
||||
const isUnavailableUnpackedEntry = (
|
||||
cause: unknown,
|
||||
entry: ArtifactEntry,
|
||||
): boolean =>
|
||||
entry.unpacked &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "unavailable";
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Resolved integrity behavior admitted to the artifact scanner. */
|
||||
export type ArtifactIntegrityPolicy =
|
||||
| { readonly mode: "fail" }
|
||||
| { readonly mode: "record-and-continue" };
|
||||
|
||||
export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
|
||||
mode: "fail",
|
||||
};
|
||||
|
||||
/** Options shared by artifact inventory scans. */
|
||||
export interface ArtifactInventoryOptions {
|
||||
readonly signal?: AbortSignal | undefined;
|
||||
readonly integrity?: ArtifactIntegrityPolicy | undefined;
|
||||
}
|
||||
|
||||
export type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
open,
|
||||
rm,
|
||||
symlink,
|
||||
unlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, it } from "vitest";
|
||||
import { readStableArtifact } from "./readStableArtifact.js";
|
||||
|
||||
const checkChange = async (
|
||||
stage: "before-open" | "after-read" | "symlink-replacement",
|
||||
): Promise<void> => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-read-"));
|
||||
const path = join(root, "selected");
|
||||
await writeFile(path, "original evidence");
|
||||
let inspected = 0;
|
||||
try {
|
||||
const reading = readStableArtifact(path, 1024, undefined, {
|
||||
async lstat(selected) {
|
||||
inspected++;
|
||||
if (stage === "after-read" && inspected === 2) await unlink(selected);
|
||||
const stat = await lstat(selected, { bigint: true });
|
||||
if (inspected === 1 && stage !== "after-read") {
|
||||
await unlink(selected);
|
||||
if (stage === "symlink-replacement")
|
||||
await symlink("missing", selected);
|
||||
}
|
||||
return stat;
|
||||
},
|
||||
open,
|
||||
});
|
||||
await expect(reading).rejects.toMatchObject({ reason: "integrity" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it.each(["before-open", "after-read"] as const)(
|
||||
"retains an actual post-validation %s change as integrity failure",
|
||||
checkChange,
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a post-validation symlink replacement as an integrity failure",
|
||||
() => checkChange("symlink-replacement"),
|
||||
);
|
||||
|
||||
it("keeps initially missing inputs distinguishable from later changes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-missing-"));
|
||||
try {
|
||||
await expect(
|
||||
readStableArtifact(join(root, "missing"), 1024),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,16 +1,50 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { constants, type BigIntStats } from "node:fs";
|
||||
import { lstat, open, type FileHandle } from "node:fs/promises";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
|
||||
export interface StableArtifactFileSystem {
|
||||
lstat(path: string): Promise<BigIntStats>;
|
||||
open(path: string, flags: number): Promise<FileHandle>;
|
||||
}
|
||||
|
||||
const FILE_SYSTEM: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open,
|
||||
};
|
||||
|
||||
const afterValidation = async <T>(
|
||||
path: string,
|
||||
stage: string,
|
||||
read: () => Promise<T>,
|
||||
): Promise<T> => {
|
||||
try {
|
||||
return await read();
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact changed ${stage}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Read one bounded regular file and reject replacement or in-place changes. */
|
||||
export const readStableArtifact = async (
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
signal?: AbortSignal,
|
||||
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
|
||||
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
|
||||
signal?.throwIfAborted();
|
||||
const before = await lstat(path, { bigint: true });
|
||||
const before = await fileSystem.lstat(path);
|
||||
if (!before.isFile() || before.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
@@ -21,9 +55,11 @@ export const readStableArtifact = async (
|
||||
"limit",
|
||||
`Selected artifact exceeds ${String(maximumBytes)} bytes: ${path}`,
|
||||
);
|
||||
const file = await open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
const file = await afterValidation(path, "before open", () =>
|
||||
fileSystem.open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
),
|
||||
);
|
||||
try {
|
||||
const initial = await file.stat({ bigint: true });
|
||||
@@ -59,7 +95,9 @@ export const readStableArtifact = async (
|
||||
chunks.push(bytes);
|
||||
}
|
||||
const after = await file.stat({ bigint: true });
|
||||
const current = await lstat(path, { bigint: true });
|
||||
const current = await afterValidation(path, "during read", () =>
|
||||
fileSystem.lstat(path),
|
||||
);
|
||||
if (
|
||||
[after, current].some(
|
||||
(stat) =>
|
||||
|
||||
Reference in New Issue
Block a user