mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
* feat(artifacts): inspect NES 2.0 container headers and regions Problem: the iNES lane refused every header whose byte 7 bits 2-3 select NES 2.0, so NES 2.0 cartridges could not be inventoried, extracted or reconstructed even though their file layout extends classic iNES. Fix: the single iNES-family header parser now reads NES 2.0 alongside classic iNES. It reports the 12-bit mapper, submapper, 12-bit and exponent-multiplier PRG/CHR sizes, declared PRG/CHR RAM and NVRAM sizes, CPU/PPU timing, console type with Vs. System and extended console codes, miscellaneous ROM count and default expansion device in a "nes-2.0" header variant; classic headers keep their exact serialization. Regions add one prg.bin/chr.bin for exponent sizes and misc-rom.bin for the bytes after CHR-ROM when miscellaneous ROMs are declared. Oversized declarations (with exact totals, including exponent sizes beyond safe integers), nonzero unused header bits, empty PRG-ROM and declared but absent miscellaneous ROM bytes are refused through the existing format error. Nested byte classification now admits NES 2.0 through the same parser. The reader limitation, tool description, guide and skill reference now state that UNIF remains unsupported and that RAM, timing and console values are declarations. Validation: new synthetic NES 2.0 unit cases fail on the base (15 of 24) and pass after the change; focused boundary and acceptance iNES suites (75 tests) pass, including NES 2.0 inventory, extraction, reconstruction and compiled CLI inspection; npm run check:fast passes. Refs morluto/rea#2072 * test(artifacts): extract an exponent-sized NES 2.0 ROM area Review follow-up for NES 2.0 headers. The exponent-multiplier case stopped at parseInesLayout, and the extraction test used counted ROM units, so prg.bin and chr.bin from an exponent-sized area never went through the reader or extraction. A boundary case now builds a NES 2.0 file with a 2^10 * 3 byte PRG-ROM area beside one counted 8 KiB CHR-ROM unit. It checks the header omits the PRG unit count, the source offsets of prg.bin and chr/000.bin, the verified reconstruction order, and that the extracted regions match the original bytes exactly. Tests: tests/boundary/filesystem/inesArtifact.test.ts passes (38). * refactor(artifacts): read NES header bytes through one helper The NES 2.0 declaration added a sixth raw Buffer read to inesContainer.ts. On current main the architecture guard allows five there, so the merged tree failed Static checks. iNES and NES 2.0 declarations and the format probe now read header bytes through one headerByte helper. The file has one raw read, and its counted baseline drops from 5 to 1 through --shrink-baselines. Tests: inesContainer domain tests (24) and the NES boundary and acceptance tests (76) pass. architecture-guards, format:check and check:ci:fast pass on the branch merged with main. * refactor(artifacts): report iNES header failures through ParseFailure Review follow-up: the NES 2.0 declaration added plain-string failures. The iNES-family parser now returns Result<_, ParseFailure> with its kind and where it was found: - malformed: a missing signature, a dirty legacy header, an empty PRG-ROM area, reserved NES 2.0 bits or an invalid file extent; - truncated: a short header, a short payload, or declared miscellaneous ROM with no bytes; - unsupported: UNIF or another header variant, with undecoded content. The detail text is unchanged. The format registry refuses with the detail, and the iNES reader and root classifier translate the failure at their boundary into the existing format ArtifactReaderFailure, with the ParseFailureError as its cause. Tests: the refusal table now asserts each failure's kind and format as well as its detail. iNES domain and recognition tests, NES boundary and acceptance tests (76), architecture-guards, format:check and check:ci:fast pass on the branch merged with main. * fix(artifacts): preserve NES header declarations and iNES evidence --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
931 lines
29 KiB
TypeScript
931 lines
29 KiB
TypeScript
import * as rootHash from "../../../src/resources/StableRootArtifact.js";
|
|
import { readFileHandlePrefix } from "../../../src/filesystem/readFileHandlePrefix.js";
|
|
import { createHash } from "node:crypto";
|
|
import {
|
|
lstat,
|
|
mkdir,
|
|
open,
|
|
readFile,
|
|
unlink,
|
|
utimes,
|
|
writeFile,
|
|
type FileHandle,
|
|
} from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { expect, it, vi } from "vitest";
|
|
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { inesFixture, nes2Fixture } from "../../fixtures/ines.js";
|
|
import {
|
|
inventoryArtifact,
|
|
scanArtifactInventory,
|
|
materializeArtifactInventory,
|
|
} from "../../fixtures/artifactInventory.js";
|
|
import { InesArtifactReader } from "../../../src/artifacts/InesArtifactReader.js";
|
|
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
|
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
|
|
import {
|
|
extractArtifact,
|
|
materializeArtifactInventoryInScope as materializeInScope,
|
|
} from "../../../src/artifacts/extraction/ArtifactExtraction.js";
|
|
import { abortIfNeeded } from "../../../src/resources/StreamDigest.js";
|
|
|
|
const AGED_FIXTURE_TIME = new Date("2000-01-01T00:00:00Z");
|
|
|
|
const sha256 = (bytes: Buffer) =>
|
|
createHash("sha256").update(bytes).digest("hex");
|
|
|
|
const fileReadPrototype = async (
|
|
path: string,
|
|
): Promise<Pick<FileHandle, "read">> => {
|
|
const handle = await open(path, "r");
|
|
try {
|
|
return Object.getPrototypeOf(handle) as Pick<FileHandle, "read">;
|
|
} finally {
|
|
await handle.close();
|
|
}
|
|
};
|
|
|
|
it("reuses scanned iNES region bytes for reconstruction without another full read", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-read-budget-");
|
|
const path = join(root, "large-tail.nes");
|
|
const bytes = inesFixture({ trailing: Buffer.alloc(2 * 1024 * 1024, 0x5a) });
|
|
await writeFile(path, bytes);
|
|
const prototype = await fileReadPrototype(path);
|
|
const originalRead = prototype.read;
|
|
let bytesRead = 0;
|
|
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
|
this: FileHandle,
|
|
...args
|
|
) {
|
|
const result = await originalRead.call(this, ...args);
|
|
bytesRead += result.bytesRead;
|
|
return result;
|
|
});
|
|
try {
|
|
const result = await inventoryArtifact(path);
|
|
expect(result.ines?.reconstruction).toMatchObject({
|
|
bytes: bytes.length,
|
|
sha256: sha256(bytes),
|
|
verified: true,
|
|
});
|
|
// Initial root hash, region scan, final freshness hash, plus bounded headers.
|
|
expect(bytesRead).toBeLessThanOrEqual(3 * bytes.length + 64 * 1024);
|
|
} finally {
|
|
read.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("rejects region bytes that disagree with stable whole-file hashes", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-region-digest-");
|
|
const path = join(root, "source.nes");
|
|
const bytes = inesFixture();
|
|
await writeFile(path, bytes);
|
|
const prototype = await fileReadPrototype(path);
|
|
const originalRead = prototype.read;
|
|
let changed = false;
|
|
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
|
this: FileHandle,
|
|
...args
|
|
) {
|
|
const result = await originalRead.call(this, ...args);
|
|
const arguments_: readonly unknown[] = args;
|
|
if (!changed && arguments_[3] === 16n && result.bytesRead === 16_384) {
|
|
// Alter only the region observation, leaving both whole-file passes intact.
|
|
if (!Buffer.isBuffer(result.buffer))
|
|
throw new Error("Expected byte buffer");
|
|
result.buffer.writeUInt8(result.buffer.readUInt8(0) ^ 0xff, 0);
|
|
changed = true;
|
|
}
|
|
return result;
|
|
});
|
|
try {
|
|
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
integrityCheck: "reconstruction",
|
|
});
|
|
expect(changed).toBe(true);
|
|
expect((await readFile(path)).equals(bytes)).toBe(true);
|
|
} finally {
|
|
read.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each(["data", "hop", "HOP"])(
|
|
"routes iNES bytes as an archive with a .%s suffix",
|
|
async (suffix) => {
|
|
const root = await createTestTempDirectory("rea-ines-target-");
|
|
const path = join(root, `cartridge.${suffix}`);
|
|
await writeFile(path, inesFixture());
|
|
const target = await parseBinaryTarget(path);
|
|
if (!target.ok) throw target.error;
|
|
expect(target.value).toMatchObject({ kind: "archive", format: "ines" });
|
|
},
|
|
);
|
|
|
|
it("honors explicit database selection before parsing NES-signature bytes", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-database-");
|
|
for (const bytes of [inesFixture(), Buffer.from("NES\x1a")]) {
|
|
const path = join(root, "selected.hop");
|
|
await writeFile(path, bytes);
|
|
expect(
|
|
await parseBinaryTarget(path, { targetKind: "database" }),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: { kind: "database", format: "analysis-database" },
|
|
});
|
|
}
|
|
});
|
|
it("inventories and reconstructs all bytes without trainer or CHR ROM", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-inventory-");
|
|
const path = join(root, "fixture.nes");
|
|
const bytes = inesFixture({
|
|
chrUnits: 0,
|
|
trailing: Buffer.from("retained tail"),
|
|
});
|
|
await writeFile(path, bytes);
|
|
const inventory = await inventoryArtifact(path);
|
|
expect(inventory.ines?.header).toMatchObject({
|
|
header_hex: bytes.subarray(0, 16).toString("hex"),
|
|
mapper: 19,
|
|
trainer_present: false,
|
|
chr_rom_units_8k: 0,
|
|
});
|
|
expect(inventory.ines?.reconstruction).toMatchObject({
|
|
bytes: bytes.length,
|
|
sha256: sha256(bytes),
|
|
verified: true,
|
|
});
|
|
const children = inventory.occurrences.filter(
|
|
({ logical_path }) => logical_path !== ".",
|
|
);
|
|
const ordered = [...children].sort(
|
|
(a, b) =>
|
|
(a.source_location?.offset ?? 0) - (b.source_location?.offset ?? 0),
|
|
);
|
|
const nodes = new Map(
|
|
inventory.nodes.map((node) => [node.artifact_id, node]),
|
|
);
|
|
const headerRegion = children.find(
|
|
({ logical_path }) => logical_path === "header.bin",
|
|
);
|
|
if (
|
|
headerRegion?.artifact_id === undefined ||
|
|
headerRegion.artifact_id === null
|
|
)
|
|
throw new Error("Missing header region");
|
|
expect(nodes.get(headerRegion.artifact_id)?.format).toBe("file");
|
|
let offset = 0;
|
|
for (const occurrence of ordered) {
|
|
const range = occurrence.source_location;
|
|
if (range === null || occurrence.artifact_id === null)
|
|
throw new Error("Missing region identity");
|
|
expect(range.offset).toBe(offset);
|
|
const original = bytes.subarray(range.offset, range.offset + range.length);
|
|
expect(nodes.get(occurrence.artifact_id)).toMatchObject({
|
|
sha256: sha256(original),
|
|
size: range.length,
|
|
});
|
|
offset += range.length;
|
|
}
|
|
expect(offset).toBe(bytes.length);
|
|
expect(inventory.ines?.reconstruction.region_order).toEqual(
|
|
ordered.map(({ logical_path }) => logical_path),
|
|
);
|
|
expect(await inventoryArtifact(path)).toEqual(inventory);
|
|
|
|
const scope = new ArtifactResourceScope();
|
|
const outputRoot = join(root, "extracted");
|
|
try {
|
|
const extraction = await extractArtifact({
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot,
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
resourceScope: scope,
|
|
});
|
|
expect(extraction.artifacts).toHaveLength(children.length);
|
|
const reconstructed = Buffer.concat(
|
|
await Promise.all(
|
|
ordered.map(({ logical_path }) =>
|
|
readFile(join(outputRoot, logical_path)),
|
|
),
|
|
),
|
|
);
|
|
expect(reconstructed.equals(bytes)).toBe(true);
|
|
} finally {
|
|
await scope.close();
|
|
}
|
|
});
|
|
|
|
it("routes, inventories and extracts NES 2.0 regions with miscellaneous ROM bytes", async () => {
|
|
const root = await createTestTempDirectory("rea-nes2-inventory-");
|
|
const path = join(root, "fixture.nes");
|
|
const bytes = nes2Fixture({
|
|
trainer: true,
|
|
// Submapper 2, mapper bits 8..11 = 1, 8 KiB PRG-RAM, one misc ROM.
|
|
header: { 8: 0x21, 10: 0x07, 14: 1 },
|
|
miscRom: Buffer.from("misc rom bytes"),
|
|
});
|
|
await writeFile(path, bytes);
|
|
expect(await parseBinaryTarget(path)).toMatchObject({
|
|
ok: true,
|
|
value: { kind: "archive", format: "ines" },
|
|
});
|
|
const inventory = await inventoryArtifact(path);
|
|
expect(inventory.manifest.root_format).toBe("ines");
|
|
expect(inventory.ines?.header).toMatchObject({
|
|
format: "nes-2.0",
|
|
header_hex: bytes.subarray(0, 16).toString("hex"),
|
|
prg_rom_units_16k: 2,
|
|
chr_rom_bytes: 8_192,
|
|
mapper: 0x113,
|
|
submapper: 2,
|
|
trainer_present: true,
|
|
prg_ram_bytes: 8_192,
|
|
misc_rom_count: 1,
|
|
});
|
|
expect(inventory.ines?.reconstruction).toEqual({
|
|
region_order: [
|
|
"header.bin",
|
|
"trainer.bin",
|
|
"prg/000.bin",
|
|
"prg/001.bin",
|
|
"chr/000.bin",
|
|
"misc-rom.bin",
|
|
],
|
|
bytes: bytes.length,
|
|
sha256: sha256(bytes),
|
|
verified: true,
|
|
});
|
|
const misc = inventory.occurrences.find(
|
|
({ logical_path }) => logical_path === "misc-rom.bin",
|
|
);
|
|
expect(misc?.source_location).toMatchObject({
|
|
offset: bytes.length - 14,
|
|
length: 14,
|
|
});
|
|
|
|
const scope = new ArtifactResourceScope();
|
|
const outputRoot = join(root, "extracted");
|
|
try {
|
|
await extractArtifact({
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot,
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
resourceScope: scope,
|
|
});
|
|
const reconstructed = Buffer.concat(
|
|
await Promise.all(
|
|
(inventory.ines?.reconstruction.region_order ?? []).map((region) =>
|
|
readFile(join(outputRoot, region)),
|
|
),
|
|
),
|
|
);
|
|
expect(reconstructed.equals(bytes)).toBe(true);
|
|
} finally {
|
|
await scope.close();
|
|
}
|
|
});
|
|
|
|
it("extracts an exponent-sized PRG-ROM area beside a counted CHR-ROM area", async () => {
|
|
const root = await createTestTempDirectory("rea-nes2-exponent-");
|
|
const path = join(root, "fixture.nes");
|
|
// Byte 9's PRG nibble 0xf selects the exponent form: 2^10 * (2 * 1 + 1).
|
|
// Its CHR nibble 0 keeps one counted 8 KiB unit.
|
|
const header = Buffer.from([
|
|
0x4e,
|
|
0x45,
|
|
0x53,
|
|
0x1a,
|
|
(10 << 2) | 1,
|
|
1,
|
|
0,
|
|
0x08,
|
|
0,
|
|
0x0f,
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
]);
|
|
const prg = Buffer.from(Array.from({ length: 3_072 }, (_, at) => at % 251));
|
|
const chr = Buffer.from(
|
|
Array.from({ length: 8_192 }, (_, at) => 255 - (at % 241)),
|
|
);
|
|
const bytes = Buffer.concat([header, prg, chr]);
|
|
await writeFile(path, bytes);
|
|
const inventory = await inventoryArtifact(path);
|
|
expect(inventory.ines?.header).toMatchObject({
|
|
format: "nes-2.0",
|
|
prg_rom_bytes: 3_072,
|
|
chr_rom_units_8k: 1,
|
|
chr_rom_bytes: 8_192,
|
|
});
|
|
// An exponent-sized area has no unit count to report.
|
|
expect(inventory.ines?.header).not.toHaveProperty("prg_rom_units_16k");
|
|
expect(inventory.ines?.reconstruction).toEqual({
|
|
region_order: ["header.bin", "prg.bin", "chr/000.bin"],
|
|
bytes: bytes.length,
|
|
sha256: sha256(bytes),
|
|
verified: true,
|
|
});
|
|
const location = (logicalPath: string) =>
|
|
inventory.occurrences.find(
|
|
({ logical_path }) => logical_path === logicalPath,
|
|
)?.source_location;
|
|
expect(location("prg.bin")).toMatchObject({ offset: 16, length: 3_072 });
|
|
expect(location("chr/000.bin")).toMatchObject({
|
|
offset: 16 + 3_072,
|
|
length: 8_192,
|
|
});
|
|
|
|
const scope = new ArtifactResourceScope();
|
|
const outputRoot = join(root, "extracted");
|
|
try {
|
|
await extractArtifact({
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot,
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
resourceScope: scope,
|
|
});
|
|
const [extractedPrg, extractedChr, extractedHeader] = await Promise.all([
|
|
readFile(join(outputRoot, "prg.bin")),
|
|
readFile(join(outputRoot, "chr/000.bin")),
|
|
readFile(join(outputRoot, "header.bin")),
|
|
]);
|
|
expect(extractedPrg.equals(prg)).toBe(true);
|
|
expect(extractedChr.equals(chr)).toBe(true);
|
|
expect(
|
|
Buffer.concat([extractedHeader, extractedPrg, extractedChr]).equals(
|
|
bytes,
|
|
),
|
|
).toBe(true);
|
|
} finally {
|
|
await scope.close();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{
|
|
name: "oversized NES 2.0",
|
|
bytes: () => nes2Fixture({ header: { 9: 0x01 } }),
|
|
reason: "truncated NES 2.0 payload",
|
|
},
|
|
{ name: "UNIF", bytes: () => Buffer.from("UNIF"), reason: "unif" },
|
|
{
|
|
name: "truncated",
|
|
bytes: () => inesFixture().subarray(0, 20),
|
|
reason: "truncated iNES payload",
|
|
},
|
|
])(
|
|
"refuses $name explicitly through both file entry points",
|
|
async ({ bytes, reason }) => {
|
|
const root = await createTestTempDirectory("rea-ines-refusal-");
|
|
const path = join(root, "invalid.nes");
|
|
await writeFile(path, bytes());
|
|
expect(await parseBinaryTarget(path)).toMatchObject({
|
|
ok: false,
|
|
error: { reason: expect.stringContaining(reason) },
|
|
});
|
|
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
|
reason: "format",
|
|
message: expect.stringContaining(reason),
|
|
});
|
|
},
|
|
);
|
|
|
|
it("does not select iNES from a .nes suffix", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-suffix-");
|
|
const path = join(root, "not-a-rom.nes");
|
|
await writeFile(path, "ordinary bytes");
|
|
expect(await parseBinaryTarget(path)).toMatchObject({ ok: false });
|
|
});
|
|
|
|
it("rejects forged region ranges, cancellation and a changed retained source", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-reader-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const handle = await open(path, "r");
|
|
const reader = new InesArtifactReader(path, {
|
|
handle,
|
|
initial: await lstat(path),
|
|
});
|
|
try {
|
|
const iterator = reader.entries()[Symbol.asyncIterator]();
|
|
const first = await iterator.next();
|
|
if (first.done) throw new Error("No header region");
|
|
await expect(
|
|
reader.open({ ...first.value, byteOffset: 16 }),
|
|
).rejects.toMatchObject({ reason: "integrity" });
|
|
await expect(
|
|
reader.open(first.value, AbortSignal.abort()),
|
|
).rejects.toMatchObject({ reason: "cancelled" });
|
|
await writeFile(
|
|
path,
|
|
Buffer.concat([inesFixture(), Buffer.from("changed")]),
|
|
);
|
|
await expect(reader.open(first.value)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
});
|
|
await iterator.return?.();
|
|
await reader.close();
|
|
expect((await handle.stat()).size).toBeGreaterThan(0);
|
|
await expect(reader.open(first.value)).rejects.toMatchObject({
|
|
reason: "unavailable",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
await handle.close();
|
|
}
|
|
});
|
|
|
|
it.each(["before", "during"])(
|
|
"reports source removal %s a region read as integrity failure",
|
|
async (when) => {
|
|
const root = await createTestTempDirectory("rea-ines-removed-source-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const handle = await open(path, "r");
|
|
const reader = new InesArtifactReader(path, {
|
|
handle,
|
|
initial: await handle.stat(),
|
|
});
|
|
try {
|
|
const entries = [];
|
|
for await (const entry of reader.entries()) entries.push(entry);
|
|
const entry = entries[0];
|
|
if (entry === undefined) throw new Error("No header region");
|
|
if (when === "before") {
|
|
await unlink(path);
|
|
await expect(reader.open(entry)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
cause: { code: "ENOENT" },
|
|
});
|
|
} else {
|
|
const stream = await reader.open(entry);
|
|
await unlink(path);
|
|
await expect(
|
|
(async () => {
|
|
for await (const chunk of stream)
|
|
expect(Buffer.isBuffer(chunk)).toBe(true);
|
|
})(),
|
|
).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
cause: { code: "ENOENT" },
|
|
});
|
|
}
|
|
} finally {
|
|
await reader.close();
|
|
await handle.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(["truncated", "overwritten"])(
|
|
"reports a header %s during admission as an integrity failure",
|
|
async (change) => {
|
|
const root = await createTestTempDirectory("rea-ines-header-race-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
// Same-size overwrites are visible only through timestamps. Age the
|
|
// fixture so a rewrite inside one clock tick cannot look unchanged.
|
|
await utimes(path, AGED_FIXTURE_TIME, AGED_FIXTURE_TIME);
|
|
const handle = await open(path, "r");
|
|
const reader = new InesArtifactReader(path, {
|
|
handle,
|
|
initial: await handle.stat(),
|
|
});
|
|
const originalRead = handle.read.bind(handle);
|
|
// Mutate the actual file after pre-read validation, at the read boundary.
|
|
const read = vi
|
|
.spyOn(handle, "read")
|
|
.mockImplementationOnce(async (...args) => {
|
|
const changed =
|
|
change === "truncated"
|
|
? Buffer.alloc(0)
|
|
: Buffer.alloc(inesFixture().length);
|
|
await writeFile(path, changed);
|
|
return originalRead(...args);
|
|
});
|
|
try {
|
|
await expect(
|
|
reader.entries()[Symbol.asyncIterator]().next(),
|
|
).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
});
|
|
} finally {
|
|
read.mockRestore();
|
|
await reader.close();
|
|
await handle.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(["inventory", "target"])(
|
|
"rejects changed iNES prefixes at the %s entry point",
|
|
async (route) => {
|
|
const root = await createTestTempDirectory("rea-ines-classification-race-");
|
|
const path = join(root, "source.nes");
|
|
for (const change of ["truncated", "counts", "signature"] as const) {
|
|
const bytes = inesFixture();
|
|
await writeFile(path, bytes);
|
|
// Same-size rewrites are only observable through timestamps. Linux
|
|
// stamps from a coarse clock, so a rewrite within one tick of creation
|
|
// can keep every stat field; age the fixture so the rewrite is visible.
|
|
await utimes(path, AGED_FIXTURE_TIME, AGED_FIXTURE_TIME);
|
|
const prototype = await fileReadPrototype(path);
|
|
const originalRead = prototype.read;
|
|
const read = vi
|
|
.spyOn(prototype, "read")
|
|
.mockImplementationOnce(async function (this: FileHandle, ...args) {
|
|
read.mockRestore();
|
|
const changed =
|
|
change === "truncated" ? bytes.subarray(0, 16) : Buffer.from(bytes);
|
|
if (change === "counts") changed[4] = 255;
|
|
if (change === "signature") changed.fill(0, 0, 4);
|
|
await writeFile(path, changed);
|
|
return originalRead.call(this, ...args);
|
|
});
|
|
try {
|
|
if (route === "inventory") {
|
|
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
});
|
|
} else {
|
|
expect(await parseBinaryTarget(path)).toMatchObject({
|
|
ok: false,
|
|
error: { reason: expect.stringContaining("changed") },
|
|
});
|
|
}
|
|
} finally {
|
|
read.mockRestore();
|
|
}
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each([1, 2])(
|
|
"reports source loss during inventory root hash pass %i as a changed input",
|
|
async (hashPass) => {
|
|
const root = await createTestTempDirectory("rea-ines-hash-loss-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const originalHash = rootHash.hashStableRootArtifactHandle;
|
|
let observedPasses = 0;
|
|
let faultInjected = false;
|
|
const hash = vi
|
|
.spyOn(rootHash, "hashStableRootArtifactHandle")
|
|
.mockImplementation(async (...args) => {
|
|
observedPasses += 1;
|
|
if (observedPasses !== hashPass) return originalHash(...args);
|
|
const handle = args[1];
|
|
const originalRead = handle.read.bind(handle);
|
|
const read = vi
|
|
.spyOn(handle, "read")
|
|
.mockImplementation(async (...readArgs) => {
|
|
const result = await originalRead(...readArgs);
|
|
if (result.bytesRead === 0) {
|
|
faultInjected = true;
|
|
await unlink(path);
|
|
}
|
|
return result;
|
|
});
|
|
try {
|
|
return await originalHash(...args);
|
|
} finally {
|
|
read.mockRestore();
|
|
}
|
|
});
|
|
try {
|
|
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
cause: { code: "ENOENT" },
|
|
});
|
|
expect(observedPasses).toBe(hashPass);
|
|
expect(faultInjected).toBe(true);
|
|
} finally {
|
|
hash.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("reports source loss during target hashing as a changed input", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-target-hash-loss-");
|
|
const path = join(root, "source.nes");
|
|
const bytes = inesFixture();
|
|
await writeFile(path, bytes);
|
|
const prototype = await fileReadPrototype(path);
|
|
const originalRead = prototype.read;
|
|
let faultInjected = false;
|
|
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
|
this: FileHandle,
|
|
...args
|
|
) {
|
|
const result = await originalRead.call(this, ...args);
|
|
const readArguments: readonly unknown[] = args;
|
|
const [buffer, , , position] = readArguments;
|
|
if (
|
|
Buffer.isBuffer(buffer) &&
|
|
buffer.byteLength === 64 * 1024 &&
|
|
position === bytes.length &&
|
|
result.bytesRead === 0
|
|
) {
|
|
faultInjected = true;
|
|
await unlink(path);
|
|
}
|
|
return result;
|
|
});
|
|
try {
|
|
expect(await parseBinaryTarget(path)).toMatchObject({
|
|
ok: false,
|
|
error: { reason: expect.stringContaining("changed") },
|
|
});
|
|
expect(faultInjected).toBe(true);
|
|
} finally {
|
|
read.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each(["removed", "directory", "malformed"])(
|
|
"rejects a %s source after inventory before extraction",
|
|
async (change) => {
|
|
const root = await createTestTempDirectory("rea-ines-extraction-change-");
|
|
const path = join(root, "source.nes");
|
|
const outputRoot = join(root, "output");
|
|
await writeFile(path, inesFixture());
|
|
const snapshot = await scanArtifactInventory(path);
|
|
await unlink(path);
|
|
if (change === "directory") await mkdir(path);
|
|
if (change === "malformed") await writeFile(path, "changed cartridge");
|
|
await expect(
|
|
materializeArtifactInventory(
|
|
{
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot,
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
},
|
|
path,
|
|
snapshot,
|
|
),
|
|
).rejects.toMatchObject({ reason: "integrity" });
|
|
await expect(lstat(outputRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
"EISDIR",
|
|
"ENOTFILE",
|
|
"ESTALE",
|
|
"EACCES",
|
|
"cancelled",
|
|
...(process.platform === "win32" ? ["changed metadata"] : []),
|
|
])(
|
|
"preserves the %s admission meaning while reopening extraction",
|
|
async (code) => {
|
|
const root = await createTestTempDirectory("rea-ines-reopen-error-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const snapshot = await scanArtifactInventory(path);
|
|
const sample = await open(path, "r");
|
|
const prototype = Object.getPrototypeOf(sample) as Pick<
|
|
typeof sample,
|
|
"stat"
|
|
>;
|
|
await sample.close();
|
|
const originalStat = prototype.stat;
|
|
const controller = new AbortController();
|
|
const stat = vi
|
|
.spyOn(prototype, "stat")
|
|
.mockImplementationOnce(async function (this: FileHandle, ...args) {
|
|
if (code === "changed metadata") {
|
|
const metadata = await originalStat.call(this, ...args);
|
|
// Change the real file between descriptor stat and admission lstat.
|
|
await writeFile(path, "replacement cartridge");
|
|
return metadata;
|
|
}
|
|
if (code !== "cancelled")
|
|
throw Object.assign(new Error("injected admission failure"), {
|
|
code,
|
|
});
|
|
const result = await originalStat.call(this, ...args);
|
|
controller.abort();
|
|
return result;
|
|
});
|
|
try {
|
|
await expect(
|
|
materializeArtifactInventory(
|
|
{
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot: join(root, "output"),
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
},
|
|
path,
|
|
snapshot,
|
|
controller.signal,
|
|
),
|
|
).rejects.toMatchObject(
|
|
code === "EACCES"
|
|
? { code }
|
|
: { reason: code === "cancelled" ? "cancelled" : "integrity" },
|
|
);
|
|
} finally {
|
|
stat.mockRestore();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("retains a failed close after rejecting changed extraction bytes", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-reopen-cleanup-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const snapshot = await scanArtifactInventory(path);
|
|
await writeFile(path, "changed source");
|
|
const scope = new ArtifactResourceScope();
|
|
const originalClose = OwnedFileHandle.prototype.close;
|
|
const owners: OwnedFileHandle[] = [];
|
|
const close = vi
|
|
.spyOn(OwnedFileHandle.prototype, "close")
|
|
.mockImplementation(async function (this: OwnedFileHandle) {
|
|
owners.push(this);
|
|
if (owners.length === 1) throw new Error("injected close failure");
|
|
await originalClose.call(this);
|
|
});
|
|
try {
|
|
await expect(
|
|
materializeInScope(
|
|
{
|
|
inputPath: path,
|
|
inputFormat: "ines",
|
|
outputRoot: join(root, "output"),
|
|
environment: process.env,
|
|
integrityPolicy: "fail",
|
|
resourceScope: scope,
|
|
},
|
|
path,
|
|
snapshot,
|
|
),
|
|
).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
cleanup: { reason: expect.stringContaining("injected close failure") },
|
|
});
|
|
expect(owners).toHaveLength(1);
|
|
await scope.close();
|
|
expect(owners).toHaveLength(2);
|
|
expect(owners[1]).toBe(owners[0]);
|
|
} finally {
|
|
close.mockRestore();
|
|
await scope.close();
|
|
}
|
|
});
|
|
|
|
it("releases an extraction-owned source descriptor on repeated close", async () => {
|
|
const root = await createTestTempDirectory("rea-ines-owned-source-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const handle = await open(path, "r");
|
|
const owner = new OwnedFileHandle(handle);
|
|
const reader = new InesArtifactReader(
|
|
path,
|
|
{ handle, initial: await handle.stat() },
|
|
owner,
|
|
);
|
|
try {
|
|
await reader.close();
|
|
await expect(handle.stat()).rejects.toMatchObject({ code: "EBADF" });
|
|
await reader.close();
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it.each(["target", "inventory", "reader"])(
|
|
"fills short iNES prefix reads at the %s boundary",
|
|
async (route) => {
|
|
const root = await createTestTempDirectory("rea-ines-short-read-");
|
|
const path = join(root, "source.nes");
|
|
await writeFile(path, inesFixture());
|
|
const sample = await open(path, "r");
|
|
const initial = await sample.stat();
|
|
const prototype = Object.getPrototypeOf(sample) as {
|
|
read(
|
|
buffer: Buffer,
|
|
offset: number,
|
|
length: number,
|
|
position: number | bigint,
|
|
): Promise<{ bytesRead: number; buffer: Buffer }>;
|
|
};
|
|
const originalRead = prototype.read;
|
|
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
|
this: FileHandle,
|
|
...args
|
|
) {
|
|
const [buffer, offset, length, position] = args;
|
|
return originalRead.call(
|
|
this,
|
|
buffer,
|
|
offset,
|
|
typeof position === "number" && position < 16
|
|
? Math.min(length, 3)
|
|
: length,
|
|
position,
|
|
);
|
|
});
|
|
try {
|
|
if (route === "target") {
|
|
expect(await parseBinaryTarget(path)).toMatchObject({
|
|
ok: true,
|
|
value: { format: "ines" },
|
|
});
|
|
} else if (route === "inventory") {
|
|
expect(
|
|
(await inventoryArtifact(path)).ines?.reconstruction.verified,
|
|
).toBe(true);
|
|
} else {
|
|
const reader = new InesArtifactReader(path, {
|
|
handle: sample,
|
|
initial,
|
|
});
|
|
try {
|
|
const entries = [];
|
|
for await (const entry of reader.entries()) entries.push(entry.path);
|
|
expect(entries).toContain("prg/000.bin");
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
}
|
|
} finally {
|
|
read.mockRestore();
|
|
await sample.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(["eof", "cancelled"])(
|
|
"preserves %s while filling a short prefix",
|
|
async (mode) => {
|
|
const root = await createTestTempDirectory("rea-prefix-boundary-");
|
|
const path = join(root, "source");
|
|
const bytes = Buffer.from(
|
|
mode === "eof" ? "NES\x1a" : "NES\x1a123456789012",
|
|
);
|
|
await writeFile(path, bytes);
|
|
const handle = await open(path, "r");
|
|
const prototype = Object.getPrototypeOf(handle) as {
|
|
read(
|
|
buffer: Buffer,
|
|
offset: number,
|
|
length: number,
|
|
position: number,
|
|
): Promise<{ bytesRead: number; buffer: Buffer }>;
|
|
};
|
|
const original = prototype.read;
|
|
const controller = new AbortController();
|
|
let reads = 0;
|
|
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
|
this: typeof handle,
|
|
buffer,
|
|
offset,
|
|
length,
|
|
position,
|
|
) {
|
|
reads++;
|
|
const observed = await original.call(
|
|
this,
|
|
buffer,
|
|
offset,
|
|
Math.min(length, 3),
|
|
position,
|
|
);
|
|
if (reads === 2 && mode === "cancelled") controller.abort();
|
|
return observed;
|
|
});
|
|
try {
|
|
const result = readFileHandlePrefix(handle, 16, () =>
|
|
abortIfNeeded(controller.signal),
|
|
);
|
|
if (mode === "eof") {
|
|
expect((await result).equals(bytes)).toBe(true);
|
|
expect(reads).toBe(3);
|
|
} else {
|
|
await expect(result).rejects.toMatchObject({ reason: "cancelled" });
|
|
expect(reads).toBe(2);
|
|
}
|
|
} finally {
|
|
read.mockRestore();
|
|
await handle.close();
|
|
}
|
|
},
|
|
);
|