Files
reverse-engineering-anything/src/domain/artifactGraph.ts
T
Ysopwnableandgensokyo-dev c2960db49f feat(artifacts): inventory resources embedded in .NET assemblies (#17105)
* refactor(managed): read ManifestResource rows and the CLI Resources directory separately

Split a ManifestResource row's columns from its data, so a caller that
holds only the metadata can list resources, and let the CLI header prefix
report its Resources directory when it is read that far.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(artifacts): bound .NET assembly manifest resource admission

Add the dotnet_assembly reader limit group: the resource count follows the
session member count, and metadata bytes bound the CLI metadata read to
list ManifestResource rows.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(artifacts): locate a managed image's metadata and Resources directory

Read only the PE headers, section table and CLI header to find where a
managed image keeps its metadata and embedded manifest resources, so
recognition does not load the image.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(artifacts): list the manifest resources a .NET assembly embeds

Add the dotnet-assembly reader. It reads the ManifestResource rows from
the CLI metadata and lists each resource embedded in the Resources
directory as its stored bytes. Linked resources are named in the root
metadata, since their bytes live in other files.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(artifacts): open managed assemblies with embedded resources as containers

A PE whose CLI header declares a Resources directory, and that carries no
other package, now inventories as dotnet-assembly, so a WPF assembly's
.g.resources can be extracted and inspected as a resource set. Managed
inspection still leads its next probes; extraction follows.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* docs(managed): describe resources embedded in a .NET assembly

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* docs(skill): route assemblies with embedded resources to extraction

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* ci: scope the .NET assembly resource reader with the managed formats

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): keep located managed directories inside the file

A section can declare raw data past the end of the file. A metadata or
Resources directory mapped there is now malformed at location, instead of
failing the later exact read.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): report invalid manifest resource rows once

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): require a complete CLI header before locating managed directories

Check the declared header size against the 72-byte header and the CLI
directory, and that the whole header lies in the file, as the managed PE
reader does.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* test(managed): build fixtures that embed several manifest resources

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): inventory manifest resource names as flat keys

Names such as `a` and `a/b` are distinct resources. Inventory keeps both,
as it does for resource set names; extraction still refuses to write
conflicting paths together.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(artifacts): add decode and retained-name controls for .NET assemblies

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): bound assembly resource names and keep readable rows

The metadata decode budget is now the group's representation_bytes
control, so a refusal names a field the caller can raise. Every listed
name counts against retained_name_bytes before output is built, since
rows can share one stored name. A row whose name cannot be read is
skipped and counted instead of refusing the whole assembly.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* docs(managed): list the .NET assembly reader controls

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* refactor(artifacts): pass the classified managed location to the assembly reader

Classification carries the located metadata and Resources directory in a
typed admission for the same descriptor, so the reader does not locate
them again.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): explain a damaged CLI Resources directory on extraction

Extraction now refuses such a PE with the location's reason instead of
reporting that the format has no reader. Inspection keeps the PE root,
where managed inspection reports the CLI header.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(artifacts): require the CLI header's declared size inside the file

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

---------

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-12-06 00:53:42 +08:00

462 lines
13 KiB
TypeScript

import { completeOrUnknownCoverageSchema } from "./coverage.js";
import {
artifactCrc32PairSchema,
artifactDfuCrc32PairSchema,
artifactIntegrityClaimSchema,
artifactSha256PairSchema,
artifactMd5PairSchema,
signedAfterPackingExplanationSchema,
} from "./artifactIntegrity.js";
import { artifactFormatMetadataSchema } from "./artifactFormatMetadata.js";
import { z } from "zod";
import { artifactReaderLimitsSchema } from "./artifactReaderLimits.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { inesInventorySchema } from "./inesContainer.js";
import { ZIP_APPLICATION_PACKAGE_FORMATS } from "./zipPackageFormat.js";
import { directoryRootDigestSchema } from "./directoryTreeDigest.js";
/** Entry kinds or subtrees deliberately excluded by an artifact traversal. */
export const artifactTraversalOmissionKindSchema = z.enum([
"fifo",
"socket",
"block-device",
"character-device",
"unsupported",
"directory-descendants",
]);
export type ArtifactTraversalOmissionKind = z.infer<
typeof artifactTraversalOmissionKindSchema
>;
const sha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);
const artifactIdSchema = prefixedDigestSchema("art");
const occurrenceIdSchema = prefixedDigestSchema("occ");
const edgeIdSchema = prefixedDigestSchema("edge");
const manifestIdSchema = prefixedDigestSchema("agm");
const extractionIdSchema = prefixedDigestSchema("aex");
const contradictionIdSchema = prefixedDigestSchema("ic");
const boundedRelativePathSchema = z
.string()
.min(1)
.refine(
(path) =>
!path.startsWith("/") &&
path.split("/").every((part) => part !== "" && part !== ".."),
"Expected a normalized relative POSIX path without traversal",
);
/** Closed artifact categories used to traverse application containers. */
const artifactKindSchema = z.enum([
"container",
"executable",
"dynamic-library",
"framework",
"native-addon",
"javascript",
"source-map",
"plist",
"entitlements",
"resource",
"universal-slice",
"package-metadata",
"unknown",
]);
/** Recognized storage or application formats; unknown bytes remain explicit. */
export const ARTIFACT_FORMAT_IDS = [
"dotnet-bundle",
"dotnet-assembly",
"bun-standalone",
"deno-standalone",
"dmg",
"zip",
"pkg",
"asar",
"ines",
"game-boy-rom",
"gba-rom",
"nds",
"mega-drive-rom",
"n64-rom",
"psx-exe",
"godot-pck",
"unityfs",
"wxapkg",
"tar",
"ar",
"dotnet-resources",
"dds",
"glb",
"ktx",
"ktx2",
"ogg-opus",
"riff-xma2",
"bink2",
"vulkan-pipeline-cache",
"uimage",
"nso",
"nro",
"android-boot-image",
"android-dtbo",
"android-ota-payload",
"android-vbmeta",
"android-sparse-image",
"android-super-image",
"ubi-image",
"iso9660",
"uefi",
"javascript-bundle",
"source-map",
"mach-o-universal",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"gamecube-dol",
"hopper",
"analysis-database",
...ZIP_APPLICATION_PACKAGE_FORMATS,
"plist",
"entitlements",
"directory",
"file",
"pyinstaller",
"node-sea",
"intel-hex",
"srec",
"esp-image",
"uf2",
"dfuse",
"bflt",
"esp-flash-image",
"fit",
"swf",
"mcuboot",
"qualcomm-mbn",
"apple-img4",
"mql-program",
"esp8266-image",
"ntfs-mft",
"systemd-journal",
"auditd-log",
"kubernetes-audit-log",
"evtx",
"sqlite",
"windows-shortcut",
"python-pyc",
"devicetree",
"esp-nvs",
"deb",
"labview-rsrc",
"unknown",
] as const;
export type ArtifactFormatId = (typeof ARTIFACT_FORMAT_IDS)[number];
const artifactFormatSchema = z.enum(ARTIFACT_FORMAT_IDS);
/** Formats established from bytes or a virtual directory tree, independent of path roles. */
const artifactContentFormatSchema = artifactFormatSchema.extract([
"ines",
"game-boy-rom",
"gba-rom",
"nds",
"mega-drive-rom",
"n64-rom",
"psx-exe",
"zip",
"godot-pck",
"unityfs",
"wxapkg",
"tar",
"ar",
"dotnet-resources",
"dds",
"glb",
"ktx",
"ktx2",
"ogg-opus",
"riff-xma2",
"bink2",
"vulkan-pipeline-cache",
"uimage",
"nso",
"nro",
"android-boot-image",
"android-dtbo",
"android-ota-payload",
"android-vbmeta",
"android-sparse-image",
"android-super-image",
"ubi-image",
"iso9660",
"uefi",
"intel-hex",
"srec",
"esp-image",
"uf2",
"dfuse",
"bflt",
"fit",
"swf",
"mcuboot",
"qualcomm-mbn",
"apple-img4",
"mql-program",
"esp8266-image",
"ntfs-mft",
"systemd-journal",
"auditd-log",
"kubernetes-audit-log",
"mach-o-universal",
"mach-o",
"elf",
"pe",
"dos-mz",
"plist",
"evtx",
"sqlite",
"windows-shortcut",
"python-pyc",
"devicetree",
"esp-nvs",
"deb",
"labview-rsrc",
"directory",
"file",
"unknown",
]);
/** File byte interval for an artifact derived without writing it to disk. */
const artifactByteRangeSchema = z.object({
offset: z.int().min(0),
length: z.int().min(0),
});
/** External command provenance, including observable side effects. */
const artifactCommandSchema = z.object({
tool: z.string().min(1),
arguments: z.array(z.string()),
tool_version: z.string().nullable(),
executable_sha256: sha256Schema.nullable(),
exit_code: z.int().nullable(),
effects: z.array(z.enum(["read", "write", "mount"])),
});
/** Parsed artifact-producing command provenance. */
export type ArtifactCommand = z.infer<typeof artifactCommandSchema>;
/** One content-addressed application artifact in deterministic manifest order. */
export const artifactNodeSchema = z.object({
artifact_id: artifactIdSchema,
format: artifactContentFormatSchema,
sha256: sha256Schema,
size: z.int().min(0).max(Number.MAX_SAFE_INTEGER),
media_type: z.string().min(1).nullable(),
architecture: z.string().min(1).nullable(),
content_state: z.enum(["materialized", "embedded", "virtual"]),
limitations: z.array(z.string()),
});
/** A symlink's stored target bytes, with their UTF-8 text when they decode strictly. */
export const artifactLinkTargetSchema = z.strictObject({
text: z.string().nullable(),
hex: z.string().regex(/^(?:[a-f0-9]{2})*$/u),
});
export type ArtifactLinkTarget = z.infer<typeof artifactLinkTargetSchema>;
/** One path or virtual location where an artifact occurs in its parent. */
export const artifactOccurrenceSchema = z.object({
occurrence_id: occurrenceIdSchema,
artifact_id: artifactIdSchema.nullable(),
parent_occurrence_id: occurrenceIdSchema.nullable(),
/** Producer coverage of this occurrence's modeled relationships. Historical omission is unknown. */
relationship_coverage: completeOrUnknownCoverageSchema.exactOptional(),
logical_path: boundedRelativePathSchema,
entry_kind: z.enum(["file", "directory", "symlink", "slice", "metadata"]),
artifact_kind: artifactKindSchema,
artifact_format: artifactFormatSchema,
declared_size: z.int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
compressed_size: z.int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
executable: z.boolean().nullable(),
encrypted: z.boolean(),
/** Reader-observed ASAR storage; omission leaves historical storage unknown. */
unpacked: z.boolean().exactOptional(),
hash_status: z.enum(["verified", "mismatched", "not-hashed", "unavailable"]),
source_location: artifactByteRangeSchema.nullable(),
/** Exact reader-source path or opaque key, including an observed empty key. */
source_path: z.string().exactOptional(),
declared_integrity: artifactIntegrityClaimSchema.exactOptional(),
format_metadata: artifactFormatMetadataSchema.exactOptional(),
/** A symlink's stored target, when the reader read it; never followed. */
link_target: artifactLinkTargetSchema.exactOptional(),
limitations: z.array(z.string()),
});
/** Observed bytes that contradict a container's declared integrity identity. */
const integrityContradictionBaseSchema = z.object({
contradiction_id: contradictionIdSchema,
occurrence_id: occurrenceIdSchema,
parent_artifact_id: artifactIdSchema,
logical_path: boundedRelativePathSchema,
entry_kind: z.enum(["file", "slice"]),
unpacked: z.boolean(),
trust: z.literal("observed-untrusted"),
provenance: z.literal("container-integrity-metadata-versus-observed-bytes"),
limitations: z.array(z.string()).min(1),
});
export const integrityContradictionSchema = z.union([
integrityContradictionBaseSchema.extend({
...artifactSha256PairSchema.shape,
/** Present when PE Authenticode stripping restores the declared SHA-256. */
signing_explanation: signedAfterPackingExplanationSchema.exactOptional(),
}),
integrityContradictionBaseSchema.extend(artifactMd5PairSchema.shape),
integrityContradictionBaseSchema.extend(artifactDfuCrc32PairSchema.shape),
integrityContradictionBaseSchema.extend(artifactCrc32PairSchema.shape),
]);
/**
* Parent-child derivation relation between two content-addressed artifacts.
* The child artifact and its logical path are those of the edge's occurrence.
*/
export const artifactEdgeSchema = z.object({
edge_id: edgeIdSchema,
ordinal: z.int().min(0),
parent_artifact_id: artifactIdSchema,
relation: z.enum([
"contains",
"extracts",
"slice-of",
"embeds",
"loads",
"maps-source",
"derived-from",
]),
occurrence_id: occurrenceIdSchema,
producer: artifactCommandSchema.nullable(),
});
/** Stable cryptographic commitment and counts for a complete artifact graph. */
export const artifactGraphManifestSchema = z.object({
manifest_id: manifestIdSchema,
root_artifact_id: artifactIdSchema,
root_sha256: sha256Schema,
root_format: artifactFormatSchema,
graph_sha256: sha256Schema,
node_count: z.int().min(1),
occurrence_count: z.int().min(1),
edge_count: z.int().min(0),
});
/** Producer-owned traversal coverage; content certainty remains on each occurrence. */
export const artifactInventoryCoverageSchema = z.strictObject({
scope: z.enum(["root", "container-entries"]),
status: completeOrUnknownCoverageSchema,
});
export type ArtifactInventoryCoverage = z.infer<
typeof artifactInventoryCoverageSchema
>;
/** Current inventory observation containing the stable artifact graph. */
export const artifactInventoryResultSchema = z.strictObject({
effective_limits: artifactReaderLimitsSchema
.exactOptional()
.describe(
"Accepted resource policy when selected; each format group applies only if that format is encountered. Not measured process memory or confirmation every reader ran.",
),
manifest: artifactGraphManifestSchema,
root_digest: directoryRootDigestSchema
.exactOptional()
.describe(
"A directory root's content-addressed tree digest. Complete only when every member was examined; partial names why and has no digest.",
),
nodes: z.array(artifactNodeSchema),
occurrences: z.array(artifactOccurrenceSchema),
edges: z.array(artifactEdgeSchema),
provenance: z.array(artifactCommandSchema),
ines: inesInventorySchema.exactOptional(),
integrity_contradictions: z.array(integrityContradictionSchema),
coverage: artifactInventoryCoverageSchema,
limitations: z.array(z.string()),
});
/** One safely materialized artifact beneath caller-approved output root. */
const extractedArtifactSchema = z.object({
artifact_id: artifactIdSchema,
relative_path: boundedRelativePathSchema,
sha256: sha256Schema,
bytes_written: z.int().min(0).max(Number.MAX_SAFE_INTEGER),
created: z.boolean(),
limitations: z
.array(z.string())
.min(1)
.exactOptional()
.describe(
"The inventory occurrence's own limitations, such as a case-folding collision or a normalized member name; absent when it has none",
),
});
/** Path-independent commitment to one selected extraction operation. */
const artifactExtractionManifestSchema = z.object({
extraction_id: extractionIdSchema,
source_manifest_id: manifestIdSchema,
selected_occurrence_ids: z.array(occurrenceIdSchema),
files_sha256: sha256Schema,
output_root_alias: z.literal("$OUTPUT_ROOT"),
});
/** Safe extraction observation with containment and cleanup verification. */
export const artifactExtractionResultSchema = z.object({
effective_limits: artifactReaderLimitsSchema.exactOptional(),
manifest: artifactGraphManifestSchema,
extraction_manifest: artifactExtractionManifestSchema,
output_root: z.string().min(1),
artifacts: z.array(extractedArtifactSchema),
containment_verified: z.boolean(),
cleanup: z.object({
attempted: z.boolean(),
verified: z.boolean(),
residual_paths: z.array(boundedRelativePathSchema),
}),
coverage: artifactInventoryCoverageSchema,
provenance: z.array(artifactCommandSchema),
integrity_contradictions: z.array(integrityContradictionSchema),
limitations: z.array(z.string()),
});
/** Parsed artifact graph node. */
export type ArtifactNode = z.infer<typeof artifactNodeSchema>;
/** Parsed artifact derivation edge. */
export type ArtifactEdge = z.infer<typeof artifactEdgeSchema>;
/** Parsed artifact occurrence. */
export type ArtifactOccurrence = z.infer<typeof artifactOccurrenceSchema>;
/** Read relationship coverage without changing authenticated historical rows. */
export const artifactOccurrenceRelationshipCoverage = (
occurrence: ArtifactOccurrence,
) => occurrence.relationship_coverage ?? "unknown";
export type IntegrityContradiction = z.infer<
typeof integrityContradictionSchema
>;
/** Parsed deterministic artifact graph manifest. */
export type ArtifactGraphManifest = z.infer<typeof artifactGraphManifestSchema>;
/** Parsed paginated inventory result. */
export type ArtifactInventoryResult = z.infer<
typeof artifactInventoryResultSchema
>;
/** Parsed paginated extraction result. */
export type ArtifactExtractionResult = z.infer<
typeof artifactExtractionResultSchema
>;