mirror of
https://github.com/morluto/rea.git
synced 2026-11-17 04:04:25 +00:00
* fix(native): keep unreported value-flow truncation and archive decode coverage unknown * test(verify): count multiline optional-fact defaults and pin the guard's exclusions * fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries (#11325) * fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries * refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker (#11355) * refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker The optional-fact-default guard counted request defaults and absence that is modelled elsewhere as hidden unknowns. A comment `// optional-fact-default: <reason>` on the default's line or the line before now exempts it; the guard reads unstripped source for the marker and ignores matches inside comment lines. Marked: the two evidence paging offsets and four Swift literal reads whose absence swiftLiteralCoverage reports. Removed instead of marked: jsdiff 9 types Change.count as required, so its two `?? 0` defaults were dead; the evidence link traversal now carries retained records, so it no longer re-looks them up behind `?? []`. Baseline 31 -> 22. * fix(verify): blank comment spans instead of skipping comment-led lines in the optional-fact guard Skipping a match whose line starts like a comment hid live code after a leading block comment and counted defaults inside a block comment without leading stars. The counter now blanks comment text (keeping offsets and line breaks, skipping string literals) and matches the blanked code, while exemption markers are still read from the original lines. * refactor(domain): mark optional-fact defaults whose absence is not an observation (#11389) * refactor(domain): mark optional-fact defaults whose absence is not an observation Per-site review of the remaining optional-fact-default entries. Each marked default is a caller option (trace ignore_fields, environment rules), a list whose producer omits the empty case (unknown_size_frames, the schema's min-1 representation_node_ids), caveat text whose completeness another field carries (call diagnostics, unresolved calls, semantic resource limits), or absence that already turns the result unknown (Wasm interface inventory, WebMCP discovery, managed ExportedType rows, legacy integrity mismatch IDs). Left counted: webCaptureDiff redirects (2; the CDP producer always records them, so absence is a legacy record that should compare as unknown, not as no redirects) and HopperCallerReconciliation (2; index-miss semantics not yet verified). Baseline 22 -> 4. * fix(browser): compare redirects as unknown when a capture predates redirect recording (#11402) * fix(browser): compare redirects as unknown when a capture predates redirect recording The CDP producer records every request's redirect chain, empty when there was none; a record without one predates redirect recording (#986). Comparing it against a current capture reported the network dimension as unchanged, treating the missing chain as "no redirects". Redirects are now compared only when both captures recorded them, and the network dimension is otherwise unknown with a reason; proven membership changes are still reported. * refactor(hopper): interpret a caller-index miss once at the lookup (#11403) The forward index holds observations from the examined procedures only, and relationship coverage stays unknown with the scan facts as its reason. A miss therefore adds no callers without showing there are none; the lookup now says so once instead of four optional reads defaulting at each site. The optional-fact-default baseline is now empty. * docs(javascript): state why an omitted representation list adds no nodes * fix(verify): count optional-fact defaults from parsed TypeScript, not comment-blanked text The guard blanked comments with a hand-written scanner and matched a regular expression on the rest, so a default quoted in a string counted and a regular expression holding /* hid the code after it. It now walks the TypeScript syntax tree for property reads defaulted with ?? 0, ?? [] or ?? false, and reads exemption markers only from comment trivia. * fix(verify): tokenize optional-fact defaults without a compiler and count chained defaults * fix(verify): match whole optional-fact default expressions across calls and operators * fix(verify): count optional-fact defaults in template substitutions and after postfix updates, and tie markers to their own expression * refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker (#11454) * refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker * fix(verify): read reason markers only from real line comments * fix(verify): read reason markers from the shared source tokenizer * fix(verify): read a regular expression after a control head as a statement start The shared tokenizer treated every closing parenthesis as the end of an operand, so in `if (ready) /[/*]/.test(v)` it read `/[` as division and `/*` inside the regex as a block comment, hiding the rest of the file from the marker-aware guards. Parentheses are now tracked: the `)` closing an if/while/for/with head allows a regular expression, while a call's `)` still means division. * fix(verify): keep a keyword-named member call out of control-head detection `policy.if(ready) / (…)` was read as an if-statement head, so the division was taken for a regular expression and the denominator's optional-fact default was not counted. A control keyword after `.` or `?.` is a member call. * refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker (#11493) * refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker The budget-arithmetic guard cannot tell a scan cursor, an observed total, a string being assembled or a tail buffer's retained length from an allowance when each is compared with a limit. A field declaration marked `// not-an-allowance: <reason>` (read through the shared reason-marker scan) is no longer counted. The four remaining sites carry a marker, so the baseline is empty and removed. * refactor(verify): exempt detail levels, lifecycle states and domain vocabularies from the completeness-enum guard by reason marker (#11510) A zod enum containing "complete" is counted as a local coverage vocabulary. Eleven are not coverage: a caller-chosen detail level, how far a command or session ran, and format states (GPU decode depth, WASM name section, SQLite column details). They now carry `// detail-level:`, `// lifecycle-state:` or `// domain-vocabulary:` with a reason, read through the shared reason-marker scan (which gains an optional predicate for the matches a guard counts). local-completeness-enum: 22 -> 11 on this branch. * fix(verify): bind a not-an-allowance marker to its own class field Exemptions were a file-wide set of names, so a marked tally in one class hid an unmarked allowance with the same name in another, and a marked object property could exempt a class field. Markers now exempt only a member declaration (at class member depth) of the top-level class that contains it, and the named- allowance count is taken per class so the same scoping applies to it. * fix(artifacts): keep main's resources import in the Deno standalone reader after merging main * fix(verify): start an expression after a template substitution and a non-member keyword, and accept any marker reason The shared tokenizer read the `/` after `${` as division, so a regular expression holding `/*` in a substitution hid the rest of the file from every tokenizer-based guard, and it treated property names such as `row.return` as keywords. Tokens now record whether template text opens a substitution and whether a name is an expression keyword (not after `.` or `?.`), and the regular-expression rule and the optional-fact-default operand rule read those facts. The optional-fact-default guard reads markers through reason-marker's isReasonMarker, so any non-empty reason exempts, as for the other reason markers. * fix(verify): blank comments with the shared tokenizer before matching architecture guards (#11573) * fix(verify): blank comments with the shared tokenizer before matching architecture guards The guards stripped comments with a regular expression that took a `/*` inside a string, template or regular expression for a comment opener and deleted code up to the next `*/`. src/flutter/FlutterBuildProvider.ts's "lib/*/libapp.so" text hid four --pool-policy remediation strings from cli-option-text-outside-cli. blankComments in source-tokens.mjs now owns comment removal for the architecture guards and the reason-marker scan: it blanks comment tokens in place (newlines kept) and keeps strings, templates and regular expressions. The scan behind it retains only the last tokens it reads, and whitespace runs are skipped at once. The cli-option-text-outside-cli baseline records FlutterBuildProvider.ts at its true count of 4; no other baseline changed. Fixes #11477 * fix(verify): read a regular expression after a statement block and keep comment offsets for wide characters The tokenizer now records whether each `{` opens a statement block or an object literal (from the token before it) and marks the `}` that closes a block, after which a statement, and so a regular expression, can start; an object literal's `}` still ends an operand. blankComments replaces each run of comment text with one space per UTF-16 unit, so a surrogate pair no longer shifts later offsets. * chore(verify): drop the Flutter CLI-text baseline entry now that main names no option there
467 lines
16 KiB
TypeScript
467 lines
16 KiB
TypeScript
import type { Stats } from "node:fs";
|
|
import type { FileHandle } from "node:fs/promises";
|
|
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
|
|
import { findDuplicateJsonMember } from "../domain/jsonDuplicateMember.js";
|
|
|
|
import { assertArtifactReadActive } from "./ArtifactFileOperation.js";
|
|
import { ArtifactReaderFailure } 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";
|
|
|
|
/**
|
|
* 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 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" }
|
|
>;
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
const parseAsarHeaderExtents = (
|
|
prefix: Uint8Array,
|
|
archiveBytes?: number,
|
|
): Result<Omit<AsarHeaderExtents, "archiveBytes">, ArtifactReaderFailure> => {
|
|
if (prefix.byteLength < 16)
|
|
return err(
|
|
new ArtifactReaderFailure(
|
|
"format",
|
|
"Truncated ASAR Pickle extent prefix",
|
|
),
|
|
);
|
|
const bytes = Buffer.from(prefix.buffer, prefix.byteOffset, 16);
|
|
const headerBytes = bytes.readUInt32LE(4);
|
|
const payloadBytes = bytes.readUInt32LE(8);
|
|
const jsonBytes = bytes.readUInt32LE(12);
|
|
if (
|
|
bytes.readUInt32LE(0) !== 4 ||
|
|
headerBytes < 8 ||
|
|
payloadBytes !== headerBytes - 4 ||
|
|
jsonBytes > payloadBytes - 4
|
|
)
|
|
return err(
|
|
new ArtifactReaderFailure(
|
|
"format",
|
|
"ASAR header has invalid Pickle extents",
|
|
),
|
|
);
|
|
if (
|
|
archiveBytes !== undefined &&
|
|
(!Number.isSafeInteger(archiveBytes) ||
|
|
archiveBytes < 8 ||
|
|
headerBytes > archiveBytes - 8)
|
|
)
|
|
return err(
|
|
new ArtifactReaderFailure(
|
|
"format",
|
|
"ASAR header leaves its observed container",
|
|
),
|
|
);
|
|
return ok({ headerBytes, jsonBytes });
|
|
};
|
|
|
|
/**
|
|
* Bounded ASAR signature probe. It retains only the 16-byte fixed prefix and
|
|
* scans the declared JSON bytes until the first non-JSON-whitespace byte.
|
|
*/
|
|
export interface AsarHeaderSignatureProbe {
|
|
readonly 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,
|
|
};
|
|
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(
|
|
"format",
|
|
"ASAR container is not a regular file",
|
|
);
|
|
const prefix = await readFileHandleRange(handle, 0, 16, () =>
|
|
assertArtifactReadActive(signal),
|
|
);
|
|
assertArtifactReadActive(signal);
|
|
if (prefix.length !== 16)
|
|
throw new ArtifactReaderFailure("format", "Truncated ASAR size pickle");
|
|
const parsed = parseAsarHeaderExtents(prefix, observed.size);
|
|
if (!parsed.ok) throw 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)
|
|
throw new ArtifactReaderFailure("format", "Truncated ASAR JSON header");
|
|
let json: string;
|
|
try {
|
|
json = strictUtf8Decoder("preserve").decode(bytes);
|
|
} catch (cause: unknown) {
|
|
throw new ArtifactReaderFailure(
|
|
"format",
|
|
"ASAR JSON header is not valid UTF-8",
|
|
{ cause },
|
|
);
|
|
}
|
|
const header = JSON.parse(json) as unknown;
|
|
rejectDuplicateAsarHeaderMembers(json);
|
|
return header;
|
|
};
|
|
|
|
/**
|
|
* `JSON.parse` keeps only the last of repeated member names, so a second
|
|
* declaration of a path would hide the first from the listing while coverage
|
|
* still read as complete. Treat a repeated name as a malformed index, like the
|
|
* unsafe path components the listing already refuses.
|
|
*/
|
|
const rejectDuplicateAsarHeaderMembers = (json: string): void => {
|
|
const duplicate = findDuplicateJsonMember(json);
|
|
if (duplicate !== undefined)
|
|
throw new ArtifactReaderFailure(
|
|
"format",
|
|
`ASAR JSON header declares member ${JSON.stringify(duplicate.name)} more than once in one object (offset ${String(duplicate.offset)})`,
|
|
);
|
|
};
|