fix(artifacts): share bounded ASAR signature observations

Parse Pickle extents once at the ASAR boundary and carry finalized signature
facts through root and nested classification. Scan JSON whitespace within its
declared extent and decode budget without retaining the whitespace prefix.
Keep prefix storage bounded independently of stream chunk ownership.

Fill fixed ASAR prefixes and DMG trailers across short reads, preserve
cancellation through admission and stream EOF, and retain existing cleanup
ownership. Cover public CLI/MCP selection, root/nested inventory, malformed
JSON whitespace and padding, limits, native/XML consumers and descriptor faults.

Validation: 24 focused files / 170 tests; full check; docs check; test discovery.
Official inert ASAR fixtures and controlled descriptor faults were exercised;
real Electron execution, Windows and natural OS short-read frequency remain
unverified. Equivalent compact CLI tasks returned identical results and reply
token estimates; repeated timings do not establish a speedup.

Fixes #3574
Fixes #5188
This commit is contained in:
morluto committed 2026-10-19 14:32:48 +08:00
1 parent 2e5171e391
commit e8da7e1edd
22 files changed
+1129 -166

No files matched your search

@@ -0,0 +1,89 @@
import {
createAsarHeaderSignatureProbe,
type FinalAsarHeaderProbeObservation,
} from "./AsarHeader.js";
import {
createXmlPlistSignatureProbe,
MAX_XML_PLIST_PROBE_BYTES,
} from "../domain/apple/appleArchiveFormat.js";
/** Initial bytes required by the other bounded format classifiers. */
export const ARTIFACT_CLASSIFICATION_PREFIX_BYTES = 8_192;
/** Retained bytes and independently parsed ASAR signature facts. */
export interface ArtifactClassificationEvidence {
readonly prefix: Buffer;
readonly asarHeader: FinalAsarHeaderProbeObservation;
}
/** Share acquisition bounds and signature observations across files and streams. */
export const createArtifactClassificationProbe = () => {
const xml = createXmlPlistSignatureProbe();
const asar = createAsarHeaderSignatureProbe();
const blocks: Buffer[] = [];
let retainedBytes = 0;
let observedBytes = 0;
const retain = (bytes: Uint8Array): void => {
let offset = 0;
while (offset < bytes.length) {
const blockOffset = retainedBytes % ARTIFACT_CLASSIFICATION_PREFIX_BYTES;
if (blockOffset === 0)
blocks.push(Buffer.allocUnsafe(ARTIFACT_CLASSIFICATION_PREFIX_BYTES));
const count = Math.min(
ARTIFACT_CLASSIFICATION_PREFIX_BYTES - blockOffset,
bytes.length - offset,
);
blocks[blocks.length - 1]!.set(
bytes.subarray(offset, offset + count),
blockOffset,
);
retainedBytes += count;
offset += count;
}
};
return {
get length(): number {
return observedBytes;
},
get limit(): number {
if (observedBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES)
return ARTIFACT_CLASSIFICATION_PREFIX_BYTES;
return Math.max(
ARTIFACT_CLASSIFICATION_PREFIX_BYTES,
xml.state === "pending" ? MAX_XML_PLIST_PROBE_BYTES : 0,
asar.observation.state === "pending" ? asar.limit : 0,
);
},
write(bytes: Uint8Array): void {
asar.write(bytes);
let offset = 0;
while (offset < bytes.length) {
const limit =
retainedBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES
? ARTIFACT_CLASSIFICATION_PREFIX_BYTES
: xml.state === "pending"
? MAX_XML_PLIST_PROBE_BYTES
: retainedBytes;
if (retainedBytes >= limit) break;
const selected = bytes.subarray(
offset,
offset + Math.min(limit - retainedBytes, bytes.length - offset),
);
retain(selected);
xml.write(selected);
offset += selected.length;
}
observedBytes += bytes.length;
},
finish(archiveBytes: number): ArtifactClassificationEvidence {
const prefix = Buffer.allocUnsafe(retainedBytes);
let copied = 0;
for (const block of blocks) {
const count = Math.min(block.length, retainedBytes - copied);
prefix.set(block.subarray(0, count), copied);
copied += count;
}
return { prefix, asarHeader: asar.finish(archiveBytes) };
},
};
};
+20
View File
@@ -0,0 +1,20 @@
import { Readable } from "node:stream";
import { expect, it } from "vitest";
import { hashReadable } from "./ArtifactHash.js";
it("preserves cancellation arriving with the final stream result", async () => {
const controller = new AbortController();
const reason = { stage: "source-eof" };
const source = Readable.from(
(async function* () {
yield Buffer.from("complete bytes");
controller.abort(reason);
})(),
);
await expect(hashReadable(source, controller.signal)).rejects.toMatchObject({
reason: "cancelled",
cause: reason,
});
});
+7 -32
View File
@@ -4,20 +4,16 @@ import type { Readable } from "node:stream";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { streamChunkToBuffer } from "./StreamBytes.js";
import {
createXmlPlistSignatureProbe,
MAX_XML_PLIST_PROBE_BYTES,
} from "../domain/apple/appleArchiveFormat.js";
createArtifactClassificationProbe,
type ArtifactClassificationEvidence,
} from "./ArtifactClassificationProbe.js";
/** Full stream digest and byte count with bounded classification evidence. */
export type HashResult = {
export type HashResult = ArtifactClassificationEvidence & {
readonly sha256: string;
readonly bytes: number;
readonly prefix: Buffer;
};
/** Bounded classification evidence; this is not an executable format size limit. */
export const ARTIFACT_CLASSIFICATION_PREFIX_BYTES = 8_192;
/** Preserve the inventory cancellation reason at a stream boundary. */
export const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
@@ -34,36 +30,15 @@ export const hashReadable = async (
signal?: AbortSignal,
): Promise<HashResult> => {
const hash = createHash("sha256");
const prefixes: Buffer[] = [];
let prefixBytes = 0;
const xmlProbe = createXmlPlistSignatureProbe();
const probe = createArtifactClassificationProbe();
let bytes = 0;
for await (const raw of stream) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
hash.update(chunk);
let chunkOffset = 0;
while (
chunkOffset < chunk.length &&
(prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES ||
(xmlProbe.state === "pending" &&
prefixBytes < MAX_XML_PLIST_PROBE_BYTES))
) {
const limit =
prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES
? ARTIFACT_CLASSIFICATION_PREFIX_BYTES
: MAX_XML_PLIST_PROBE_BYTES;
const selected = chunk.subarray(
chunkOffset,
Math.min(chunkOffset + limit - prefixBytes, chunk.length),
);
prefixes.push(selected);
prefixBytes += selected.length;
chunkOffset += selected.length;
xmlProbe.write(selected);
}
probe.write(chunk);
}
abortIfNeeded(signal);
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };
return { sha256: hash.digest("hex"), bytes, ...probe.finish(bytes) };
};
+6 -3
View File
@@ -63,7 +63,7 @@ export class AsarArtifactReader implements ArtifactReader {
const snapshotPath = this.#snapshotPath();
this.#resetArchiveState();
this.#entries.clear();
const admitted = await this.#admitHeader(snapshotPath);
const admitted = await this.#admitHeader(snapshotPath, signal);
this.#archiveSize = admitted.archiveBytes;
this.#headerSize = admitted.headerBytes;
abortIfNeeded(signal);
@@ -122,7 +122,7 @@ export class AsarArtifactReader implements ArtifactReader {
}
}
async #admitHeader(snapshotPath: string) {
async #admitHeader(snapshotPath: string, signal?: AbortSignal) {
const headerHandle = await this.#openOwned(
snapshotPath,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
@@ -134,7 +134,10 @@ export class AsarArtifactReader implements ArtifactReader {
}
| { readonly ok: false; readonly cause: unknown };
try {
admission = { ok: true, value: await admitAsarHeader(headerHandle) };
admission = {
ok: true,
value: await admitAsarHeader(headerHandle, signal),
};
} catch (cause: unknown) {
admission = { ok: false, cause };
}
+80
View File
@@ -0,0 +1,80 @@
import type { Stats } from "node:fs";
import { expect, it, vi } from "vitest";
import {
admitAsarHeader,
createAsarHeaderSignatureProbe,
} from "./AsarHeader.js";
import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js";
const makeArchive = (): Buffer => asarHeaderBytes(' \t\r\n{"files":{}} ');
it("fills the fixed Pickle prefix across controlled short reads", async () => {
const archive = makeArchive();
const calls: Array<readonly [number, number, number]> = [];
const handle = {
stat: vi.fn(
async () =>
({
isFile: () => true,
size: archive.length,
}) as Stats,
),
read: vi.fn(
async (
target: Buffer,
offset: number,
length: number,
position: number,
) => {
calls.push([offset, length, position]);
const bytesRead = Math.min(3, length, archive.length - position);
archive.copy(target, offset, position, position + bytesRead);
return { bytesRead, buffer: target };
},
),
} as unknown as Parameters<typeof admitAsarHeader>[0];
await expect(admitAsarHeader(handle)).resolves.toEqual({
archiveBytes: archive.length,
headerBytes: archive.readUInt32LE(4),
jsonBytes: archive.readUInt32LE(12),
});
expect(calls).toEqual([
[0, 16, 0],
[3, 13, 3],
[6, 10, 6],
[9, 7, 9],
[12, 4, 12],
[15, 1, 15],
]);
});
it("recognizes JSON whitespace before the object token and finalizes file extents", () => {
const archive = makeArchive();
const probe = createAsarHeaderSignatureProbe();
probe.write(archive.subarray(0, 7));
expect(probe.observation.state).toBe("pending");
probe.write(archive.subarray(7, 21));
expect(probe.observation.state).toBe("matched");
const result = probe.finish(archive.length);
expect(result).toMatchObject({
state: "matched",
extents: {
archiveBytes: archive.length,
headerBytes: archive.readUInt32LE(4),
jsonBytes: archive.readUInt32LE(12),
},
signatureOffset: 20,
});
});
it("rejects a signature whose declared header exceeds the observed archive", () => {
const archive = makeArchive();
const probe = createAsarHeaderSignatureProbe();
probe.write(archive);
expect(probe.finish(archive.length - 1)).toMatchObject({
state: "rejected",
reason: "archive-too-short",
});
});
+335 -25
View File
@@ -1,49 +1,359 @@
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { err, ok, type Result } from "../domain/result.js";
/** Shared resource budget for the eagerly decoded ASAR header, not member bytes. */
export const MAX_ASAR_HEADER_BYTES = 16 * 1024 * 1024;
/** Admit both Chromium pickle extents before an upstream decoder allocates them. */
export const admitAsarHeader = async (
handle: Pick<FileHandle, "read"> & { stat(): Promise<Stats> },
): Promise<{
/** Absolute archive prefix required to inspect an admitted header. */
export const MAX_ASAR_HEADER_PROBE_BYTES = MAX_ASAR_HEADER_BYTES + 8;
export interface AsarHeaderExtents {
readonly archiveBytes: number;
readonly headerBytes: number;
readonly jsonBytes: number;
}> => {
}
export type AsarHeaderProbeExtents = Pick<
AsarHeaderExtents,
"headerBytes" | "jsonBytes"
> & { readonly archiveBytes?: number };
export type AsarHeaderProbeObservation =
| {
readonly state: "pending";
readonly extents?: AsarHeaderProbeExtents;
readonly scannedJsonBytes: number;
}
| {
/** The declared JSON begins with an object token; this does not validate JSON. */
readonly state: "matched";
readonly extents: AsarHeaderProbeExtents;
readonly signatureOffset: number;
readonly scannedJsonBytes: number;
}
| {
readonly state: "rejected";
readonly reason:
| "invalid-pickle-extents"
| "archive-too-short"
| "json-not-object";
readonly extents?: AsarHeaderProbeExtents;
readonly scannedJsonBytes: number;
}
| {
readonly state: "limit";
readonly extents?: AsarHeaderProbeExtents;
readonly scannedJsonBytes: number;
readonly limitBytes: number;
};
export type FinalAsarHeaderProbeObservation = Exclude<
AsarHeaderProbeObservation,
{ readonly state: "pending" }
>;
/**
* Parse the fixed two-Pickle prefix and optionally check it against the actual
* observed archive size. This establishes byte extents only; JSON validity and
* the ASAR header schema belong to the decoder at the interpretation boundary.
*/
export const parseAsarHeaderExtents = (
prefix: Uint8Array,
archiveBytes?: number,
): Result<Omit<AsarHeaderExtents, "archiveBytes">, ArtifactReaderFailure> => {
if (prefix.byteLength < 16)
return err(
new ArtifactReaderFailure(
"format",
"Truncated ASAR Pickle extent prefix",
),
);
const bytes = Buffer.from(prefix.buffer, prefix.byteOffset, 16);
const headerBytes = bytes.readUInt32LE(4);
const payloadBytes = bytes.readUInt32LE(8);
const jsonBytes = bytes.readUInt32LE(12);
if (
bytes.readUInt32LE(0) !== 4 ||
headerBytes < 8 ||
payloadBytes !== headerBytes - 4 ||
jsonBytes > payloadBytes - 4
)
return err(
new ArtifactReaderFailure(
"format",
"ASAR header has invalid Pickle extents",
),
);
if (
archiveBytes !== undefined &&
(!Number.isSafeInteger(archiveBytes) ||
archiveBytes < 8 ||
headerBytes > archiveBytes - 8)
)
return err(
new ArtifactReaderFailure(
"format",
"ASAR header leaves its observed container",
),
);
return ok({ headerBytes, jsonBytes });
};
/**
* Bounded ASAR signature probe. It retains only the 16-byte fixed prefix and
* scans the declared JSON bytes until the first non-JSON-whitespace byte.
*/
export interface AsarHeaderSignatureProbe {
readonly limit: number;
readonly observation: AsarHeaderProbeObservation;
write(input: Uint8Array): AsarHeaderProbeObservation;
finish(archiveBytes: number): FinalAsarHeaderProbeObservation;
}
class AsarHeaderSignatureProbeImpl implements AsarHeaderSignatureProbe {
readonly limit = MAX_ASAR_HEADER_PROBE_BYTES;
readonly #fixed = Buffer.alloc(16);
#fixedBytes = 0;
#scannedJsonBytes = 0;
#extents: Omit<AsarHeaderExtents, "archiveBytes"> | undefined;
#stop: ProbeStop = { state: "pending" };
get observation(): AsarHeaderProbeObservation {
return this.#observation();
}
/** Consume sequential archive bytes without retaining JSON or member data. */
write(input: Uint8Array): AsarHeaderProbeObservation {
if (this.#stop.state === "finalized") return this.#stop.observation;
const bytes = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
let offset = 0;
while (offset < bytes.length && !this.#isTerminal()) {
if (this.#fixedBytes < this.#fixed.length) {
const count = Math.min(
this.#fixed.length - this.#fixedBytes,
bytes.length - offset,
);
bytes.copy(this.#fixed, this.#fixedBytes, offset, offset + count);
this.#fixedBytes += count;
offset += count;
if (this.#fixedBytes === this.#fixed.length) this.#parseFixed();
continue;
}
const extents = this.#extents;
if (extents === undefined || this.#stop.state === "matched") break;
const jsonRemaining = extents.jsonBytes - this.#scannedJsonBytes;
if (jsonRemaining <= 0) {
this.#stop = { state: "rejected", reason: "json-not-object" };
break;
}
const archiveBytesScanned = 16 + this.#scannedJsonBytes;
if (archiveBytesScanned >= this.limit) {
this.#stop = { state: "limit" };
break;
}
const count = Math.min(
bytes.length - offset,
jsonRemaining,
this.limit - archiveBytesScanned,
);
for (let index = 0; index < count; index += 1) {
const value = bytes[offset + index]!;
if (!isJsonWhitespace(value)) {
if (value === 0x7b)
this.#stop = {
state: "matched",
signatureOffset: 16 + this.#scannedJsonBytes,
extents,
};
else this.#stop = { state: "rejected", reason: "json-not-object" };
break;
}
this.#scannedJsonBytes += 1;
}
offset += count;
if (this.#stop.state !== "pending") break;
if (this.#scannedJsonBytes >= extents.jsonBytes) {
this.#stop = { state: "rejected", reason: "json-not-object" };
break;
}
if (16 + this.#scannedJsonBytes >= this.limit)
this.#stop = { state: "limit" };
}
return this.#observation();
}
/** Finalize against the actual byte count; a signature alone is not validity. */
finish(archiveBytes: number): FinalAsarHeaderProbeObservation {
if (this.#stop.state === "finalized") return this.#stop.observation;
if (this.#fixedBytes < this.#fixed.length) {
this.#stop = { state: "rejected", reason: "invalid-pickle-extents" };
} else if (this.#extents !== undefined) {
if (
!Number.isSafeInteger(archiveBytes) ||
archiveBytes < 8 ||
this.#extents.headerBytes > archiveBytes - 8
) {
this.#stop = { state: "rejected", reason: "archive-too-short" };
} else if (
this.#extents.headerBytes > MAX_ASAR_HEADER_BYTES &&
this.#stop.state === "matched"
) {
this.#stop = { state: "limit" };
}
}
const observation = this.#observation(archiveBytes);
this.#stop = { state: "finalized", observation };
return observation;
}
#parseFixed(): void {
const result = parseAsarHeaderExtents(this.#fixed);
if (!result.ok) {
this.#stop = { state: "rejected", reason: "invalid-pickle-extents" };
return;
}
this.#extents = result.value;
if (this.#extents.jsonBytes === 0)
this.#stop = { state: "rejected", reason: "json-not-object" };
}
#isTerminal(): boolean {
return this.#stop.state !== "pending";
}
#observation(): AsarHeaderProbeObservation;
#observation(archiveBytes: number): FinalAsarHeaderProbeObservation;
#observation(
archiveBytes?: number,
): AsarHeaderProbeObservation | FinalAsarHeaderProbeObservation {
if (this.#stop.state === "finalized") return this.#stop.observation;
const extents: AsarHeaderProbeExtents | undefined =
this.#extents === undefined
? undefined
: archiveBytes === undefined
? this.#extents
: { archiveBytes, ...this.#extents };
switch (this.#stop.state) {
case "rejected":
return {
state: "rejected",
reason: this.#stop.reason,
...(extents === undefined ? {} : { extents }),
scannedJsonBytes: this.#scannedJsonBytes,
};
case "limit":
return {
state: "limit",
...(extents === undefined ? {} : { extents }),
scannedJsonBytes: this.#scannedJsonBytes,
limitBytes: this.limit,
};
case "matched":
return {
state: "matched",
extents:
archiveBytes === undefined
? this.#stop.extents
: { archiveBytes, ...this.#stop.extents },
signatureOffset: this.#stop.signatureOffset,
scannedJsonBytes: this.#scannedJsonBytes,
};
case "pending":
if (archiveBytes !== undefined && this.#extents !== undefined) {
const finalizedExtents = {
archiveBytes,
...this.#extents,
};
if (this.#scannedJsonBytes >= this.#extents.jsonBytes)
return {
state: "rejected",
reason: "json-not-object",
extents: finalizedExtents,
scannedJsonBytes: this.#scannedJsonBytes,
};
return {
state: "limit",
extents: finalizedExtents,
scannedJsonBytes: this.#scannedJsonBytes,
limitBytes: this.limit,
};
}
return {
state: "pending",
...(extents === undefined ? {} : { extents }),
scannedJsonBytes: this.#scannedJsonBytes,
};
}
}
}
type ProbeStop =
| { readonly state: "pending" }
| {
readonly state: "matched";
readonly signatureOffset: number;
readonly extents: Omit<AsarHeaderExtents, "archiveBytes">;
}
| {
readonly state: "rejected";
readonly reason:
| "invalid-pickle-extents"
| "archive-too-short"
| "json-not-object";
}
| { readonly state: "limit" }
| {
readonly state: "finalized";
readonly observation: FinalAsarHeaderProbeObservation;
};
const isJsonWhitespace = (value: number): boolean =>
value === 0x20 || value === 0x09 || value === 0x0a || value === 0x0d;
/** Admit Pickle extents before an upstream decoder allocates them. */
export const admitAsarHeader = async (
handle: Pick<FileHandle, "read"> & { stat(): Promise<Stats> },
signal?: AbortSignal,
): Promise<AsarHeaderExtents> => {
assertArtifactReadActive(signal);
const observed = await handle.stat();
assertArtifactReadActive(signal);
if (!observed.isFile())
throw new ArtifactReaderFailure(
"format",
"ASAR container is not a regular file",
);
const prefix = Buffer.alloc(16);
const read = await handle.read(prefix, 0, prefix.length, 0);
if (read.bytesRead !== prefix.length || prefix.readUInt32LE(0) !== 4)
throw new ArtifactReaderFailure(
"format",
"Truncated or invalid ASAR size pickle",
let bytesRead = 0;
while (bytesRead < prefix.length) {
assertArtifactReadActive(signal);
const read = await handle.read(
prefix,
bytesRead,
prefix.length - bytesRead,
bytesRead,
);
const headerBytes = prefix.readUInt32LE(4);
const payloadBytes = prefix.readUInt32LE(8);
const jsonBytes = prefix.readUInt32LE(12);
if (
headerBytes < 8 ||
headerBytes > observed.size - 8 ||
payloadBytes !== headerBytes - 4 ||
jsonBytes > payloadBytes - 4
)
throw new ArtifactReaderFailure(
"format",
"ASAR header leaves its container or has invalid pickle extents",
);
if (headerBytes > MAX_ASAR_HEADER_BYTES)
assertArtifactReadActive(signal);
if (read.bytesRead === 0)
throw new ArtifactReaderFailure("format", "Truncated ASAR size pickle");
bytesRead += read.bytesRead;
}
const parsed = parseAsarHeaderExtents(prefix, observed.size);
if (!parsed.ok) throw parsed.error;
if (parsed.value.headerBytes > MAX_ASAR_HEADER_BYTES)
throw new ArtifactReaderFailure(
"limit",
`ASAR header exceeds the ${String(MAX_ASAR_HEADER_BYTES)} byte decode budget`,
);
return { archiveBytes: observed.size, headerBytes, jsonBytes };
return {
archiveBytes: observed.size,
...parsed.value,
};
};
export const createAsarHeaderSignatureProbe = (): AsarHeaderSignatureProbe =>
new AsarHeaderSignatureProbeImpl();
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import { CPU, fatImage, machoImage } from "../apple/MachoImage.fixture.js";
import {
classifyArtifactContent,
createArtifactEdges,
createOccurrence,
indexOccurrencesByPath,
@@ -11,6 +10,8 @@ import {
import { artifactIdForContent } from "../../domain/artifactIdentity.js";
import type { ArtifactEntry } from "../ArtifactReader.js";
import { classifyArtifactBytesAtPath } from "../../../tests/fixtures/artifactClassification.js";
const entry = (path: string, kind: ArtifactEntry["kind"]): ArtifactEntry => ({
path,
kind,
@@ -168,7 +169,7 @@ describe("bounded FAT inventory classification", () => {
const bytes = fat();
for (const length of [4, 7, 8, 27]) {
expect(
classifyArtifactContent(
classifyArtifactBytesAtPath(
"native",
bytes.subarray(0, length),
bytes.length,
@@ -176,7 +177,7 @@ describe("bounded FAT inventory classification", () => {
).toEqual({ kind: "unknown", format: "unknown" });
}
expect(
classifyArtifactContent(
classifyArtifactBytesAtPath(
"native.class",
bytes.subarray(0, 28),
bytes.length,
@@ -197,7 +198,7 @@ describe("bounded FAT inventory classification", () => {
] as const)("keeps %s unknown", (_label, mutate) => {
const bytes = fat();
mutate(bytes);
expect(classifyArtifactContent("native", bytes)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
@@ -206,7 +207,7 @@ describe("bounded FAT inventory classification", () => {
it("does not infer Mach-O from an out-of-bounds architecture count", () => {
const bytes = fat();
bytes.writeUInt32BE(0xffffffff, 4);
expect(classifyArtifactContent("native", bytes)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes)).toEqual({
kind: "resource",
format: "file",
});
@@ -215,7 +216,7 @@ describe("bounded FAT inventory classification", () => {
it("does not lose unsafe FAT64 range values to number conversion", () => {
const bytes = fat(true);
bytes.writeBigUInt64BE(BigInt(Number.MAX_SAFE_INTEGER) + 1n, 16);
expect(classifyArtifactContent("native", bytes)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
@@ -229,7 +230,7 @@ describe("bounded FAT inventory classification", () => {
]),
);
bytes.writeUInt32BE(bytes.length, 40);
expect(classifyArtifactContent("native", bytes)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
@@ -239,9 +240,13 @@ describe("bounded FAT inventory classification", () => {
const cpu = { type: 0x12345678, subtype: 0 };
const bytes = Buffer.from(fatImage([{ cpu, bytes: machoImage({ cpu }) }]));
expect(
classifyArtifactContent("native", bytes.subarray(0, 28), bytes.length),
classifyArtifactBytesAtPath(
"native",
bytes.subarray(0, 28),
bytes.length,
),
).toEqual({ kind: "unknown", format: "unknown" });
expect(classifyArtifactContent("native", bytes)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes)).toEqual({
kind: "executable",
format: "mach-o-universal",
});
@@ -251,7 +256,7 @@ describe("bounded FAT inventory classification", () => {
"keeps invalid or contradictory file size %s unknown",
(size) => {
const bytes = fat();
expect(classifyArtifactContent("native", bytes, size)).toEqual({
expect(classifyArtifactBytesAtPath("native", bytes, size)).toEqual({
kind: "unknown",
format: "unknown",
});
@@ -263,19 +268,19 @@ it("preserves path-selected inventory roles for XML content", () => {
const xml = Buffer.from(
'<?xml version="1.0"?><plist version="1.0"><dict/></plist>',
);
expect(classifyArtifactContent("state.archive", xml)).toEqual({
expect(classifyArtifactBytesAtPath("state.archive", xml)).toEqual({
kind: "plist",
format: "plist",
});
expect(classifyArtifactContent("state.js", xml)).toEqual({
expect(classifyArtifactBytesAtPath("state.js", xml)).toEqual({
kind: "javascript",
format: "javascript-bundle",
});
expect(classifyArtifactContent("state.map", xml)).toEqual({
expect(classifyArtifactBytesAtPath("state.map", xml)).toEqual({
kind: "source-map",
format: "source-map",
});
expect(classifyArtifactContent("state.asar", xml)).toEqual({
expect(classifyArtifactBytesAtPath("state.asar", xml)).toEqual({
kind: "resource",
format: "file",
});
@@ -1,3 +1,5 @@
import type { ArtifactClassificationEvidence } from "../ArtifactClassificationProbe.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { isJavaScriptSourcePath } from "../../domain/javascript/javascriptArtifactFiles.js";
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
@@ -473,12 +475,13 @@ export const classifyArtifactPath = (
/** Classify executable formats from bytes while retaining path-specific roles. */
export const classifyArtifactContent = (
path: string,
prefix: Buffer,
fileSize = prefix.length,
evidence: ArtifactClassificationEvidence,
fileSize = evidence.prefix.length,
): {
readonly kind: ArtifactOccurrence["artifact_kind"];
readonly format: ArtifactOccurrence["artifact_format"];
} => {
const { prefix, asarHeader } = evidence;
const format = classifyArtifactBytes(prefix, fileSize);
const byPath = classifyArtifactPath(path);
if (
@@ -491,27 +494,19 @@ export const classifyArtifactContent = (
if (
format === "file" &&
path.toLowerCase().endsWith(".asar") &&
hasAsarHeader(prefix)
)
return { kind: "container", format: "asar" };
asarHeader.state !== "rejected"
) {
if (asarHeader.state === "limit")
throw new ArtifactReaderFailure(
"limit",
"ASAR header exceeds the bounded classification or decode budget",
);
if (asarHeader.state === "matched")
return { kind: "container", format: "asar" };
}
return artifactRoleForFormat(path, format);
};
/**
* Electron ASAR starts with a size pickle whose payload is one uint32, then
* a header pickle whose payload begins with a JSON object.
*/
export const hasAsarHeader = (prefix: Buffer): boolean => {
if (prefix.length < 17 || prefix.readUInt32LE(0) !== 4) return false;
const headerSize = prefix.readUInt32LE(4);
const payloadSize = prefix.readUInt32LE(8);
if (headerSize < 16 || payloadSize !== headerSize - 4) return false;
const stringLength = prefix.readUInt32LE(12);
return (
stringLength >= 2 && stringLength <= payloadSize - 4 && prefix[16] === 0x7b
);
};
const artifactRoleForFormat = (
path: string,
format: ArtifactOccurrence["artifact_format"],
+46 -42
View File
@@ -5,14 +5,8 @@ import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.j
import type { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js";
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
import {
abortIfNeeded,
ARTIFACT_CLASSIFICATION_PREFIX_BYTES,
} from "../ArtifactHash.js";
import {
createXmlPlistSignatureProbe,
MAX_XML_PLIST_PROBE_BYTES,
} from "../../domain/apple/appleArchiveFormat.js";
import { abortIfNeeded } from "../ArtifactHash.js";
import { createArtifactClassificationProbe } from "../ArtifactClassificationProbe.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import {
hasZipSignature,
@@ -143,41 +137,36 @@ const classifyRootFormat = async (
handle: FileHandle,
signal?: AbortSignal,
): Promise<ArtifactOccurrence["artifact_format"]> => {
const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES);
const observed = await handle.read(magic, 0, magic.length, 0);
let prefix = magic.subarray(0, observed.bytesRead);
const lower = path.toLowerCase();
if (hasZipSignature(prefix)) return zipRootPackageFormat(lower);
if (
lower.endsWith(".pkg") &&
prefix.subarray(0, 4).equals(Buffer.from("xar!"))
)
return "pkg";
if (lower.endsWith(".dmg") && (await hasKolyTrailer(handle))) return "dmg";
const xmlProbe = createXmlPlistSignatureProbe();
xmlProbe.write(prefix);
const chunks = [prefix];
let prefixBytes = prefix.length;
while (
xmlProbe.state === "pending" &&
prefixBytes < MAX_XML_PLIST_PROBE_BYTES
) {
const probe = createArtifactClassificationProbe();
const chunk = Buffer.alloc(64 * 1024);
while (probe.length < probe.limit) {
abortIfNeeded(signal);
const chunk = Buffer.alloc(
Math.min(64 * 1024, MAX_XML_PLIST_PROBE_BYTES - prefixBytes),
const read = await handle.read(
chunk,
0,
Math.min(chunk.length, probe.limit - probe.length),
probe.length,
);
const read = await handle.read(chunk, 0, chunk.length, prefixBytes);
abortIfNeeded(signal);
if (read.bytesRead === 0) break;
const selected = chunk.subarray(0, read.bytesRead);
chunks.push(selected);
prefixBytes += selected.length;
xmlProbe.write(selected);
probe.write(chunk.subarray(0, read.bytesRead));
}
prefix = Buffer.concat(chunks);
// ASAR is chosen from its header pickle; any other suffix is a role hint.
return classifyArtifactContent(path, prefix, (await handle.stat()).size)
.format;
const archiveBytes = (await handle.stat()).size;
const evidence = probe.finish(archiveBytes);
abortIfNeeded(signal);
const lower = path.toLowerCase();
if (hasZipSignature(evidence.prefix)) return zipRootPackageFormat(lower);
if (
lower.endsWith(".pkg") &&
evidence.prefix.subarray(0, 4).equals(Buffer.from("xar!"))
)
return "pkg";
if (
lower.endsWith(".dmg") &&
(await hasKolyTrailer(handle, archiveBytes, signal))
)
return "dmg";
return classifyArtifactContent(path, evidence, archiveBytes).format;
};
/** App Pack is a verified ZIP root role; nested .app members retain their observed format. */
@@ -186,10 +175,25 @@ const zipRootPackageFormat = (lower: string): ZipPackageFormat =>
? "app-pack"
: (zipPackageFormatForPath(lower) ?? "zip");
const hasKolyTrailer = async (handle: FileHandle): Promise<boolean> => {
const size = (await handle.stat()).size;
const hasKolyTrailer = async (
handle: FileHandle,
size: number,
signal?: AbortSignal,
): Promise<boolean> => {
if (size < 512) return false;
const trailer = Buffer.alloc(4);
const read = await handle.read(trailer, 0, trailer.length, size - 512);
return read.bytesRead === 4 && trailer.equals(Buffer.from("koly"));
let bytes = 0;
while (bytes < trailer.length) {
abortIfNeeded(signal);
const read = await handle.read(
trailer,
bytes,
trailer.length - bytes,
size - 512 + bytes,
);
abortIfNeeded(signal);
if (read.bytesRead === 0) return false;
bytes += read.bytesRead;
}
return trailer.equals(Buffer.from("koly"));
};
+1 -1
View File
@@ -317,7 +317,7 @@ const digestArtifactEntry = async (
const classified =
entry.kind === "slice"
? ({ kind: "universal-slice", format: "mach-o" } as const)
: classifyArtifactContent(logicalPath, digest.prefix, digest.bytes);
: classifyArtifactContent(logicalPath, digest, digest.bytes);
return {
node: createArtifactNode({
sha256: digest.sha256,