refactor(domain): remove provider-specific target and snapshot state
Move Hopper loader derivation and compatibility projection into the Hopper adapter so BinaryTarget carries only provider-neutral identity and format metadata. Introduce bounded canonical analysis-profile commitments, exact provider/profile snapshot v2 bindings, legacy snapshot rejection guidance, and backward-compatible profiled Evidence v2 records. Partition cache and replay behavior by target, concrete provider build, and profile while preserving custom Hopper loader overrides. Propagate profiles consistently through CLI, MCP, composed workflows, and session lifecycle; preserve the 78-tool contract and legacy loaderArgs response projection. Add migration documentation, generated API updates, property regressions, package verification, and real Hopper coverage.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { isJsonWithinLimits } from "./jsonLimits.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "./jsonValue.js";
|
||||
|
||||
const PROFILE_MAX_BYTES = 64 * 1024;
|
||||
const PROFILE_JSON_LIMITS = Object.freeze({
|
||||
maxDepth: 16,
|
||||
maxStringLength: 16 * 1024,
|
||||
maxNodes: 4_096,
|
||||
});
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
|
||||
/** Concrete provider identity committed by an analysis profile. */
|
||||
export const committedProviderSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
version: z.string().min(1),
|
||||
});
|
||||
|
||||
const boundedParametersSchema = jsonObjectSchema.superRefine(
|
||||
(parameters, context) => {
|
||||
if (!isJsonWithinLimits(parameters, PROFILE_JSON_LIMITS)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Analysis profile parameters exceed structural limits",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
Buffer.byteLength(canonicalJson(parameters), "utf8") > PROFILE_MAX_BYTES
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Analysis profile parameters exceed the byte limit",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const unsignedAnalysisProfileSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
provider: committedProviderSchema,
|
||||
provider_profile_schema_version: z.number().int().min(1),
|
||||
parameters: boundedParametersSchema,
|
||||
});
|
||||
|
||||
/** Canonical, provider-neutral commitment to analysis-affecting semantics. */
|
||||
export const analysisProfileSchema = unsignedAnalysisProfileSchema
|
||||
.extend({ digest: digestSchema })
|
||||
.superRefine((profile, context) => {
|
||||
const { digest: _digest, ...unsigned } = profile;
|
||||
if (profileDigest(unsigned) !== profile.digest)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["digest"],
|
||||
message: "Analysis profile digest does not match its parameters",
|
||||
});
|
||||
});
|
||||
|
||||
export type CommittedProviderIdentity = z.infer<typeof committedProviderSchema>;
|
||||
export type AnalysisProfileCommitment = z.infer<typeof analysisProfileSchema>;
|
||||
|
||||
/** Create a validated RFC 8785 profile commitment at a provider boundary. */
|
||||
export const createAnalysisProfile = (
|
||||
provider: CommittedProviderIdentity,
|
||||
providerProfileSchemaVersion: number,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
): AnalysisProfileCommitment => {
|
||||
const unsigned = unsignedAnalysisProfileSchema.parse({
|
||||
schema_version: 1,
|
||||
provider,
|
||||
provider_profile_schema_version: providerProfileSchemaVersion,
|
||||
parameters,
|
||||
});
|
||||
return analysisProfileSchema.parse({
|
||||
...unsigned,
|
||||
digest: profileDigest(unsigned),
|
||||
});
|
||||
};
|
||||
|
||||
/** Compare two already-validated commitments without interpreting parameters. */
|
||||
export const analysisProfilesEqual = (
|
||||
left: AnalysisProfileCommitment,
|
||||
right: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
left.digest === right.digest &&
|
||||
left.provider.id === right.provider.id &&
|
||||
left.provider.name === right.provider.name &&
|
||||
left.provider.version === right.provider.version &&
|
||||
left.schema_version === right.schema_version &&
|
||||
left.provider_profile_schema_version ===
|
||||
right.provider_profile_schema_version;
|
||||
|
||||
const profileDigest = (
|
||||
profile: z.infer<typeof unsignedAnalysisProfileSchema>,
|
||||
): string => createHash("sha256").update(canonicalJson(profile)).digest("hex");
|
||||
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("RFC 8785 canonicalization rejected analysis profile");
|
||||
return encoded;
|
||||
};
|
||||
+158
-58
@@ -3,10 +3,12 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
analysisProfilesEqual,
|
||||
committedProviderSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import {
|
||||
evidenceBundleForTarget,
|
||||
@@ -15,8 +17,9 @@ import {
|
||||
} from "./evidenceBundle.js";
|
||||
import {
|
||||
evidenceLocationSchema,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
type EvidenceLocation,
|
||||
type EvidenceSubjectTarget,
|
||||
} from "./evidence.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
@@ -27,7 +30,7 @@ import {
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const architectureSchema = z.enum(["x86", "x86_64", "arm", "arm64"]);
|
||||
const formatSchema = z.enum([
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
@@ -41,11 +44,13 @@ const formatSchema = z.enum([
|
||||
"javascript",
|
||||
"source-map",
|
||||
]);
|
||||
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
"hopper",
|
||||
"directory",
|
||||
"file",
|
||||
"unknown",
|
||||
@@ -57,10 +62,27 @@ const subjectSchema = z.object({
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
sha256: digestSchema,
|
||||
kind: kindSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
loader_args: z.array(z.string()),
|
||||
});
|
||||
const bindingSchema = z
|
||||
.object({
|
||||
provider: committedProviderSchema,
|
||||
analysis_profile: analysisProfileSchema,
|
||||
})
|
||||
.superRefine((binding, context) => {
|
||||
if (
|
||||
binding.provider.id !== binding.analysis_profile.provider.id ||
|
||||
binding.provider.name !== binding.analysis_profile.provider.name ||
|
||||
binding.provider.version !== binding.analysis_profile.provider.version
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["provider"],
|
||||
message: "Snapshot binding provider does not match analysis profile",
|
||||
});
|
||||
});
|
||||
const entrySchema = z.object({
|
||||
query_id: z.string().regex(/^query_[a-f0-9]{64}$/u),
|
||||
operation: z.string().min(1),
|
||||
@@ -68,17 +90,18 @@ const entrySchema = z.object({
|
||||
execution: z.object({
|
||||
result: jsonValueSchema,
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
provider: committedProviderSchema,
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
subject: subjectSchema.nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
/** Provider-neutral, deterministic cache of successful immutable analysis calls. */
|
||||
/** Provider- and profile-exact cache of successful immutable analysis calls. */
|
||||
export const analysisSnapshotSchema = z.object({
|
||||
snapshot_version: z.literal(1),
|
||||
snapshot_version: z.literal(2),
|
||||
target: targetSchema,
|
||||
binding: bindingSchema,
|
||||
entries: z.array(entrySchema).max(10_000),
|
||||
evidence_bundle: evidenceBundleSchema,
|
||||
});
|
||||
@@ -86,6 +109,21 @@ export const analysisSnapshotSchema = z.object({
|
||||
export type AnalysisSnapshot = z.infer<typeof analysisSnapshotSchema>;
|
||||
export type AnalysisSnapshotEntry = z.infer<typeof entrySchema>;
|
||||
export type AnalysisSnapshotTarget = z.infer<typeof targetSchema>;
|
||||
export type AnalysisSnapshotBinding = z.infer<typeof bindingSchema>;
|
||||
|
||||
interface SnapshotExecution {
|
||||
readonly result: JsonValue;
|
||||
readonly rawResult: JsonValue | null;
|
||||
readonly provider: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly version: string | null;
|
||||
};
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations: readonly EvidenceLocation[];
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
}
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const json = jsonValueSchema.parse(value);
|
||||
@@ -100,33 +138,71 @@ export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
loader_args: [...target.loaderArgs],
|
||||
});
|
||||
|
||||
/** Compare an open binary with the immutable identity in a snapshot. */
|
||||
/** Build the immutable provider/profile binding used by snapshot v2. */
|
||||
export const snapshotBinding = (
|
||||
profile: AnalysisProfileCommitment,
|
||||
): AnalysisSnapshotBinding =>
|
||||
bindingSchema.parse({
|
||||
provider: profile.provider,
|
||||
analysis_profile: profile,
|
||||
});
|
||||
|
||||
/** Compare an open binary with the immutable target identity in a snapshot. */
|
||||
export const snapshotMatchesTarget = (
|
||||
snapshot: AnalysisSnapshotTarget,
|
||||
target: BinaryTarget,
|
||||
): boolean =>
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.kind === target.kind &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
JSON.stringify(snapshot.loader_args) === JSON.stringify(target.loaderArgs);
|
||||
snapshot.architecture === (target.architecture ?? null);
|
||||
|
||||
/** Find exact persisted CLI evidence without starting an analysis provider. */
|
||||
/** Compare a snapshot binding with the selected concrete analysis profile. */
|
||||
export const snapshotMatchesProfile = (
|
||||
binding: AnalysisSnapshotBinding,
|
||||
profile: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
binding.provider.id === profile.provider.id &&
|
||||
binding.provider.name === profile.provider.name &&
|
||||
binding.provider.version === profile.provider.version &&
|
||||
analysisProfilesEqual(binding.analysis_profile, profile);
|
||||
|
||||
/** Require an exact target and selected provider/profile cache partition. */
|
||||
export const snapshotMatchesBinding = (
|
||||
snapshot: Pick<AnalysisSnapshot, "target" | "binding">,
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment,
|
||||
): boolean =>
|
||||
snapshotMatchesTarget(snapshot.target, target) &&
|
||||
snapshotMatchesProfile(snapshot.binding, profile);
|
||||
|
||||
/** Find exact persisted CLI Evidence without starting an analysis provider. */
|
||||
export const snapshotEvidenceForQuery = (
|
||||
snapshot: AnalysisSnapshot,
|
||||
query: {
|
||||
readonly target: BinaryTarget;
|
||||
readonly bindingProfile: AnalysisProfileCommitment;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly provider: AnalysisExecution["provider"];
|
||||
readonly provider: SnapshotExecution["provider"];
|
||||
readonly evidenceProfile: AnalysisProfileCommitment;
|
||||
},
|
||||
): Evidence | undefined => {
|
||||
const { target, operation, parameters, provider } = query;
|
||||
if (!snapshotMatchesTarget(snapshot.target, target)) return undefined;
|
||||
const {
|
||||
target,
|
||||
bindingProfile,
|
||||
operation,
|
||||
parameters,
|
||||
provider,
|
||||
evidenceProfile,
|
||||
} = query;
|
||||
if (!snapshotMatchesBinding(snapshot, target, bindingProfile))
|
||||
return undefined;
|
||||
const encodedParameters = canonicalJson(parameters);
|
||||
return snapshot.evidence_bundle.records.find(
|
||||
(record) =>
|
||||
@@ -135,60 +211,66 @@ export const snapshotEvidenceForQuery = (
|
||||
record.provider.id === provider.id &&
|
||||
record.provider.name === provider.name &&
|
||||
record.provider.version === provider.version &&
|
||||
"analysis_profile" in record &&
|
||||
analysisProfilesEqual(record.analysis_profile, evidenceProfile) &&
|
||||
canonicalJson(record.parameters) === encodedParameters,
|
||||
);
|
||||
};
|
||||
|
||||
/** Compute the stable lookup key for one provider-specific analysis query. */
|
||||
/** Compute the stable lookup key for one provider/profile-specific query. */
|
||||
export const analysisQueryId = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
binding: AnalysisSnapshotBinding,
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
provider: AnalysisExecution["provider"],
|
||||
): string =>
|
||||
`query_${createHash("sha256")
|
||||
.update(
|
||||
canonicalJson({
|
||||
target,
|
||||
operation,
|
||||
parameters,
|
||||
provider: {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
version: provider.version,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.update(canonicalJson({ target, binding, operation, parameters }))
|
||||
.digest("hex")}`;
|
||||
|
||||
/** Create one serializable snapshot entry from a successful provider call. */
|
||||
export const createAnalysisSnapshotEntry = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
): AnalysisSnapshotEntry => ({
|
||||
query_id: analysisQueryId(target, operation, parameters, execution.provider),
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parameters),
|
||||
execution: {
|
||||
result: execution.result,
|
||||
raw_result: execution.rawResult,
|
||||
provider: execution.provider,
|
||||
limitations: [...execution.limitations],
|
||||
locations: [...execution.locations],
|
||||
subject:
|
||||
execution.subject === null
|
||||
? null
|
||||
: {
|
||||
...execution.subject,
|
||||
architecture: execution.subject.architecture ?? null,
|
||||
},
|
||||
},
|
||||
});
|
||||
export const createAnalysisSnapshotEntry = (input: {
|
||||
readonly target: AnalysisSnapshotTarget;
|
||||
readonly binding: AnalysisSnapshotBinding;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly execution: SnapshotExecution;
|
||||
}): AnalysisSnapshotEntry => {
|
||||
const { target, binding, operation, parameters, execution } = input;
|
||||
if (
|
||||
execution.analysisProfile === undefined ||
|
||||
!snapshotMatchesProfile(binding, execution.analysisProfile) ||
|
||||
execution.provider.id !== binding.provider.id ||
|
||||
execution.provider.name !== binding.provider.name ||
|
||||
execution.provider.version !== binding.provider.version
|
||||
)
|
||||
throw new TypeError(
|
||||
"Snapshot execution does not match its provider/profile binding",
|
||||
);
|
||||
return {
|
||||
query_id: analysisQueryId(target, binding, operation, parameters),
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parameters),
|
||||
execution: {
|
||||
result: execution.result,
|
||||
raw_result: execution.rawResult,
|
||||
provider: binding.provider,
|
||||
limitations: [...execution.limitations],
|
||||
locations: [...execution.locations],
|
||||
subject:
|
||||
execution.subject === null
|
||||
? null
|
||||
: {
|
||||
...execution.subject,
|
||||
architecture: execution.subject.architecture ?? null,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Parse a snapshot and reject altered query IDs or non-canonical entry order. */
|
||||
/** Parse v2 and reject legacy snapshots, altered query IDs, or non-canonical order. */
|
||||
export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
rejectLegacySnapshot(input);
|
||||
const parsed = analysisSnapshotSchema.parse(input);
|
||||
parseEvidenceBundle(parsed.evidence_bundle);
|
||||
if (
|
||||
@@ -201,11 +283,17 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
for (const entry of parsed.entries) {
|
||||
if (
|
||||
entry.execution.provider.id !== parsed.binding.provider.id ||
|
||||
entry.execution.provider.name !== parsed.binding.provider.name ||
|
||||
entry.execution.provider.version !== parsed.binding.provider.version
|
||||
)
|
||||
throw new TypeError("Analysis snapshot entry provider does not match");
|
||||
const expected = analysisQueryId(
|
||||
parsed.target,
|
||||
parsed.binding,
|
||||
entry.operation,
|
||||
entry.parameters,
|
||||
entry.execution.provider,
|
||||
);
|
||||
if (entry.query_id !== expected)
|
||||
throw new TypeError("Analysis snapshot query identifier does not match");
|
||||
@@ -224,3 +312,15 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
|
||||
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
|
||||
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
|
||||
|
||||
const rejectLegacySnapshot = (input: unknown): void => {
|
||||
if (
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"snapshot_version" in input &&
|
||||
input.snapshot_version === 1
|
||||
)
|
||||
throw new TypeError(
|
||||
"Analysis snapshot v1 is incompatible with profile-exact replay; recapture it as snapshot v2. Its Evidence bundle may be imported separately.",
|
||||
);
|
||||
};
|
||||
|
||||
@@ -49,6 +49,7 @@ const artifactFormatSchema = z.enum([
|
||||
"elf",
|
||||
"pe",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
"apk",
|
||||
"plist",
|
||||
|
||||
+14
-39
@@ -18,12 +18,11 @@ import { err, ok, type Result } from "./result.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** CPU families understood by the supported executable loaders. */
|
||||
type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
|
||||
/** Provider-neutral CPU families detected from supported executable headers. */
|
||||
export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
|
||||
/**
|
||||
* A canonical local target plus deterministic Hopper loader arguments.
|
||||
* Explicit loader and architecture flags prevent Hopper from presenting modal
|
||||
* format or FAT-architecture selection dialogs during agent-driven analysis.
|
||||
* Canonical local target identity and provider-neutral file classification.
|
||||
* Provider adapters translate this metadata into their own open options.
|
||||
*/
|
||||
export interface BinaryTarget {
|
||||
readonly path: string;
|
||||
@@ -31,7 +30,7 @@ export interface BinaryTarget {
|
||||
readonly sha256: string;
|
||||
readonly kind: "executable" | "database" | "archive" | "artifact";
|
||||
readonly format:
|
||||
| "hopper"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
@@ -46,11 +45,10 @@ export interface BinaryTarget {
|
||||
| "source-map";
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly availableArchitectures?: readonly BinaryArchitecture[];
|
||||
readonly loaderArgs: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before Hopper is launched.
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
* non-interactive; unsupported or ambiguous inputs are returned as typed errors.
|
||||
*/
|
||||
@@ -78,8 +76,7 @@ export const parseBinaryTarget = async (
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256File(path),
|
||||
kind: "database",
|
||||
format: "hopper",
|
||||
loaderArgs: [],
|
||||
format: "analysis-database",
|
||||
});
|
||||
const handle = await open(path, "r");
|
||||
let detected: Result<ExecutableMetadata, string>;
|
||||
@@ -92,7 +89,6 @@ export const parseBinaryTarget = async (
|
||||
sha256: await sha256File(path),
|
||||
kind: isArchiveFormat(artifactFormat) ? "archive" : "artifact",
|
||||
format: artifactFormat,
|
||||
loaderArgs: [],
|
||||
});
|
||||
detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
} finally {
|
||||
@@ -117,7 +113,10 @@ const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
): Promise<
|
||||
| Exclude<BinaryTarget["format"], "hopper" | "mach-o" | "elf" | "pe">
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
const lower = path.toLowerCase();
|
||||
@@ -263,7 +262,7 @@ const decodeXml = (value: string): string =>
|
||||
|
||||
type ExecutableMetadata = Pick<
|
||||
BinaryTarget,
|
||||
"format" | "architecture" | "availableArchitectures" | "loaderArgs"
|
||||
"format" | "architecture" | "availableArchitectures"
|
||||
>;
|
||||
|
||||
const readExecutableMetadata = async (
|
||||
@@ -303,9 +302,8 @@ const readExecutableMetadata = async (
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse supported executable headers without I/O and derive explicit Hopper
|
||||
* loader arguments. The caller must supply the host architecture used for FAT
|
||||
* Mach-O slice selection.
|
||||
* Parse supported executable headers without I/O. The caller supplies the host
|
||||
* architecture used for deterministic FAT Mach-O slice selection.
|
||||
*/
|
||||
export const parseExecutableHeader = (
|
||||
bytes: Buffer,
|
||||
@@ -341,7 +339,6 @@ const parseThinMachO = (
|
||||
format: "mach-o",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "Mach-O", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -381,13 +378,6 @@ const parseFatMachO = (
|
||||
format: "mach-o",
|
||||
architecture: preferred,
|
||||
availableArchitectures: architectures,
|
||||
loaderArgs: [
|
||||
"-l",
|
||||
"FAT",
|
||||
hopperArchitectureFlag(preferred),
|
||||
"-l",
|
||||
"Mach-O",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -403,7 +393,6 @@ const parseElf = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
format: "elf",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "ELF", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -423,7 +412,6 @@ const parsePeRecord = (record: Buffer): Result<ExecutableMetadata, string> => {
|
||||
format: "pe",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
loaderArgs: ["-l", "WinPE", hopperArchitectureFlag(architecture)],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -468,16 +456,3 @@ const peArchitecture = (machine: number): BinaryArchitecture | undefined => {
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const hopperArchitectureFlag = (architecture: BinaryArchitecture): string => {
|
||||
switch (architecture) {
|
||||
case "x86":
|
||||
return "--intel-32";
|
||||
case "x86_64":
|
||||
return "--intel-64";
|
||||
case "arm":
|
||||
return "--armv7";
|
||||
case "arm64":
|
||||
return "--aarch64";
|
||||
}
|
||||
};
|
||||
|
||||
+83
-25
@@ -3,6 +3,10 @@ import { createHash } from "node:crypto";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
|
||||
@@ -18,6 +22,7 @@ const subjectSchema = z.object({
|
||||
digest: z.object({ sha256: digestSchema }),
|
||||
format: z.enum([
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
@@ -73,26 +78,65 @@ const executionEnvironmentSchema = z.object({
|
||||
isolation: z.enum(["none", "process", "container", "virtual-machine"]),
|
||||
});
|
||||
|
||||
/** Strict, provider-neutral record for one successful public observation. */
|
||||
export const evidenceSchema = z.object({
|
||||
schema_version: z.literal(2),
|
||||
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
subject: subjectSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
authority: evidenceAuthoritySchema,
|
||||
environment: executionEnvironmentSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
evidence_links: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)),
|
||||
const evidenceBaseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(2),
|
||||
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
subject: subjectSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
authority: evidenceAuthoritySchema,
|
||||
environment: executionEnvironmentSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
evidence_links: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Object envelope used to specialize caller-visible Evidence result schemas. */
|
||||
export const evidenceEnvelopeSchema = evidenceBaseSchema.extend({
|
||||
analysis_profile: analysisProfileSchema.optional(),
|
||||
});
|
||||
|
||||
export type Evidence = z.infer<typeof evidenceSchema>;
|
||||
const validateAnalysisProfileProvider = (
|
||||
evidence: z.infer<typeof evidenceEnvelopeSchema>,
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
const profile = evidence.analysis_profile;
|
||||
if (
|
||||
profile !== undefined &&
|
||||
(profile.provider.id !== evidence.provider.id ||
|
||||
profile.provider.name !== evidence.provider.name ||
|
||||
profile.provider.version !== evidence.provider.version)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["analysis_profile", "provider"],
|
||||
message: "Analysis profile provider does not match Evidence provider",
|
||||
});
|
||||
};
|
||||
|
||||
/** Strict, provider-neutral record for one successful public observation. */
|
||||
export const evidenceSchema = evidenceEnvelopeSchema.superRefine(
|
||||
validateAnalysisProfileProvider,
|
||||
);
|
||||
|
||||
const profiledEvidenceSchema = evidenceBaseSchema
|
||||
.extend({ analysis_profile: analysisProfileSchema })
|
||||
.superRefine(validateAnalysisProfileProvider);
|
||||
|
||||
/** JSON-exact union used where Evidence participates in larger schemas. */
|
||||
export const evidenceRecordSchema = z.union([
|
||||
profiledEvidenceSchema,
|
||||
evidenceBaseSchema,
|
||||
]);
|
||||
|
||||
export type Evidence = z.infer<typeof evidenceRecordSchema>;
|
||||
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
|
||||
|
||||
/** Minimal immutable local artifact identity accepted by Evidence v2. */
|
||||
@@ -116,6 +160,7 @@ export interface EvidenceObservation {
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly result: JsonValue;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly rawResult?: JsonValue;
|
||||
readonly confidence?: "observed" | "derived" | "inferred";
|
||||
readonly authority?: EvidenceAuthority;
|
||||
@@ -128,6 +173,11 @@ export interface EvidenceObservation {
|
||||
const sha256 = (value: string): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
type WithoutEvidenceId<Record_> = Record_ extends unknown
|
||||
? Omit<Record_, "evidence_id">
|
||||
: never;
|
||||
type EvidenceWithoutId = WithoutEvidenceId<Evidence>;
|
||||
|
||||
/** Serialize JSON according to RFC 8785 JSON Canonicalization Scheme. */
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const serialized = canonicalize(value);
|
||||
@@ -136,9 +186,7 @@ const canonicalJson = (value: JsonValue): string => {
|
||||
return serialized;
|
||||
};
|
||||
|
||||
const semanticProjection = (
|
||||
evidence: Omit<Evidence, "evidence_id">,
|
||||
): JsonValue => ({
|
||||
const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
|
||||
schema_version: evidence.schema_version,
|
||||
subject:
|
||||
evidence.subject === null
|
||||
@@ -149,6 +197,9 @@ const semanticProjection = (
|
||||
architecture: evidence.subject.architecture,
|
||||
},
|
||||
provider: evidence.provider,
|
||||
...(!("analysis_profile" in evidence)
|
||||
? {}
|
||||
: { analysis_profile: evidence.analysis_profile }),
|
||||
predicate_type: evidence.predicate_type,
|
||||
operation: evidence.operation,
|
||||
parameters: evidence.parameters,
|
||||
@@ -163,7 +214,7 @@ const semanticProjection = (
|
||||
});
|
||||
|
||||
/** Recompute the semantic identifier, excluding paths and raw payload bytes. */
|
||||
const computeEvidenceId = (evidence: Omit<Evidence, "evidence_id">): string =>
|
||||
const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
|
||||
`ev_${sha256(canonicalJson(semanticProjection(evidence)))}`;
|
||||
|
||||
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
|
||||
@@ -177,7 +228,7 @@ export const parseEvidence = (input: unknown): Evidence => {
|
||||
throw new TypeError(
|
||||
`Unsupported evidence schema_version ${String(input.schema_version)}; Evidence v1 is not accepted. Produce Evidence v2.`,
|
||||
);
|
||||
const evidence = evidenceSchema.parse(input);
|
||||
const evidence = evidenceRecordSchema.parse(input);
|
||||
const { evidence_id: evidenceId, ...withoutId } = evidence;
|
||||
if (computeEvidenceId(withoutId) !== evidenceId)
|
||||
throw new TypeError(
|
||||
@@ -217,6 +268,9 @@ export const createEvidence = (
|
||||
name: provider.name,
|
||||
version: provider.version,
|
||||
},
|
||||
...(observation.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysis_profile: observation.analysisProfile }),
|
||||
predicate_type: observation.predicateType ?? "rea.analysis/v2",
|
||||
operation: observation.operation,
|
||||
parameters: observation.parameters,
|
||||
@@ -234,9 +288,13 @@ export const createEvidence = (
|
||||
locations: [...(observation.locations ?? [])],
|
||||
evidence_links: [...(observation.evidenceLinks ?? [])],
|
||||
} satisfies JsonValue;
|
||||
return evidenceSchema.parse({
|
||||
const normalized = evidenceRecordSchema.parse({
|
||||
...semantic,
|
||||
evidence_id: `ev_${sha256(canonicalJson(semantic))}`,
|
||||
evidence_id: `ev_${"0".repeat(64)}`,
|
||||
subject,
|
||||
});
|
||||
return parseEvidence({
|
||||
...normalized,
|
||||
evidence_id: computeEvidenceId(normalized),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
import { z } from "zod";
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js";
|
||||
import {
|
||||
evidenceEnvelopeSchema,
|
||||
evidenceRecordSchema,
|
||||
parseEvidence,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
} from "./evidence.js";
|
||||
import {
|
||||
residualUnknownSchema,
|
||||
type ResidualUnknown,
|
||||
} from "./residualUnknown.js";
|
||||
|
||||
const artifactManifestSchema = evidenceSchema.shape.subject.unwrap().pick({
|
||||
digest: true,
|
||||
format: true,
|
||||
architecture: true,
|
||||
});
|
||||
const providerManifestSchema = evidenceSchema.shape.provider;
|
||||
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
|
||||
const artifactManifestSchema = evidenceEnvelopeSchema.shape.subject
|
||||
.unwrap()
|
||||
.pick({
|
||||
digest: true,
|
||||
format: true,
|
||||
architecture: true,
|
||||
});
|
||||
const providerManifestSchema = providerSchema;
|
||||
const environmentManifestSchema =
|
||||
evidenceEnvelopeSchema.shape.environment.unwrap();
|
||||
const scenarioManifestSchema = z.object({
|
||||
evidence_id: evidenceSchema.shape.evidence_id,
|
||||
evidence_id: evidenceEnvelopeSchema.shape.evidence_id,
|
||||
operation: z.string().min(1),
|
||||
authority: z.literal("controlled-replay"),
|
||||
});
|
||||
const captureManifestSchema = z.object({
|
||||
evidence_id: evidenceSchema.shape.evidence_id,
|
||||
evidence_id: evidenceEnvelopeSchema.shape.evidence_id,
|
||||
predicate_type: z.string().min(1),
|
||||
});
|
||||
|
||||
@@ -32,7 +41,7 @@ export const evidenceBundleSchema = z.object({
|
||||
scenarios: z.array(scenarioManifestSchema),
|
||||
captures: z.array(captureManifestSchema),
|
||||
unknowns: z.array(residualUnknownSchema),
|
||||
records: z.array(evidenceSchema),
|
||||
records: z.array(evidenceRecordSchema),
|
||||
});
|
||||
|
||||
export type EvidenceBundle = z.infer<typeof evidenceBundleSchema>;
|
||||
|
||||
Reference in New Issue
Block a user