refactor(managed): group capability workflows and verification (#926)

This commit is contained in:
ysopwnable
2026-10-07 19:22:04 +08:00
committed by GitHub
parent 2ccc86cd13
commit 28713f9b4d
75 changed files with 217 additions and 177 deletions
@@ -0,0 +1,283 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence, type Evidence } from "../evidence.js";
import {
createJavaScriptApplicationGraph,
javascriptApplicationGraphSchema,
type ApplicationEdge,
type ApplicationNode,
} from "../javascript/javascriptApplicationGraph.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
managedNativeBoundaryInspectionSchema,
type ManagedArtifactInspection,
type ManagedMemberInspection,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "../jsonValue.js";
import {
assessManagedGraphOmissions,
managedGraphEvidenceCoverage,
managedGraphResultCoverage,
} from "./managedApplicationGraphCoverage.js";
import {
addArtifactNode,
addArtifactIdentityNodes,
addBoundaryNodes,
addMemberNodes,
} from "./managedApplicationGraphNodes.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const textSchema = z.string().min(1);
/** Authenticated managed Evidence records projected into the application graph. */
export const projectManagedApplicationGraphInputSchema = z
.strictObject({
managed_artifact: evidenceSchema.optional(),
managed_members: evidenceSchema.optional(),
managed_native_boundaries: evidenceSchema.optional(),
})
.superRefine((input, context) => {
if (
input.managed_artifact === undefined &&
input.managed_members === undefined &&
input.managed_native_boundaries === undefined
)
context.addIssue({
code: "custom",
message:
"At least one managed artifact, member, or native-boundary Evidence record is required",
});
});
/** Managed-code projection result containing a validated application graph. */
export const managedApplicationGraphResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("magp"),
root_artifact_sha256: digestSchema,
source_evidence: z.strictObject({
managed_artifact_evidence_id: evidenceIdSchema.nullable(),
managed_members_evidence_id: evidenceIdSchema.nullable(),
managed_native_boundaries_evidence_id: evidenceIdSchema.nullable(),
}),
summary: z.strictObject({
graph_nodes: z.number().int().min(0),
graph_edges: z.number().int().min(0),
assemblies: z.number().int().min(0),
modules: z.number().int().min(0),
types: z.number().int().min(0),
methods: z.number().int().min(0),
fields: z.number().int().min(0),
pinvoke_imports: z.number().int().min(0),
native_implementations: z.number().int().min(0),
}),
graph: javascriptApplicationGraphSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial"]),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(3),
limitations: z.array(textSchema),
});
export type ProjectManagedApplicationGraphInput = z.infer<
typeof projectManagedApplicationGraphInputSchema
>;
export type ManagedApplicationGraphResult = z.infer<
typeof managedApplicationGraphResultSchema
>;
export interface ParsedManagedGraphInput {
readonly artifact: {
readonly evidence: Evidence;
readonly result: ManagedArtifactInspection;
} | null;
readonly members: {
readonly evidence: Evidence;
readonly result: ManagedMemberInspection;
} | null;
readonly boundaries: {
readonly evidence: Evidence;
readonly result: ManagedNativeBoundaryInspection;
} | null;
}
export interface GraphBuildState {
readonly nodes: ApplicationNode[];
readonly edges: ApplicationEdge[];
readonly artifactSha256: string;
readonly artifactPath: string;
readonly evidenceLinks: string[];
readonly typeNodes: Map<string, ApplicationNode>;
readonly methodNodes: Map<string, ApplicationNode>;
readonly fieldNodes: Map<string, ApplicationNode>;
}
const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed application graph canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
/** Project authenticated managed Evidence records into the application graph. */
export const projectManagedApplicationGraph = (
input: ProjectManagedApplicationGraphInput,
): ManagedApplicationGraphResult => {
const parsed = parseManagedInputs(input);
const artifactIdentity = chooseArtifact(parsed);
assertSameArtifact(parsed, artifactIdentity.sha256);
const evidenceLinks = [
parsed.artifact?.evidence.evidence_id,
parsed.members?.evidence.evidence_id,
parsed.boundaries?.evidence.evidence_id,
].filter((id): id is string => id !== undefined);
const state: GraphBuildState = {
nodes: [],
edges: [],
artifactSha256: artifactIdentity.sha256,
artifactPath: artifactIdentity.path,
evidenceLinks,
typeNodes: new Map(),
methodNodes: new Map(),
fieldNodes: new Map(),
};
const artifactNode = addArtifactNode(state);
addArtifactIdentityNodes(state, artifactNode, parsed);
const memberCounts = addMemberNodes(state, artifactNode, parsed);
const boundaryCounts = addBoundaryNodes(state, artifactNode, parsed);
const omissions = omittedCounts(parsed);
const limitations = projectionLimitations(parsed, omissions);
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [artifactNode.node_id],
nodes: state.nodes,
edges: state.edges,
coverage: managedGraphEvidenceCoverage(omissions),
limitations,
});
const withoutId = {
root_artifact_sha256: state.artifactSha256,
source_evidence: {
managed_artifact_evidence_id:
parsed.artifact?.evidence.evidence_id ?? null,
managed_members_evidence_id: parsed.members?.evidence.evidence_id ?? null,
managed_native_boundaries_evidence_id:
parsed.boundaries?.evidence.evidence_id ?? null,
},
summary: {
graph_nodes: graph.nodes.length,
graph_edges: graph.edges.length,
assemblies: parsed.artifact?.result.assembly === null ? 0 : 1,
modules: parsed.artifact?.result.module === null ? 0 : 1,
...memberCounts,
...boundaryCounts,
},
graph,
coverage: managedGraphResultCoverage(omissions),
evidence_links: evidenceLinks,
limitations,
};
return managedApplicationGraphResultSchema.parse({
...withoutId,
projection_id: `magp_${sha256(withoutId)}`,
});
};
const parseManagedInputs = (
input: ProjectManagedApplicationGraphInput,
): ParsedManagedGraphInput => ({
artifact:
input.managed_artifact === undefined
? null
: parseManagedEvidence(
input.managed_artifact,
"inspect_managed_artifact",
managedArtifactInspectionSchema,
),
members:
input.managed_members === undefined
? null
: parseManagedEvidence(
input.managed_members,
"inspect_managed_members",
managedMemberInspectionSchema,
),
boundaries:
input.managed_native_boundaries === undefined
? null
: parseManagedEvidence(
input.managed_native_boundaries,
"inspect_managed_native_boundaries",
managedNativeBoundaryInspectionSchema,
),
});
const parseManagedEvidence = <Result>(
rawEvidence: unknown,
operation: string,
schema: z.ZodType<Result>,
): { readonly evidence: Evidence; readonly result: Result } => {
const evidence = parseEvidence(rawEvidence);
if (evidence.operation !== operation)
throw new TypeError(`Evidence operation is not ${operation}`);
return { evidence, result: schema.parse(evidence.normalized_result) };
};
const chooseArtifact = (
parsed: ParsedManagedGraphInput,
): { readonly sha256: string; readonly path: string } => {
const result =
parsed.artifact?.result ??
parsed.members?.result ??
parsed.boundaries?.result;
if (result === undefined)
throw new TypeError("Managed graph projection requires managed Evidence");
return { sha256: result.artifact.sha256, path: result.artifact.path };
};
const assertSameArtifact = (
parsed: ParsedManagedGraphInput,
sha256Value: string,
): void => {
for (const result of [
parsed.artifact?.result,
parsed.members?.result,
parsed.boundaries?.result,
])
if (result !== undefined && result.artifact.sha256 !== sha256Value)
throw new TypeError(
"Managed graph projection inputs must describe the same artifact SHA-256",
);
};
const omittedCounts = (parsed: ParsedManagedGraphInput) =>
assessManagedGraphOmissions({
artifact: parsed.artifact?.result ?? null,
members: parsed.members?.result ?? null,
boundaries: parsed.boundaries?.result ?? null,
});
const projectionLimitations = (
parsed: ParsedManagedGraphInput,
omissions: ReturnType<typeof omittedCounts>,
): string[] => [
"Managed graph projection preserves static metadata observations only; it does not execute managed code, load assemblies, or map managed tokens to native addresses.",
...(parsed.members === null
? [
"Managed member Evidence was not supplied; type, method, and field nodes are absent.",
]
: []),
...(parsed.boundaries === null
? [
"Managed native-boundary Evidence was not supplied; P/Invoke and native-implementation nodes are absent.",
]
: []),
...(omissions.partialInput
? ["At least one supplied managed Evidence record has partial coverage."]
: []),
];
@@ -0,0 +1,73 @@
import type { ApplicationGraphEvidence } from "../javascript/javascriptApplicationGraph.js";
import type {
ManagedArtifactInspection,
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
type ManagedCoverageState = "complete" | "partial" | "unavailable";
/** Source observations used to derive managed graph coverage. */
export interface ManagedGraphCoverageSources {
readonly artifact: ManagedArtifactInspection | null;
readonly members: ManagedMemberInspection | null;
readonly boundaries: ManagedNativeBoundaryInspection | null;
}
/** Whether any supplied source has incomplete coverage. */
export interface ManagedGraphProjectionOmissions {
readonly partialInput: boolean;
}
const completeCoverage = (): ApplicationGraphEvidence["coverage"] => ({
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
});
/** Preserve the source parser's coverage state on projected observations. */
export const managedSourceCoverage = (
state: ManagedCoverageState,
): ApplicationGraphEvidence["coverage"] =>
state === "complete"
? completeCoverage()
: {
status: state,
truncated: false,
omitted_count: null,
limits: [],
};
/** Determine whether any supplied managed inspection was partial. */
export const assessManagedGraphOmissions = (
sources: ManagedGraphCoverageSources,
): ManagedGraphProjectionOmissions => ({
partialInput: [
sources.members?.coverage.state,
sources.boundaries?.coverage.state,
sources.artifact?.coverage.state,
].some((state) => state !== undefined && state !== "complete"),
});
/** Derive graph coverage solely from the coverage of supplied source evidence. */
export const managedGraphEvidenceCoverage = (
omissions: ManagedGraphProjectionOmissions,
): ApplicationGraphEvidence["coverage"] =>
omissions.partialInput
? {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
}
: completeCoverage();
/** Report whether all supplied source evidence was complete. */
export const managedGraphResultCoverage = (
omissions: ManagedGraphProjectionOmissions,
) => ({
status: omissions.partialInput
? ("partial" as const)
: ("complete-within-inputs" as const),
});
@@ -0,0 +1,11 @@
import type { ParsedManagedGraphInput } from "./managedApplicationGraph.js";
/** Derive module coverage from the best available managed evidence source. */
export const moduleCoverageState = (
parsed: ParsedManagedGraphInput,
): "complete" | "partial" | "unavailable" =>
parsed.artifact !== null && parsed.artifact.result.module !== null
? parsed.artifact.result.coverage.state
: parsed.members !== null && parsed.members.result.module !== null
? parsed.members.result.coverage.state
: (parsed.boundaries?.result.coverage.state ?? "complete");
@@ -0,0 +1,493 @@
import { basename } from "node:path";
import {
createJavaScriptApplicationEdge,
createJavaScriptApplicationNode,
type ApplicationGraphEvidence,
type ApplicationNode,
} from "../javascript/javascriptApplicationGraph.js";
import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js";
import {
type ManagedMemberInspection,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import type {
GraphBuildState,
ParsedManagedGraphInput,
} from "./managedApplicationGraph.js";
import { moduleCoverageState } from "./managedApplicationGraphNodeCoverage.js";
type ManagedMethod = ManagedMemberInspection["methods"][number];
type ManagedField = ManagedMemberInspection["fields"][number];
type ManagedType = ManagedMemberInspection["types"][number];
type PinvokeImport = ManagedNativeBoundaryInspection["pinvoke_imports"][number];
type NativeImplementation =
ManagedNativeBoundaryInspection["native_implementations"][number];
/** Options for a managed contains relationship edge. */
export interface ContainsEdgeOptions {
readonly kind: string;
readonly coverage: ApplicationGraphEvidence["coverage"];
}
/** Add the root managed artifact node to the graph state. */
export const addArtifactNode = (state: GraphBuildState): ApplicationNode => {
const node = createJavaScriptApplicationNode({
kind: "artifact",
identity: {
strategy: "content-digest",
stability: "global-exact",
sha256: state.artifactSha256,
},
observations: [
{
label: basename(state.artifactPath),
properties: {
format: "pe",
source: "managed-application-graph",
},
evidence: managedEvidence(state, "project-managed-artifact"),
},
],
});
state.nodes.push(node);
return node;
};
/** Add managed assembly and module identity nodes for the artifact. */
export const addArtifactIdentityNodes = (
state: GraphBuildState,
artifactNode: ApplicationNode,
parsed: ParsedManagedGraphInput,
): void => {
const artifact = parsed.artifact?.result;
const artifactCoverage = managedSourceCoverage(
parsed.artifact?.result.coverage.state ?? "complete",
);
if (artifact?.assembly !== undefined && artifact.assembly !== null) {
const assembly = createJavaScriptApplicationNode({
kind: "managed-assembly",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-assembly",
artifact.assembly.token,
),
observations: [
{
label: artifact.assembly.name,
properties: {
name: artifact.assembly.name,
version: artifact.assembly.version,
culture: artifact.assembly.culture,
public_key_kind: artifact.assembly.public_key.kind,
},
evidence: managedEvidence(
state,
"inspect_managed_artifact",
artifactCoverage,
),
},
],
});
state.nodes.push(assembly);
addContainsEdge(state, artifactNode, assembly, {
kind: "declares-managed-assembly",
coverage: artifactCoverage,
});
}
const module =
artifact?.module ??
parsed.members?.result.module ??
parsed.boundaries?.result.module;
if (module !== undefined && module !== null) {
const moduleCoverage = managedSourceCoverage(moduleCoverageState(parsed));
const moduleNode = createJavaScriptApplicationNode({
kind: "managed-module",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-module",
module.mvid ?? module.token,
),
observations: [
{
label: module.name,
properties: {
name: module.name,
mvid: module.mvid,
generation: module.generation,
token: module.token,
},
evidence: managedEvidence(
state,
"inspect_managed_artifact",
moduleCoverage,
),
},
],
});
state.nodes.push(moduleNode);
addContainsEdge(state, artifactNode, moduleNode, {
kind: "declares-managed-module",
coverage: moduleCoverage,
});
}
};
/** Add managed type, method, and field nodes from member evidence. */
export const addMemberNodes = (
state: GraphBuildState,
artifactNode: ApplicationNode,
parsed: ParsedManagedGraphInput,
) => {
const members = parsed.members?.result;
if (members === undefined) return { types: 0, methods: 0, fields: 0 };
const { types, methods, fields } = members;
const typeCoverage = managedSourceCoverage(members.coverage.state);
const methodCoverage = managedSourceCoverage(members.coverage.state);
const fieldCoverage = managedSourceCoverage(members.coverage.state);
for (const type of types) {
const node = typeNode(state, type, typeCoverage);
state.nodes.push(node);
state.typeNodes.set(type.token, node);
addContainsEdge(state, artifactNode, node, {
kind: "declares-managed-type",
coverage: typeCoverage,
});
}
for (const method of methods) {
const node = methodNode(state, method, methodCoverage);
state.nodes.push(node);
state.methodNodes.set(method.token, node);
const owner =
method.declaring_type_token === null
? artifactNode
: (state.typeNodes.get(method.declaring_type_token) ?? artifactNode);
addContainsEdge(state, owner, node, {
kind: "declares-managed-method",
coverage: methodCoverage,
});
}
for (const field of fields) {
const node = fieldNode(state, field, fieldCoverage);
state.nodes.push(node);
state.fieldNodes.set(field.token, node);
const owner =
field.declaring_type_token === null
? artifactNode
: (state.typeNodes.get(field.declaring_type_token) ?? artifactNode);
addContainsEdge(state, owner, node, {
kind: "declares-managed-field",
coverage: fieldCoverage,
});
}
return {
types: types.length,
methods: methods.length,
fields: fields.length,
};
};
/** Build a managed type application node. */
const typeNode = (
state: GraphBuildState,
type: ManagedType,
coverage: ApplicationGraphEvidence["coverage"],
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "managed-type",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-type-token",
type.token,
),
observations: [
{
label: type.full_name,
properties: {
token: type.token,
namespace: type.namespace,
name: type.name,
full_name: type.full_name,
flags: type.flags,
extends_token: type.extends_token,
},
evidence: managedEvidence(state, "inspect_managed_members", coverage),
},
],
});
/** Build a managed method application node. */
const methodNode = (
state: GraphBuildState,
method: ManagedMethod,
coverage: ApplicationGraphEvidence["coverage"],
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "managed-method",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-method-token",
method.token,
),
observations: [
{
label:
method.declaring_type === null
? method.name
: `${method.declaring_type}.${method.name}`,
properties: {
token: method.token,
declaring_type_token: method.declaring_type_token,
declaring_type: method.declaring_type,
name: method.name,
rva: method.rva,
signature_sha256: method.signature.raw_sha256,
signature_status: method.signature.parse_status,
body_status: method.body.status,
normalized_il_sha256: method.body.normalized_il_sha256,
il_size: method.body.il_size,
},
evidence: managedEvidence(state, "inspect_managed_members", coverage),
},
],
});
/** Build a managed field application node. */
const fieldNode = (
state: GraphBuildState,
field: ManagedField,
coverage: ApplicationGraphEvidence["coverage"],
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "managed-field",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-field-token",
field.token,
),
observations: [
{
label:
field.declaring_type === null
? field.name
: `${field.declaring_type}.${field.name}`,
properties: {
token: field.token,
declaring_type_token: field.declaring_type_token,
declaring_type: field.declaring_type,
name: field.name,
flags: field.flags,
signature_sha256: field.signature.raw_sha256,
signature_status: field.signature.parse_status,
},
evidence: managedEvidence(state, "inspect_managed_members", coverage),
},
],
});
/** Add P/Invoke import and native implementation boundary nodes. */
export const addBoundaryNodes = (
state: GraphBuildState,
artifactNode: ApplicationNode,
parsed: ParsedManagedGraphInput,
) => {
const boundaries = parsed.boundaries?.result;
if (boundaries === undefined)
return { pinvoke_imports: 0, native_implementations: 0 };
const { pinvoke_imports: pinvokes, native_implementations: implementations } =
boundaries;
const pinvokeCoverage = managedSourceCoverage(boundaries.coverage.state);
const implementationCoverage = managedSourceCoverage(
boundaries.coverage.state,
);
for (const pinvoke of pinvokes) {
const node = pinvokeNode(state, pinvoke, pinvokeCoverage);
state.nodes.push(node);
const owner =
pinvoke.member_token === null
? artifactNode
: (state.methodNodes.get(pinvoke.member_token) ?? artifactNode);
state.edges.push(
createJavaScriptApplicationEdge({
source_node_id: owner.node_id,
target_node_id: node.node_id,
relation: "imports",
properties: {
kind: "managed-pinvoke",
import_name: pinvoke.import_name,
import_scope_name: pinvoke.import_scope_name,
},
evidence: managedEvidence(
state,
"inspect_managed_native_boundaries",
pinvokeCoverage,
),
}),
);
}
for (const implementation of implementations) {
const node = nativeImplementationNode(
state,
implementation,
implementationCoverage,
);
state.nodes.push(node);
const owner = state.methodNodes.get(implementation.token) ?? artifactNode;
addContainsEdge(state, owner, node, {
kind: "declares-managed-native-implementation",
coverage: implementationCoverage,
});
}
return {
pinvoke_imports: pinvokes.length,
native_implementations: implementations.length,
};
};
/** Build a managed P/Invoke import application node. */
const pinvokeNode = (
state: GraphBuildState,
pinvoke: PinvokeImport,
coverage: ApplicationGraphEvidence["coverage"],
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "managed-pinvoke-import",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-pinvoke-token",
pinvoke.token,
),
observations: [
{
label: pinvoke.import_name,
properties: {
token: pinvoke.token,
member_token: pinvoke.member_token,
member_name: pinvoke.member_name,
import_name: pinvoke.import_name,
import_scope_name: pinvoke.import_scope_name,
char_set: pinvoke.char_set,
call_convention: pinvoke.call_convention,
verification: pinvoke.verification,
},
evidence: managedEvidence(
state,
"inspect_managed_native_boundaries",
coverage,
),
},
],
});
/** Build a managed native implementation application node. */
const nativeImplementationNode = (
state: GraphBuildState,
implementation: NativeImplementation,
coverage: ApplicationGraphEvidence["coverage"],
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "managed-native-implementation",
identity: artifactLocalIdentity(
state.artifactSha256,
"managed-native-implementation-token",
implementation.token,
),
observations: [
{
label: implementation.name,
properties: {
token: implementation.token,
name: implementation.name,
rva: implementation.rva,
code_type: implementation.code_type,
managed_kind: implementation.managed_kind,
pinvoke_declared: implementation.pinvoke_declared,
boundary_kind: implementation.boundary_kind,
body_interpretation: implementation.body_interpretation,
},
evidence: managedEvidence(
state,
"inspect_managed_native_boundaries",
coverage,
),
},
],
});
/** Add a contains relationship edge between two nodes. */
const addContainsEdge = (
state: GraphBuildState,
source: ApplicationNode,
target: ApplicationNode,
options: ContainsEdgeOptions,
): void => {
state.edges.push(
createJavaScriptApplicationEdge({
source_node_id: source.node_id,
target_node_id: target.node_id,
relation: "contains",
properties: { kind: options.kind },
evidence: managedEvidence(
state,
"project-managed-contains",
options.coverage,
),
}),
);
};
/** Build an artifact-local key identity for a managed graph entity. */
const artifactLocalIdentity = (
artifactSha256: string,
namespace: string,
key: string,
) => ({
strategy: "artifact-local-key" as const,
stability: "artifact-version" as const,
artifact_sha256: artifactSha256,
namespace,
key,
});
/** Build managed static-analysis evidence for a graph observation. */
const managedEvidence = (
state: GraphBuildState,
operation: string,
coverage: ApplicationGraphEvidence["coverage"] = managedSourceCoverage(
"complete",
),
): ApplicationGraphEvidence => ({
authority: "managed-static-analysis",
state: "observed",
confidence: "exact",
artifact: {
available: true,
artifact_id: `art_${state.artifactSha256}`,
sha256: state.artifactSha256,
},
location: {
available: true,
value: {
kind: "artifact-path",
path: graphArtifactPath(state.artifactPath),
},
},
extractor: {
name: "rea-dotnet-static",
version: "1",
operation,
executable_sha256: null,
},
coverage,
limitations:
coverage.status === "complete"
? []
: [
"The source managed Evidence slice is incomplete; unreturned or unavailable items remain unobserved.",
],
evidence_ids: state.evidenceLinks,
});
/** Sanitize an artifact path into a managed graph location. */
const graphArtifactPath = (path: string): string => {
const name = basename(path).replaceAll(/[^A-Za-z0-9._-]/gu, "_");
return `managed/${name.length === 0 ? "artifact.pe" : name}`;
};
+491
View File
@@ -0,0 +1,491 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const offsetSchema = z.number().int().min(0);
/** A 16-byte CLI metadata GUID without RFC 4122 version/variant restrictions. */
export const cliMetadataGuidSchema = z
.string()
.regex(/^[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$/u);
const publicKeyIdentitySchema = z.object({
kind: z.enum(["none", "public-key", "public-key-token"]),
byte_length: z.number().int().min(0),
sha256: digestSchema.nullable(),
token: z
.string()
.regex(/^[a-f0-9]{16}$/u)
.nullable(),
});
const assemblyIdentitySchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
hash_algorithm: z.number().int().min(0).max(0xffff_ffff),
public_key: publicKeyIdentitySchema,
token: tokenSchema,
row_offset: offsetSchema,
});
const moduleIdentitySchema = z.object({
name: z.string(),
generation: z.number().int().min(0).max(0xffff),
mvid: cliMetadataGuidSchema.nullable(),
enc_id: cliMetadataGuidSchema.nullable(),
enc_base_id: cliMetadataGuidSchema.nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const assemblyReferenceSchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
public_key_or_token: publicKeyIdentitySchema,
hash_value_sha256: digestSchema.nullable(),
hash_value_length: z.number().int().min(0),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedResourceSchema = z.object({
name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
visibility: z.enum(["public", "private", "unknown"]),
implementation_token: tokenSchema.nullable(),
embedded: z.boolean(),
declared_offset: z.number().int().min(0).max(0xffff_ffff),
data_length: z.number().int().min(0).nullable(),
data_sha256: digestSchema.nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const customAttributeSchema = z.object({
parent_token: tokenSchema,
constructor_token: tokenSchema.nullable(),
type_name: z.string().nullable(),
value_length: z.number().int().min(0),
value_sha256: digestSchema,
decoded_fixed_string: z.string().nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedSignatureSchema = z.object({
raw_length: z.number().int().min(0),
raw_sha256: digestSchema,
kind: z.enum(["method", "field", "unknown"]),
parse_status: z.enum(["decoded", "partial", "unsupported", "malformed"]),
calling_convention: z.string().nullable(),
generic_parameter_count: z.number().int().min(0).nullable(),
parameter_count: z.number().int().min(0).nullable(),
return_type: z.string().nullable(),
parameter_types: z.array(z.string()),
field_type: z.string().nullable(),
issue: z.string().nullable(),
});
const managedTypeSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
namespace: z.string(),
name: z.string(),
full_name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
extends_token: tokenSchema.nullable(),
field_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
method_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
});
const managedFieldSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
});
const managedExceptionRegionSchema = z.object({
flags: z.number().int().min(0).max(0xffff_ffff),
try_offset: z.number().int().min(0),
try_length: z.number().int().min(0),
handler_offset: z.number().int().min(0),
handler_length: z.number().int().min(0),
class_token: tokenSchema.nullable(),
filter_offset: z.number().int().min(0).nullable(),
});
const managedInstructionAnchorSchema = z.object({
il_offset: z.number().int().min(0),
opcode: z.string().min(1),
operand_kind: z.enum([
"none",
"branch",
"constant",
"field",
"method",
"signature",
"string",
"switch",
"token",
"type",
"variable",
"unknown",
]),
operand: z.string().nullable(),
});
const managedMethodBodySchema = z.object({
status: z.enum(["present", "partial", "absent", "malformed"]),
header_format: z.enum(["tiny", "fat", "none", "unknown"]),
rva: z.number().int().min(0).max(0xffff_ffff),
file_offset: offsetSchema.nullable(),
max_stack: z.number().int().min(0).nullable(),
init_locals: z.boolean().nullable(),
local_var_sig_token: tokenSchema.nullable(),
il_size: z.number().int().min(0),
il_sha256: digestSchema
.nullable()
.describe(
"SHA-256 of exactly the raw il_size CIL bytes; excludes the method header, locals signature, alignment, and extra sections",
),
normalized_il_sha256: digestSchema
.nullable()
.describe(
"Member-result-v1 SHA-256 of UTF-8 JSON [opcode, operand_kind, operand] tuples for a complete decode; retains build-local tokens, omits switch targets, and excludes headers, locals, and exception regions",
),
instruction_count: z.number().int().min(0),
decoded_instruction_count: z.number().int().min(0),
truncated_instructions: z.number().int().min(0),
opcode_counts: z.record(z.string(), z.number().int().min(1)),
anchors: z.array(managedInstructionAnchorSchema),
exception_regions: z.array(managedExceptionRegionSchema),
issue: z.string().nullable(),
});
const managedMethodSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
rva: z.number().int().min(0).max(0xffff_ffff),
impl_flags: z.number().int().min(0).max(0xffff),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
body: managedMethodBodySchema,
});
const managedMemberReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
parent_token: tokenSchema.nullable(),
name: z.string(),
signature: managedSignatureSchema,
});
const managedModuleReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
name: z.string(),
});
const managedNativeImportSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
mapping_flags: z.number().int().min(0).max(0xffff),
mapping_flags_hex: z.string().regex(/^0x[0-9a-f]{4}$/u),
member_token: tokenSchema.nullable(),
member_kind: z.enum(["method", "field", "unknown"]),
member_name: z.string().nullable(),
import_name: z.string(),
import_scope_token: tokenSchema.nullable(),
import_scope_name: z.string().nullable(),
no_mangle: z.boolean(),
char_set: z.enum(["not-specified", "ansi", "unicode", "auto", "unknown"]),
call_convention: z.enum([
"not-specified",
"winapi",
"cdecl",
"stdcall",
"thiscall",
"fastcall",
"unknown",
]),
supports_last_error: z.boolean(),
best_fit: z.enum(["assembly-default", "enabled", "disabled", "unknown"]),
throw_on_unmappable_char: z.enum([
"assembly-default",
"enabled",
"disabled",
"unknown",
]),
verification: z.literal("managed-declaration-only"),
});
const managedNativeImplementationSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
name: z.string(),
rva: z.number().int().min(0).max(0xffff_ffff),
flags: z.number().int().min(0).max(0xffff),
impl_flags: z.number().int().min(0).max(0xffff),
code_type: z.enum(["il", "native", "optil", "runtime", "unknown"]),
managed_kind: z.enum(["managed", "unmanaged", "unknown"]),
pinvoke_declared: z.boolean(),
boundary_kind: z.enum([
"pinvoke",
"native-body",
"runtime-provided",
"unmanaged-method",
"mixed-or-unknown",
]),
body_interpretation: z.enum([
"managed-cil",
"native-or-runtime",
"not-file-backed",
"unknown",
]),
});
const managedCallEdgeSchema = z.object({
caller_token: tokenSchema,
caller: z.string().nullable(),
opcode: z.string(),
target_token: tokenSchema,
target_kind: z.enum(["method-def", "member-ref", "method-spec", "unknown"]),
target_name: z.string().nullable(),
});
const managedFieldAccessSchema = z.object({
method_token: tokenSchema,
method: z.string().nullable(),
opcode: z.string(),
field_token: tokenSchema,
field_name: z.string().nullable(),
});
const managedParseIssueSchema = z.object({
code: z.enum([
"invalid-cli-header",
"invalid-directory",
"invalid-metadata-root",
"invalid-stream",
"missing-stream",
"invalid-tables",
"invalid-row",
"invalid-heap-index",
"invalid-string",
"invalid-blob",
"unsupported-signature",
"invalid-guid",
"invalid-resource",
]),
scope: z.string().min(1),
offset: offsetSchema.nullable(),
detail: z.string().min(1),
});
/** Provider-neutral, execution-free PE/CLI triage and identity result. */
export const managedArtifactInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
pe: z.object({
machine: z.number().int().min(0).max(0xffff),
machine_hex: z.string().regex(/^0x[0-9a-f]{4}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
optional_header: z.enum(["pe32", "pe32-plus"]),
section_count: z.number().int().min(1).max(0xffff),
characteristics: z.number().int().min(0).max(0xffff),
cli: z
.object({
header_offset: offsetSchema,
header_size: z.number().int().min(72),
runtime_version: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
flag_names: z.array(z.string()),
entry_point: z.object({
kind: z.enum(["metadata-token", "native-rva", "none"]),
value: z.string().nullable(),
}),
metadata_rva: z.number().int().min(1).max(0xffff_ffff),
metadata_size: z.number().int().min(1).max(0xffff_ffff),
resources_rva: z.number().int().min(0).max(0xffff_ffff),
resources_size: z.number().int().min(0).max(0xffff_ffff),
strong_name_rva: z.number().int().min(0).max(0xffff_ffff),
strong_name_size: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
ready_to_run_signature: z.boolean(),
})
.nullable(),
}),
classification: z.object({
status: z.enum(["managed", "not-managed", "malformed"]),
container: z.literal("pe"),
runtime_family: z.enum([
"dotnet-framework",
"modern-dotnet",
"unity-mono",
"mixed-clr-native",
"unknown",
]),
implementation: z.enum([
"cil",
"cil-and-ready-to-run",
"cpp-cli-mixed",
"metadata-only",
"not-managed",
"unknown",
]),
managed_architecture: z.enum([
"anycpu",
"anycpu-prefer-32",
"x86",
"x86_64",
"arm",
"arm64",
"unknown",
]),
evidence: z.array(
z.object({
code: z.string().min(1),
detail: z.string().min(1),
file_offset: offsetSchema.nullable(),
}),
),
}),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
stream_names: z.array(z.string()),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
module: moduleIdentitySchema.nullable(),
assembly: assemblyIdentitySchema.nullable(),
target_frameworks: z.array(z.string()),
references: z.array(assemblyReferenceSchema),
resources: z.array(managedResourceSchema),
attributes: z.array(customAttributeSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
/** Provider-neutral, execution-free metadata/signature/IL member inspection. */
export const managedMemberInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
module: moduleIdentitySchema.nullable(),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
identity_scope: z.object({
token_identity: z.literal("build-local"),
requires_artifact_sha256: digestSchema,
requires_mvid: cliMetadataGuidSchema.nullable(),
}),
types: z.array(managedTypeSchema),
fields: z.array(managedFieldSchema),
methods: z.array(managedMethodSchema),
member_refs: z.array(managedMemberReferenceSchema),
call_edges: z.array(managedCallEdgeSchema),
field_accesses: z.array(managedFieldAccessSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
/** Provider-neutral managed/native boundary observations from PE/CLI metadata. */
export const managedNativeBoundaryInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
module: moduleIdentitySchema.nullable(),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
identity_scope: z.object({
token_identity: z.literal("build-local"),
requires_artifact_sha256: digestSchema,
requires_mvid: cliMetadataGuidSchema.nullable(),
}),
cli_native: z.object({
il_only: z.boolean(),
requires_32bit: z.boolean(),
strong_name_signed: z.boolean(),
native_entry_point: z.boolean(),
ready_to_run_signature: z.boolean(),
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
}),
module_refs: z.array(managedModuleReferenceSchema),
pinvoke_imports: z.array(managedNativeImportSchema),
native_implementations: z.array(managedNativeImplementationSchema),
summary: z.object({
module_ref_count: z.number().int().min(0),
pinvoke_import_count: z.number().int().min(0),
native_implementation_count: z.number().int().min(0),
ready_to_run: z.boolean(),
mixed_mode_or_native_header: z.boolean(),
}),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
export type ManagedArtifactInspection = z.infer<
typeof managedArtifactInspectionSchema
>;
export type ManagedMemberInspection = z.infer<
typeof managedMemberInspectionSchema
>;
export type ManagedNativeBoundaryInspection = z.infer<
typeof managedNativeBoundaryInspectionSchema
>;
export type ManagedParseIssue = z.infer<typeof managedParseIssueSchema>;
@@ -0,0 +1,269 @@
import { z } from "zod";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import {
cliMetadataGuidSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import {
buildComparisonCoverage,
buildComparisonMatching,
buildComparisonSummary,
comparisonLimitations,
sideManifest,
} from "./managedMemberComparisonCoverage.js";
import {
buildFieldItems,
buildMethodItems,
} from "./managedMemberComparisonItems.js";
import { keyMembers, sha256 } from "./managedMemberComparisonMatch.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1);
/** Two authenticated managed member observations. */
export const compareManagedMembersInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
})
.superRefine((input, context) => {
if (input.left.evidence_id === input.right.evidence_id)
context.addIssue({
code: "custom",
path: ["right"],
message: "Managed member Evidence must be distinct",
});
});
const concreteMatchBasisSchema = z.enum([
"exact-il-signature",
"exact-signature",
"structural-method-shape",
"field-signature",
]);
const candidateTokensSchema = z.array(tokenSchema).min(1);
const matchedComparisonSchema = z.strictObject({
status: z.literal("matched"),
basis: concreteMatchBasisSchema,
confidence: z.enum(["exact", "high"]),
candidate_left_tokens: emptyArraySchema,
candidate_right_tokens: emptyArraySchema,
});
const unmatchedComparisonSchema = z.strictObject({
status: z.literal("unmatched"),
basis: z.literal("none"),
confidence: z.literal("unknown"),
candidate_left_tokens: emptyArraySchema,
candidate_right_tokens: emptyArraySchema,
});
const ambiguousComparisonSchema = z.strictObject({
status: z.literal("ambiguous"),
basis: concreteMatchBasisSchema,
confidence: z.literal("unknown"),
candidate_left_tokens: candidateTokensSchema,
candidate_right_tokens: candidateTokensSchema,
});
const memberIdentitySchema = z.strictObject({
token: tokenSchema,
declaring_type: z.string().nullable(),
name: z.string(),
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
});
const comparisonItemSchema = <
Identity extends z.ZodType,
Base extends Record<string, z.ZodType>,
>(
base: Base,
identity: Identity,
) =>
z.union([
z.strictObject({
...base,
status: z.enum(["unchanged", "changed", "unknown"]),
left: identity,
right: identity,
match: matchedComparisonSchema,
}),
z.strictObject({
...base,
status: z.enum(["removed", "unknown"]),
left: identity,
right: z.null(),
match: unmatchedComparisonSchema,
}),
z.strictObject({
...base,
status: z.enum(["added", "unknown"]),
left: z.null(),
right: identity,
match: unmatchedComparisonSchema,
}),
z.strictObject({
...base,
status: z.literal("unknown"),
left: z.null(),
right: z.null(),
match: ambiguousComparisonSchema,
}),
]);
const comparisonItemContextShape = {
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema),
};
const methodComparisonItemSchema = comparisonItemSchema(
{
...comparisonItemContextShape,
item_id: prefixedDigestSchema("mmc_method"),
dimensions: z.array(
z.enum([
"metadata",
"signature",
"cil",
"opcode-shape",
"call-shape",
"field-shape",
"exception-shape",
"availability",
"body-coverage",
]),
),
},
memberIdentitySchema,
);
const fieldComparisonItemSchema = comparisonItemSchema(
{
...comparisonItemContextShape,
item_id: prefixedDigestSchema("mmc_field"),
},
memberIdentitySchema.omit({ normalized_il_sha256: true }),
);
/** Obfuscation-resistant, execution-free managed member comparison. */
export const managedMemberComparisonResultSchema = z.strictObject({
comparison_id: prefixedDigestSchema("mmc"),
algorithm: z.strictObject({
name: z.literal("rea-managed-member-comparison"),
token_identity: z.literal("build-local"),
name_matching: z.literal("exact-signature-fallback"),
}),
left: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
mvid: cliMetadataGuidSchema.nullable(),
module_name: z.string().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
methods_total: z.number().int().min(0),
fields_total: z.number().int().min(0),
}),
right: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
mvid: cliMetadataGuidSchema.nullable(),
module_name: z.string().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
methods_total: z.number().int().min(0),
fields_total: z.number().int().min(0),
}),
summary: z.strictObject({
unchanged: z.number().int().min(0),
changed: z.number().int().min(0),
added: z.number().int().min(0),
removed: z.number().int().min(0),
unknown: z.number().int().min(0),
}),
matching: z.strictObject({
exact_il_signature: z.number().int().min(0),
exact_signature: z.number().int().min(0),
structural_method_shape: z.number().int().min(0),
field_signature: z.number().int().min(0),
ambiguous: z.number().int().min(0),
unmatched: z.number().int().min(0),
}),
methods: z.array(methodComparisonItemSchema),
fields: z.array(fieldComparisonItemSchema),
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial"]),
left_status: z.enum(["complete", "partial", "unavailable"]),
right_status: z.enum(["complete", "partial", "unavailable"]),
}),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema),
});
export type CompareManagedMembersInput = z.infer<
typeof compareManagedMembersInputSchema
>;
export type ManagedMemberComparisonResult = z.infer<
typeof managedMemberComparisonResultSchema
>;
/** One authenticated side of a managed member comparison. */
export interface ManagedMemberComparisonSide {
readonly evidenceId: string;
readonly result: ManagedMemberInspection;
}
/** Compare managed members with constrained exact and structural identities. */
export const compareManagedMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
): ManagedMemberComparisonResult => {
const leftCoverage = {
sourceComplete: left.result.coverage.state === "complete",
};
const rightCoverage = {
sourceComplete: right.result.coverage.state === "complete",
};
const { methodMatches, fieldMatches } = keyMembers(left, right);
const itemContext = {
leftEvidenceId: left.evidenceId,
rightEvidenceId: right.evidenceId,
leftComplete: leftCoverage.sourceComplete,
rightComplete: rightCoverage.sourceComplete,
};
const methodItems = buildMethodItems(methodMatches, itemContext);
const fieldItems = buildFieldItems(fieldMatches, itemContext);
const allItems = [...methodItems, ...fieldItems];
const summary = buildComparisonSummary(allItems);
const matching = buildComparisonMatching(methodItems, fieldItems);
const coverage = buildComparisonCoverage({
left: left.result,
right: right.result,
});
const limitations = comparisonLimitations(left.result, right.result);
const result = {
comparison_id: `mmc_${sha256({
left: left.evidenceId,
right: right.evidenceId,
methods: [...methodItems],
fields: [...fieldItems],
})}`,
algorithm: {
name: "rea-managed-member-comparison" as const,
token_identity: "build-local" as const,
name_matching: "exact-signature-fallback" as const,
},
left: sideManifest(left),
right: sideManifest(right),
summary,
matching,
methods: methodItems,
fields: fieldItems,
coverage,
evidence_links: [left.evidenceId, right.evidenceId],
limitations,
} satisfies ManagedMemberComparisonResult;
return managedMemberComparisonResultSchema.parse(result);
};
export { parseManagedMemberEvidence } from "./managedMemberComparisonMatch.js";
@@ -0,0 +1,100 @@
import type {
ManagedMemberComparisonResult,
ManagedMemberComparisonSide,
} from "./managedMemberComparison.js";
import type { ManagedMemberInspection } from "./managedArtifact.js";
interface ComparisonCoverageInput {
readonly left: ManagedMemberInspection;
readonly right: ManagedMemberInspection;
}
export const buildComparisonCoverage = ({
left,
right,
}: ComparisonCoverageInput): ManagedMemberComparisonResult["coverage"] => {
const leftStatus = sideCoverageStatus(left);
const rightStatus = sideCoverageStatus(right);
const unknownInput =
left.coverage.state !== "complete" || right.coverage.state !== "complete";
return {
status:
!unknownInput && leftStatus === "complete" && rightStatus === "complete"
? "complete-within-inputs"
: "partial",
left_status: leftStatus,
right_status: rightStatus,
};
};
const sideCoverageStatus = (
result: ManagedMemberInspection,
): ManagedMemberComparisonResult["coverage"]["left_status"] =>
result.coverage.state === "unavailable"
? "unavailable"
: result.coverage.state === "complete"
? "complete"
: "partial";
export const sideManifest = (
side: ManagedMemberComparisonSide,
): ManagedMemberComparisonResult["left"] => ({
evidence_id: side.evidenceId,
artifact_sha256: side.result.artifact.sha256,
mvid: side.result.module?.mvid ?? null,
module_name: side.result.module?.name ?? null,
metadata_status: side.result.metadata.status,
methods_total: side.result.methods.length,
fields_total: side.result.fields.length,
});
export const buildComparisonSummary = (
items: readonly (
| ManagedMemberComparisonResult["methods"][number]
| ManagedMemberComparisonResult["fields"][number]
)[],
): ManagedMemberComparisonResult["summary"] => ({
unchanged: items.filter(({ status }) => status === "unchanged").length,
changed: items.filter(({ status }) => status === "changed").length,
added: items.filter(({ status }) => status === "added").length,
removed: items.filter(({ status }) => status === "removed").length,
unknown: items.filter(({ status }) => status === "unknown").length,
});
export const buildComparisonMatching = (
methodItems: readonly ManagedMemberComparisonResult["methods"][number][],
fieldItems: readonly ManagedMemberComparisonResult["fields"][number][],
): ManagedMemberComparisonResult["matching"] => ({
exact_il_signature: methodItems.filter(
({ match }) => match.basis === "exact-il-signature",
).length,
exact_signature: [...methodItems, ...fieldItems].filter(
({ match }) => match.basis === "exact-signature",
).length,
structural_method_shape: methodItems.filter(
({ match }) => match.basis === "structural-method-shape",
).length,
field_signature: fieldItems.filter(
({ match }) => match.basis === "field-signature",
).length,
ambiguous:
methodItems.filter(({ match }) => match.status === "ambiguous").length +
fieldItems.filter(({ match }) => match.status === "ambiguous").length,
unmatched: [...methodItems, ...fieldItems].filter(
({ match }) => match.status === "unmatched",
).length,
});
export const comparisonLimitations = (
left: ManagedMemberInspection,
right: ManagedMemberInspection,
): string[] => {
const limitations: string[] = [
"Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.",
"Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.",
"Fields pair by exact signature, then declared type, name, and signature; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.",
];
if (left.coverage.state !== "complete" || right.coverage.state !== "complete")
limitations.push("At least one managed member observation is partial.");
return limitations;
};
@@ -0,0 +1,410 @@
import canonicalize from "canonicalize";
import type { ManagedMemberInspection } from "./managedArtifact.js";
import type { ManagedMemberComparisonResult } from "./managedMemberComparison.js";
import {
type ManagedFieldMatches,
type ManagedMethodMatches,
sha256,
} from "./managedMemberComparisonMatch.js";
type Method = ManagedMemberInspection["methods"][number];
type Field = ManagedMemberInspection["fields"][number];
type MethodItem = ManagedMemberComparisonResult["methods"][number];
type FieldItem = ManagedMemberComparisonResult["fields"][number];
type UnmatchedComparison = Extract<
MethodItem["match"],
{ readonly status: "unmatched" }
>;
type OneSided<Item> =
| { readonly left: Item; readonly right?: never }
| { readonly left?: never; readonly right: Item };
interface ComparisonItemContext {
readonly leftEvidenceId: string;
readonly rightEvidenceId: string;
readonly leftComplete: boolean;
readonly rightComplete: boolean;
}
/** Declared type and name of each unpaired member, per side, whose signature was not decoded. */
interface UndecodedOneSidedNames {
readonly left: ReadonlySet<string>;
readonly right: ReadonlySet<string>;
}
const methodDimensions = (
left: Method,
right: Method,
): {
readonly dimensions: MethodItem["dimensions"];
readonly bodyUnknown: boolean;
} => {
const dimensions: MethodItem["dimensions"] = [];
if (left.flags !== right.flags || left.impl_flags !== right.impl_flags)
dimensions.push("metadata");
if (left.signature.raw_sha256 !== right.signature.raw_sha256)
dimensions.push("signature");
const leftBodyComplete =
left.body.status === "present" && left.body.truncated_instructions === 0;
const rightBodyComplete =
right.body.status === "present" && right.body.truncated_instructions === 0;
const bothAbsent =
left.body.status === "absent" && right.body.status === "absent";
if (
(left.body.status === "absent" && rightBodyComplete) ||
(right.body.status === "absent" && leftBodyComplete)
)
dimensions.push("availability");
if (bothAbsent) return { dimensions, bodyUnknown: false };
if (!leftBodyComplete || !rightBodyComplete)
return { dimensions, bodyUnknown: true };
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
dimensions.push("cil");
if (
canonicalize(left.body.opcode_counts) !==
canonicalize(right.body.opcode_counts)
)
dimensions.push("opcode-shape");
if (callShape(left.body.anchors) !== callShape(right.body.anchors))
dimensions.push("call-shape");
if (fieldShape(left.body.anchors) !== fieldShape(right.body.anchors))
dimensions.push("field-shape");
if (
canonicalize(left.body.exception_regions) !==
canonicalize(right.body.exception_regions)
)
dimensions.push("exception-shape");
return { dimensions, bodyUnknown: false };
};
const callShape = (anchors: Method["body"]["anchors"]): string =>
JSON.stringify(
anchors
.filter(({ operand_kind }) => operand_kind === "method")
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
);
const fieldShape = (anchors: Method["body"]["anchors"]): string =>
JSON.stringify(
anchors
.filter(({ operand_kind }) => operand_kind === "field")
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
);
const methodIdentity = (item: Method): NonNullable<MethodItem["left"]> => ({
token: item.token,
declaring_type: item.declaring_type,
name: item.name,
signature_sha256: item.signature.raw_sha256,
normalized_il_sha256: item.body.normalized_il_sha256,
});
const fieldIdentity = (item: Field): NonNullable<FieldItem["left"]> => ({
token: item.token,
declaring_type: item.declaring_type,
name: item.name,
signature_sha256: item.signature.raw_sha256,
});
const unmatchedComparison = (): UnmatchedComparison => ({
status: "unmatched",
basis: "none",
confidence: "unknown",
candidate_left_tokens: [],
candidate_right_tokens: [],
});
const methodOnlyItem = (
member: OneSided<Method>,
context: ComparisonItemContext,
undecoded: UndecodedOneSidedNames,
): MethodItem => {
if (member.left !== undefined) {
const limitations = absenceLimitations(member.left, {
oppositeComplete: context.rightComplete,
oppositeUndecodedNames: undecoded.right,
opposite: "right",
inventory: "method",
});
return {
item_id: `mmc_method_${sha256({ token: member.left.token, side: "left" })}`,
status: limitations.length === 0 ? "removed" : "unknown",
left: methodIdentity(member.left),
right: null,
match: unmatchedComparison(),
dimensions: ["availability"],
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations,
};
}
const limitations = absenceLimitations(member.right, {
oppositeComplete: context.leftComplete,
oppositeUndecodedNames: undecoded.left,
opposite: "left",
inventory: "method",
});
return {
item_id: `mmc_method_${sha256({ token: member.right.token, side: "right" })}`,
status: limitations.length === 0 ? "added" : "unknown",
left: null,
right: methodIdentity(member.right),
match: unmatchedComparison(),
dimensions: ["availability"],
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations,
};
};
/**
* Why a one-sided member's absence from the other inventory was not
* observed: that inventory is incomplete, the member's own signature was not
* decoded, so no shape round could seek a changed counterpart, or the other
* inventory has an unpaired (one-sided or ambiguous) same-named member whose
* signature was not decoded, which may be this member with a changed
* signature.
*/
const absenceLimitations = (
member: Method | Field,
opposite: {
readonly oppositeComplete: boolean;
readonly oppositeUndecodedNames: ReadonlySet<string>;
readonly opposite: "left" | "right";
readonly inventory: "method" | "field";
},
): string[] => [
...(opposite.oppositeComplete
? []
: [
`unknown-within-incomplete-metadata: The ${opposite.opposite} ${opposite.inventory} inventory is incomplete, so absence was not observed.`,
]),
...(member.signature.parse_status === "decoded"
? []
: [
`signature-not-decoded: The member's ${member.signature.parse_status} signature was compared only by exact declared type, name, and raw bytes, so a changed or renamed counterpart could not be sought.`,
]),
...(member.signature.parse_status === "decoded" &&
opposite.oppositeUndecodedNames.has(declaredName(member))
? [
`counterpart-signature-not-decoded: The ${opposite.opposite} ${opposite.inventory} inventory has an unpaired member with the same declared type and name whose signature was not decoded, so it may be this member with a changed signature.`,
]
: []),
];
const declaredName = (member: Method | Field): string =>
JSON.stringify([member.declaring_type, member.name]);
/**
* Declared names of unpaired members whose signature was not decoded: one-sided
* members and candidates of ambiguous groups, which also remain unpaired.
*/
const undecodedOneSidedNames = (members: {
readonly leftOnly: readonly { readonly item: Method | Field }[];
readonly rightOnly: readonly { readonly item: Method | Field }[];
readonly ambiguous: readonly {
readonly left: readonly { readonly item: Method | Field }[];
readonly right: readonly { readonly item: Method | Field }[];
}[];
}): UndecodedOneSidedNames => {
const names = (side: readonly { readonly item: Method | Field }[]) =>
new Set(
side
.filter(({ item }) => item.signature.parse_status !== "decoded")
.map(({ item }) => declaredName(item)),
);
return {
left: names([
...members.leftOnly,
...members.ambiguous.flatMap(({ left }) => left),
]),
right: names([
...members.rightOnly,
...members.ambiguous.flatMap(({ right }) => right),
]),
};
};
const fieldOnlyItem = (
member: OneSided<Field>,
context: ComparisonItemContext,
undecoded: UndecodedOneSidedNames,
): FieldItem => {
if (member.left !== undefined) {
const limitations = absenceLimitations(member.left, {
oppositeComplete: context.rightComplete,
oppositeUndecodedNames: undecoded.right,
opposite: "right",
inventory: "field",
});
return {
item_id: `mmc_field_${sha256({ token: member.left.token, side: "left" })}`,
status: limitations.length === 0 ? "removed" : "unknown",
left: fieldIdentity(member.left),
right: null,
match: unmatchedComparison(),
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations,
};
}
const limitations = absenceLimitations(member.right, {
oppositeComplete: context.leftComplete,
oppositeUndecodedNames: undecoded.left,
opposite: "left",
inventory: "field",
});
return {
item_id: `mmc_field_${sha256({ token: member.right.token, side: "right" })}`,
status: limitations.length === 0 ? "added" : "unknown",
left: null,
right: fieldIdentity(member.right),
match: unmatchedComparison(),
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations,
};
};
/**
* Name the identity key an ambiguous group shares. The exact-signature key
* already includes the declared type and name, so names cannot separate it.
*/
const ambiguityLimitation = (
members: "methods" | "fields",
basis: MethodItem["match"]["basis"],
): string =>
basis === "exact-signature"
? `Multiple managed ${members} share the same declared type, name, and raw signature; REA did not guess a token remap.`
: members === "methods"
? "Multiple managed methods share the same non-name identity key; REA did not guess a token remap."
: "Multiple managed fields share the same signature; REA did not guess a token remap from names.";
export const buildMethodItems = (
matches: ManagedMethodMatches,
context: ComparisonItemContext,
): MethodItem[] => {
const items: MethodItem[] = [];
for (const pair of matches.pairs) {
const { dimensions: observedDimensions, bodyUnknown } = methodDimensions(
pair.left.item,
pair.right.item,
);
const dimensions = bodyUnknown
? [...observedDimensions, "body-coverage" as const]
: observedDimensions;
const observedChange = observedDimensions.length > 0;
items.push({
item_id: `mmc_method_${sha256({
left: pair.left.item.token,
right: pair.right.item.token,
basis: pair.basis,
})}`,
status: observedChange
? "changed"
: bodyUnknown
? "unknown"
: "unchanged",
left: methodIdentity(pair.left.item),
right: methodIdentity(pair.right.item),
match: {
status: "matched",
basis: pair.basis,
confidence: pair.confidence,
candidate_left_tokens: [],
candidate_right_tokens: [],
},
dimensions,
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations: bodyUnknown
? [
"Method body facets are unknown because at least one side has unavailable or partial body data.",
]
: [],
});
}
for (const ambiguous of matches.ambiguous) {
items.push({
item_id: `mmc_method_${sha256({
left: ambiguous.left.map(({ item }) => item.token),
right: ambiguous.right.map(({ item }) => item.token),
basis: ambiguous.basis,
})}`,
status: "unknown",
left: null,
right: null,
match: {
status: "ambiguous",
basis: ambiguous.basis,
confidence: "unknown",
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
},
dimensions: ["availability"],
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations: [ambiguityLimitation("methods", ambiguous.basis)],
});
}
const undecoded = undecodedOneSidedNames(matches);
for (const item of matches.leftOnly)
items.push(methodOnlyItem({ left: item.item }, context, undecoded));
for (const item of matches.rightOnly)
items.push(methodOnlyItem({ right: item.item }, context, undecoded));
return items;
};
export const buildFieldItems = (
matches: ManagedFieldMatches,
context: ComparisonItemContext,
): FieldItem[] => {
const items: FieldItem[] = [];
for (const pair of matches.pairs) {
const changed =
pair.left.item.signature.raw_sha256 !==
pair.right.item.signature.raw_sha256 ||
pair.left.item.flags !== pair.right.item.flags;
items.push({
item_id: `mmc_field_${sha256({
left: pair.left.item.token,
right: pair.right.item.token,
})}`,
status: changed ? "changed" : "unchanged",
left: fieldIdentity(pair.left.item),
right: fieldIdentity(pair.right.item),
match: {
status: "matched",
basis: pair.basis,
confidence: pair.confidence,
candidate_left_tokens: [],
candidate_right_tokens: [],
},
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations: [],
});
}
for (const ambiguous of matches.ambiguous)
items.push({
item_id: `mmc_field_${sha256({
left: ambiguous.left.map(({ item }) => item.token),
right: ambiguous.right.map(({ item }) => item.token),
})}`,
status: "unknown",
left: null,
right: null,
match: {
status: "ambiguous",
basis: ambiguous.basis,
confidence: "unknown",
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
},
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
limitations: [ambiguityLimitation("fields", ambiguous.basis)],
});
const undecoded = undecodedOneSidedNames(matches);
for (const item of matches.leftOnly)
items.push(fieldOnlyItem({ left: item.item }, context, undecoded));
for (const item of matches.rightOnly)
items.push(fieldOnlyItem({ right: item.item }, context, undecoded));
return items;
};
@@ -0,0 +1,287 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { parseEvidence } from "../evidence.js";
import {
managedMemberInspectionSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import type {
ManagedMemberComparisonResult,
ManagedMemberComparisonSide,
} from "./managedMemberComparison.js";
import type { JsonValue } from "../jsonValue.js";
export const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed comparison canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
type Method = ManagedMemberInspection["methods"][number];
type Field = ManagedMemberInspection["fields"][number];
type MatchBasis =
ManagedMemberComparisonResult["methods"][number]["match"]["basis"];
type ConcreteMatchBasis = Exclude<MatchBasis, "none">;
interface Keyed<Item> {
readonly item: Item;
readonly exactKey: string | null;
readonly signatureKey: string | null;
readonly structuralKey: string | null;
}
interface MatchedPair<Item> {
readonly left: Keyed<Item>;
readonly right: Keyed<Item>;
readonly basis: ConcreteMatchBasis;
readonly confidence: "exact" | "high";
}
interface Ambiguous<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly basis: ConcreteMatchBasis;
}
const keyMethod = (item: Method): Keyed<Method> => ({
item,
exactKey:
item.signature.parse_status === "decoded" &&
item.body.status === "present" &&
item.body.normalized_il_sha256 !== null
? stableKey([
"method-exact",
item.signature.raw_sha256,
item.body.normalized_il_sha256,
])
: null,
// The raw blob is the exact signature; decoding only feeds shape keys.
signatureKey: stableKey([
"method-signature",
item.declaring_type,
item.name,
item.signature.raw_sha256,
]),
structuralKey:
item.signature.parse_status === "decoded" && item.body.status === "present"
? stableKey([
"method-structural",
item.signature.kind,
item.signature.calling_convention,
item.signature.generic_parameter_count,
item.signature.parameter_count,
item.signature.return_type,
item.signature.parameter_types,
item.body.status,
item.body.header_format,
item.body.il_size,
item.body.max_stack,
item.body.init_locals,
item.body.opcode_counts,
item.body.anchors.map(({ opcode, operand_kind }) => [
opcode,
operand_kind,
]),
item.body.exception_regions.map((region) => [
region.flags,
region.try_length,
region.handler_length,
region.class_token === null ? null : "type-token",
region.filter_offset === null ? null : "filter",
]),
])
: null,
});
const keyField = (item: Field): Keyed<Field> => ({
item,
exactKey:
item.signature.parse_status === "decoded"
? stableKey(["field-exact", item.signature.raw_sha256])
: null,
// Only an undecoded field reaches this round: a decoded field with the
// same raw signature already met its counterpart in the exact round.
signatureKey: stableKey([
"field-signature",
item.declaring_type,
item.name,
item.signature.raw_sha256,
]),
structuralKey: stableKey([
"field-structural",
item.signature.kind,
item.signature.field_type,
item.flags,
]),
});
const stableKey = (value: JsonValue): string => sha256(value);
const matchMethods = (
left: readonly Keyed<Method>[],
right: readonly Keyed<Method>[],
) =>
matchByKeys({
left,
right,
exactBasis: "exact-il-signature",
fallbackBases: [
{
basis: "exact-signature",
key: ({ signatureKey }) => signatureKey,
},
{
basis: "structural-method-shape",
key: ({ structuralKey }) => structuralKey,
},
],
});
const matchFields = (
left: readonly Keyed<Field>[],
right: readonly Keyed<Field>[],
) =>
matchByKeys({
left,
right,
exactBasis: "field-signature",
fallbackBases: [
{
basis: "exact-signature",
key: ({ signatureKey }) => signatureKey,
},
],
});
export type ManagedMethodMatches = ReturnType<typeof matchMethods>;
export type ManagedFieldMatches = ReturnType<typeof matchFields>;
interface MatchByKeysInput<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly exactBasis: ConcreteMatchBasis;
readonly fallbackBases: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[];
}
const matchByKeys = <Item>({
left,
right,
exactBasis,
fallbackBases,
}: MatchByKeysInput<Item>): {
readonly pairs: readonly MatchedPair<Item>[];
readonly ambiguous: readonly Ambiguous<Item>[];
readonly leftOnly: readonly Keyed<Item>[];
readonly rightOnly: readonly Keyed<Item>[];
} => {
const usedLeft = new Set<Keyed<Item>>();
const usedRight = new Set<Keyed<Item>>();
const pairs: MatchedPair<Item>[] = [];
const ambiguous: Ambiguous<Item>[] = [];
const rounds: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
}[] = [
{ basis: exactBasis, key: ({ exactKey }) => exactKey },
...fallbackBases,
];
for (const round of rounds) {
const leftGroups = groupBy(
left.filter((item) => !usedLeft.has(item)),
round.key,
);
const rightGroups = groupBy(
right.filter((item) => !usedRight.has(item)),
round.key,
);
for (const [key, leftItems] of leftGroups) {
const rightItems = rightGroups.get(key);
if (rightItems === undefined) continue;
if (leftItems.length === 1 && rightItems.length === 1) {
const [leftItem] = leftItems;
const [rightItem] = rightItems;
if (leftItem === undefined || rightItem === undefined) continue;
usedLeft.add(leftItem);
usedRight.add(rightItem);
pairs.push({
left: leftItem,
right: rightItem,
basis: round.basis,
confidence:
round.basis === "exact-il-signature" ||
round.basis === "exact-signature" ||
round.basis === "field-signature"
? "exact"
: "high",
});
} else {
for (const item of leftItems) usedLeft.add(item);
for (const item of rightItems) usedRight.add(item);
ambiguous.push({
left: leftItems,
right: rightItems,
basis: round.basis,
});
}
}
}
return {
pairs,
ambiguous,
leftOnly: left.filter((item) => !usedLeft.has(item)),
rightOnly: right.filter((item) => !usedRight.has(item)),
};
};
const groupBy = <Item>(
items: readonly Item[],
keyOf: (item: Item) => string | null,
): Map<string, readonly Item[]> => {
const grouped = new Map<string, Item[]>();
for (const item of items) {
const key = keyOf(item);
if (key === null) continue;
const bucket = grouped.get(key) ?? [];
bucket.push(item);
grouped.set(key, bucket);
}
return grouped;
};
export const keyMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
): {
readonly methodMatches: ReturnType<typeof matchMethods>;
readonly fieldMatches: ReturnType<typeof matchFields>;
} => ({
methodMatches: matchMethods(
left.result.methods.map(keyMethod),
right.result.methods.map(keyMethod),
),
fieldMatches: matchFields(
left.result.fields.map(keyField),
right.result.fields.map(keyField),
),
});
export const parseManagedMemberEvidence = (
evidence: unknown,
): {
readonly evidenceId: string;
readonly result: ManagedMemberInspection;
} => {
const parsed = parseEvidence(evidence);
if (parsed.operation !== "inspect_managed_members")
throw new TypeError("Evidence operation is not inspect_managed_members");
return {
evidenceId: parsed.evidence_id,
result: managedMemberInspectionSchema.parse(parsed.normalized_result),
};
};
@@ -0,0 +1,77 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { parseEvidence } from "../evidence.js";
import {
managedNativeBoundaryInspectionSchema,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "../jsonValue.js";
import {
managedNativeVerificationResultSchema,
type ManagedNativeVerificationInput,
type ManagedNativeVerificationResult,
} from "./managedNativeVerificationSchemas.js";
import {
buildVerificationResult,
collectNativeSymbols,
verifyPinvoke,
} from "./managedNativeVerificationMatch.js";
export {
managedNativeVerificationInputSchema,
type ManagedNativeVerificationInput,
type ManagedNativeVerificationResult,
} from "./managedNativeVerificationSchemas.js";
export { managedNativeVerificationResultSchema };
const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed/native verification canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
const managedBoundaryFromInput = (
input: ManagedNativeVerificationInput,
): ManagedNativeBoundaryInspection => {
const managedEvidence = parseEvidence(input.managed_boundaries);
if (managedEvidence.operation !== "inspect_managed_native_boundaries")
throw new TypeError(
"Evidence operation is not inspect_managed_native_boundaries",
);
return managedNativeBoundaryInspectionSchema.parse(
managedEvidence.normalized_result,
);
};
/** Verify managed P/Invoke declarations against authenticated native Evidence. */
export const verifyManagedNativeBoundaries = (
input: ManagedNativeVerificationInput,
): ManagedNativeVerificationResult => {
const managed = managedBoundaryFromInput(input);
const managedEvidence = parseEvidence(input.managed_boundaries);
const native = collectNativeSymbols(input.native_observations);
const verifiedPinvokes = managed.pinvoke_imports.map((item) =>
verifyPinvoke({
item,
managedEvidenceId: managedEvidence.evidence_id,
native,
}),
);
const pinvokeImports = verifiedPinvokes.map(
({ verification }) => verification,
);
const withoutId = buildVerificationResult({
managedEvidence,
managed,
native,
pinvokeImports,
input,
});
return managedNativeVerificationResultSchema.parse({
...withoutId,
verification_id: `mnv_${sha256(withoutId)}`,
});
};
@@ -0,0 +1,396 @@
import { createHash } from "node:crypto";
import { basename } from "node:path";
import canonicalize from "canonicalize";
import { parseEvidence } from "../evidence.js";
import { functionDossierSchema } from "../hopperValues.js";
import { inspectMachoSchema } from "../nativeInspection.js";
import type { ManagedNativeBoundaryInspection } from "./managedArtifact.js";
import type { JsonValue } from "../jsonValue.js";
import {
pinvokeVerificationSchema,
type ManagedNativeVerificationInput,
type ManagedNativeVerificationResult,
type NativeSymbol,
type PinvokeVerification,
} from "./managedNativeVerificationSchemas.js";
const digest = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed/native verification canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
type PinvokeImport = ManagedNativeBoundaryInspection["pinvoke_imports"][number];
type VerifiedPinvoke = {
readonly verification: PinvokeVerification;
};
const moduleName = (
evidence: ReturnType<typeof parseEvidence>,
): string | null => evidence.subject?.name ?? null;
const modulePath = (
evidence: ReturnType<typeof parseEvidence>,
): string | null => evidence.subject?.local_path ?? null;
const symbolsForEvidence = (
evidence: ReturnType<typeof parseEvidence>,
): {
readonly supported: boolean;
readonly symbols: readonly NativeSymbol[];
} => {
if (evidence.operation === "inspect_macho") {
const result = inspectMachoSchema.parse(evidence.normalized_result);
return {
supported: true,
symbols: result.exports.items.map((symbol) => ({
evidence_id: evidence.evidence_id,
operation: evidence.operation,
name: symbol.name,
address: symbol.address,
module_name: moduleName(evidence),
module_path: modulePath(evidence),
source: "macho-export" as const,
})),
};
}
if (evidence.operation === "analyze_function") {
const dossier = functionDossierSchema.parse(evidence.normalized_result);
return {
supported: true,
symbols: [
{
evidence_id: evidence.evidence_id,
operation: evidence.operation,
name: dossier.procedure.name,
address: dossier.procedure.address,
module_name: moduleName(evidence),
module_path: modulePath(evidence),
source: "function-dossier" as const,
},
],
};
}
return { supported: false, symbols: [] };
};
export const collectNativeSymbols = (
observations: readonly ManagedNativeVerificationInput["native_observations"][number][],
): {
readonly symbols: readonly NativeSymbol[];
readonly accepted: number;
readonly unsupported: number;
} => {
const symbols: NativeSymbol[] = [];
let accepted = 0;
let unsupported = 0;
for (const raw of observations) {
const evidence = parseEvidence(raw);
const extracted = symbolsForEvidence(evidence);
if (!extracted.supported) {
unsupported += 1;
} else {
accepted += 1;
symbols.push(...extracted.symbols);
}
}
return { symbols, accepted, unsupported };
};
const sameSymbolName = (expected: string, native: NativeSymbol): boolean =>
expected ===
(native.source === "macho-export" && native.name.startsWith("_")
? native.name.slice(1)
: native.name);
const normalizeModule = (value: string): string =>
basename(value)
.toLowerCase()
.replace(/^lib/u, "")
.replace(/\.(dll|dylib|so|node|exe)$/u, "");
const moduleCompatible = (
scope: string | null,
symbol: NativeSymbol,
): boolean => {
if (scope === null) return true;
const expected = normalizeModule(scope);
return [symbol.module_name, symbol.module_path]
.filter((value): value is string => value !== null)
.map(normalizeModule)
.some((value) => value === expected);
};
const candidateNames = (
managed: Pick<
PinvokeImport,
"import_name" | "char_set" | "call_convention" | "no_mangle"
>,
): readonly string[] => {
const names = new Set<string>([managed.import_name]);
if (!managed.no_mangle) {
if (managed.char_set === "unicode") names.add(`${managed.import_name}W`);
if (managed.char_set === "ansi") names.add(`${managed.import_name}A`);
if (managed.call_convention === "stdcall") {
names.add(`_${managed.import_name}`);
names.add(`_${managed.import_name}@0`);
}
}
return [...names];
};
type PinvokeMatchField =
| "status"
| "basis"
| "confidence"
| "matched_native"
| "candidates";
type PinvokeMatch<
Verification extends PinvokeVerification = PinvokeVerification,
> = Verification extends PinvokeVerification
? Pick<Verification, PinvokeMatchField>
: never;
interface PinvokeCandidateMatch {
readonly match: PinvokeMatch;
}
const matchPinvoke = (
managed: PinvokeImport,
symbols: readonly NativeSymbol[],
supportedNativeEvidence: number,
): PinvokeCandidateMatch => {
const names = candidateNames(managed);
const allCandidates = symbols.filter((symbol) =>
names.some((name) => sameSymbolName(name, symbol)),
);
const [first, ...remaining] = allCandidates;
if (first === undefined)
return {
match: {
status: "unresolved",
basis:
supportedNativeEvidence > 0
? "no-native-candidate"
: "unsupported-native-evidence",
confidence: "unknown",
matched_native: null,
candidates: [],
},
};
const candidates: [NativeSymbol, ...NativeSymbol[]] = [first, ...remaining];
const exact = candidates.find(
(symbol) =>
managed.import_name === symbol.name &&
moduleCompatible(managed.import_scope_name, symbol),
);
const decorated = candidates.find((symbol) =>
moduleCompatible(managed.import_scope_name, symbol),
);
const selected = exact ?? decorated ?? first;
if (!moduleCompatible(managed.import_scope_name, selected))
return {
match: {
status: "contradicted",
basis: "module-mismatch",
confidence: "unknown",
matched_native: selected,
candidates,
},
};
if (exact !== undefined)
return {
match: {
status: "verified",
basis:
selected.source === "macho-export"
? "exact-export-name"
: "exact-function-name",
confidence: "observed",
matched_native: selected,
candidates,
},
};
return {
match: {
basis: "decorated-name-candidate",
status: "inferred",
confidence: "inferred",
matched_native: selected,
candidates,
},
};
};
const pinvokeLimitations = (
status: PinvokeVerification["status"],
managed: PinvokeImport,
): readonly string[] => [
...(managed.import_scope_name === null
? ["Managed declaration does not name an import scope/module."]
: []),
...(status === "inferred"
? [
"Native symbol matched a decorated candidate rather than the exact declared import name.",
]
: []),
...(status === "contradicted"
? [
"A symbol name candidate exists, but the supplied native Evidence module identity does not match the managed import scope.",
]
: []),
...(status === "unresolved"
? [
"No supplied native export/function Evidence matched this declared import.",
]
: []),
];
interface VerifyPinvokeContext {
readonly item: PinvokeImport;
readonly managedEvidenceId: string;
readonly native: {
readonly symbols: readonly NativeSymbol[];
readonly accepted: number;
};
}
export const verifyPinvoke = ({
item,
managedEvidenceId,
native,
}: VerifyPinvokeContext): VerifiedPinvoke => {
const managed = {
token: item.token,
member_token: item.member_token,
member_name: item.member_name,
import_name: item.import_name,
import_scope_name: item.import_scope_name,
no_mangle: item.no_mangle,
char_set: item.char_set,
call_convention: item.call_convention,
declaration_verification: item.verification,
};
const selection = matchPinvoke(item, native.symbols, native.accepted);
const limitations = pinvokeLimitations(selection.match.status, item);
return {
verification: pinvokeVerificationSchema.parse({
item_id: `mnv_pinvoke_${digest({
managedEvidenceId,
token: item.token,
importName: item.import_name,
importScope: item.import_scope_name,
candidates: selection.match.candidates,
})}`,
managed,
...selection.match,
evidence_links: [
managedEvidenceId,
...new Set(selection.match.candidates.map(({ evidence_id: id }) => id)),
],
limitations,
}),
};
};
const countStatuses = (
items: readonly PinvokeVerification[],
): Pick<
ManagedNativeVerificationResult["summary"],
"verified" | "inferred" | "unresolved" | "contradicted"
> => ({
verified: items.filter(({ status }) => status === "verified").length,
inferred: items.filter(({ status }) => status === "inferred").length,
unresolved: items.filter(({ status }) => status === "unresolved").length,
contradicted: items.filter(({ status }) => status === "contradicted").length,
});
interface VerificationResultInput {
readonly managedEvidence: ReturnType<typeof parseEvidence>;
readonly managed: ManagedNativeBoundaryInspection;
readonly native: {
readonly symbols: readonly NativeSymbol[];
readonly accepted: number;
readonly unsupported: number;
};
readonly pinvokeImports: readonly PinvokeVerification[];
readonly input: ManagedNativeVerificationInput;
}
export const buildVerificationResult = ({
managedEvidence,
managed,
native,
pinvokeImports,
input,
}: VerificationResultInput): Omit<
ManagedNativeVerificationResult,
"verification_id"
> => {
const counts = countStatuses(pinvokeImports);
const nativeBodyUnresolved = managed.native_implementations.filter(
({ boundary_kind: kind }) => kind !== "pinvoke",
).length;
const coverage: ManagedNativeVerificationResult["coverage"] = {
status:
managed.coverage.state === "complete" && native.unsupported === 0
? "complete-within-inputs"
: "partial",
};
return {
algorithm: {
name: "rea-managed-native-verification" as const,
token_identity: "build-local" as const,
token_to_address_mapping: "not-inferred" as const,
},
managed_boundary: {
evidence_id: managedEvidence.evidence_id,
artifact_sha256: managed.artifact.sha256,
artifact_path: managed.artifact.path,
mvid: managed.module?.mvid ?? null,
metadata_status: managed.metadata.status,
pinvoke_imports_total: managed.pinvoke_imports.length,
native_implementations_total: managed.native_implementations.length,
coverage_state: managed.coverage.state,
},
native_observations: {
total: input.native_observations.length,
accepted: native.accepted,
unsupported: native.unsupported,
symbols: native.symbols.length,
},
summary: {
...counts,
native_body_unresolved: nativeBodyUnresolved,
},
pinvoke_imports: [...pinvokeImports],
native_implementations: {
unresolved: nativeBodyUnresolved,
reason:
"Managed metadata tokens and RVAs are not translated to native provider addresses by this workflow; C++/CLI, ReadyToRun, and native-body mappings require explicit provider-supported bridge evidence.",
},
coverage,
evidence_links: [
managedEvidence.evidence_id,
...input.native_observations.map(({ evidence_id: id }) => id),
],
limitations: [
"P/Invoke verification checks declared import names against supplied native export or function-name Evidence only.",
"A matching native symbol verifies that a candidate export/function was observed; it does not prove CLR binding, marshaling behavior, call reachability, or runtime loading.",
"Missing supplied native symbols are reported as unresolved, not proof that a dependency cannot exist.",
"Managed metadata tokens and method RVAs are not interpreted as native addresses.",
...(managed.coverage.state === "complete"
? []
: ["Managed boundary input is partial or unavailable."]),
...(native.unsupported === 0
? []
: [
"Some native Evidence operations were unsupported by this workflow.",
]),
],
};
};
@@ -0,0 +1,206 @@
import { z } from "zod";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import { cliMetadataGuidSchema } from "./managedArtifact.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const textSchema = z.string().min(1);
const nativeSymbolSchema = z.strictObject({
evidence_id: evidenceIdSchema,
operation: z.string().min(1),
name: z.string().min(1),
address: z.string().nullable(),
module_name: z.string().nullable(),
module_path: z.string().nullable(),
source: z.enum(["macho-export", "function-dossier"]),
});
export type NativeSymbol = z.infer<typeof nativeSymbolSchema>;
const pinvokeVerificationContextShape = {
item_id: prefixedDigestSchema("mnv_pinvoke"),
managed: z.strictObject({
token: tokenSchema,
member_token: tokenSchema.nullable(),
member_name: z.string().nullable(),
import_name: z.string().min(1),
import_scope_name: z.string().nullable(),
no_mangle: z.boolean(),
char_set: z.enum(["not-specified", "ansi", "unicode", "auto", "unknown"]),
call_convention: z.enum([
"not-specified",
"winapi",
"cdecl",
"stdcall",
"thiscall",
"fastcall",
"unknown",
]),
declaration_verification: z.literal("managed-declaration-only"),
}),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(textSchema),
};
const observedCandidatesSchema = z
.tuple([nativeSymbolSchema])
.rest(nativeSymbolSchema);
export const pinvokeVerificationSchema = z.discriminatedUnion("status", [
z.strictObject({
...pinvokeVerificationContextShape,
status: z.literal("verified"),
basis: z.enum(["exact-export-name", "exact-function-name"]),
confidence: z.literal("observed"),
matched_native: nativeSymbolSchema,
candidates: observedCandidatesSchema,
}),
z.strictObject({
...pinvokeVerificationContextShape,
status: z.literal("inferred"),
basis: z.literal("decorated-name-candidate"),
confidence: z.literal("inferred"),
matched_native: nativeSymbolSchema,
candidates: observedCandidatesSchema,
}),
z.strictObject({
...pinvokeVerificationContextShape,
status: z.literal("unresolved"),
basis: z.enum(["no-native-candidate", "unsupported-native-evidence"]),
confidence: z.literal("unknown"),
matched_native: z.null(),
candidates: emptyArraySchema,
}),
z.strictObject({
...pinvokeVerificationContextShape,
status: z.literal("contradicted"),
basis: z.literal("module-mismatch"),
confidence: z.literal("unknown"),
matched_native: nativeSymbolSchema,
candidates: observedCandidatesSchema,
}),
]);
export type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
/** Authenticated managed boundary Evidence plus native observations. */
export const managedNativeVerificationInputSchema = z
.strictObject({
managed_boundaries: evidenceSchema,
native_observations: z.array(evidenceSchema).min(1),
})
.superRefine((input, context) => {
const ids = new Set<string>();
for (const [index, evidence] of input.native_observations.entries()) {
if (evidence.evidence_id === input.managed_boundaries.evidence_id) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message:
"Native observation Evidence must be distinct from managed boundary Evidence",
});
}
if (ids.has(evidence.evidence_id)) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message: "Native observation Evidence IDs must be unique",
});
}
ids.add(evidence.evidence_id);
}
});
export type ManagedNativeVerificationInput = z.infer<
typeof managedNativeVerificationInputSchema
>;
const verificationCoverageSchema = z.strictObject({
status: z.enum(["complete-within-inputs", "partial"]),
});
/** Provider-neutral managed/native verification result. */
export const managedNativeVerificationResultSchema = z
.strictObject({
verification_id: prefixedDigestSchema("mnv"),
algorithm: z.strictObject({
name: z.literal("rea-managed-native-verification"),
token_identity: z.literal("build-local"),
token_to_address_mapping: z.literal("not-inferred"),
}),
managed_boundary: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1),
mvid: cliMetadataGuidSchema.nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
pinvoke_imports_total: z.number().int().min(0),
native_implementations_total: z.number().int().min(0),
coverage_state: z.enum(["complete", "partial", "unavailable"]),
}),
native_observations: z.strictObject({
total: z.number().int().min(1),
accepted: z.number().int().min(0),
unsupported: z.number().int().min(0),
symbols: z.number().int().min(0),
}),
summary: z.strictObject({
verified: z.number().int().min(0),
inferred: z.number().int().min(0),
unresolved: z.number().int().min(0),
contradicted: z.number().int().min(0),
native_body_unresolved: z.number().int().min(0),
}),
pinvoke_imports: z.array(pinvokeVerificationSchema),
native_implementations: z.strictObject({
unresolved: z.number().int().min(0),
reason: textSchema,
}),
coverage: verificationCoverageSchema,
evidence_links: z.array(evidenceIdSchema).min(2),
limitations: z.array(textSchema),
})
.superRefine((result, context) => {
const observedNativeCount =
result.native_observations.accepted +
result.native_observations.unsupported;
if (observedNativeCount !== result.native_observations.total)
context.addIssue({
code: "custom",
path: ["native_observations"],
message: "Native observation counts must account for the total input",
});
for (const status of [
"verified",
"inferred",
"unresolved",
"contradicted",
] as const)
if (
result.summary[status] !==
result.pinvoke_imports.filter((item) => item.status === status).length
)
context.addIssue({
code: "custom",
path: ["summary", status],
message: `P/Invoke ${status} count must match the item results`,
});
if (
result.summary.native_body_unresolved !==
result.native_implementations.unresolved
)
context.addIssue({
code: "custom",
path: ["summary", "native_body_unresolved"],
message: "Native body summary must match unresolved implementations",
});
});
export type ManagedNativeVerificationResult = z.infer<
typeof managedNativeVerificationResultSchema
>;
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "../evidence.js";
import { managedReconstructionImportInputSchema } from "./managedReconstruction.js";
describe("managed reconstruction import input", () => {
it("accepts more than the former 50-method and 100-note ceilings", () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "inspect_managed_members",
parameters: {},
result: {},
},
);
const method = {
token: "0x06000001",
signature_sha256: "a".repeat(64),
normalized_il_sha256: null,
reconstruction: {
kind: "semantic-pseudocode",
language: "pseudocode",
text: "return;",
},
};
const parsed = managedReconstructionImportInputSchema.parse({
static_members: evidence,
decompiler: {
name: "Fixture decompiler",
family: "other",
options: Array.from({ length: 51 }, (_, index) => `option-${index}`),
},
methods: Array.from({ length: 51 }, (_, index) => ({
...method,
token: `0x${(0x06000001 + index).toString(16).padStart(8, "0")}`,
signature_sha256: index.toString(16).padStart(64, "0"),
})),
notes: Array.from({ length: 101 }, (_, index) => `note-${index}`),
});
expect(parsed.methods).toHaveLength(51);
expect(parsed.decompiler.options).toHaveLength(51);
expect(parsed.decompiler).toMatchObject({
version: null,
executable_sha256: null,
});
expect(parsed.notes).toHaveLength(101);
});
it("accepts decompiler text and metadata without arbitrary length ceilings", () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "inspect_managed_members",
parameters: {},
result: {},
},
);
const text = "x".repeat(65_537);
const metadata = "m".repeat(4_097);
const result = managedReconstructionImportInputSchema.parse({
static_members: evidence,
decompiler: {
name: metadata,
version: metadata,
family: "other",
executable_sha256: null,
options: ["o".repeat(513)],
},
methods: [
{
token: "0x06000001",
signature_sha256: "a".repeat(64),
normalized_il_sha256: null,
reconstruction: {
kind: "semantic-pseudocode",
language: "pseudocode",
text,
source_path: metadata,
},
},
],
notes: [metadata],
});
expect(result.methods[0]?.reconstruction.text).toHaveLength(65_537);
expect(result.decompiler.name).toHaveLength(4_097);
});
});
+286
View File
@@ -0,0 +1,286 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "../evidence.js";
import {
cliMetadataGuidSchema,
managedMemberInspectionSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import type { JsonValue } from "../jsonValue.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const textSchema = z.string().min(1);
const decompilerSchema = z.strictObject({
name: textSchema,
version: textSchema.nullable().default(null),
family: z.enum(["ilspy", "dnspy", "dnlib", "mono-cecil", "other"]),
executable_sha256: digestSchema.nullable().default(null),
options: z.array(z.string()).default([]),
});
const managedReconstructionMethodInputSchema = z.strictObject({
token: tokenSchema,
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
reconstruction: z.strictObject({
kind: z.enum(["decompiled-csharp", "decompiled-il", "semantic-pseudocode"]),
language: z.enum(["csharp", "il", "pseudocode"]),
text: textSchema,
text_sha256: digestSchema.optional(),
source_path: textSchema.nullable().optional(),
start_line: z.number().int().min(1).nullable().optional(),
end_line: z.number().int().min(1).nullable().optional(),
}),
});
type ManagedReconstructionMethodInput = z.infer<
typeof managedReconstructionMethodInputSchema
>;
export const managedReconstructionImportInputSchema = z.strictObject({
static_members: evidenceSchema,
decompiler: decompilerSchema,
methods: z.array(managedReconstructionMethodInputSchema).min(1),
notes: z.array(textSchema).default([]),
});
const importedMethodSchema = z.strictObject({
token: tokenSchema,
declaring_type: z.string().nullable(),
name: z.string(),
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
body_sha256: digestSchema.nullable(),
il_size: z.number().int().min(0),
reconstruction: z.strictObject({
kind: z.enum(["decompiled-csharp", "decompiled-il", "semantic-pseudocode"]),
language: z.enum(["csharp", "il", "pseudocode"]),
text: textSchema,
text_sha256: digestSchema,
text_length: z.number().int().min(1),
line_count: z.number().int().min(1),
source_path: textSchema.nullable(),
start_line: z.number().int().min(1).nullable(),
end_line: z.number().int().min(1).nullable(),
}),
validation: z.strictObject({
matched_static_member: z.literal(true),
exact_build_required: z.literal(true),
canonical_observation: z.literal(false),
confidence_floor: z.literal("inference"),
}),
});
export const managedReconstructionImportResultSchema = z.strictObject({
reconstruction_id: prefixedDigestSchema("mre"),
phase: z.literal("reconstruction-import"),
executed: z.literal(false),
static_observation: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1),
byte_length: z.number().int().min(0),
module_name: z.string().nullable(),
mvid: cliMetadataGuidSchema.nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
}),
decompiler: decompilerSchema.extend({
options_sha256: digestSchema,
}),
summary: z.strictObject({
imported_methods: z.number().int().min(1),
decompiled_csharp_methods: z.number().int().min(0),
decompiled_il_methods: z.number().int().min(0),
pseudocode_methods: z.number().int().min(0),
total_text_bytes: z.number().int().min(1),
}),
methods: z.array(importedMethodSchema).min(1),
notes: z.array(textSchema),
evidence_links: z.array(evidenceIdSchema).length(1),
limitations: z.array(textSchema),
});
export type ManagedReconstructionImportInput = z.infer<
typeof managedReconstructionImportInputSchema
>;
export type ManagedReconstructionImportResult = z.infer<
typeof managedReconstructionImportResultSchema
>;
type Member = ManagedMemberInspection["methods"][number];
type ImportedMethod = ManagedReconstructionImportResult["methods"][number];
type StaticObservation =
ManagedReconstructionImportResult["static_observation"];
const sha256Text = (value: string): string =>
createHash("sha256").update(value).digest("hex");
const sha256Json = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed reconstruction canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
const countLines = (text: string): number =>
text.length === 0 ? 0 : text.split(/\r\n|\r|\n/u).length;
const findObservedMethod = (
members: ManagedMemberInspection,
candidate: ManagedReconstructionMethodInput,
): Member | undefined =>
members.methods.find(
(item) =>
item.token === candidate.token &&
item.signature.raw_sha256 === candidate.signature_sha256 &&
item.body.status === "present" &&
item.body.normalized_il_sha256 !== null &&
candidate.normalized_il_sha256 !== null &&
item.body.normalized_il_sha256 === candidate.normalized_il_sha256,
);
const verifyTextSha256 = (
candidate: ManagedReconstructionMethodInput,
textSha256: string,
): void => {
if (
candidate.reconstruction.text_sha256 !== undefined &&
candidate.reconstruction.text_sha256 !== textSha256
)
throw new TypeError(
`Reconstruction text hash mismatch for ${candidate.token}`,
);
};
const buildImportedMethod = (
observed: Member,
candidate: ManagedReconstructionMethodInput,
textSha256: string,
): ImportedMethod => ({
token: observed.token,
declaring_type: observed.declaring_type,
name: observed.name,
signature_sha256: observed.signature.raw_sha256,
normalized_il_sha256: observed.body.normalized_il_sha256,
body_sha256: observed.body.il_sha256,
il_size: observed.body.il_size,
reconstruction: {
kind: candidate.reconstruction.kind,
language: candidate.reconstruction.language,
text: candidate.reconstruction.text,
text_sha256: textSha256,
text_length: candidate.reconstruction.text.length,
line_count: countLines(candidate.reconstruction.text),
source_path: candidate.reconstruction.source_path ?? null,
start_line: candidate.reconstruction.start_line ?? null,
end_line: candidate.reconstruction.end_line ?? null,
},
validation: {
matched_static_member: true as const,
exact_build_required: true as const,
canonical_observation: false as const,
confidence_floor: "inference" as const,
},
});
const buildReconstructionSummary = (
methods: readonly ImportedMethod[],
): ManagedReconstructionImportResult["summary"] => ({
imported_methods: methods.length,
decompiled_csharp_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "decompiled-csharp",
).length,
decompiled_il_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "decompiled-il",
).length,
pseudocode_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "semantic-pseudocode",
).length,
total_text_bytes: methods.reduce(
(total, { reconstruction }) => total + reconstruction.text_length,
0,
),
});
const buildStaticObservation = (
staticEvidence: ReturnType<typeof parseEvidence>,
members: ManagedMemberInspection,
): StaticObservation => ({
evidence_id: staticEvidence.evidence_id,
artifact_sha256: members.artifact.sha256,
artifact_path: members.artifact.path,
byte_length: members.artifact.byte_length,
module_name: members.module?.name ?? null,
mvid: members.module?.mvid ?? null,
metadata_status: members.metadata.status,
});
const buildDecompilerRecord = (
decompiler: ManagedReconstructionImportInput["decompiler"],
): ManagedReconstructionImportResult["decompiler"] => ({
...decompiler,
options_sha256: sha256Json(decompiler.options),
});
const RECONSTRUCTION_LIMITATIONS = [
"Decompiler output is imported as reconstruction evidence and analyst inference; metadata and IL observations remain canonical.",
"This operation did not execute, load, reflect over, debug, instrument, patch, or decompile the target artifact.",
"The imported reconstruction is valid only for the exact artifact SHA-256, MVID, method signature, and normalized IL shape recorded here.",
"Obfuscated names, decompiler variables, and control-flow restructuring are not treated as proof without separate validation.",
];
const buildReconstructionWithoutId = (
input: ManagedReconstructionImportInput,
staticEvidence: ReturnType<typeof parseEvidence>,
members: ManagedMemberInspection,
methods: readonly ImportedMethod[],
): Omit<ManagedReconstructionImportResult, "reconstruction_id"> => ({
phase: "reconstruction-import" as const,
executed: false as const,
static_observation: buildStaticObservation(staticEvidence, members),
decompiler: buildDecompilerRecord(input.decompiler),
summary: buildReconstructionSummary(methods),
methods: [...methods],
notes: input.notes,
evidence_links: [staticEvidence.evidence_id],
limitations: RECONSTRUCTION_LIMITATIONS,
});
/** Authenticate decompiler reconstruction against static IL Evidence. */
export const importManagedReconstruction = (
input: ManagedReconstructionImportInput,
): ManagedReconstructionImportResult => {
const staticEvidence = parseEvidence(input.static_members);
if (staticEvidence.operation !== "inspect_managed_members")
throw new TypeError("Evidence operation is not inspect_managed_members");
const members = managedMemberInspectionSchema.parse(
staticEvidence.normalized_result,
);
const methods = input.methods.map((candidate) => {
const observed = findObservedMethod(members, candidate);
if (observed === undefined)
throw new TypeError(
`Reconstruction method lock ${candidate.token} does not match a static managed member observation`,
);
const textSha256 = sha256Text(candidate.reconstruction.text);
verifyTextSha256(candidate, textSha256);
return buildImportedMethod(observed, candidate, textSha256);
});
const withoutId = buildReconstructionWithoutId(
input,
staticEvidence,
members,
methods,
);
return managedReconstructionImportResultSchema.parse({
...withoutId,
reconstruction_id: `mre_${sha256Json(withoutId)}`,
});
};