Files
reverse-engineering-anything/src/artifacts/nodeSea/NodeSeaBlob.ts
T
6f267022ed fix(errors)!: raise container reader byte faults as malformed or truncated targets (#14265)
* 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>
2026-11-24 21:17:43 -05:00

422 lines
14 KiB
TypeScript

import { setImmediate } from "node:timers/promises";
import {
assertArtifactReadActive,
ArtifactReaderFailure,
malformedArtifact,
truncatedArtifact,
artifactReaderLimitFailure,
} from "../../resources/index.js";
import {
DEFAULT_NODE_SEA_READER_LIMITS,
type NodeSeaReaderLimits,
} from "../../domain/artifactReaderLimits.js";
import { BinaryReader } from "../../domain/binaryContainer.js";
import type { NodeSeaMainCodeFormat } from "../../domain/formatMetadata/packageAndGameMetadata.js";
import { hostRangeErrorKind } from "../../domain/parseFailure.js";
import { strictUtf8Decoder } from "../../domain/strictUtf8.js";
/** Node `SeaBlob::kMagic` from `src/node_sea.h` (v24). */
const NODE_SEA_MAGIC = 0x143da20;
const SIZE_BYTES = 8;
const MIN_ASSET_ROW_BYTES = 2 * SIZE_BYTES;
const FLAG_DISABLE_EXPERIMENTAL_SEA_WARNING = 1 << 0;
const FLAG_USE_SNAPSHOT = 1 << 1;
const FLAG_USE_CODE_CACHE = 1 << 2;
const FLAG_INCLUDE_ASSETS = 1 << 3;
const FLAG_INCLUDE_EXEC_ARGV = 1 << 4;
const KNOWN_FLAGS =
FLAG_DISABLE_EXPERIMENTAL_SEA_WARNING |
FLAG_USE_SNAPSHOT |
FLAG_USE_CODE_CACHE |
FLAG_INCLUDE_ASSETS |
FLAG_INCLUDE_EXEC_ARGV;
const NODE_SEA_BAD_MAGIC = "Node SEA blob magic is not 0x143da20";
export const NODE_SEA_TRUNCATED = "Node SEA blob is truncated";
const NODE_SEA_UNKNOWN_FLAGS = "Node SEA blob flags contain unknown bits";
const NODE_SEA_UNKNOWN_EXTENSION = "Node SEA exec argv extension is unknown";
const NODE_SEA_TRAILING_BYTES = "Node SEA blob has trailing bytes";
export const NODE_SEA_DUPLICATE_BLOB =
"Node SEA blob is declared more than once";
export const NODE_SEA_ELF_DESCRIPTOR_TRUNCATED =
"Node SEA ELF note descriptor is truncated";
export const NODE_SEA_ELF_TABLE_TRUNCATED =
"Node SEA ELF note table is truncated";
export const NODE_SEA_ELF_NOTES_REPEATED =
"Node SEA ELF note tables declare more notes than the file holds";
export const NODE_SEA_MACHO_COMMANDS_TRUNCATED =
"Node SEA Mach-O load commands are truncated";
export const NODE_SEA_MACHO_SEGMENT_TRUNCATED =
"Node SEA Mach-O segment table is truncated";
const NODE_SEA_FUSE_ABSENT =
"Node SEA blob is present but no NODE_SEA_FUSE sentinel was observed";
const NODE_SEA_FUSE_UNSET =
"Node SEA blob is present but the NODE_SEA_FUSE sentinel is unset";
const NODE_SEA_FUSE_CONFLICT = "Node SEA fuse sentinels disagree";
const NODE_SEA_EMPTY_CODE_PATH = "Node SEA code path is empty";
const NODE_SEA_INVALID_UTF8 = "Node SEA string is not valid UTF-8";
const FUSE_PREFIX = "NODE_SEA_FUSE_";
export interface NodeSeaByteRange {
readonly offset: number;
readonly length: number;
}
export interface NodeSeaAsset {
readonly name: string;
readonly range: NodeSeaByteRange;
}
export type NodeSeaExecArgvExtension = "none" | "env" | "cli";
/** Decoded SEA blob. Ranges are relative to the start of the blob. */
export interface DecodedNodeSeaBlob {
readonly magic: typeof NODE_SEA_MAGIC;
readonly flags: number;
readonly disableExperimentalSeaWarning: boolean;
readonly useSnapshot: boolean;
readonly useCodeCache: boolean;
readonly includeAssets: boolean;
readonly includeExecArgv: boolean;
readonly execArgvExtension: NodeSeaExecArgvExtension;
readonly mainCodeFormat?: NodeSeaMainCodeFormat;
readonly codePath: string;
readonly mainScript: NodeSeaByteRange | null;
readonly snapshot: NodeSeaByteRange | null;
readonly codeCache: NodeSeaByteRange | null;
readonly assets: readonly NodeSeaAsset[];
readonly execArgv: readonly string[];
}
export interface NodeSeaFuseObservation {
readonly fuseState: "set" | "unset" | "absent" | "conflicting";
readonly fuseSentinel: string | null;
readonly fuseContradiction: string | null;
}
const formatFailure = (
message: string,
cause?: unknown,
): ArtifactReaderFailure =>
malformedArtifact("node-sea", message, cause === undefined ? {} : { cause });
const truncatedFailure = (message: string): ArtifactReaderFailure =>
truncatedArtifact("node-sea", message);
/**
* Decode either SEA layout with an exec-argv extension byte.
* Lengths are 64-bit little-endian `size_t` values. Trailing zero padding is
* admitted; any other trailing byte fails closed. 32-bit `size_t` producers
* are outside this reader.
*/
export const decodeNodeSeaBlob = async (
bytes: Buffer,
signal?: AbortSignal,
limits: NodeSeaReaderLimits = DEFAULT_NODE_SEA_READER_LIMITS,
): Promise<DecodedNodeSeaBlob> => {
assertArtifactReadActive(signal);
if (bytes.length > limits.blob_bytes)
throw artifactReaderLimitFailure(
"artifact_limits.node_sea.blob_bytes",
limits.blob_bytes,
"bytes",
bytes.length,
"memory",
);
const cursor = new BlobCursor(bytes, limits);
if (cursor.remaining < 4) throw truncatedFailure(NODE_SEA_TRUNCATED);
const magic = cursor.u32();
if (magic !== NODE_SEA_MAGIC) throw formatFailure(NODE_SEA_BAD_MAGIC);
if (cursor.remaining < 5) throw truncatedFailure(NODE_SEA_TRUNCATED);
const flags = cursor.u32();
if ((flags & ~KNOWN_FLAGS) !== 0) throw formatFailure(NODE_SEA_UNKNOWN_FLAGS);
const execArgvExtension = extensionName(cursor.u8());
const mainCodeFormat = cursor.mainCodeFormat();
const useSnapshot = (flags & FLAG_USE_SNAPSHOT) !== 0;
const useCodeCache = (flags & FLAG_USE_CODE_CACHE) !== 0;
const includeAssets = (flags & FLAG_INCLUDE_ASSETS) !== 0;
const includeExecArgv = (flags & FLAG_INCLUDE_EXEC_ARGV) !== 0;
const argumentHeaderBytes = includeExecArgv ? SIZE_BYTES : 0;
const collectionHeaderBytes =
(includeAssets ? SIZE_BYTES : 0) + argumentHeaderBytes;
const afterBody = (useCodeCache ? SIZE_BYTES : 0) + collectionHeaderBytes;
const codePath = cursor.text(
false,
NODE_SEA_EMPTY_CODE_PATH,
SIZE_BYTES + afterBody,
);
if (codePath.startsWith("\0"))
throw formatFailure("Node SEA code path begins with a NUL byte");
const body = cursor.byteRange(afterBody);
const codeCache = useCodeCache
? cursor.byteRange(collectionHeaderBytes)
: null;
const assets = includeAssets
? await cursor.assets(argumentHeaderBytes, signal)
: [];
const execArgv = includeExecArgv ? await cursor.execArgv(signal) : [];
if (await cursor.hasNonZeroTail(signal))
throw formatFailure(NODE_SEA_TRAILING_BYTES);
return {
magic: NODE_SEA_MAGIC,
flags,
disableExperimentalSeaWarning:
(flags & FLAG_DISABLE_EXPERIMENTAL_SEA_WARNING) !== 0,
useSnapshot,
useCodeCache,
includeAssets,
includeExecArgv,
execArgvExtension,
...(mainCodeFormat === undefined ? {} : { mainCodeFormat }),
codePath,
mainScript: useSnapshot ? null : body,
snapshot: useSnapshot ? body : null,
codeCache,
assets,
execArgv,
};
};
/** Classify every observed `NODE_SEA_FUSE_<32 lowercase hex>:[01]` sentinel. */
export const observeNodeSeaFuseMatches = (
matches: readonly string[],
): NodeSeaFuseObservation => {
const unique = [...new Set(matches)];
if (unique.length === 0)
return {
fuseState: "absent",
fuseSentinel: null,
fuseContradiction: NODE_SEA_FUSE_ABSENT,
};
const hashes = new Set(
unique.map((item) =>
item.slice(FUSE_PREFIX.length, FUSE_PREFIX.length + 32),
),
);
const digits = new Set(unique.map((item) => item.at(-1)));
if (hashes.size !== 1 || digits.size !== 1)
return {
fuseState: "conflicting",
fuseSentinel: null,
fuseContradiction: NODE_SEA_FUSE_CONFLICT,
};
const sentinel = unique[0];
if (sentinel === undefined) throw formatFailure(NODE_SEA_FUSE_CONFLICT);
if (digits.has("1"))
return {
fuseState: "set",
fuseSentinel: sentinel,
fuseContradiction: null,
};
return {
fuseState: "unset",
fuseSentinel: sentinel,
fuseContradiction: NODE_SEA_FUSE_UNSET,
};
};
const extensionName = (value: number): NodeSeaExecArgvExtension => {
if (value === 0) return "none";
if (value === 1) return "env";
if (value === 2) return "cli";
throw formatFailure(NODE_SEA_UNKNOWN_EXTENSION);
};
/** Sequential little-endian reader over one owned blob buffer. */
class BlobCursor {
#offset = 0;
readonly #reader: BinaryReader;
constructor(
private readonly bytes: Buffer,
private readonly limits: NodeSeaReaderLimits,
) {
this.#reader = new BinaryReader(bytes, true, "Node SEA");
}
get remaining(): number {
return this.bytes.length - this.#offset;
}
u32(): number {
return this.#reader.u32(this.#takeOffset(4));
}
u8(): number {
return this.bytes[this.#takeOffset(1)]!;
}
/** The byte after the legacy size field is either the first path byte or the
* high byte of the newer size field. A producer cannot open a path that
* starts with NUL, and a readable blob cannot fit a size of 2^56 or more.
*/
mainCodeFormat(): NodeSeaMainCodeFormat | undefined {
if (this.bytes[this.#offset + SIZE_BYTES] !== 0) return undefined;
const value = this.u8();
if (value === 0) return "commonjs";
if (value === 1) return "module";
throw formatFailure("Node SEA main code format is unknown");
}
/** `charge` sees the raw byte length before decoding allocates a string. */
text(
allowEmpty: boolean,
emptyMessage: string,
minimumTailBytes: number,
charge?: (bytes: number) => void,
): string {
const length = this.#size(minimumTailBytes);
charge?.(length);
const offset = this.#takeOffset(length);
const raw = this.bytes.subarray(offset, offset + length);
let text: string;
try {
text = strictUtf8Decoder("preserve").decode(raw);
} catch (cause: unknown) {
if (hostRangeErrorKind(cause) === "host-capacity")
throw new ArtifactReaderFailure(
"limit",
"Node SEA UTF-8 text exceeds this runtime's string or memory capacity. Admission budgets do not raise runtime representation limits or reserve host memory.",
{ boundary: "memory", cause },
);
throw formatFailure(NODE_SEA_INVALID_UTF8, cause);
}
if (!allowEmpty && text.length === 0) throw formatFailure(emptyMessage);
return text;
}
byteRange(minimumTailBytes: number): NodeSeaByteRange {
const length = this.#size(minimumTailBytes);
return { offset: this.#takeOffset(length), length };
}
async assets(
minimumTailBytes: number,
signal?: AbortSignal,
): Promise<NodeSeaAsset[]> {
const count = this.#count(
"asset_count",
MIN_ASSET_ROW_BYTES,
minimumTailBytes,
);
const seen = new Set<string>();
const assets: NodeSeaAsset[] = [];
let nameBytes = 0;
const charge = (bytes: number): void => {
nameBytes += bytes;
if (nameBytes > this.limits.asset_name_bytes)
throw artifactReaderLimitFailure(
"artifact_limits.node_sea.asset_name_bytes",
this.limits.asset_name_bytes,
"bytes",
nameBytes,
"memory",
);
};
for (let index = 0; index < count; index += 1) {
if (index % 256 === 0) {
await setImmediate();
assertArtifactReadActive(signal);
}
const tail = (count - index - 1) * MIN_ASSET_ROW_BYTES + minimumTailBytes;
const name = this.text(
true,
NODE_SEA_INVALID_UTF8,
SIZE_BYTES + tail,
charge,
);
if (seen.has(name))
throw formatFailure(`Node SEA asset name collides: ${name}`);
seen.add(name);
assets.push({ name, range: this.byteRange(tail) });
}
return assets;
}
async execArgv(signal?: AbortSignal): Promise<string[]> {
const count = this.#count("argument_count", SIZE_BYTES, 0);
const values: string[] = [];
let textBytes = 0;
const charge = (bytes: number): void => {
textBytes += bytes;
if (textBytes > this.limits.argument_bytes)
throw artifactReaderLimitFailure(
"artifact_limits.node_sea.argument_bytes",
this.limits.argument_bytes,
"bytes",
textBytes,
"memory",
);
};
for (let index = 0; index < count; index += 1) {
if (index % 256 === 0) {
await setImmediate();
assertArtifactReadActive(signal);
}
const tail = (count - index - 1) * SIZE_BYTES;
values.push(this.text(true, NODE_SEA_INVALID_UTF8, tail, charge));
}
return values;
}
async hasNonZeroTail(signal?: AbortSignal): Promise<boolean> {
for (
let start = this.#offset;
start < this.bytes.length;
start += 64 * 1024
) {
await setImmediate();
assertArtifactReadActive(signal);
const end = Math.min(start + 64 * 1024, this.bytes.length);
for (let index = start; index < end; index += 1)
if (this.bytes[index] !== 0) return true;
}
assertArtifactReadActive(signal);
return false;
}
#readSizeField(): bigint {
return this.#reader.word(this.#takeOffset(SIZE_BYTES), 64);
}
#size(minimumTailBytes: number): number {
const value = this.#readSizeField();
if (value > BigInt(this.remaining - minimumTailBytes))
throw truncatedFailure(NODE_SEA_TRUNCATED);
return Number(value);
}
#count(
field: "asset_count" | "argument_count",
minimumRowBytes: number,
minimumTailBytes: number,
): number {
const value = this.#readSizeField();
if (
value >
BigInt(Math.floor((this.remaining - minimumTailBytes) / minimumRowBytes))
)
throw truncatedFailure(NODE_SEA_TRUNCATED);
const count = Number(value);
if (count > this.limits[field])
throw artifactReaderLimitFailure(
`artifact_limits.node_sea.${field}`,
this.limits[field],
"count",
count,
);
return count;
}
#takeOffset(length: number): number {
if (length > this.remaining) throw truncatedFailure(NODE_SEA_TRUNCATED);
const start = this.#offset;
this.#offset += length;
return start;
}
}