mirror of
https://github.com/morluto/rea.git
synced 2026-12-05 14:31:22 +00:00
* feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
498 lines
17 KiB
TypeScript
498 lines
17 KiB
TypeScript
import type { Stats } from "node:fs";
|
|
import type { FileHandle } from "node:fs/promises";
|
|
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
|
|
import { parseJsonWithDuplicatePolicy } from "../domain/jsonDuplicateMember.js";
|
|
import { retainRoundedAsarSize } from "../domain/asarNode.js";
|
|
|
|
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
|
|
import {
|
|
ArtifactReaderFailure,
|
|
malformedArtifact,
|
|
truncatedArtifact,
|
|
} from "./ArtifactReader.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import {
|
|
ASAR_HEADER_ADMISSION_SETTING,
|
|
DEFAULT_ASAR_HEADER_ADMISSION,
|
|
parseAsarHeaderAdmission,
|
|
type AsarHeaderAdmission,
|
|
} from "../config/asarHeaderAdmission.js";
|
|
import {
|
|
DEFAULT_ASAR_MAX_HEADER_BYTES,
|
|
MAXIMUM_ASAR_MAX_HEADER_BYTES,
|
|
} from "../domain/analysisResourceLimits.js";
|
|
import { parseAsarListingAdmission } from "../config/asarListingAdmission.js";
|
|
import { strictUtf8Decoder } from "../domain/strictUtf8.js";
|
|
import { BinaryReader } from "../domain/binaryContainer.js";
|
|
|
|
/**
|
|
* Resolve the admission from a composition root's selected environment; an
|
|
* invalid setting is refused, not ignored. Callers without an environment use
|
|
* the default.
|
|
*/
|
|
export const resolveAsarHeaderAdmission = (
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
): AsarHeaderAdmission => {
|
|
const parsed = parseAsarHeaderAdmission(
|
|
environment[ASAR_HEADER_ADMISSION_SETTING],
|
|
);
|
|
if (!parsed.ok) throw parsed.error;
|
|
const listing = parseAsarListingAdmission(
|
|
environment.REA_ASAR_MAX_LISTING_BYTES,
|
|
);
|
|
if (!listing.ok) throw listing.error;
|
|
return { ...parsed.value, listing: listing.value };
|
|
};
|
|
|
|
const MEBIBYTE = 1024 * 1024;
|
|
|
|
const byteAllowance = (bytes: number): string => {
|
|
const mebibytes = bytes / MEBIBYTE;
|
|
return Number.isInteger(mebibytes)
|
|
? `${String(mebibytes)} MiB / ${String(bytes)} bytes`
|
|
: `${String(bytes)} bytes`;
|
|
};
|
|
|
|
/** User-visible recovery for the effective ASAR header/index admission budget. */
|
|
export const asarHeaderAdmissionRecovery = (
|
|
admission: AsarHeaderAdmission,
|
|
): string =>
|
|
[
|
|
`ASAR header/index admission is limited to ${byteAllowance(admission.maximumBytes)}${admission.source === "setting" ? ` by ${ASAR_HEADER_ADMISSION_SETTING}` : ""}.`,
|
|
`On MCP, call update_analysis_settings with setting asar.max_header_bytes, action set, and a value in bytes up to ${byteAllowance(MAXIMUM_ASAR_MAX_HEADER_BYTES)} (default ${byteAllowance(DEFAULT_ASAR_MAX_HEADER_BYTES)}), then retry the original request. It applies to the next operation without restarting REA. For CLI or future REA processes, set ${ASAR_HEADER_ADMISSION_SETTING} in the launch environment.`,
|
|
"Selecting fewer sources or narrowing an internal path does not bypass header admission, because the archive index is read before any member can be selected.",
|
|
"Raising max_heap_mb or available host memory does not raise it.",
|
|
"Alternatively, analyze an extracted application directory, which does not admit an ASAR header.",
|
|
"Repeating the unchanged request fails the same way.",
|
|
].join(" ");
|
|
|
|
/** Refuse an ASAR whose header/index exceeds the effective admission budget. */
|
|
export const asarHeaderAdmissionFailure = (
|
|
admission: AsarHeaderAdmission,
|
|
requiredBytes?: number,
|
|
): ArtifactReaderFailure =>
|
|
new ArtifactReaderFailure("limit", asarHeaderAdmissionRecovery(admission), {
|
|
admission: {
|
|
kind: "asar-header",
|
|
...admission,
|
|
...(requiredBytes === undefined ? {} : { requiredBytes }),
|
|
},
|
|
});
|
|
|
|
/** Absolute archive prefix required to inspect a header under this admission. */
|
|
const asarHeaderProbeBytes = (admission: AsarHeaderAdmission): number =>
|
|
admission.maximumBytes + 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 admission: AsarHeaderAdmission;
|
|
}
|
|
| {
|
|
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;
|
|
readonly admission: AsarHeaderAdmission;
|
|
};
|
|
|
|
export type FinalAsarHeaderProbeObservation = Exclude<
|
|
AsarHeaderProbeObservation,
|
|
{ readonly state: "pending" }
|
|
>;
|
|
|
|
/** Why a fixed two-Pickle prefix does not establish ASAR header extents. */
|
|
const ASAR_EXTENT_REFUSALS = {
|
|
truncated: () =>
|
|
truncatedArtifact("asar", "Truncated ASAR Pickle extent prefix", {
|
|
offset: 0,
|
|
field: "pickle-prefix",
|
|
}),
|
|
"invalid-pickle-extents": () =>
|
|
malformedArtifact("asar", "ASAR header has invalid Pickle extents", {
|
|
offset: 0,
|
|
field: "pickle-prefix",
|
|
}),
|
|
"leaves-container": () =>
|
|
truncatedArtifact("asar", "ASAR header leaves its observed container", {
|
|
offset: 8,
|
|
field: "header",
|
|
}),
|
|
} as const satisfies Record<string, () => ArtifactReaderFailure>;
|
|
type AsarExtentRefusal = keyof typeof ASAR_EXTENT_REFUSALS;
|
|
|
|
/**
|
|
* 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.
|
|
* Refusals are plain tags: the signature probe refuses most streams it sees.
|
|
*/
|
|
const parseAsarHeaderExtents = (
|
|
prefix: Uint8Array,
|
|
archiveBytes?: number,
|
|
): Result<Omit<AsarHeaderExtents, "archiveBytes">, AsarExtentRefusal> => {
|
|
if (prefix.byteLength < 16) return err("truncated");
|
|
const reader = new BinaryReader(
|
|
Buffer.from(prefix.buffer, prefix.byteOffset, 16),
|
|
true,
|
|
"asar",
|
|
);
|
|
const headerBytes = reader.u32(4);
|
|
const payloadBytes = reader.u32(8);
|
|
const jsonBytes = reader.u32(12);
|
|
if (
|
|
reader.u32(0) !== 4 ||
|
|
headerBytes < 8 ||
|
|
payloadBytes !== headerBytes - 4 ||
|
|
jsonBytes > payloadBytes - 4
|
|
)
|
|
return err("invalid-pickle-extents");
|
|
if (
|
|
archiveBytes !== undefined &&
|
|
(!Number.isSafeInteger(archiveBytes) ||
|
|
archiveBytes < 8 ||
|
|
headerBytes > archiveBytes - 8)
|
|
)
|
|
return err("leaves-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 admission: AsarHeaderAdmission;
|
|
readonly limit: number;
|
|
readonly observation: AsarHeaderProbeObservation;
|
|
write(input: Uint8Array): AsarHeaderProbeObservation;
|
|
finish(archiveBytes: number): FinalAsarHeaderProbeObservation;
|
|
}
|
|
|
|
class AsarHeaderSignatureProbeImpl implements AsarHeaderSignatureProbe {
|
|
readonly limit: number;
|
|
readonly #fixed = Buffer.alloc(16);
|
|
#fixedBytes = 0;
|
|
// not-an-allowance: scan position in the JSON header; reaching the probe limit stops the probe, it charges nothing.
|
|
#scannedJsonBytes = 0;
|
|
#extents: Omit<AsarHeaderExtents, "archiveBytes"> | undefined;
|
|
#stop: ProbeStop = { state: "pending" };
|
|
|
|
constructor(readonly admission: AsarHeaderAdmission) {
|
|
this.limit = asarHeaderProbeBytes(admission);
|
|
}
|
|
|
|
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 > this.admission.maximumBytes &&
|
|
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,
|
|
admission: this.admission,
|
|
};
|
|
case "matched":
|
|
return {
|
|
state: "matched",
|
|
extents:
|
|
archiveBytes === undefined
|
|
? this.#stop.extents
|
|
: { archiveBytes, ...this.#stop.extents },
|
|
signatureOffset: this.#stop.signatureOffset,
|
|
scannedJsonBytes: this.#scannedJsonBytes,
|
|
admission: this.admission,
|
|
};
|
|
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,
|
|
admission: this.admission,
|
|
};
|
|
}
|
|
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,
|
|
admission: AsarHeaderAdmission = DEFAULT_ASAR_HEADER_ADMISSION,
|
|
): Promise<AsarHeaderExtents> => {
|
|
assertArtifactReadActive(signal);
|
|
const observed = await handle.stat();
|
|
assertArtifactReadActive(signal);
|
|
if (!observed.isFile())
|
|
throw new ArtifactReaderFailure(
|
|
"path",
|
|
"ASAR container is not a regular file",
|
|
);
|
|
const prefix = await readFileHandleRange(handle, 0, 16, () =>
|
|
assertArtifactReadActive(signal),
|
|
);
|
|
assertArtifactReadActive(signal);
|
|
if (prefix.length !== 16)
|
|
throw observed.size < 16
|
|
? truncatedArtifact("asar", "Truncated ASAR size pickle", {
|
|
offset: 0,
|
|
field: "pickle-prefix",
|
|
})
|
|
: new ArtifactReaderFailure(
|
|
"integrity",
|
|
"ASAR size pickle read ended before the measured file size",
|
|
{ integrityCheck: "read-coverage" },
|
|
);
|
|
const parsed = parseAsarHeaderExtents(prefix, observed.size);
|
|
if (!parsed.ok) throw ASAR_EXTENT_REFUSALS[parsed.error]();
|
|
if (parsed.value.headerBytes > admission.maximumBytes)
|
|
throw asarHeaderAdmissionFailure(admission, parsed.value.headerBytes);
|
|
return {
|
|
archiveBytes: observed.size,
|
|
...parsed.value,
|
|
};
|
|
};
|
|
|
|
export const createAsarHeaderSignatureProbe = (
|
|
admission: AsarHeaderAdmission = DEFAULT_ASAR_HEADER_ADMISSION,
|
|
): AsarHeaderSignatureProbe => new AsarHeaderSignatureProbeImpl(admission);
|
|
|
|
/** Decode only admitted JSON bytes from the same owned descriptor as its extents. */
|
|
export const readAsarHeader = async (
|
|
handle: Pick<FileHandle, "read">,
|
|
extents: AsarHeaderExtents,
|
|
signal?: AbortSignal,
|
|
): Promise<unknown> => {
|
|
const bytes = await readFileHandleRange(handle, 16, extents.jsonBytes, () =>
|
|
assertArtifactReadActive(signal),
|
|
);
|
|
assertArtifactReadActive(signal);
|
|
if (bytes.length !== extents.jsonBytes)
|
|
// The extents were checked against the measured size, so a short read
|
|
// means the file changed underneath the read.
|
|
throw new ArtifactReaderFailure(
|
|
"integrity",
|
|
"ASAR JSON header read ended before its admitted extent",
|
|
{ integrityCheck: "read-coverage" },
|
|
);
|
|
let json: string;
|
|
try {
|
|
json = strictUtf8Decoder("preserve").decode(bytes);
|
|
} catch (cause: unknown) {
|
|
throw malformedArtifact("asar", "ASAR JSON header is not valid UTF-8", {
|
|
cause,
|
|
offset: 16,
|
|
field: "header",
|
|
});
|
|
}
|
|
const parsed = parseJsonWithDuplicatePolicy(json, "reject", {
|
|
name: "size",
|
|
read: retainRoundedAsarSize,
|
|
});
|
|
if (!parsed.ok) {
|
|
if (parsed.duplicate !== undefined)
|
|
throw malformedArtifact(
|
|
"asar",
|
|
`ASAR JSON header declares member ${JSON.stringify(parsed.duplicate.name)} more than once in one object (offset ${String(parsed.duplicate.offset)})`,
|
|
);
|
|
throw malformedArtifact("asar", "ASAR JSON header is not valid JSON", {
|
|
cause: parsed.cause,
|
|
offset: 16,
|
|
field: "header",
|
|
});
|
|
}
|
|
return parsed.value;
|
|
};
|