chore: reconcile iNES inventory with current main

This commit is contained in:
64579525
2026-10-13 09:36:35 +08:00
646 changed files with 49020 additions and 6280 deletions
+9
View File
@@ -6,6 +6,7 @@ import type { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js";
import type { ArtifactReader } from "./ArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { SafeOutputTree } from "./SafeOutputTree.js";
import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
/** One artifact resource and its format-specific cleanup owner. */
export type ArtifactResourceOwner =
@@ -38,6 +39,11 @@ export type ArtifactResourceOwner =
readonly kind: "staged-output";
readonly resource: string;
readonly output: OwnedStagedOutput;
}
| {
readonly kind: "private-runtime-root";
readonly resource: string;
readonly root: Pick<PrivateRuntimeRoot, "path" | "close">;
};
export type ArtifactCleanupAttempt =
@@ -161,5 +167,8 @@ const cleanup = async (owner: ArtifactResourceOwner): Promise<void> => {
return;
case "staged-output":
await owner.output.close();
return;
case "private-runtime-root":
await owner.root.close();
}
};
+2
View File
@@ -625,7 +625,9 @@ const verifyFailureReason = (
processOutput(cause, "stderr"),
);
switch (diagnostic) {
// hdiutil follows AppleLanguages, so en-GB and en-AU spell it "recognised".
case "image not recognized":
case "image not recognised":
return "format";
case "invalid checksum":
case "image data corrupted":
+23 -1
View File
@@ -1,4 +1,4 @@
import type { Stats } from "node:fs";
import type { BigIntStats, Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { afterEach, expect, it, vi } from "vitest";
@@ -6,6 +6,7 @@ import {
NonRegularFileReadError,
openRegularFile,
RegularFileAdmissionFailure,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
const { mockOpen } = vi.hoisted(() => ({ mockOpen: vi.fn() }));
@@ -66,3 +67,24 @@ it.each(["cancellation after open", "non-regular metadata", "stat failure"])(
else expect(cause.cause).toBe(cancellation);
},
);
it("compares available nanosecond timestamps without rounding away source changes", () => {
const before = {
dev: 1n,
ino: 2n,
size: 3n,
mode: 0o100400n,
mtimeMs: 10n,
ctimeMs: 20n,
mtimeNs: 10_000_001n,
ctimeNs: 20_000_001n,
isFile: () => true,
} as BigIntStats;
expect(sameRegularFileState(before, { ...before })).toBe(true);
expect(
sameRegularFileState(before, { ...before, mtimeNs: before.mtimeNs + 1n }),
).toBe(false);
expect(
sameRegularFileState(before, { ...before, ctimeNs: before.ctimeNs + 1n }),
).toBe(false);
});
+191
View File
@@ -0,0 +1,191 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { ZipArtifactReader } from "./ZipArtifactReader.js";
import {
ARTIFACT_DECOMPRESSION_RATIO,
artifactDecompressionBudgetBytes,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
} from "../domain/artifactDecompressionBudget.js";
/** Small real ZIP carriers with forged sizes; metadata-only controls, never decompressed. */
const writeZipWithDeclaredSize = async (
directory: string,
declaredBytes: readonly number[],
): Promise<string> => {
const path = join(directory, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [index] of declaredBytes.entries())
await writer.add(
`member-${index}.bin`,
new TextReader("real member bytes"),
);
await writeFile(path, await writer.close());
const bytes = await readFile(path);
let offset = 0;
for (const declared of declaredBytes) {
const centralDirectory = bytes.indexOf(
Buffer.from([0x50, 0x4b, 0x01, 0x02]),
offset,
);
if (centralDirectory < 0)
throw new Error("Expected a ZIP central directory");
// Metadata-only controls: these declarations do not describe valid member streams.
bytes.writeUInt32LE(declared, centralDirectory + 24);
offset = centralDirectory + 46;
}
await writeFile(path, bytes);
return path;
};
const enumerate = async (reader: ZipArtifactReader): Promise<number> => {
let files = 0;
for await (const entry of reader.entries())
if (entry.kind === "file") files += 1;
return files;
};
describe("ZipArtifactReader decompression budget", () => {
it("refuses an archive whose entries declare more than its size can justify", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-bomb-");
// A ~160-byte archive cannot declare 2 GiB of members without being a bomb.
const path = await writeZipWithDeclaredSize(directory, [2_147_483_647]);
const reader = new ZipArtifactReader(path, "zip");
try {
await expect(enumerate(reader)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "limit",
});
} finally {
await reader.close();
}
});
it("charges all declarations in one traversal before yielding an over-budget member", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-total-");
const half = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2;
const path = await writeZipWithDeclaredSize(directory, [half, half + 1]);
const reader = new ZipArtifactReader(path, "zip");
const iterator = reader.entries()[Symbol.asyncIterator]();
try {
expect((await iterator.next()).value?.declaredSize).toBe(half);
await expect(iterator.next()).rejects.toMatchObject({ reason: "limit" });
} finally {
await iterator.return?.();
await reader.close();
}
});
it("keeps repeated and interleaved metadata traversals independently charged", async () => {
const directory = await createTestTempDirectory(
"rea-zip-budget-iterators-",
);
const path = await writeZipWithDeclaredSize(directory, [
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES / 2,
]);
const reader = new ZipArtifactReader(path, "zip");
const first = reader.entries()[Symbol.asyncIterator]();
const second = reader.entries()[Symbol.asyncIterator]();
try {
expect((await first.next()).done).toBe(false);
expect((await second.next()).done).toBe(false);
expect((await first.next()).done).toBe(false);
expect((await second.next()).done).toBe(false);
expect((await first.next()).done).toBe(true);
expect((await second.next()).done).toBe(true);
expect(await enumerate(reader)).toBe(2);
} finally {
await Promise.all([first.return?.(), second.return?.()]);
await reader.close();
}
});
it("streams a valid small member through open", async () => {
const directory = await createTestTempDirectory("rea-zip-budget-valid-");
const path = join(directory, "valid.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("member.bin", new TextReader("valid member bytes"));
await writeFile(path, await writer.close());
const reader = new ZipArtifactReader(path, "zip");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries[0];
if (entry === undefined) throw new Error("Expected a ZIP member");
const chunks: Buffer[] = [];
for await (const chunk of await reader.open(entry))
chunks.push(Buffer.from(chunk));
expect(Buffer.concat(chunks).toString()).toBe("valid member bytes");
} finally {
await reader.close();
}
});
it("rejects under-declared member output before delivering its complete actual bytes", async () => {
const directory = await createTestTempDirectory("rea-zip-underdeclared-");
const path = join(directory, "underdeclared.zip");
const content = new Uint8Array(128 * 1024);
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("member.bin", new Uint8ArrayReader(content), {
dataDescriptor: false,
bufferedWrite: true,
});
const bytes = Buffer.from(await writer.close());
const local = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
if (local < 0 || central < 0) throw new Error("Expected ZIP entry headers");
// Both headers agree and no descriptor remains: rejection must enforce
// actual decompressed output, not merely detect conflicting metadata.
expect(bytes.readUInt16LE(local + 6) & 8).toBe(0);
expect(bytes.readUInt16LE(local + 8)).toBe(8);
expect(bytes.readUInt32LE(local + 22)).toBe(content.length);
expect(bytes.readUInt32LE(central + 24)).toBe(content.length);
bytes.writeUInt32LE(1, local + 22);
bytes.writeUInt32LE(1, central + 24);
await writeFile(path, bytes);
const reader = new ZipArtifactReader(path, "zip");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries[0];
if (entry === undefined) throw new Error("Expected a ZIP member");
expect(entry.declaredSize).toBe(1);
let deliveredBytes = 0;
await expect(
(async () => {
for await (const chunk of await reader.open(entry))
deliveredBytes += Buffer.from(chunk).length;
})(),
).rejects.toThrow("Invalid uncompressed size");
expect(deliveredBytes).toBeLessThan(content.length);
} finally {
await reader.close();
}
});
});
describe("artifactDecompressionBudgetBytes", () => {
it("grants at least the floor and grows with the compressed size", () => {
expect(artifactDecompressionBudgetBytes(0)).toBe(
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
);
expect(artifactDecompressionBudgetBytes(1024)).toBe(
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
);
const large = MINIMUM_ARTIFACT_DECOMPRESSION_BYTES * 4;
expect(artifactDecompressionBudgetBytes(large)).toBe(
large * ARTIFACT_DECOMPRESSION_RATIO,
);
});
});
+23 -1
View File
@@ -12,6 +12,11 @@ import {
type ArtifactReader,
} from "./ArtifactReader.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import {
ARTIFACT_DECOMPRESSION_RATIO,
artifactDecompressionBudgetBytes,
MINIMUM_ARTIFACT_DECOMPRESSION_BYTES,
} from "../domain/artifactDecompressionBudget.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
NonRegularFileReadError,
@@ -132,7 +137,6 @@ export class ZipArtifactReader implements ArtifactReader {
string,
{ readonly source: Entry; readonly metadata: ArtifactEntry }
>();
/** Optionally bound each metadata read before allocating its backing buffer. */
constructor(
path: string,
@@ -153,6 +157,8 @@ export class ZipArtifactReader implements ArtifactReader {
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
let index = 0;
// A traversal owns its accounting, including overlapping or repeated passes.
let declaredFileBytes = 0;
for await (const entry of this.#reader.getEntriesGenerator({
decodeText: decodeZipEntryText,
})) {
@@ -160,6 +166,22 @@ export class ZipArtifactReader implements ArtifactReader {
// ZIP member identity is its directory occurrence, not its filename.
// Logical path uniqueness belongs to the artifact inventory boundary.
const metadata = projectZipEntry(entry, index++);
// zip.js enforces each member's declared output size, so this sum bounds streamed work.
if (
metadata.kind === "file" &&
!metadata.encrypted &&
metadata.declaredSize !== null &&
Number.isSafeInteger(metadata.declaredSize) &&
metadata.declaredSize >= 0
) {
declaredFileBytes += metadata.declaredSize;
const budget = artifactDecompressionBudgetBytes(this.#source.size);
if (declaredFileBytes > budget)
throw new ArtifactReaderFailure(
"limit",
`ZIP entries declare ${String(declaredFileBytes)} uncompressed bytes, exceeding this archive's ${String(budget)}-byte decompression budget (${String(MINIMUM_ARTIFACT_DECOMPRESSION_BYTES)}-byte minimum, ${String(ARTIFACT_DECOMPRESSION_RATIO)}x archive size); a small archive cannot expand this far`,
);
}
const stored = this.#entries.get(metadata.adapterKey);
if (stored !== undefined && !sameArtifactEntry(metadata, stored.metadata))
throw new ArtifactReaderFailure(
@@ -1,9 +1,11 @@
import { createHash } from "node:crypto";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { encodeNibArchiveFixture } from "./NibArchive.fixture.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import {
analyzeAppleAssetCatalogs,
@@ -22,6 +24,13 @@ describe("Apple asset catalog application workflow", () => {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
nibValues: {
title: "not-an-asset-key",
imageName: { value: "not-a-scalar" },
image: 42,
assetName: "",
nested: { NSImageName: "not-a-direct-field" },
},
},
evidence: [
{
@@ -34,8 +43,13 @@ describe("Apple asset catalog application workflow", () => {
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
attributes: { title: "not-an-asset-key" },
evidence: [],
attributes: { NSImageName: "Toolbar", imageName: "Toolbar" },
evidence: [
{
artifact_path: "Contents/Resources/Main.nib",
artifact_sha256: "d".repeat(64),
},
],
},
]),
).toEqual([
@@ -118,3 +132,77 @@ describe("Apple asset catalog application workflow", () => {
);
});
});
it.each([1, 2])(
"joins NIBArchive keys against %i supplied assetutil renditions",
async (count) => {
const bundle = await createTestTempDirectory("rea-asset-nib-join-");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const archive = encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { image: { ref: 2 } } },
{ classIndex: 2, values: { NSImageName: { ref: 3 } } },
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
],
});
await writeFile(join(resources, "Panel.nib"), archive);
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
// Supplied metadata tests the post-engine join; it does not establish native catalog validity.
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () =>
Promise.resolve(
JSON.stringify(
Array.from({ length: count }, (_, index) => ({
Name: "Toolbar",
RenditionName: `toolbar-${String(index)}.png`,
})),
),
),
});
expect(result.resource_key_matches).toHaveLength(1);
expect(result.resource_key_matches[0]).toMatchObject({
field: "NSImageName",
key: "Toolbar",
status: count === 1 ? "matched" : "ambiguous",
source_path: "Contents/Resources/Panel.nib",
source_archive_sha256: createHash("sha256").update(archive).digest("hex"),
renditions: Array.from({ length: count }, (_, index) =>
expect.objectContaining({
record_index: index,
rendition_name: `toolbar-${String(index)}.png`,
}),
),
});
},
);
it("keeps recognized image fields on NIBArchive controls out of resource joins", async () => {
const bundle = await createTestTempDirectory("rea-asset-nib-control-");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await writeFile(
join(resources, "Panel.nib"),
encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSButton", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { NSImageName: { ref: 2 } } },
{ classIndex: 2, values: { "NS.bytes": "Toolbar" } },
],
}),
);
await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () => Promise.resolve(JSON.stringify([{ Name: "Toolbar" }])),
});
expect(result.resource_key_matches).toEqual([]);
});
@@ -8,6 +8,7 @@ import {
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
appleResourceKeyFields,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../../domain/apple/appleAssetCatalog.js";
@@ -16,17 +17,6 @@ import { execFileOutput } from "../../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
@@ -201,27 +191,22 @@ export const collectInterfaceBuilderResourceKeys = (
}[],
) =>
nodes.flatMap((node) => {
if (node.kind !== "resource") return [];
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return Object.entries(node.attributes).flatMap(([field, value]) =>
RESOURCE_KEY_FIELDS.has(field) &&
typeof value === "string" &&
value.length > 0
? [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]
: [],
);
return appleResourceKeyFields(node.attributes).flatMap(([field, value]) => [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]);
});
const runAssetUtil = async (
+36 -18
View File
@@ -1,6 +1,11 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
import {
interfaceBuilderConnectionFieldNames,
isUIKitRuntimeConnectionClass,
} from "../../domain/apple/interfaceBuilderKeyedArchive.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
@@ -28,6 +33,10 @@ import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import {
hasBinaryPlistSignature,
hasNibArchiveSignature,
} from "../../domain/apple/appleArchiveFormat.js";
const MAX_AGGREGATE_INPUT_BYTES = 32 * 1024 * 1024;
const MAX_AGGREGATE_DECODE_BYTES = 256 * 1024 * 1024;
@@ -89,8 +98,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
remainingInputBytes,
);
aggregateInputBytes += bytes.length;
const isNibArchive =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive";
const isNibArchive = hasNibArchiveSignature(bytes);
let nib: ReturnType<typeof projectNibArchive> | null = null;
let xmlText: string | undefined;
let binaryPrototypeKeyObserved = false;
@@ -108,7 +116,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
"NIBArchive representation exceeds the aggregate Interface Builder decode budget",
);
} else {
if (bytes.subarray(0, 8).toString("ascii") !== "bplist00")
if (!hasBinaryPlistSignature(bytes))
xmlText = decodeXmlPlistText(bytes);
const decodedReservation = preflightPropertyListDecode(
bytes,
@@ -437,8 +445,10 @@ const projectNibArchive = (
archive.objects
.filter((object) => {
const name = runtimeClass(object.id) ?? "";
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
name,
return (
!/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector)$/u.test(
name,
) && !isUIKitRuntimeConnectionClass(name)
);
})
.map((object) => {
@@ -459,18 +469,27 @@ const projectNibArchive = (
break;
}
budget.reserveJsonStringOccurrence(name);
const nibValues = Object.fromEntries(
Object.entries(object.values).map(([key, value]) => {
budget.reserveJsonPropertyNameOccurrence(key);
return [key, dereference(value) ?? null];
}),
);
// Normalize only recognized scalar fields at the format owner. A keyed
// archive's authored nibValues dictionary must not gain this meaning.
const resourceFields = appleResourceKeyFields(nibValues);
for (const [field, value] of resourceFields) {
budget.reserveJsonPropertyNameOccurrence(field);
budget.reserveJsonStringOccurrence(value);
}
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
nibValues: Object.fromEntries(
Object.entries(object.values).map(([key, value]) => {
budget.reserveJsonPropertyNameOccurrence(key);
return [key, dereference(value) ?? null];
}),
),
nibValues,
...Object.fromEntries(resourceFields),
},
];
}),
@@ -488,15 +507,14 @@ const projectNibArchive = (
const className = normalizeClassName(object.class_name);
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
// event connections use UI-prefixed keys with the same roles.
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
const uiKit = isUIKitRuntimeConnectionClass(className);
if (!uiKit && !className.includes("Connector")) continue;
const values = object.values;
const source = reference(uiKit ? values.UISource : values.NSSource);
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = reference(values[connectionFields.source]);
if (source === null) continue;
const destination = reference(
uiKit ? values.UIDestination : values.NSDestination,
);
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
const destination = reference(values[connectionFields.destination]);
const label = referencedString(values[connectionFields.label]);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control") || className.includes("Event")
@@ -650,7 +668,7 @@ const decodePlist = (
readonly value: JsonValue;
readonly omittedPrototypeKeys: number | null;
} => {
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const binary = hasBinaryPlistSignature(bytes);
const { value, omittedPrototypeKeys } = binary
? {
value: parseBinary(bytes),
@@ -1,4 +1,5 @@
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
/** Reason reported when an archive would exceed the shared decoding budget. */
export type InterfaceBuilderBudgetReason = "aggregate_decode_budget_exhausted";
@@ -94,13 +95,12 @@ export const preflightPropertyListDecode = (
maxBytes: number,
xmlText?: string,
): PlistDecodePreflight => {
const expansion =
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? estimateBinaryPlistExpansion(bytes, maxBytes)
: {
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
binaryPrototypeKeyObserved: false,
};
const expansion = hasBinaryPlistSignature(bytes)
? estimateBinaryPlistExpansion(bytes, maxBytes)
: {
estimatedBytes: estimateXmlPlistExpansion(bytes, maxBytes, xmlText),
binaryPrototypeKeyObserved: false,
};
if (expansion.estimatedBytes > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
@@ -170,8 +170,8 @@ export interface BinaryPlistExpansionOptions {
readonly fail?: (kind: BinaryPlistExpansionFailure, message: string) => Error;
/**
* Structural bounds: "strict" keeps objects and the offset table before the
* trailer; "decoder" admits exactly what plist.parseBinary can read, so
* expansion is bounded without rejecting archives that decoder accepts.
* trailer; "decoder" follows the decoder's object-table boundary policy
* while still rejecting structures whose coercion would lose plist facts.
*/
readonly bounds?: "strict" | "decoder";
}
@@ -267,6 +267,8 @@ export const estimateBinaryPlistExpansion = (
throw new TypeError("binary plist object offset is invalid");
const marker = bytes[offset] ?? 0;
const type = marker >> 4;
if (entry.dictionaryKey && type !== 5 && type !== 6)
throw new TypeError("binary plist dictionary key is not a string");
let size = marker & 0x0f;
let cursor = offset + 1;
if (size === 0x0f && type !== 0 && type !== 8) {
+113 -1
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { build, buildBinary } from "plist";
import { build, buildBinary, type PlistValue } from "plist";
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
import { deeplyNestedXmlPlist } from "../../../tests/fixtures/keyedArchiveXmlNesting.js";
const archive = {
$archiver: "NSKeyedArchiver",
@@ -22,6 +23,23 @@ const archive = {
$top: { root: { UID: 1 }, other: { UID: 2 } },
};
describe("inert keyed archive decoding", () => {
it.each(["bplist00", "NIBArchive"])(
"rejects high-bit mutations of %s as malformed bytes rather than another archive kind",
(signature) => {
for (let index = 0; index < signature.length; index += 1) {
const bytes = Buffer.from(signature);
bytes[index] = (bytes[index] ?? 0) | 0x80;
expect(() =>
decodeKeyedArchiveBytes(bytes, { offset: 0, limit: 1 }),
).toThrow(
expect.objectContaining({
code: "ERR_ENCODING_INVALID_ENCODED_DATA",
}),
);
}
},
);
it("preserves CF$UID, malformed references and original pagination identities", () => {
const bytes = Buffer.from(
build({
@@ -201,6 +219,37 @@ const keyedRoot = (payload: readonly Buffer[]): Buffer =>
describe("binary plist reference preflight", () => {
const selection = { offset: 0, limit: 10 };
it("rejects an array key that coerces to __proto__ before parsing", () => {
expect(() =>
decodeKeyedArchiveBytes(
keyedRoot([
plistArray([9]),
Buffer.from([0xd1, 0, 10, 0, 11]),
plistArray([12]),
Buffer.from([0xd1, 0, 13, 0, 14]),
plistString("__proto__"),
plistString("lost"),
plistString("value"),
]),
selection,
),
).toThrow("binary plist dictionary key is not a string");
});
it("rejects binary data dictionary keys", () => {
expect(() =>
decodeKeyedArchiveBytes(
keyedRoot([
plistArray([9]),
Buffer.from([0xd1, 0, 10, 0, 11]),
Buffer.from([0x41, 0xab]),
plistString("value"),
]),
selection,
),
).toThrow("binary plist dictionary key is not a string");
});
it("reports a reference cycle as malformed, not as an oversized archive", () => {
expect(() =>
decodeKeyedArchiveBytes(keyedRoot([plistArray([8])]), selection),
@@ -323,3 +372,66 @@ describe("binary plist reference preflight", () => {
);
});
});
describe("XML plist nesting preflight", () => {
const selection = { offset: 0, limit: 1 };
/** A valid XML NSKeyedArchiver envelope whose object 1 nests `depth` dictionaries. */
const deeplyNestedArchive = (depth: number) => {
let payload: PlistValue = "leaf";
for (let level = 0; level < depth; level += 1) payload = { k: payload };
return Buffer.from(
build({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: ["$null", payload],
$top: { root: { UID: 1 } },
}),
);
};
/** Follow the single-member chain of a decoded object to its deepest value. */
const deepestValue = (value: unknown): unknown => {
let cursor = value;
while (
cursor !== null &&
typeof cursor === "object" &&
!Array.isArray(cursor) &&
"k" in cursor
) {
cursor = (cursor as Record<string, unknown>).k;
}
return cursor;
};
it.each([129, 4000])(
"rejects %i-level XML nesting as the documented resource limit",
(depth) => {
// Recursive decoding exceeds the call stack before the projection limit
// can report it, so the decoder must reject the nesting up front with
// the same bounded-resource error an in-reach document would produce.
expect(() =>
decodeKeyedArchiveBytes(
Buffer.from(deeplyNestedXmlPlist(depth)),
selection,
),
).toThrow(new RangeError("Plist exceeds 128 nesting levels"));
},
);
it("decodes a valid XML keyed archive exactly at the nesting limit", () => {
const graph = decodeKeyedArchiveBytes(deeplyNestedArchive(126), {
root: "root",
offset: 1,
limit: 1,
});
expect(graph.objects).toHaveLength(1);
expect(deepestValue(graph.objects[0]?.value)).toBe("leaf");
});
it("rejects one nesting level past the limit before decoding", () => {
expect(() =>
decodeKeyedArchiveBytes(deeplyNestedArchive(127), selection),
).toThrow(new RangeError("Plist exceeds 128 nesting levels"));
});
});
+6 -2
View File
@@ -27,6 +27,10 @@ import { ArtifactReaderFailure } from "../ArtifactReader.js";
import type { ArtifactEntry } from "../ArtifactReader.js";
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import {
hasBinaryPlistSignature,
hasNibArchiveSignature,
} from "../../domain/apple/appleArchiveFormat.js";
import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";
const MAX_BYTES = 64 * 1024 * 1024;
@@ -40,12 +44,12 @@ export const decodeKeyedArchiveBytes = (
) => {
if (bytes.length > MAX_BYTES)
throw new RangeError("Keyed archive exceeds 64 MiB");
if (bytes.subarray(0, 10).toString("ascii") === "NIBArchive")
if (hasNibArchiveSignature(bytes))
throw new KeyedArchiveKindError(
"Selected file is a compiled NIBArchive, not a Foundation plist archive; decode it with decode_interface_builder",
"nib-archive",
);
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const binary = hasBinaryPlistSignature(bytes);
const xmlText = binary ? undefined : decodeXmlPlistText(bytes);
// plist.parseBinary recurses on every object reference and copies shared
// containers, so a few hundred bytes can exhaust memory or the stack.
@@ -21,6 +21,7 @@ export const CPU = {
i386: { type: 7, subtype: 3 },
arm64: { type: 0x0100000c, subtype: 0 },
arm64e: { type: 0x0100000c, subtype: 0x80000002 },
arm64eX1: { type: 0x0100000c, subtype: 0x8000000c },
x86_64: { type: 0x01000007, subtype: 3 },
} as const;
@@ -26,6 +26,7 @@ import {
} from "./MachoLoadCommandReader.js";
import { traceDylibResolution } from "./DylibResolutionReader.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javaClassFile } from "../../../tests/fixtures/javaClassFile.js";
const read = (bytes: Uint8Array) =>
readMachoImage(readerOf(bytes), bytes.length);
@@ -135,6 +136,98 @@ it("uses legacy simulator and device platform facts when resolving dylibs", asyn
);
});
it("selects matching arm64e subtype slices when tracing a mixed FAT image", async () => {
const root = await createTestTempDirectory("rea-macho-arm64e-subtypes-");
const executablePath = "Contents/MacOS/App";
const dylibPath = "Contents/MacOS/libVariant.dylib";
const installName = "@executable_path/libVariant.dylib";
const arm64eDependency = "@executable_path/libArm64e.dylib";
const arm64eX1Dependency = "@executable_path/libArm64eX1.dylib";
const executableSlice = (cpu: typeof CPU.arm64e | typeof CPU.arm64eX1) =>
machoImage({
cpu,
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, installName),
],
});
const executable = fatImage([
{
cpu: CPU.arm64eX1,
bytes: executableSlice(CPU.arm64eX1),
},
{
cpu: CPU.arm64e,
bytes: executableSlice(CPU.arm64e),
},
]);
const variantSlice = (
cpu: typeof CPU.arm64e | typeof CPU.arm64eX1,
dependencyName: string,
) =>
machoImage({
cpu,
fileType: FILE_TYPE.dylib,
commands: [
buildVersionCommand(1),
dylibCommand(LC.ID_DYLIB, installName),
dylibCommand(LC.LOAD_DYLIB, dependencyName),
],
});
const completeDylib = fatImage([
{
cpu: CPU.arm64e,
bytes: variantSlice(CPU.arm64e, arm64eDependency),
},
{
cpu: CPU.arm64eX1,
bytes: variantSlice(CPU.arm64eX1, arm64eX1Dependency),
},
]);
await mkdir(join(root, "Contents/MacOS"), { recursive: true });
await writeFile(join(root, executablePath), executable);
await writeFile(join(root, dylibPath), completeDylib);
const trace = () =>
traceDylibResolution({
rootPath: root,
targetPath: join(root, executablePath),
targetSha256: createHash("sha256").update(executable).digest("hex"),
enumerateRoots: false,
parameters: { roots: [executablePath] },
});
const complete = await trace();
expect(
complete.edges
.filter(({ loader }) => loader === dylibPath)
.map(({ install_name: dependencyName }) => dependencyName),
).toEqual([arm64eX1Dependency, arm64eDependency]);
const onlyArm64e = fatImage([
{
cpu: CPU.arm64e,
bytes: variantSlice(CPU.arm64e, arm64eDependency),
},
]);
await writeFile(join(root, dylibPath), onlyArm64e);
const missingVariant = await trace();
expect(
missingVariant.edges
.filter(
({ loader, install_name: dependencyName }) =>
loader === executablePath && dependencyName === installName,
)
.map(({ candidates, resolution }) => [
candidates[0]?.outcome,
resolution.status,
]),
).toEqual([
["architecture-missing", "unresolved"],
["resolved", "resolved"],
]);
});
describe("Mach-O load command reader: decodes thin-image load commands", () => {
it("decodes dylib loading commands of a thin image", async () => {
const image = machoImage({
@@ -345,10 +438,13 @@ describe("Mach-O load command reader inputs", () => {
expect(i386.status === "parsed" && i386.slices[0]?.architecture).toBe(
"i386",
);
// A Java class file shares the FAT magic; its version is not a slice count.
const javaClass = Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
// A Java class file shares the FAT magic; version fields are not a slice count.
const javaClasses = [javaClassFile(), javaClassFile(4000)];
expect(javaClasses.map(({ length }) => length)).toEqual([57, 4060]);
for (const javaClass of javaClasses) {
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
}
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
status: "not-mach-o",
});
@@ -489,6 +585,16 @@ describe("Mach-O load command reader failures", () => {
reason: "FAT architecture 0 slice range extends beyond the file",
});
});
it("preserves unsupported status for an unsupported FAT alignment exponent", async () => {
const fat = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
new DataView(fat.buffer).setUint32(24, 53, false);
expect(await read(fat)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("alignment exponent 53 is unsupported"),
});
});
});
it.each([true, false])(
+38 -80
View File
@@ -3,9 +3,11 @@ import type {
MachoImageFacts,
MachoSlice,
} from "../../domain/apple/dylibResolution.js";
import { machoCpuSubtypeBase } from "../../domain/apple/machoCpuIdentity.js";
import {
readFatSliceDeclarations,
validateFatSlice,
classifyFatContainerIdentity,
readFatContainerHeader,
validateFatSliceIdentity,
type FatSliceDeclaration,
} from "../../domain/apple/machoContainer.js";
@@ -14,13 +16,6 @@ export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
/** Load commands larger than this are refused instead of buffered. */
export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
const MAX_FAT_ARCHITECTURES = 128;
/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
const KNOWN_CPU_TYPES: readonly number[] = [
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
];
const MH_MAGIC = 0xfeedface;
const MH_MAGIC_64 = 0xfeedfacf;
const MH_CIGAM = 0xcefaedfe;
@@ -146,69 +141,41 @@ export const readMachoImage = async (
: { status: "not-mach-o" };
const view = viewOf(head);
const magic = view.getUint32(0, false);
if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
// FAT headers are big-endian; the swapped magics store them little-endian.
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
const count = view.getUint32(4, littleEndian);
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
// A Java class file's nonzero major version reads as the count, so an
// empty architecture table can only be a malformed universal header.
if (count === 0)
return {
status: "malformed",
reason: "FAT header declares no architectures",
};
if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
return { status: "not-mach-o" };
const tableBytes = await readExact(
readAt,
8,
count * (wide ? 32 : 20),
"FAT table",
);
const declarations = readFatSliceDeclarations(tableBytes, {
count,
wide,
littleEndian,
});
if (declarations.status !== "parsed")
throw new MachoFormatIssue("malformed", declarations.reason);
// A Java class file's version fields read as a FAT count; its "table" names no CPU.
if (
!declarations.slices.some(({ cpuType }) =>
KNOWN_CPU_TYPES.includes(cpuType),
)
) {
let hasMachOSliceHeader = false;
for (const declaration of declarations.slices) {
if (
validateFatSlice(
declaration,
size,
8 + count * (wide ? 32 : 20),
) !== null
)
continue;
const bytes = await readAt(declaration.offset, 4);
if (bytes.byteLength < 4) continue;
const sliceMagic = viewOf(bytes).getUint32(0, false);
if (
[MH_MAGIC, MH_MAGIC_64, MH_CIGAM, MH_CIGAM_64].includes(sliceMagic)
) {
hasMachOSliceHeader = true;
break;
}
}
if (!hasMachOSliceHeader) return { status: "not-mach-o" };
let header = readFatContainerHeader(head, size);
if (header.state !== "not-fat") {
if (header.state === "needs-data") {
header = readFatContainerHeader(
await readAt(0, header.requiredBytes),
size,
);
}
if (header.state === "not-fat") return { status: "not-mach-o" };
if (header.state === "needs-data")
throw new MachoFormatIssue("malformed", "FAT table is truncated");
if (header.state === "malformed")
throw new MachoFormatIssue("malformed", header.reason);
let identity = classifyFatContainerIdentity(header, () => undefined);
if (identity.state === "needs-slice-header") {
const sliceHeaders = new Map<number, number | null>();
for (const offset of identity.offsets) {
const bytes = await readAt(offset, 4);
sliceHeaders.set(
offset,
bytes.byteLength < 4 ? null : viewOf(bytes).getUint32(0, false),
);
}
identity = classifyFatContainerIdentity(header, (offset) =>
sliceHeaders.get(offset),
);
}
if (identity.state === "not-mach-o") return { status: "not-mach-o" };
if (identity.state === "malformed")
throw new MachoFormatIssue(identity.category, identity.reason);
if (identity.state === "needs-slice-header")
return { status: "not-mach-o" };
return {
status: "parsed",
slices: await readFatSlices(
readAt,
size,
8 + count * (wide ? 32 : 20),
declarations.slices,
),
slices: await readFatSlices(readAt, header.slices),
};
}
if (magic === MH_CIGAM || magic === MH_CIGAM_64)
@@ -228,25 +195,17 @@ export const readMachoImage = async (
const readFatSlices = async (
readAt: ReadAt,
size: number,
tableEnd: number,
declarations: readonly FatSliceDeclaration[],
): Promise<MachoSlice[]> => {
const slices: MachoSlice[] = [];
for (const declaration of declarations) {
const { offset, size: length, cpuType, cpuSubtype } = declaration;
const rangeIssue = validateFatSlice(declaration, size, tableEnd);
if (rangeIssue !== null)
throw new MachoFormatIssue(
rangeIssue.includes("unsupported") ? "unsupported" : "malformed",
rangeIssue,
);
const slice = await readSlice(readAt, offset, length, {
fatCpuType: cpuType,
fatCpuSubtype: cpuSubtype,
alignmentExponent: declaration.alignmentExponent,
});
const identityIssue = validateFatSlice(declaration, size, tableEnd, {
const identityIssue = validateFatSliceIdentity(declaration, {
cpuType: slice.cpu_type,
cpuSubtype: slice.cpu_subtype,
});
@@ -524,13 +483,12 @@ const CPU_ARCH_ABI64 = 0x01000000;
const CPU_ARCH_ABI64_32 = 0x02000000;
const CPU_TYPE_X86 = 7;
const CPU_TYPE_ARM = 12;
const CPU_SUBTYPE_MASK = 0xff000000;
const CPU_SUBTYPE_ARM64E = 2;
const CPU_SUBTYPE_ARM64E_X1 = 12;
const CPU_SUBTYPE_X86_64_H = 8;
const architectureName = (cpuType: number, cpuSubtype: number): string => {
const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
const subtype = machoCpuSubtypeBase(cpuSubtype);
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
// Both pointer-authentication subtypes belong to the arm64e family.
return subtype === CPU_SUBTYPE_ARM64E || subtype === CPU_SUBTYPE_ARM64E_X1
+2 -2
View File
@@ -1,11 +1,11 @@
import type { JsonValue } from "../../domain/jsonValue.js";
import { hasNibArchiveSignature } from "../../domain/apple/appleArchiveFormat.js";
import { TextDecoder } from "node:util";
import {
InterfaceBuilderDecodeBudget,
InterfaceBuilderDecodeBudgetExceeded,
} from "./InterfaceBuilderDecodeBudget.js";
const MAGIC = Buffer.from("NIBArchive", "ascii");
const DEFAULT_DECODE_BUDGET_BYTES = 128 * 1024 * 1024;
interface NibObjectRecord {
@@ -39,7 +39,7 @@ export const decodeNibArchive = (
bytes: Buffer,
budget = new InterfaceBuilderDecodeBudget(DEFAULT_DECODE_BUDGET_BYTES),
): NibArchiveDocument => {
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
if (bytes.length < 50 || !hasNibArchiveSignature(bytes))
throw new TypeError("NIBArchive magic or header is invalid");
const formatVersion = readU32(bytes, 10);
+2 -4
View File
@@ -1,5 +1,6 @@
import type { PlistNumberLiterals } from "../../domain/apple/plistNumbers.js";
import { decodeXmlText } from "../../domain/propertyListKeys.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
const collector = () => {
const integers = new Map<number, Set<string>>();
@@ -124,10 +125,7 @@ export const binaryPlistNumberLiterals = (
bytes: Buffer,
): PlistNumberLiterals => {
const output = collector();
if (
bytes.length < 40 ||
bytes.subarray(0, 8).toString("ascii") !== "bplist00"
)
if (bytes.length < 40 || !hasBinaryPlistSignature(bytes))
return output.result(true);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const trailer = bytes.length - 32;
@@ -1,5 +1,6 @@
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
import {
artifactEdgeId,
artifactIdForContent,
@@ -18,7 +19,14 @@ import {
zipPackageFormatForPath,
type ZipPackageFormat,
} from "../../domain/zipPackageFormat.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
import {
observeMzWindowsHeader,
parseDosMzHeader,
} from "../../domain/dosMz.js";
import {
classifyFatContainerIdentity,
readFatContainerHeader,
} from "../../domain/apple/machoContainer.js";
import {
nesContainerFormat,
parseInesLayout,
@@ -445,11 +453,11 @@ export const classifyArtifactBytes = (
)
return "ines";
if (hasZipSignature(prefix)) return "zip";
if (prefix.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist";
if (hasBinaryPlistSignature(prefix)) return "plist";
const fatFormat = classifyFatArtifact(prefix, fileSize);
if (fatFormat !== null) return fatFormat;
if (prefix.length >= 4) {
const magic = prefix.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return "mach-o";
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
@@ -462,22 +470,40 @@ export const classifyArtifactBytes = (
prefix.length < Math.min(fileSize, 64)
)
return "unknown";
const windowsOffset = mzWindowsHeaderOffset(prefix);
if (windowsOffset !== null) {
const windowsHeader = observeMzWindowsHeader(prefix, fileSize);
if (windowsHeader.state === "signature-needed") return "unknown";
if (windowsHeader.state === "declared") {
const windowsOffset = windowsHeader.offset;
if (
windowsHeader.signature === "PE" &&
windowsOffset >= 64 &&
windowsOffset <= prefix.length - 4 &&
prefix
.subarray(windowsOffset, windowsOffset + 4)
.equals(Buffer.from([0x50, 0x45, 0, 0]))
windowsOffset <= prefix.length - 4
)
return "pe";
} else if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
return "unknown";
}
if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
return "unknown";
}
return "file";
};
const classifyFatArtifact = (
prefix: Buffer,
fileSize: number,
): ArtifactNode["format"] | null => {
const fatHeader = readFatContainerHeader(prefix, fileSize);
if (fatHeader.state === "needs-data" || fatHeader.state === "malformed")
return "unknown";
if (fatHeader.state === "not-fat") return null;
const identity = classifyFatContainerIdentity(fatHeader, (offset) => {
if (offset >= prefix.length) return undefined;
if (offset + 4 > prefix.length) return null;
return prefix.readUInt32BE(offset);
});
return identity.state === "mach-o" ? "mach-o-universal" : "unknown";
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
const lower = path.toLowerCase();
if (lower.endsWith(".map")) return "maps-source";
+4 -4
View File
@@ -1,8 +1,8 @@
import { realpath } from "node:fs/promises";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
artifactInventoryOutputSchema,
type ArtifactInventoryOutput,
} from "../../domain/artifactGraph.js";
import { abortIfNeeded } from "../ArtifactHash.js";
import { scanCanonicalArtifactInventoryInScope } from "./scanCanonical.js";
@@ -13,9 +13,9 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySn
export const inventoryArtifact = async (
inputPath: string,
options: ArtifactInventoryOptions,
): Promise<ArtifactInventoryResult> => {
): Promise<ArtifactInventoryOutput> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
return artifactInventoryOutputSchema.parse(snapshot);
};
/** Scan an artifact once and retain the complete immutable graph for projection. */
+41 -15
View File
@@ -6,7 +6,11 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import type {
ArtifactInventoryCoverage,
ArtifactOccurrence,
IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import {
isZipPackageFormat,
ZIP_NON_ENTRY_TAIL_LIMITATION,
@@ -45,21 +49,43 @@ export const createReader = (
}
};
export const inventoryLimitations = (
/** Classify source coverage and preserve its user-facing explanation once. */
export const inventoryAssessment = (
format: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
): string[] => {
if (format === "ines") return [INES_LIMITATION];
if (reader !== undefined)
return isZipPackageFormat(reader.format)
? [ZIP_NON_ENTRY_TAIL_LIMITATION]
: [];
// dmg and pkg reach here only after classifyRootFormat matched their bytes.
if (format === "dmg" || format === "pkg")
return [
integrityContradictions: readonly IntegrityContradiction[],
caseCollisionLimitation: string | undefined,
): {
readonly coverage_status: ArtifactInventoryCoverage;
readonly limitations: string[];
} => {
let coverageStatus: ArtifactInventoryCoverage = "complete";
const limitations: string[] = [];
if (format === "ines") limitations.push(INES_LIMITATION);
if (reader !== undefined) {
if (isZipPackageFormat(reader.format))
limitations.push(ZIP_NON_ENTRY_TAIL_LIMITATION);
} else if (format === "dmg" || format === "pkg") {
coverageStatus = "partial";
limitations.push(
`${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."];
);
} else if (format === "mach-o-universal" && process.platform !== "darwin") {
coverageStatus = "partial";
limitations.push(
"Universal Mach-O slices require the native macOS lipo adapter.",
);
} else {
// The graph's modeled scope is the root itself for recognized leaf formats.
limitations.push("Artifact has no child container entries.");
}
if (caseCollisionLimitation !== undefined) {
coverageStatus = "partial";
limitations.push(caseCollisionLimitation);
}
if (integrityContradictions.length > 0)
limitations.push(
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
);
return { coverage_status: coverageStatus, limitations };
};
+9 -22
View File
@@ -41,7 +41,7 @@ import {
hashStableRootArtifact,
hashStableRootArtifactHandle,
} from "./hashStableRootArtifact.js";
import { createReader, inventoryLimitations } from "./reader.js";
import { createReader, inventoryAssessment } from "./reader.js";
import {
scanReader,
type PendingIntegrityContradiction,
@@ -269,6 +269,12 @@ const buildInventorySnapshot = async (
orderedOccurrences,
orderedEdges,
});
const assessment = inventoryAssessment(
rootFormat,
reader,
integrityContradictions,
input.caseCollisionLimitation,
);
return {
manifest,
...(reader instanceof InesArtifactReader && rootDigest !== null
@@ -279,12 +285,8 @@ const buildInventorySnapshot = async (
edges: orderedEdges,
provenance: reader?.provenance() ?? [],
integrity_contradictions: integrityContradictions,
limitations: buildLimitations(
rootFormat,
reader,
integrityContradictions,
input.caseCollisionLimitation,
),
coverage_status: assessment.coverage_status,
limitations: assessment.limitations,
};
};
@@ -397,18 +399,3 @@ const buildManifest = ({
occurrence_count: orderedOccurrences.length,
edge_count: orderedEdges.length,
});
const buildLimitations = (
rootFormat: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
integrityContradictions: readonly IntegrityContradiction[],
caseCollisionLimitation: string | undefined,
): string[] => [
...inventoryLimitations(rootFormat, reader),
...(caseCollisionLimitation === undefined ? [] : [caseCollisionLimitation]),
...(integrityContradictions.length === 0
? []
: [
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
]),
];
+22 -1
View File
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import { constants, type BigIntStats } from "node:fs";
import { lstat, open, type FileHandle } from "node:fs/promises";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
export interface StableArtifactFileSystem {
@@ -42,6 +44,7 @@ export const readStableArtifact = async (
maximumBytes: number,
signal?: AbortSignal,
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
resourceScope?: ArtifactResourceScope,
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
signal?.throwIfAborted();
const before = await fileSystem.lstat(path);
@@ -61,6 +64,9 @@ export const readStableArtifact = async (
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
),
);
const owner =
resourceScope === undefined ? undefined : new OwnedFileHandle(file);
let failure: unknown;
try {
const initial = await file.stat({ bigint: true });
if (
@@ -116,7 +122,22 @@ export const readStableArtifact = async (
);
const bytes = Buffer.concat(chunks, count);
return { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
} catch (cause: unknown) {
failure = cause;
throw cause;
} finally {
await file.close();
if (owner === undefined || resourceScope === undefined) await file.close();
else {
const cleanup = await resourceScope.release({
kind: "file-handle",
resource: path,
handle: owner,
});
if (cleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
failure ?? cleanup.cause,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, path),
);
}
}
};