Skip to content

Commit e8da7e1

Browse files
committed
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
1 parent 2e5171e commit e8da7e1

22 files changed

Lines changed: 1128 additions & 165 deletions
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import {
2+
createAsarHeaderSignatureProbe,
3+
type FinalAsarHeaderProbeObservation,
4+
} from "./AsarHeader.js";
5+
import {
6+
createXmlPlistSignatureProbe,
7+
MAX_XML_PLIST_PROBE_BYTES,
8+
} from "../domain/apple/appleArchiveFormat.js";
9+
10+
/** Initial bytes required by the other bounded format classifiers. */
11+
export const ARTIFACT_CLASSIFICATION_PREFIX_BYTES = 8_192;
12+
13+
/** Retained bytes and independently parsed ASAR signature facts. */
14+
export interface ArtifactClassificationEvidence {
15+
readonly prefix: Buffer;
16+
readonly asarHeader: FinalAsarHeaderProbeObservation;
17+
}
18+
19+
/** Share acquisition bounds and signature observations across files and streams. */
20+
export const createArtifactClassificationProbe = () => {
21+
const xml = createXmlPlistSignatureProbe();
22+
const asar = createAsarHeaderSignatureProbe();
23+
const blocks: Buffer[] = [];
24+
let retainedBytes = 0;
25+
let observedBytes = 0;
26+
const retain = (bytes: Uint8Array): void => {
27+
let offset = 0;
28+
while (offset < bytes.length) {
29+
const blockOffset = retainedBytes % ARTIFACT_CLASSIFICATION_PREFIX_BYTES;
30+
if (blockOffset === 0)
31+
blocks.push(Buffer.allocUnsafe(ARTIFACT_CLASSIFICATION_PREFIX_BYTES));
32+
const count = Math.min(
33+
ARTIFACT_CLASSIFICATION_PREFIX_BYTES - blockOffset,
34+
bytes.length - offset,
35+
);
36+
blocks[blocks.length - 1]!.set(
37+
bytes.subarray(offset, offset + count),
38+
blockOffset,
39+
);
40+
retainedBytes += count;
41+
offset += count;
42+
}
43+
};
44+
return {
45+
get length(): number {
46+
return observedBytes;
47+
},
48+
get limit(): number {
49+
if (observedBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES)
50+
return ARTIFACT_CLASSIFICATION_PREFIX_BYTES;
51+
return Math.max(
52+
ARTIFACT_CLASSIFICATION_PREFIX_BYTES,
53+
xml.state === "pending" ? MAX_XML_PLIST_PROBE_BYTES : 0,
54+
asar.observation.state === "pending" ? asar.limit : 0,
55+
);
56+
},
57+
write(bytes: Uint8Array): void {
58+
asar.write(bytes);
59+
let offset = 0;
60+
while (offset < bytes.length) {
61+
const limit =
62+
retainedBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES
63+
? ARTIFACT_CLASSIFICATION_PREFIX_BYTES
64+
: xml.state === "pending"
65+
? MAX_XML_PLIST_PROBE_BYTES
66+
: retainedBytes;
67+
if (retainedBytes >= limit) break;
68+
const selected = bytes.subarray(
69+
offset,
70+
offset + Math.min(limit - retainedBytes, bytes.length - offset),
71+
);
72+
retain(selected);
73+
xml.write(selected);
74+
offset += selected.length;
75+
}
76+
observedBytes += bytes.length;
77+
},
78+
finish(archiveBytes: number): ArtifactClassificationEvidence {
79+
const prefix = Buffer.allocUnsafe(retainedBytes);
80+
let copied = 0;
81+
for (const block of blocks) {
82+
const count = Math.min(block.length, retainedBytes - copied);
83+
prefix.set(block.subarray(0, count), copied);
84+
copied += count;
85+
}
86+
return { prefix, asarHeader: asar.finish(archiveBytes) };
87+
},
88+
};
89+
};

‎src/artifacts/ArtifactHash.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Readable } from "node:stream";
2+
import { expect, it } from "vitest";
3+
4+
import { hashReadable } from "./ArtifactHash.js";
5+
6+
it("preserves cancellation arriving with the final stream result", async () => {
7+
const controller = new AbortController();
8+
const reason = { stage: "source-eof" };
9+
const source = Readable.from(
10+
(async function* () {
11+
yield Buffer.from("complete bytes");
12+
controller.abort(reason);
13+
})(),
14+
);
15+
16+
await expect(hashReadable(source, controller.signal)).rejects.toMatchObject({
17+
reason: "cancelled",
18+
cause: reason,
19+
});
20+
});

‎src/artifacts/ArtifactHash.ts‎

Lines changed: 7 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,16 @@ import type { Readable } from "node:stream";
44
import { ArtifactReaderFailure } from "./ArtifactReader.js";
55
import { streamChunkToBuffer } from "./StreamBytes.js";
66
import {
7-
createXmlPlistSignatureProbe,
8-
MAX_XML_PLIST_PROBE_BYTES,
9-
} from "../domain/apple/appleArchiveFormat.js";
7+
createArtifactClassificationProbe,
8+
type ArtifactClassificationEvidence,
9+
} from "./ArtifactClassificationProbe.js";
1010

1111
/** Full stream digest and byte count with bounded classification evidence. */
12-
export type HashResult = {
12+
export type HashResult = ArtifactClassificationEvidence & {
1313
readonly sha256: string;
1414
readonly bytes: number;
15-
readonly prefix: Buffer;
1615
};
1716

18-
/** Bounded classification evidence; this is not an executable format size limit. */
19-
export const ARTIFACT_CLASSIFICATION_PREFIX_BYTES = 8_192;
20-
2117
/** Preserve the inventory cancellation reason at a stream boundary. */
2218
export const abortIfNeeded = (signal?: AbortSignal): void => {
2319
if (signal?.aborted === true)
@@ -34,36 +30,15 @@ export const hashReadable = async (
3430
signal?: AbortSignal,
3531
): Promise<HashResult> => {
3632
const hash = createHash("sha256");
37-
const prefixes: Buffer[] = [];
38-
let prefixBytes = 0;
39-
const xmlProbe = createXmlPlistSignatureProbe();
33+
const probe = createArtifactClassificationProbe();
4034
let bytes = 0;
4135
for await (const raw of stream) {
4236
abortIfNeeded(signal);
4337
const chunk = streamChunkToBuffer(raw);
4438
bytes += chunk.length;
4539
hash.update(chunk);
46-
let chunkOffset = 0;
47-
while (
48-
chunkOffset < chunk.length &&
49-
(prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES ||
50-
(xmlProbe.state === "pending" &&
51-
prefixBytes < MAX_XML_PLIST_PROBE_BYTES))
52-
) {
53-
const limit =
54-
prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES
55-
? ARTIFACT_CLASSIFICATION_PREFIX_BYTES
56-
: MAX_XML_PLIST_PROBE_BYTES;
57-
const selected = chunk.subarray(
58-
chunkOffset,
59-
Math.min(chunkOffset + limit - prefixBytes, chunk.length),
60-
);
61-
prefixes.push(selected);
62-
prefixBytes += selected.length;
63-
chunkOffset += selected.length;
64-
xmlProbe.write(selected);
65-
}
40+
probe.write(chunk);
6641
}
6742
abortIfNeeded(signal);
68-
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };
43+
return { sha256: hash.digest("hex"), bytes, ...probe.finish(bytes) };
6944
};

‎src/artifacts/AsarArtifactReader.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export class AsarArtifactReader implements ArtifactReader {
6363
const snapshotPath = this.#snapshotPath();
6464
this.#resetArchiveState();
6565
this.#entries.clear();
66-
const admitted = await this.#admitHeader(snapshotPath);
66+
const admitted = await this.#admitHeader(snapshotPath, signal);
6767
this.#archiveSize = admitted.archiveBytes;
6868
this.#headerSize = admitted.headerBytes;
6969
abortIfNeeded(signal);
@@ -122,7 +122,7 @@ export class AsarArtifactReader implements ArtifactReader {
122122
}
123123
}
124124

125-
async #admitHeader(snapshotPath: string) {
125+
async #admitHeader(snapshotPath: string, signal?: AbortSignal) {
126126
const headerHandle = await this.#openOwned(
127127
snapshotPath,
128128
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
@@ -134,7 +134,10 @@ export class AsarArtifactReader implements ArtifactReader {
134134
}
135135
| { readonly ok: false; readonly cause: unknown };
136136
try {
137-
admission = { ok: true, value: await admitAsarHeader(headerHandle) };
137+
admission = {
138+
ok: true,
139+
value: await admitAsarHeader(headerHandle, signal),
140+
};
138141
} catch (cause: unknown) {
139142
admission = { ok: false, cause };
140143
}

‎src/artifacts/AsarHeader.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import type { Stats } from "node:fs";
2+
import { expect, it, vi } from "vitest";
3+
4+
import {
5+
admitAsarHeader,
6+
createAsarHeaderSignatureProbe,
7+
} from "./AsarHeader.js";
8+
import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js";
9+
10+
const makeArchive = (): Buffer => asarHeaderBytes(' \t\r\n{"files":{}} ');
11+
12+
it("fills the fixed Pickle prefix across controlled short reads", async () => {
13+
const archive = makeArchive();
14+
const calls: Array<readonly [number, number, number]> = [];
15+
const handle = {
16+
stat: vi.fn(
17+
async () =>
18+
({
19+
isFile: () => true,
20+
size: archive.length,
21+
}) as Stats,
22+
),
23+
read: vi.fn(
24+
async (
25+
target: Buffer,
26+
offset: number,
27+
length: number,
28+
position: number,
29+
) => {
30+
calls.push([offset, length, position]);
31+
const bytesRead = Math.min(3, length, archive.length - position);
32+
archive.copy(target, offset, position, position + bytesRead);
33+
return { bytesRead, buffer: target };
34+
},
35+
),
36+
} as unknown as Parameters<typeof admitAsarHeader>[0];
37+
38+
await expect(admitAsarHeader(handle)).resolves.toEqual({
39+
archiveBytes: archive.length,
40+
headerBytes: archive.readUInt32LE(4),
41+
jsonBytes: archive.readUInt32LE(12),
42+
});
43+
expect(calls).toEqual([
44+
[0, 16, 0],
45+
[3, 13, 3],
46+
[6, 10, 6],
47+
[9, 7, 9],
48+
[12, 4, 12],
49+
[15, 1, 15],
50+
]);
51+
});
52+
53+
it("recognizes JSON whitespace before the object token and finalizes file extents", () => {
54+
const archive = makeArchive();
55+
const probe = createAsarHeaderSignatureProbe();
56+
probe.write(archive.subarray(0, 7));
57+
expect(probe.observation.state).toBe("pending");
58+
probe.write(archive.subarray(7, 21));
59+
expect(probe.observation.state).toBe("matched");
60+
const result = probe.finish(archive.length);
61+
expect(result).toMatchObject({
62+
state: "matched",
63+
extents: {
64+
archiveBytes: archive.length,
65+
headerBytes: archive.readUInt32LE(4),
66+
jsonBytes: archive.readUInt32LE(12),
67+
},
68+
signatureOffset: 20,
69+
});
70+
});
71+
72+
it("rejects a signature whose declared header exceeds the observed archive", () => {
73+
const archive = makeArchive();
74+
const probe = createAsarHeaderSignatureProbe();
75+
probe.write(archive);
76+
expect(probe.finish(archive.length - 1)).toMatchObject({
77+
state: "rejected",
78+
reason: "archive-too-short",
79+
});
80+
});

0 commit comments

Comments
 (0)