fix(artifacts): bind ASAR interpretation to owned snapshots

Verify captured container bytes against their inventoried digest before listing or reading packed members. Isolate per-reader ASAR metadata, preserve original unpacked companions, and retain complete inventories when snapshot cleanup fails.
This commit is contained in:
morluto
2026-10-10 06:20:28 +08:00
parent bf934d5592
commit d79317cda0
7 changed files with 323 additions and 78 deletions
+123 -16
View File
@@ -1,7 +1,23 @@
import { constants, createReadStream, type Stats } from "node:fs"; import {
import { lstat, open, realpath, type FileHandle } from "node:fs/promises"; constants,
createReadStream,
createWriteStream,
type ReadStream,
type Stats,
} from "node:fs";
import {
lstat,
mkdtemp,
open,
realpath,
rm,
type FileHandle,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { createHash } from "node:crypto";
import { isAbsolute, join, relative, sep } from "node:path"; import { isAbsolute, join, relative, sep } from "node:path";
import { Readable } from "node:stream"; import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar"; import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar";
@@ -24,24 +40,28 @@ export class AsarArtifactReader implements ArtifactReader {
#archiveSize: number | undefined; #archiveSize: number | undefined;
#headerSize: number | undefined; #headerSize: number | undefined;
readonly #entries = new Map<string, AsarEntryState>(); readonly #entries = new Map<string, AsarEntryState>();
#snapshot: { readonly path: string; readonly sha256: string } | undefined;
#snapshotRoot: string | undefined;
constructor( constructor(
private readonly path: string, private readonly path: string,
private readonly openUnpackedFile: OpenAsarUnpackedFile = open, private readonly openUnpackedFile: OpenAsarUnpackedFile = open,
private readonly removeSnapshot: (path: string) => Promise<void> = (path) =>
rm(path, { recursive: true, force: true }),
) {} ) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> { async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
let paths: string[]; let paths: string[];
try { try {
// ASAR caches headers by path even after the archive has been replaced. await this.prepareContainer(undefined, signal);
const snapshotPath = this.#snapshotPath();
this.#resetArchiveState(); this.#resetArchiveState();
this.#entries.clear(); this.#entries.clear();
uncache(this.path); paths = listPackage(snapshotPath, { isPack: false }).sort((left, right) =>
paths = listPackage(this.path, { isPack: false }).sort((left, right) =>
left.localeCompare(right, "en"), left.localeCompare(right, "en"),
); );
this.#headerSize = getRawHeader(this.path).headerSize; this.#headerSize = getRawHeader(snapshotPath).headerSize;
const archiveMetadata = await lstat(this.path); const archiveMetadata = await lstat(snapshotPath);
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink()) if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
throw new ArtifactReaderFailure( throw new ArtifactReaderFailure(
"format", "format",
@@ -64,7 +84,7 @@ export class AsarArtifactReader implements ArtifactReader {
: listed; : listed;
let metadata: ReturnType<typeof statFile>; let metadata: ReturnType<typeof statFile>;
try { try {
metadata = statFile(this.path, providerPath, false); metadata = statFile(this.#snapshotPath(), providerPath, false);
} catch (cause: unknown) { } catch (cause: unknown) {
throw asarFailure(this.path, `stat ${path}`, cause); throw asarFailure(this.path, `stat ${path}`, cause);
} }
@@ -176,7 +196,7 @@ export class AsarArtifactReader implements ArtifactReader {
let handle: FileHandle | undefined; let handle: FileHandle | undefined;
try { try {
const openedHandle = await open( const openedHandle = await open(
this.path, this.#snapshotPath(),
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
); );
handle = openedHandle; handle = openedHandle;
@@ -210,17 +230,104 @@ export class AsarArtifactReader implements ArtifactReader {
} }
} }
/** Open raw container bytes to verify the inventory identity before analysis. */ /** Capture once per reader lifetime; bind all interpretation to these exact bytes. */
openContainer(signal?: AbortSignal): Readable { async prepareContainer(
expectedSha256?: string,
signal?: AbortSignal,
): Promise<void> {
abortIfNeeded(signal); abortIfNeeded(signal);
return createReadStream(this.path, signal === undefined ? {} : { signal }); if (this.#snapshot === undefined && this.#snapshotRoot !== undefined)
await this.close();
if (this.#snapshot === undefined) {
try {
this.#snapshotRoot = await mkdtemp(
join(tmpdir(), "rea-asar-snapshot-"),
);
const snapshotPath = join(this.#snapshotRoot, "container.asar");
const hash = createHash("sha256");
const handle = await open(
this.path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
const source = handle.createReadStream();
const digesting = new Transform({
transform(chunk: Buffer, _encoding, callback) {
hash.update(chunk);
callback(null, chunk);
},
});
await pipeline(
source,
digesting,
createWriteStream(snapshotPath, { flags: "wx", mode: 0o600 }),
signal === undefined ? {} : { signal },
);
this.#snapshot = { path: snapshotPath, sha256: hash.digest("hex") };
} catch (cause: unknown) {
const primary =
signal?.aborted === true
? new ArtifactReaderFailure(
"cancelled",
"ASAR operation cancelled",
{ cause },
)
: asarFailure(this.path, "snapshot", cause);
try {
await this.close();
} catch (cleanupCause: unknown) {
throw ArtifactReaderFailure.withCleanup(
primary,
ArtifactReaderFailure.cleanupObservation(cleanupCause, this.path),
);
}
throw primary;
}
}
if (
expectedSha256 !== undefined &&
this.#snapshot.sha256 !== expectedSha256
)
throw new ArtifactReaderFailure(
"integrity",
`ASAR container changed before interpretation: ${this.path}`,
);
} }
close(): Promise<void> { /** Read the same captured container that supplies headers and packed members. */
uncache(this.path); async openContainer(signal?: AbortSignal): Promise<ReadStream> {
await this.prepareContainer(undefined, signal);
return createReadStream(
this.#snapshotPath(),
signal === undefined ? {} : { signal },
);
}
async close(): Promise<void> {
const root = this.#snapshotRoot;
if (root !== undefined) {
try {
await this.removeSnapshot(root);
} catch (cause: unknown) {
throw ArtifactReaderFailure.withCleanup(cause, {
reason: `Could not remove ASAR snapshot: ${root}`,
resources: [root],
});
}
this.#snapshotRoot = undefined;
}
if (this.#snapshot !== undefined) uncache(this.#snapshot.path);
this.#snapshot = undefined;
this.#resetArchiveState(); this.#resetArchiveState();
this.#entries.clear(); this.#entries.clear();
return Promise.resolve(); }
#snapshotPath(): string {
if (this.#snapshot === undefined)
throw new ArtifactReaderFailure(
"integrity",
"ASAR snapshot is not available",
);
return this.#snapshot.path;
} }
provenance(): readonly [] { provenance(): readonly [] {
+25 -15
View File
@@ -1,6 +1,8 @@
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import { AsarArtifactReader } from "../AsarArtifactReader.js";
import { lstat } from "node:fs/promises"; import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs"; import type { Stats } from "node:fs";
@@ -61,6 +63,7 @@ export const scanCanonicalArtifactInventory = async (
options.environment ?? {}, options.environment ?? {},
options.signal, options.signal,
); );
const ownedReaders: ArtifactReader[] = reader === undefined ? [] : [reader];
let outcome: let outcome:
| { | {
readonly kind: "completed"; readonly kind: "completed";
@@ -68,8 +71,11 @@ export const scanCanonicalArtifactInventory = async (
} }
| { readonly kind: "failed"; readonly cause: unknown }; | { readonly kind: "failed"; readonly cause: unknown };
try { try {
if (reader instanceof AsarArtifactReader)
await reader.prepareContainer(rootDigest?.sha256, options.signal);
const { nodes, occurrences, pendingContradictions } = await scanReader( const { nodes, occurrences, pendingContradictions } = await scanReader(
reader, reader,
ownedReaders,
options.signal, options.signal,
integrity, integrity,
); );
@@ -90,22 +96,26 @@ export const scanCanonicalArtifactInventory = async (
} catch (cause: unknown) { } catch (cause: unknown) {
outcome = { kind: "failed", cause }; outcome = { kind: "failed", cause };
} }
try { let cleanupFailure: ArtifactReaderFailure | undefined;
await reader?.close(); for (const owned of ownedReaders.reverse()) {
} catch (cleanupCause: unknown) { try {
const cleanup = ArtifactReaderFailure.cleanupObservation( await owned.close();
cleanupCause, } catch (cleanupCause: unknown) {
`artifact reader for ${path}`, const cleanup = ArtifactReaderFailure.cleanupObservation(
); cleanupCause,
const primary = outcome.kind === "failed" ? outcome.cause : cleanupCause; `artifact reader for ${path}`,
throw ArtifactReaderFailure.withCleanup( );
primary, cleanupFailure = ArtifactReaderFailure.withCleanup(
cleanup, cleanupFailure ??
outcome.kind === "completed" (outcome.kind === "failed" ? outcome.cause : cleanupCause),
? { kind: "artifact-inventory", inventory: outcome.snapshot } cleanup,
: undefined, outcome.kind === "completed"
); ? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
} }
if (cleanupFailure !== undefined) throw cleanupFailure;
if (outcome.kind === "failed") throw outcome.cause; if (outcome.kind === "failed") throw outcome.cause;
return outcome.snapshot; return outcome.snapshot;
}; };
+8 -13
View File
@@ -52,10 +52,12 @@ interface ScanContext {
readonly occurrenceByPath: Map<string, MutableOccurrence>; readonly occurrenceByPath: Map<string, MutableOccurrence>;
readonly registry: ArtifactPathRegistry; readonly registry: ArtifactPathRegistry;
readonly expandedContainerIds: Set<string>; readonly expandedContainerIds: Set<string>;
readonly ownedReaders: ArtifactReader[];
} }
export const scanReader = async ( export const scanReader = async (
reader: ArtifactReader | undefined, reader: ArtifactReader | undefined,
ownedReaders: ArtifactReader[],
signal?: AbortSignal, signal?: AbortSignal,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY, integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<{ ): Promise<{
@@ -76,6 +78,7 @@ export const scanReader = async (
occurrenceByPath: new Map<string, MutableOccurrence>(), occurrenceByPath: new Map<string, MutableOccurrence>(),
registry: new ArtifactPathRegistry(), registry: new ArtifactPathRegistry(),
expandedContainerIds: new Set<string>(), expandedContainerIds: new Set<string>(),
ownedReaders,
}; };
await visitArtifactEntries(context, reader, ""); await visitArtifactEntries(context, reader, "");
// Archive directories may appear after their children. Resolve containment // Archive directories may appear after their children. Resolve containment
@@ -99,13 +102,11 @@ const visitArtifactEntries = async (
readonly reader: ArtifactReader; readonly reader: ArtifactReader;
readonly prefix: string; readonly prefix: string;
readonly iterator: AsyncIterator<ArtifactEntry>; readonly iterator: AsyncIterator<ArtifactEntry>;
readonly owned: boolean;
}> = [ }> = [
{ {
reader: currentReader, reader: currentReader,
prefix, prefix,
iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](), iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](),
owned: false,
}, },
]; ];
try { try {
@@ -115,7 +116,6 @@ const visitArtifactEntries = async (
const next = await frame.iterator.next(); const next = await frame.iterator.next();
if (next.done) { if (next.done) {
stack.pop(); stack.pop();
if (frame.owned) await frame.reader.close();
continue; continue;
} }
const entry = next.value; const entry = next.value;
@@ -164,27 +164,22 @@ const visitArtifactEntries = async (
} }
context.occurrences.push(occurrence); context.occurrences.push(occurrence);
context.occurrenceByPath.set(logicalPath, occurrence); context.occurrenceByPath.set(logicalPath, occurrence);
if (expandableAsar && digested?.mismatched !== true) { if (expandableAsar && digested !== undefined && !digested.mismatched) {
const nested = new AsarArtifactReader(entry.adapterKey); const nested = new AsarArtifactReader(entry.adapterKey);
context.ownedReaders.push(nested);
await nested.prepareContainer(digested.node.sha256, context.signal);
// Only traversed containers can own members, not opaque ASAR-named files. // Only traversed containers can own members, not opaque ASAR-named files.
context.expandedContainerIds.add(occurrence.occurrence_id); context.expandedContainerIds.add(occurrence.occurrence_id);
stack.push({ stack.push({
reader: nested, reader: nested,
prefix: logicalPath, prefix: logicalPath,
iterator: nested.entries(context.signal)[Symbol.asyncIterator](), iterator: nested.entries(context.signal)[Symbol.asyncIterator](),
owned: true,
}); });
} }
} }
} finally { } finally {
await Promise.allSettled( // Readers remain owned by the inventory until its complete observation is built.
stack for (const { iterator } of stack) await iterator.return?.();
.filter(({ owned }) => owned)
.map(async ({ reader, iterator }) => {
await iterator.return?.();
await reader.close();
}),
);
} }
}; };
@@ -71,7 +71,7 @@ export const readJavaScriptArtifactFiles = async (
"Root artifact node is missing", "Root artifact node is missing",
); );
await verifyEntryBytes( await verifyEntryBytes(
reader.openContainer(signal), await reader.openContainer(signal),
{ path: ".", sha256: root.sha256, bytes: root.size }, { path: ".", sha256: root.sha256, bytes: root.size },
signal, signal,
); );
@@ -114,16 +114,16 @@ const visitReader = async (
readonly prefix: string; readonly prefix: string;
readonly containerSha256: string; readonly containerSha256: string;
readonly iterator: AsyncIterator<ArtifactEntry>; readonly iterator: AsyncIterator<ArtifactEntry>;
readonly owned: boolean;
}> = [ }> = [
{ {
reader, reader,
prefix, prefix,
containerSha256, containerSha256,
iterator: reader.entries(context.signal)[Symbol.asyncIterator](), iterator: reader.entries(context.signal)[Symbol.asyncIterator](),
owned: false,
}, },
]; ];
const ownedReaders: ArtifactReader[] = [];
let failure: { readonly cause: unknown } | undefined;
try { try {
while (stack.length > 0) { while (stack.length > 0) {
const frame = stack.at(-1); const frame = stack.at(-1);
@@ -131,7 +131,6 @@ const visitReader = async (
const next = await frame.iterator.next(); const next = await frame.iterator.next();
if (next.done) { if (next.done) {
stack.pop(); stack.pop();
if (frame.owned) await frame.reader.close();
continue; continue;
} }
const entry = next.value; const entry = next.value;
@@ -175,13 +174,14 @@ const visitReader = async (
); );
context.containers.push(inventory); context.containers.push(inventory);
const nested = new AsarArtifactReader(entry.adapterKey); const nested = new AsarArtifactReader(entry.adapterKey);
ownedReaders.push(nested);
stack.push({ stack.push({
reader: nested, reader: nested,
prefix: path, prefix: path,
containerSha256: inventory.sha256, containerSha256: inventory.sha256,
iterator: nested.entries(context.signal)[Symbol.asyncIterator](), iterator: nested.entries(context.signal)[Symbol.asyncIterator](),
owned: true,
}); });
await nested.prepareContainer(inventory.sha256, context.signal);
continue; continue;
} }
const expected = context.expected.get(path); const expected = context.expected.get(path);
@@ -202,16 +202,33 @@ const visitReader = async (
text, text,
}); });
} }
} catch (cause: unknown) {
failure = { cause };
} finally { } finally {
await Promise.allSettled( for (const { iterator } of stack) {
stack try {
.filter(({ owned }) => owned) await iterator.return?.();
.map(async ({ reader, iterator }) => { } catch (cause: unknown) {
await iterator.return?.(); failure ??= { cause };
await reader.close(); }
}), }
); for (const owned of ownedReaders.reverse()) {
try {
await owned.close();
} catch (cause: unknown) {
failure = {
cause: ArtifactReaderFailure.withCleanup(
failure?.cause ?? cause,
ArtifactReaderFailure.cleanupObservation(
cause,
`nested ASAR reader for ${prefix}`,
),
),
};
}
}
} }
if (failure !== undefined) throw failure.cause;
}; };
const readText = async ( const readText = async (
@@ -1,10 +1,13 @@
import { mkdir, rm, symlink, writeFile } from "node:fs/promises"; import { lstat, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { join, sep } from "node:path"; import { join, sep } from "node:path";
import { Readable } from "node:stream";
import { buffer } from "node:stream/consumers"; import { buffer } from "node:stream/consumers";
import { createPackage, listPackage, uncache } from "@electron/asar"; import { createPackage, listPackage, uncache } from "@electron/asar";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js"; import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js"; import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -165,7 +168,121 @@ describe("ASAR inventory freshness", () => {
} }
}, },
); );
});
describe("ASAR captured-byte identity", () => {
it("rejects same-size nested-container replacement between hashing and interpretation", async () => {
const fixture = await archiveFixture();
const originalSize = (await lstat(fixture.archive)).size;
const directory = new DirectoryArtifactReader(fixture.bundle);
await expect(
scanCanonicalArtifactInventory(fixture.bundle, {}, async () => ({
format: directory.format,
entries: (signal) => directory.entries(signal),
provenance: () => directory.provenance(),
close: () => directory.close(),
async open(entry, signal) {
const source = await directory.open(entry, signal);
return Readable.from(
(async function* () {
yield* source;
await fixture.replace();
expect((await lstat(fixture.archive)).size).toBe(originalSize);
})(),
);
},
})),
).rejects.toMatchObject({
reason: "integrity",
message: expect.stringContaining("changed before interpretation"),
});
});
it("isolates interleaved readers from replacement headers and packed bytes", async () => {
const fixture = await archiveFixture();
await writeFile(join(fixture.source, "second.js"), "original metadata");
await createPackage(fixture.source, fixture.archive);
const first = new AsarArtifactReader(fixture.archive);
const second = new AsarArtifactReader(fixture.archive);
const left = first.entries()[Symbol.asyncIterator]();
const right = second.entries()[Symbol.asyncIterator]();
try {
const initial = await left.next();
if (initial.done) throw new Error("Expected first member");
expect(initial.value.path).toBe("old.js");
await fixture.replace();
await writeFile(join(fixture.source, "second.js"), "replaced metadata");
await createPackage(fixture.source, fixture.archive);
const replacement = await right.next();
if (replacement.done) throw new Error("Expected replacement member");
expect(replacement.value.path).toBe("new.js");
const originalMember = await left.next();
const replacementMember = await right.next();
if (originalMember.done || replacementMember.done)
throw new Error("Expected second members");
expect(originalMember.value.declaredSha256).not.toBe(
replacementMember.value.declaredSha256,
);
expect(
(await buffer(await first.open(originalMember.value))).toString(),
).toBe("original metadata");
await first.close();
expect(
(await buffer(await second.open(replacementMember.value))).toString(),
).toBe("replaced metadata");
} finally {
await left.return?.();
await right.return?.();
await first.close();
await second.close();
}
});
it("retains a completed inventory and snapshot ownership when cleanup fails", async () => {
const fixture = await archiveFixture();
const attempts: string[] = [];
const reader = new AsarArtifactReader(
fixture.archive,
undefined,
async (path) => {
attempts.push(path);
if (attempts.length === 1) throw new Error("snapshot removal denied");
await rm(path, { recursive: true, force: true });
},
);
try {
const failure: unknown = await scanCanonicalArtifactInventory(
fixture.archive,
{},
async () => reader,
).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
cleanup: { resources: [attempts[0]] },
partialObservation: {
kind: "artifact-inventory",
inventory: {
occurrences: expect.arrayContaining([
expect.objectContaining({
logical_path: "old.js",
hash_status: "verified",
}),
]),
},
},
});
const root = attempts[0];
if (root === undefined) throw new Error("Expected owned snapshot");
expect((await lstat(root)).isDirectory()).toBe(true);
await reader.close();
expect(attempts).toEqual([root, root]);
await expect(lstat(root)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
await reader.close();
}
});
});
describe("ASAR reader lifecycle", () => {
it("refreshes a header cached before the reader was created", async () => { it("refreshes a header cached before the reader was created", async () => {
const fixture = await archiveFixture(); const fixture = await archiveFixture();
try { try {
@@ -69,11 +69,6 @@ describe("ASAR entry streaming", () => {
await writeFile(join(source, "small.js"), "module.exports = 1;\n"); await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {}); await createPackageWithOptions(source, archive, {});
const identity = await lstat(archive);
const probe = await openFile(archive, "r");
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await probe.close();
await waitForNoMatchingDescriptor(identity);
const reader = new AsarArtifactReader(archive); const reader = new AsarArtifactReader(archive);
try { try {
@@ -83,6 +78,12 @@ describe("ASAR entry streaming", () => {
} }
const entry = entries.find(({ path }) => path === "small.js"); const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member"); if (entry === undefined) throw new Error("Expected packed ASAR member");
const snapshot = await reader.openContainer();
const identity = await lstat(snapshot.path);
await buffer(snapshot);
const probe = await openFile(snapshot.path, "r");
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await probe.close();
expect(await matchingDescriptorCount(identity)).toBe(0); expect(await matchingDescriptorCount(identity)).toBe(0);
const output = await reader.open(entry); const output = await reader.open(entry);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0); expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
@@ -108,7 +109,6 @@ describe("ASAR entry streaming", () => {
await writeFile(join(source, "small.js"), "module.exports = 1;\n"); await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {}); await createPackageWithOptions(source, archive, {});
const identity = await lstat(archive);
const reader = new AsarArtifactReader(archive); const reader = new AsarArtifactReader(archive);
try { try {
@@ -116,6 +116,9 @@ describe("ASAR entry streaming", () => {
for await (const entry of reader.entries()) entries.push(entry); for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js"); const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member"); if (entry === undefined) throw new Error("Expected packed ASAR member");
const snapshot = await reader.openContainer();
const identity = await lstat(snapshot.path);
await buffer(snapshot);
const controller = new AbortController(); const controller = new AbortController();
const opening = reader.open(entry, controller.signal); const opening = reader.open(entry, controller.signal);
controller.abort(); controller.abort();
@@ -127,7 +130,7 @@ describe("ASAR entry streaming", () => {
}, },
); );
it("classifies a missing packed member container as an I/O failure", async () => { it("keeps captured packed bytes readable after the original container disappears", async () => {
const root = await createTestTempDirectory("rea-asar-missing-member-"); const root = await createTestTempDirectory("rea-asar-missing-member-");
const source = join(root, "source"); const source = join(root, "source");
const archive = join(root, "fixture.asar"); const archive = join(root, "fixture.asar");
@@ -142,10 +145,9 @@ describe("ASAR entry streaming", () => {
const entry = entries.find(({ path }) => path === "small.js"); const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member"); if (entry === undefined) throw new Error("Expected packed ASAR member");
await rm(archive); await rm(archive);
await expect(reader.open(entry)).rejects.toMatchObject({ expect((await buffer(await reader.open(entry))).toString()).toBe(
reason: "io", "module.exports = 1;\n",
cause: { code: "ENOENT" }, );
});
} finally { } finally {
await reader.close(); await reader.close();
} }
@@ -205,7 +207,7 @@ describe("ASAR entry producer identity", () => {
["packed to unpacked", false], ["packed to unpacked", false],
["unpacked to packed", true], ["unpacked to packed", true],
] as const)( ] as const)(
"rejects a retained %s entry after a new entries pass", "rejects a retained %s entry after closing and recapturing the archive",
async (_transition, wasUnpacked) => { async (_transition, wasUnpacked) => {
const root = await createTestTempDirectory("rea-asar-entry-refresh-"); const root = await createTestTempDirectory("rea-asar-entry-refresh-");
const source = join(root, "source"); const source = join(root, "source");
@@ -236,6 +238,7 @@ describe("ASAR entry producer identity", () => {
archive, archive,
wasUnpacked ? {} : { unpack: "small.js" }, wasUnpacked ? {} : { unpack: "small.js" },
); );
await reader.close();
const currentEntries = []; const currentEntries = [];
for await (const entry of reader.entries()) currentEntries.push(entry); for await (const entry of reader.entries()) currentEntries.push(entry);
const current = currentEntries.find(({ path }) => path === "small.js"); const current = currentEntries.find(({ path }) => path === "small.js");
@@ -345,7 +348,7 @@ describe("ASAR read failures", () => {
); );
it.each(["missing", "replaced"] as const)( it.each(["missing", "replaced"] as const)(
"validates the container before returning a zero-length member when it is %s", "reads a captured zero-length member when the original container is %s",
async (change) => { async (change) => {
const root = await createTestTempDirectory("rea-asar-empty-member-"); const root = await createTestTempDirectory("rea-asar-empty-member-");
const source = join(root, "source"); const source = join(root, "source");
@@ -363,11 +366,7 @@ describe("ASAR read failures", () => {
if (change === "missing") await rm(archive); if (change === "missing") await rm(archive);
else await writeFile(archive, "replacement container"); else await writeFile(archive, "replacement container");
await expect(reader.open(entry)).rejects.toMatchObject( expect(await buffer(await reader.open(entry))).toHaveLength(0);
change === "missing"
? { reason: "io", cause: { code: "ENOENT" } }
: { reason: "integrity" },
);
} finally { } finally {
await reader.close(); await reader.close();
} }
@@ -122,7 +122,7 @@ describe("JavaScript artifact ingestion content identities", () => {
} }
}); });
it("retains native filesystem errors for outer IO classification", async () => { it("retains filesystem error context in typed IO failures", async () => {
const { archive } = await fixture(); const { archive } = await fixture();
const snapshot = await scanArtifactInventory(archive); const snapshot = await scanArtifactInventory(archive);
await rm(archive); await rm(archive);
@@ -130,7 +130,7 @@ describe("JavaScript artifact ingestion content identities", () => {
try { try {
await expect( await expect(
readJavaScriptArtifactFiles(reader, snapshot), readJavaScriptArtifactFiles(reader, snapshot),
).rejects.toMatchObject({ code: "ENOENT" }); ).rejects.toMatchObject({ reason: "io", cause: { code: "ENOENT" } });
} finally { } finally {
await reader.close(); await reader.close();
} }