feat: expand cross-platform investigation workflows
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
androidApplicationProjectionInputSchema,
|
||||
projectAndroidApplication,
|
||||
} from "../domain/androidApplication.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { ANDROID_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { projectInventoryEvidence } from "./InventoryProjectionEvidence.js";
|
||||
|
||||
const OPERATION = "project_android_application_graph" as const;
|
||||
|
||||
/** Project authenticated APK inventory Evidence into Android application Evidence. */
|
||||
export const projectAndroidApplicationEvidence = (
|
||||
rawInput: unknown,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
return projectInventoryEvidence({
|
||||
rawInput,
|
||||
schema: androidApplicationProjectionInputSchema,
|
||||
project: projectAndroidApplication,
|
||||
operation: OPERATION,
|
||||
predicateType: "rea.android-application-graph/v1",
|
||||
provider: ANDROID_APPLICATION_PROVIDER,
|
||||
subjectFormat: () => "apk",
|
||||
protocolError: "Android application projection produced an invalid result",
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
appleApplicationProjectionInputSchema,
|
||||
projectAppleApplication,
|
||||
} from "../domain/appleApplication.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { APPLE_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { projectInventoryEvidence } from "./InventoryProjectionEvidence.js";
|
||||
|
||||
const OPERATION = "project_apple_application_graph" as const;
|
||||
|
||||
/** Project authenticated IPA inventory Evidence into Apple application evidence. */
|
||||
export const projectAppleApplicationEvidence = (
|
||||
rawInput: unknown,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
return projectInventoryEvidence({
|
||||
rawInput,
|
||||
schema: appleApplicationProjectionInputSchema,
|
||||
project: projectAppleApplication,
|
||||
operation: OPERATION,
|
||||
predicateType: "rea.apple-application-graph/v1",
|
||||
provider: APPLE_APPLICATION_PROVIDER,
|
||||
subjectFormat: () => "ipa",
|
||||
protocolError: "Apple application projection produced an invalid result",
|
||||
});
|
||||
};
|
||||
@@ -15,6 +15,7 @@ import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js
|
||||
import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
|
||||
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../artifacts/NativeDmgArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
type ArtifactExtractionResult,
|
||||
@@ -23,7 +24,10 @@ import {
|
||||
type ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { scanArtifactInventory } from "./ArtifactInventory.js";
|
||||
import {
|
||||
scanArtifactInventory,
|
||||
type ArtifactNativeMountPolicy,
|
||||
} from "./ArtifactInventory.js";
|
||||
import {
|
||||
digestCanonical,
|
||||
pageOf,
|
||||
@@ -41,6 +45,7 @@ export interface ArtifactExtractionInput {
|
||||
readonly offset: number;
|
||||
readonly limit: number;
|
||||
readonly limits: ArtifactLimits;
|
||||
readonly nativeMount: ArtifactNativeMountPolicy;
|
||||
}
|
||||
|
||||
/** Extract selected inventory occurrences into an exclusively owned absent root. */
|
||||
@@ -49,14 +54,16 @@ export const extractArtifact = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactExtractionResult> => {
|
||||
validateSelection(input.occurrenceIds);
|
||||
assertNativeMountAuthority(input.inputFormat, input.nativeMount);
|
||||
const sourcePath = await realpath(input.inputPath);
|
||||
const selectedIds = new Set(input.occurrenceIds);
|
||||
const inventory = await loadInventory(
|
||||
sourcePath,
|
||||
input.limits,
|
||||
const inventory = await loadInventory({
|
||||
path: sourcePath,
|
||||
limits: input.limits,
|
||||
selectedIds,
|
||||
signal,
|
||||
);
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
nativeMount: input.nativeMount,
|
||||
});
|
||||
const selected = input.occurrenceIds.map((id) => {
|
||||
const occurrence = inventory.occurrences.get(id);
|
||||
if (occurrence === undefined)
|
||||
@@ -120,7 +127,12 @@ const materializeSelection = async ({
|
||||
const byPath = new Map(
|
||||
selected.map((item) => [item.occurrence.logical_path, item]),
|
||||
);
|
||||
const reader = await createReader(sourcePath, input.inputFormat);
|
||||
const reader = await createReader(
|
||||
sourcePath,
|
||||
input.inputFormat,
|
||||
input.nativeMount,
|
||||
signal,
|
||||
);
|
||||
const output = await SafeOutputTree.create(input.outputRoot, input.limits);
|
||||
let readerClosed = false;
|
||||
const extracted: ExtractedOccurrence[] = [];
|
||||
@@ -166,12 +178,13 @@ const materializeSelection = async ({
|
||||
extracted.sort((left, right) =>
|
||||
left.relative_path.localeCompare(right.relative_path, "en"),
|
||||
);
|
||||
const result = createExtractionResult(
|
||||
const result = createExtractionResult({
|
||||
input,
|
||||
inventory,
|
||||
selected,
|
||||
extracted,
|
||||
);
|
||||
provenance: reader.provenance(),
|
||||
});
|
||||
await output.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
@@ -181,12 +194,21 @@ const materializeSelection = async ({
|
||||
}
|
||||
};
|
||||
|
||||
const createExtractionResult = (
|
||||
input: ArtifactExtractionInput,
|
||||
inventory: LoadedInventory,
|
||||
selected: readonly SelectedOccurrence[],
|
||||
extracted: readonly ExtractedOccurrence[],
|
||||
): ArtifactExtractionResult => {
|
||||
interface ExtractionResultInput {
|
||||
readonly input: ArtifactExtractionInput;
|
||||
readonly inventory: LoadedInventory;
|
||||
readonly selected: readonly SelectedOccurrence[];
|
||||
readonly extracted: readonly ExtractedOccurrence[];
|
||||
readonly provenance: ReturnType<ArtifactReader["provenance"]>;
|
||||
}
|
||||
|
||||
const createExtractionResult = ({
|
||||
input,
|
||||
inventory,
|
||||
selected,
|
||||
extracted,
|
||||
provenance,
|
||||
}: ExtractionResultInput): ArtifactExtractionResult => {
|
||||
const extractionSemantic = {
|
||||
schema_version: 1 as const,
|
||||
source_manifest_id: inventory.manifest.manifest_id,
|
||||
@@ -205,11 +227,19 @@ const createExtractionResult = (
|
||||
output_root: "$OUTPUT_ROOT",
|
||||
artifacts: pageOf(extracted, input.offset, input.limit),
|
||||
containment_verified: true,
|
||||
cleanup: { attempted: false, verified: true, residual_paths: [] },
|
||||
cleanup:
|
||||
input.inputFormat === "dmg"
|
||||
? { attempted: true, verified: true, residual_paths: [] }
|
||||
: { attempted: false, verified: true, residual_paths: [] },
|
||||
limits: toOutputLimits(input.limits),
|
||||
provenance: [],
|
||||
provenance,
|
||||
limitations: [
|
||||
"Only caller-selected regular file occurrences were materialized.",
|
||||
...(input.inputFormat === "dmg"
|
||||
? [
|
||||
"The read-only DMG mount was detached before this result was returned; the committed output tree remains caller-owned.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -220,13 +250,27 @@ interface LoadedInventory {
|
||||
readonly nodes: ReadonlyMap<string, ArtifactNode>;
|
||||
}
|
||||
|
||||
const loadInventory = async (
|
||||
path: string,
|
||||
limits: ArtifactLimits,
|
||||
selectedIds: ReadonlySet<string>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LoadedInventory> => {
|
||||
const snapshot = await scanArtifactInventory(path, limits, signal);
|
||||
interface InventoryLoadInput {
|
||||
readonly path: string;
|
||||
readonly limits: ArtifactLimits;
|
||||
readonly selectedIds: ReadonlySet<string>;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly nativeMount: ArtifactNativeMountPolicy;
|
||||
}
|
||||
|
||||
const loadInventory = async ({
|
||||
path,
|
||||
limits,
|
||||
selectedIds,
|
||||
signal,
|
||||
nativeMount,
|
||||
}: InventoryLoadInput): Promise<LoadedInventory> => {
|
||||
const snapshot = await scanArtifactInventory(
|
||||
path,
|
||||
limits,
|
||||
signal,
|
||||
nativeMount,
|
||||
);
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const neededNodes = new Set<string>();
|
||||
collectOccurrences(
|
||||
@@ -265,6 +309,8 @@ const collectNodes = (
|
||||
const createReader = async (
|
||||
path: string,
|
||||
format: BinaryTarget["format"],
|
||||
nativeMount: ArtifactNativeMountPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactReader> => {
|
||||
if ((await lstat(path)).isDirectory())
|
||||
return new DirectoryArtifactReader(path);
|
||||
@@ -272,12 +318,33 @@ const createReader = async (
|
||||
if (format === "ipa" || format === "apk" || format === "zip")
|
||||
return new ZipArtifactReader(path, format);
|
||||
if (format === "mach-o") return new MachOSliceArtifactReader(path);
|
||||
if (format === "dmg") {
|
||||
assertNativeMountAuthority(format, nativeMount);
|
||||
return NativeDmgArtifactReader.create(path, signal);
|
||||
}
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`Artifact format has no extraction reader: ${format}`,
|
||||
);
|
||||
};
|
||||
|
||||
const assertNativeMountAuthority = (
|
||||
format: BinaryTarget["format"],
|
||||
nativeMount: ArtifactNativeMountPolicy,
|
||||
): void => {
|
||||
if (format !== "dmg") return;
|
||||
if (!nativeMount.nativeMountApproved)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"DMG extraction requires explicit native mount approval",
|
||||
);
|
||||
if (!nativeMount.nativeMountEnabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Native DMG mounting is disabled by operator policy",
|
||||
);
|
||||
};
|
||||
|
||||
const validateSelection = (ids: readonly string[]): void => {
|
||||
if (ids.length === 0 || ids.length > PAGE_SIZE)
|
||||
throw new ArtifactReaderFailure(
|
||||
|
||||
@@ -259,6 +259,16 @@ export const classifyArtifactPath = (
|
||||
path: string,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const lower = path.toLowerCase();
|
||||
if (/(?:^|\/)androidmanifest\.xml$/u.test(lower))
|
||||
return { kind: "package-metadata", format: "android-manifest" };
|
||||
if (/(?:^|\/)resources\.(?:arsc|pb)$/u.test(lower))
|
||||
return { kind: "resource", format: "android-resources" };
|
||||
if (/\.(?:dex|odex)$/u.test(lower))
|
||||
return { kind: "bytecode", format: "dex" };
|
||||
if (lower.endsWith(".class"))
|
||||
return { kind: "bytecode", format: "jvm-class" };
|
||||
if (lower.endsWith(".wasm"))
|
||||
return { kind: "bytecode", format: "webassembly" };
|
||||
if (lower.endsWith(".map"))
|
||||
return { kind: "source-map", format: "source-map" };
|
||||
if (/\.(?:m?js|cjs)$/u.test(lower))
|
||||
@@ -286,6 +296,18 @@ export const classifyArtifactContent = (
|
||||
prefix: Buffer,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const byPath = classifyArtifactPath(path);
|
||||
if (PATH_AUTHORITATIVE_FORMATS.has(byPath.format)) return byPath;
|
||||
if (
|
||||
prefix.length >= 8 &&
|
||||
prefix.subarray(0, 4).toString("ascii") === "dex\n" &&
|
||||
prefix[7] === 0
|
||||
)
|
||||
return { kind: "bytecode", format: "dex" };
|
||||
if (
|
||||
prefix.length >= 4 &&
|
||||
prefix.subarray(0, 4).equals(Buffer.from([0, 0x61, 0x73, 0x6d]))
|
||||
)
|
||||
return { kind: "bytecode", format: "webassembly" };
|
||||
if (prefix.length >= 4) {
|
||||
const magic = prefix.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
|
||||
@@ -316,6 +338,14 @@ export const classifyArtifactContent = (
|
||||
return byPath;
|
||||
};
|
||||
|
||||
const PATH_AUTHORITATIVE_FORMATS = new Set<ArtifactNode["format"]>([
|
||||
"dex",
|
||||
"jvm-class",
|
||||
"webassembly",
|
||||
"android-manifest",
|
||||
"android-resources",
|
||||
]);
|
||||
|
||||
export const pageOf = <Value>(
|
||||
items: readonly Value[],
|
||||
offset: number,
|
||||
|
||||
@@ -10,14 +10,22 @@ import {
|
||||
} from "./ArtifactInventory.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
export interface AuthorizedArtifactInventoryInput {
|
||||
readonly inputPath: string;
|
||||
readonly roots: readonly string[];
|
||||
readonly limits: ArtifactLimits;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly integrity?: ArtifactIntegrityPolicy;
|
||||
}
|
||||
|
||||
/** Resolve, authorize, and scan one artifact without a second path resolution. */
|
||||
export const scanAuthorizedArtifactInventory = async (
|
||||
inputPath: string,
|
||||
roots: readonly string[],
|
||||
limits: ArtifactLimits,
|
||||
signal?: AbortSignal,
|
||||
integrity?: ArtifactIntegrityPolicy,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
export const scanAuthorizedArtifactInventory = async ({
|
||||
inputPath,
|
||||
roots,
|
||||
limits,
|
||||
signal,
|
||||
integrity,
|
||||
}: AuthorizedArtifactInventoryInput): Promise<ArtifactInventorySnapshot> => {
|
||||
if (roots.length === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
|
||||
+181
-127
@@ -4,7 +4,6 @@ import {
|
||||
analysisProfilesEqual,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "../domain/analysisProfile.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
EvidenceIntegrityError,
|
||||
@@ -57,7 +56,10 @@ import {
|
||||
unknownEvidenceLinks,
|
||||
unknownMutationEvidence,
|
||||
} from "./UnknownEvidence.js";
|
||||
import type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
import type {
|
||||
BinarySessionOpenOptions,
|
||||
BinarySessionPort,
|
||||
} from "./BinarySessionPort.js";
|
||||
import {
|
||||
parseInvestigationWorkspace,
|
||||
type InvestigationWorkspace,
|
||||
@@ -75,6 +77,21 @@ const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
|
||||
interface ActiveBinarySession {
|
||||
readonly target: BinaryTarget;
|
||||
readonly client: AnalysisClient;
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
readonly route: SessionProviderRoute;
|
||||
}
|
||||
|
||||
interface ExecutionPlan {
|
||||
readonly capability: CapabilityDescriptor | undefined;
|
||||
readonly profile: AnalysisProfileCommitment | undefined;
|
||||
readonly cacheable: boolean;
|
||||
readonly cached: AnalysisExecution | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the single active target shared by CLI and MCP adapters.
|
||||
*
|
||||
@@ -83,15 +100,7 @@ const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
* of retaining a client whose resources were already shut down.
|
||||
*/
|
||||
export class BinarySession implements BinarySessionPort {
|
||||
#active:
|
||||
| {
|
||||
readonly target: BinaryTarget;
|
||||
readonly client: AnalysisClient;
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
readonly route: SessionProviderRoute;
|
||||
}
|
||||
| undefined;
|
||||
#active: ActiveBinarySession | undefined;
|
||||
#transition: Promise<void> = Promise.resolve();
|
||||
readonly #calls = new Set<Promise<unknown>>();
|
||||
readonly #providerRouter: SessionProviderRouter;
|
||||
@@ -404,12 +413,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
*/
|
||||
open(
|
||||
path: string,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
} = {},
|
||||
options: BinarySessionOpenOptions = {},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#serialize(async () => {
|
||||
if (isAborted(options.signal))
|
||||
@@ -421,96 +425,135 @@ export class BinarySession implements BinarySessionPort {
|
||||
options.targetKind,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
const sameTarget =
|
||||
this.#active?.target.path === parsed.value.path &&
|
||||
snapshotMatchesTarget(
|
||||
snapshotTarget(this.#active.target),
|
||||
parsed.value,
|
||||
);
|
||||
const resolvedRoute =
|
||||
sameTarget &&
|
||||
options.providerId === undefined &&
|
||||
this.#active !== undefined
|
||||
? ok(this.#active.route)
|
||||
: await this.#providerRouter.resolve(
|
||||
parsed.value,
|
||||
options.providerId,
|
||||
options.signal,
|
||||
);
|
||||
if (!resolvedRoute.ok) return resolvedRoute;
|
||||
const route = resolvedRoute.value;
|
||||
const { profile, compatibility } = route;
|
||||
if (
|
||||
options.snapshot !== undefined &&
|
||||
(profile === null ||
|
||||
!snapshotMatchesBinding(options.snapshot, parsed.value, profile))
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
|
||||
),
|
||||
);
|
||||
if (
|
||||
this.#active === undefined &&
|
||||
!this.#snapshot.matches(parsed.value, profile ?? undefined)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
|
||||
),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const activeProfile = this.#active?.profile;
|
||||
const sameProfile =
|
||||
activeProfile === null || activeProfile === undefined
|
||||
? profile === null
|
||||
: profile !== null && analysisProfilesEqual(activeProfile, profile);
|
||||
if (sameTarget && sameProfile) {
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
return ok(parsed.value);
|
||||
}
|
||||
await this.#drainCalls();
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await previous?.client.close();
|
||||
const client = route.createClient(parsed.value);
|
||||
const started = await client.execute("health", {}, options);
|
||||
if (!started.ok) {
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return started;
|
||||
}
|
||||
if (isAborted(options.signal)) {
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
}
|
||||
this.#active = {
|
||||
target: parsed.value,
|
||||
client,
|
||||
profile,
|
||||
compatibility: structuredClone(compatibility),
|
||||
route,
|
||||
};
|
||||
this.#clearRuntimeAvailability();
|
||||
if (profile === null) this.#snapshot.clear();
|
||||
else this.#snapshot.select(parsed.value, profile);
|
||||
return this.#openTarget(parsed.value, options);
|
||||
});
|
||||
}
|
||||
|
||||
async #openTarget(
|
||||
target: BinaryTarget,
|
||||
options: BinarySessionOpenOptions,
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
const sameTarget = this.#isSameTarget(target);
|
||||
const resolvedRoute = await this.#resolveOpenRoute(
|
||||
target,
|
||||
sameTarget,
|
||||
options,
|
||||
);
|
||||
if (!resolvedRoute.ok) return resolvedRoute;
|
||||
const route = resolvedRoute.value;
|
||||
const { profile, compatibility } = route;
|
||||
const snapshotValidation = this.#validateOpenSnapshot(
|
||||
target,
|
||||
profile,
|
||||
options.snapshot,
|
||||
);
|
||||
if (!snapshotValidation.ok) return snapshotValidation;
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
if (sameTarget && this.#isSameProfile(profile)) {
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) {
|
||||
this.#active = undefined;
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return imported;
|
||||
}
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
this.#snapshotInvalidated = false;
|
||||
return ok(parsed.value);
|
||||
});
|
||||
return ok(target);
|
||||
}
|
||||
await this.#drainCalls();
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await previous?.client.close();
|
||||
const client = route.createClient(target);
|
||||
const started = await client.execute("health", {}, options);
|
||||
if (!started.ok) {
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return started;
|
||||
}
|
||||
if (isAborted(options.signal)) {
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
}
|
||||
this.#active = {
|
||||
target,
|
||||
client,
|
||||
profile,
|
||||
compatibility: structuredClone(compatibility),
|
||||
route,
|
||||
};
|
||||
this.#clearRuntimeAvailability();
|
||||
if (profile === null) this.#snapshot.clear();
|
||||
else this.#snapshot.select(target, profile);
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) {
|
||||
this.#active = undefined;
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
this.#snapshotInvalidated = false;
|
||||
return ok(target);
|
||||
}
|
||||
|
||||
#isSameTarget(target: BinaryTarget): boolean {
|
||||
const active = this.#active;
|
||||
return (
|
||||
active !== undefined &&
|
||||
active.target.path === target.path &&
|
||||
snapshotMatchesTarget(snapshotTarget(active.target), target)
|
||||
);
|
||||
}
|
||||
|
||||
#resolveOpenRoute(
|
||||
target: BinaryTarget,
|
||||
sameTarget: boolean,
|
||||
options: BinarySessionOpenOptions,
|
||||
): Promise<Result<SessionProviderRoute, AnalysisError>> {
|
||||
if (
|
||||
sameTarget &&
|
||||
options.providerId === undefined &&
|
||||
this.#active !== undefined
|
||||
)
|
||||
return Promise.resolve(ok(this.#active.route));
|
||||
return this.#providerRouter.resolve(
|
||||
target,
|
||||
options.providerId,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
|
||||
#validateOpenSnapshot(
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment | null,
|
||||
snapshot: AnalysisSnapshot | undefined,
|
||||
): Result<undefined, EvidenceIntegrityError> {
|
||||
if (
|
||||
snapshot !== undefined &&
|
||||
(profile === null || !snapshotMatchesBinding(snapshot, target, profile))
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
|
||||
),
|
||||
);
|
||||
if (
|
||||
this.#active === undefined &&
|
||||
!this.#snapshot.matches(target, profile ?? undefined)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
|
||||
),
|
||||
);
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
#isSameProfile(profile: AnalysisProfileCommitment | null): boolean {
|
||||
const activeProfile = this.#active?.profile;
|
||||
if (activeProfile === null || activeProfile === undefined)
|
||||
return profile === null;
|
||||
return profile !== null && analysisProfilesEqual(activeProfile, profile);
|
||||
}
|
||||
|
||||
/** Close the active target, if any. */
|
||||
@@ -632,6 +675,39 @@ export class BinarySession implements BinarySessionPort {
|
||||
if (!transitioned.ok) return transitioned;
|
||||
const active = this.#active;
|
||||
if (active === undefined) return err(new NoBinaryOpenError());
|
||||
const prepared = this.#prepareExecution(active, name, arguments_);
|
||||
if (!prepared.ok) return prepared;
|
||||
const { capability, profile, cacheable, cached } = prepared.value;
|
||||
if (cached !== undefined) return ok(cached);
|
||||
const call = active.client.execute(name, arguments_, options);
|
||||
this.#calls.add(call);
|
||||
try {
|
||||
const result = await call;
|
||||
const profiled = commitExecutionProfile(name, result, profile);
|
||||
this.#observeRuntimeAvailability(name, profiled);
|
||||
if (profiled.ok && cacheable && profile !== undefined)
|
||||
this.#snapshot.record({
|
||||
target: active.target,
|
||||
profile,
|
||||
operation: name,
|
||||
parameters: arguments_,
|
||||
execution: profiled.value,
|
||||
});
|
||||
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
}
|
||||
return profiled;
|
||||
} finally {
|
||||
this.#calls.delete(call);
|
||||
}
|
||||
}
|
||||
|
||||
#prepareExecution(
|
||||
active: ActiveBinarySession,
|
||||
name: AnalysisOperation,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
): Result<ExecutionPlan, AnalysisError> {
|
||||
const capability = active.route.capabilities?.get(name);
|
||||
if (
|
||||
active.route.capabilities !== undefined &&
|
||||
@@ -662,29 +738,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
const cached = cacheable
|
||||
? this.#snapshot.lookup(active.target, profile, name, arguments_)
|
||||
: undefined;
|
||||
if (cached !== undefined) return ok(cached);
|
||||
const call = active.client.execute(name, arguments_, options);
|
||||
this.#calls.add(call);
|
||||
try {
|
||||
const result = await call;
|
||||
const profiled = commitExecutionProfile(name, result, profile);
|
||||
this.#observeRuntimeAvailability(name, profiled);
|
||||
if (profiled.ok && cacheable)
|
||||
this.#snapshot.record({
|
||||
target: active.target,
|
||||
profile,
|
||||
operation: name,
|
||||
parameters: arguments_,
|
||||
execution: profiled.value,
|
||||
});
|
||||
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
}
|
||||
return profiled;
|
||||
} finally {
|
||||
this.#calls.delete(call);
|
||||
}
|
||||
return ok({ capability, profile, cacheable, cached });
|
||||
}
|
||||
|
||||
#observeRuntimeAvailability(
|
||||
|
||||
@@ -26,16 +26,19 @@ import type {
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
/** Optional cancellation, target-kind, snapshot, and provider selection for open. */
|
||||
export interface BinarySessionOpenOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
}
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
open(
|
||||
path: string,
|
||||
options?: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
},
|
||||
options?: BinarySessionOpenOptions,
|
||||
): Promise<Result<BinaryTarget, AnalysisError>>;
|
||||
close(): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
|
||||
@@ -172,7 +172,7 @@ const browserPredicate = (operation: BrowserEvidenceOperation): string => {
|
||||
case "discover_webmcp_tools":
|
||||
return "rea.webmcp-discovery/v1";
|
||||
case "compare_web_captures":
|
||||
return "rea.web-capture-diff/v1";
|
||||
return "rea.web-capture-diff/v2";
|
||||
case "capture_web_screenshot":
|
||||
return "rea.web-screenshot/v1";
|
||||
case "compare_web_screenshots":
|
||||
|
||||
@@ -53,20 +53,20 @@ export const scanVersionInventories = async (
|
||||
scanner: VersionInventoryScanner = scanAuthorizedArtifactInventory,
|
||||
): Promise<VersionSnapshots> => {
|
||||
const [left, right] = await Promise.all([
|
||||
scanner(
|
||||
options.leftPath,
|
||||
options.inputRoots,
|
||||
options.limits,
|
||||
options.signal,
|
||||
options.integrity,
|
||||
),
|
||||
scanner(
|
||||
options.rightPath,
|
||||
options.inputRoots,
|
||||
options.limits,
|
||||
options.signal,
|
||||
options.integrity,
|
||||
),
|
||||
scanner({
|
||||
inputPath: options.leftPath,
|
||||
roots: options.inputRoots,
|
||||
limits: options.limits,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
integrity: options.integrity,
|
||||
}),
|
||||
scanner({
|
||||
inputPath: options.rightPath,
|
||||
roots: options.inputRoots,
|
||||
limits: options.limits,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
integrity: options.integrity,
|
||||
}),
|
||||
]);
|
||||
return { left, right };
|
||||
};
|
||||
|
||||
@@ -313,15 +313,13 @@ const ensureComparisonCheckpoint = async (
|
||||
],
|
||||
comparison_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
records: [evidence],
|
||||
return checkpointRunEvidence({
|
||||
input,
|
||||
workspace: state.workspace,
|
||||
evidence,
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const finalizeInvestigation = async (
|
||||
@@ -348,15 +346,42 @@ const finalizeInvestigation = async (
|
||||
],
|
||||
result_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpointRunEvidence({
|
||||
input,
|
||||
workspace: state.workspace,
|
||||
evidence,
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok
|
||||
? completeOutcome(saved.value.workspace, saved.value.run, false, session)
|
||||
: saved;
|
||||
};
|
||||
|
||||
interface RunEvidenceCheckpoint {
|
||||
readonly input: CrossVersionInvestigationInput;
|
||||
readonly workspace: InvestigationWorkspace;
|
||||
readonly evidence: Evidence;
|
||||
readonly run: InvestigationRun;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
}
|
||||
|
||||
const checkpointRunEvidence = async ({
|
||||
input,
|
||||
workspace,
|
||||
evidence,
|
||||
run,
|
||||
policy,
|
||||
}: RunEvidenceCheckpoint): Promise<Result<RunState, AnalysisError>> => {
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
current: workspace,
|
||||
records: [evidence],
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? completeOutcome(saved.value, run, false, session) : saved;
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const comparisonEvidenceFor = (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { createServerIdentity } from "../serverIdentity.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import type { AnalysisOperation } from "./AnalysisProvider.js";
|
||||
import { createBinarySession } from "./runtime.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
@@ -41,15 +42,17 @@ import {
|
||||
workflowAnalysisProfile,
|
||||
} from "./InvestigationProviders.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import {
|
||||
enhancedToolNameSchema,
|
||||
type EnhancedToolName,
|
||||
} from "../contracts/enhancedInputs.js";
|
||||
|
||||
type DirectAnalysisTool =
|
||||
| "binary_overview"
|
||||
| EnhancedToolName
|
||||
| "procedure_pseudo_code"
|
||||
| "analyze_function"
|
||||
| "search_strings"
|
||||
| "search_procedures"
|
||||
| "xrefs"
|
||||
| "trace_feature";
|
||||
| "xrefs";
|
||||
|
||||
/**
|
||||
* Open one binary, execute one tool, and always release provider resources.
|
||||
@@ -312,11 +315,7 @@ const runAnalysis = async (
|
||||
if (!writable.ok) return cliError(writable.error);
|
||||
let output: JsonValue;
|
||||
let evidence: Evidence | undefined;
|
||||
if (
|
||||
tool === "binary_overview" ||
|
||||
tool === "analyze_function" ||
|
||||
tool === "trace_feature"
|
||||
) {
|
||||
if (isEnhancedTool(tool)) {
|
||||
const result = await new EnhancedTools(session).execute(
|
||||
tool,
|
||||
arguments_,
|
||||
@@ -324,22 +323,16 @@ const runAnalysis = async (
|
||||
);
|
||||
if (!result.ok) output = cliError(result.error);
|
||||
else {
|
||||
evidence = createEvidence(
|
||||
opened.value,
|
||||
tool === "analyze_function"
|
||||
? session.providerIdentity(tool)
|
||||
: REA_WORKFLOW_PROVIDER,
|
||||
{
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
...(evidenceProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: evidenceProfile }),
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
},
|
||||
);
|
||||
evidence = createEvidence(opened.value, REA_WORKFLOW_PROVIDER, {
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
...(evidenceProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: evidenceProfile }),
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
});
|
||||
output = evidence;
|
||||
}
|
||||
} else {
|
||||
@@ -428,9 +421,7 @@ const replayProviderFor = (
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
) =>
|
||||
tool === "binary_overview" || tool === "trace_feature"
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: session.providerIdentity(tool);
|
||||
isEnhancedTool(tool) ? REA_WORKFLOW_PROVIDER : session.providerIdentity(tool);
|
||||
|
||||
const analysisProfileForEvidence = (
|
||||
session: ReturnType<typeof createBinarySession>,
|
||||
@@ -440,12 +431,14 @@ const analysisProfileForEvidence = (
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
): AnalysisProfileCommitment | undefined => {
|
||||
if (tool !== "binary_overview" && tool !== "trace_feature")
|
||||
return session.analysisProfile(tool);
|
||||
if (!isEnhancedTool(tool)) return session.analysisProfile(tool);
|
||||
const upstream = session.analysisProfile();
|
||||
return upstream === undefined ? undefined : workflowAnalysisProfile(upstream);
|
||||
};
|
||||
|
||||
const isEnhancedTool = (tool: AnalysisOperation): tool is EnhancedToolName =>
|
||||
enhancedToolNameSchema.safeParse(tool).success;
|
||||
|
||||
const fileExists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await access(path);
|
||||
|
||||
@@ -70,6 +70,7 @@ export interface DoctorHost {
|
||||
readonly nodeVersion: string;
|
||||
readonly configuredHopperPath?: string;
|
||||
readonly configuredIlspyCmdPath?: string;
|
||||
readonly configuredJadxCmdPath?: string;
|
||||
macosVersion(): Promise<string | undefined>;
|
||||
linuxDistribution(): Promise<LinuxDistribution | undefined>;
|
||||
validTarget(path: string): Promise<boolean>;
|
||||
@@ -85,6 +86,7 @@ export interface DoctorHost {
|
||||
clientRegistrations?(): Promise<readonly ClientRegistrationStatus[]>;
|
||||
javascriptReplayCheck?(): Promise<DoctorCheck>;
|
||||
ilspyCmdVersion?(path: string): Promise<string | undefined>;
|
||||
jadxCmdVersion?(path: string): Promise<string | undefined>;
|
||||
runtimeExecutables?(): Promise<RuntimeExecutableInventory>;
|
||||
}
|
||||
|
||||
@@ -284,6 +286,9 @@ export const systemDoctorHost = (
|
||||
...(process.env.REA_ILSPY_CMD_PATH === undefined
|
||||
? {}
|
||||
: { configuredIlspyCmdPath: process.env.REA_ILSPY_CMD_PATH }),
|
||||
...(process.env.REA_JADX_CMD_PATH === undefined
|
||||
? {}
|
||||
: { configuredJadxCmdPath: process.env.REA_JADX_CMD_PATH }),
|
||||
async macosVersion() {
|
||||
try {
|
||||
return (
|
||||
@@ -374,6 +379,16 @@ export const systemDoctorHost = (
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
async jadxCmdVersion(path) {
|
||||
try {
|
||||
await access(path, constants.X_OK);
|
||||
return firstJadxVersionLine(
|
||||
(await execFileAsync(path, ["--version"], { timeout: 10_000 })).stdout,
|
||||
);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
runtimeExecutables: () =>
|
||||
inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
@@ -449,3 +464,6 @@ const uniqueLines = (value: string): string[] => [
|
||||
|
||||
const firstIlspyVersionLine = (value: string): string | undefined =>
|
||||
uniqueLines(value).find((line) => line.startsWith("ilspycmd:"));
|
||||
|
||||
const firstJadxVersionLine = (value: string): string | undefined =>
|
||||
uniqueLines(value).find((line) => /^\d+\.\d+\.\d+(?:[-+].+)?$/u.test(line));
|
||||
|
||||
@@ -46,6 +46,8 @@ export const collectDoctorDiagnostics = async (
|
||||
if (javascriptReplayCheck !== undefined) checks.push(javascriptReplayCheck);
|
||||
const ilspyCheck = await optionalIlspyCheck(host);
|
||||
if (ilspyCheck !== undefined) checks.push(ilspyCheck);
|
||||
const jadxCheck = await optionalJadxCheck(host);
|
||||
if (jadxCheck !== undefined) checks.push(jadxCheck);
|
||||
const hopperDemoCheck = await optionalHopperDemoCheck(host, hopperPath);
|
||||
if (hopperDemoCheck !== undefined) checks.push(hopperDemoCheck);
|
||||
const targetCheck = await optionalTargetCheck(target, host);
|
||||
@@ -250,6 +252,25 @@ const optionalIlspyCheck = async (
|
||||
);
|
||||
};
|
||||
|
||||
const optionalJadxCheck = async (
|
||||
host: DoctorHost,
|
||||
): Promise<DoctorCheck | undefined> => {
|
||||
if (host.configuredJadxCmdPath === undefined) return undefined;
|
||||
const version = await host.jadxCmdVersion?.(host.configuredJadxCmdPath);
|
||||
return check(
|
||||
"jadx",
|
||||
version !== undefined,
|
||||
version === undefined
|
||||
? host.configuredJadxCmdPath
|
||||
: `${host.configuredJadxCmdPath} (${version})`,
|
||||
{
|
||||
remediation:
|
||||
"Unset REA_JADX_CMD_PATH or point it at a runnable jadx executable.",
|
||||
classification: "config_drift",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const optionalTargetCheck = async (
|
||||
target: string | undefined,
|
||||
host: DoctorHost,
|
||||
|
||||
@@ -225,21 +225,9 @@ export class EvidenceLedger {
|
||||
existingUnknown.revision_digest !== unknown.revision_digest
|
||||
)
|
||||
return err(new UnknownRegistryError("already-exists"));
|
||||
const checked = this.#validateCandidate(
|
||||
pendingRecords,
|
||||
this.#unknownRevisions,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, this.#unknownRevisions, checked.value);
|
||||
return ok(null);
|
||||
return this.#commitCandidate(pendingRecords, this.#unknownRevisions);
|
||||
}
|
||||
pendingRecords.set(mutation.evidence_id, mutation);
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(structuredClone(unknown));
|
||||
return this.#appendUnknownCandidate(unknown, mutation, pendingRecords);
|
||||
}
|
||||
|
||||
/** Apply one approved full-state update using optimistic revision matching. */
|
||||
@@ -332,14 +320,39 @@ export class EvidenceLedger {
|
||||
}),
|
||||
);
|
||||
}
|
||||
const pendingRecords = new Map(this.#records);
|
||||
return this.#appendUnknownCandidate(
|
||||
unknown,
|
||||
mutationEvidence,
|
||||
new Map(this.#records),
|
||||
);
|
||||
}
|
||||
|
||||
#appendUnknownCandidate(
|
||||
unknown: ResidualUnknown,
|
||||
mutationEvidence: Evidence,
|
||||
pendingRecords: Map<string, Evidence>,
|
||||
): Result<
|
||||
ResidualUnknown,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
pendingRecords.set(mutationEvidence.evidence_id, mutationEvidence);
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
const committed = this.#commitCandidate(pendingRecords, pendingUnknowns);
|
||||
return committed.ok ? ok(structuredClone(unknown)) : err(committed.error);
|
||||
}
|
||||
|
||||
#commitCandidate(
|
||||
records: ReadonlyMap<string, Evidence>,
|
||||
unknowns: ReadonlyMap<string, ResidualUnknown>,
|
||||
): Result<
|
||||
null,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
const checked = this.#validateCandidate(records, unknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(structuredClone(unknown));
|
||||
this.#commit(records, unknowns, checked.value);
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
#validateCandidate(
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
createEvidence,
|
||||
type Evidence,
|
||||
type EvidenceProvider,
|
||||
type EvidenceSubjectTarget,
|
||||
} from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
interface InventoryProjectionInput {
|
||||
readonly inventory_evidence: readonly Evidence[];
|
||||
readonly limits: unknown;
|
||||
}
|
||||
|
||||
interface InventoryProjectionResult {
|
||||
readonly root_sha256: string;
|
||||
readonly source_evidence_ids: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
interface InventoryProjectionOptions<
|
||||
Input extends InventoryProjectionInput,
|
||||
Output extends InventoryProjectionResult,
|
||||
> {
|
||||
readonly rawInput: unknown;
|
||||
readonly schema: z.ZodType<Input>;
|
||||
readonly project: (input: Input) => Output;
|
||||
readonly operation: string;
|
||||
readonly predicateType: string;
|
||||
readonly provider: EvidenceProvider;
|
||||
readonly subjectFormat: (first: Evidence) => EvidenceSubjectTarget["format"];
|
||||
readonly protocolError: string;
|
||||
}
|
||||
|
||||
/** Parse one inventory projection and wrap its deterministic result in Evidence v2. */
|
||||
export const projectInventoryEvidence = <
|
||||
Input extends InventoryProjectionInput,
|
||||
Output extends InventoryProjectionResult,
|
||||
>(
|
||||
options: InventoryProjectionOptions<Input, Output>,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
const parsed = options.schema.safeParse(options.rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(options.operation, { cause: parsed.error }),
|
||||
);
|
||||
try {
|
||||
const result = options.project(parsed.data);
|
||||
const first = parsed.data.inventory_evidence[0];
|
||||
return ok(
|
||||
createEvidence(
|
||||
first?.subject === null || first?.subject === undefined
|
||||
? undefined
|
||||
: {
|
||||
path: first.subject.local_path,
|
||||
sha256: result.root_sha256,
|
||||
format: options.subjectFormat(first),
|
||||
},
|
||||
options.provider,
|
||||
{
|
||||
predicateType: options.predicateType,
|
||||
operation: options.operation,
|
||||
parameters: {
|
||||
inventory_evidence_ids: [...result.source_evidence_ids],
|
||||
limits: jsonValueSchema.parse(parsed.data.limits),
|
||||
},
|
||||
result: jsonValueSchema.parse(result) as JsonValue,
|
||||
rawResult: null,
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
environment: null,
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: result.source_evidence_ids,
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof TypeError || cause instanceof z.ZodError
|
||||
? new AnalysisInputError(options.operation, { cause })
|
||||
: new AnalysisProtocolError(options.protocolError, { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -39,6 +39,26 @@ export const MANAGED_WORKFLOW_PROVIDER = {
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Apple application projections. */
|
||||
export const APPLE_APPLICATION_PROVIDER = {
|
||||
id: "rea-apple-application",
|
||||
name: "REA Apple application workflows",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Android application projections. */
|
||||
export const ANDROID_APPLICATION_PROVIDER = {
|
||||
id: "rea-android-application",
|
||||
name: "REA Android application workflows",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
export const RUNTIME_IDENTIFICATION_PROVIDER = {
|
||||
id: "rea-runtime-identification",
|
||||
name: "REA runtime identification",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic static JavaScript application analysis. */
|
||||
export const JAVASCRIPT_APPLICATION_PROVIDER = {
|
||||
id: "rea-javascript-application",
|
||||
|
||||
@@ -74,24 +74,29 @@ export const writeInvestigationWorkspace = async (
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> =>
|
||||
writeRevisionedWorkspace(
|
||||
workspace,
|
||||
writeRevisionedWorkspace({
|
||||
document: workspace,
|
||||
path,
|
||||
expectedRevision,
|
||||
policy,
|
||||
investigationWorkspaceCodec,
|
||||
);
|
||||
codec: investigationWorkspaceCodec,
|
||||
});
|
||||
|
||||
interface RevisionedWorkspaceWrite<Document> {
|
||||
readonly document: Document;
|
||||
readonly path: string;
|
||||
readonly expectedRevision: number | null;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
readonly codec: RevisionedWorkspaceCodec<Document>;
|
||||
}
|
||||
|
||||
/** Atomically append one validated CAS-linked revision under an exclusive lock. */
|
||||
export const writeRevisionedWorkspace = async <Document>(
|
||||
document: Document,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
input: RevisionedWorkspaceWrite<Document>,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> => {
|
||||
const { codec, document, expectedRevision, path, policy } = input;
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("update", "disabled"));
|
||||
let encoded: string;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import type { WebSocket } from "ws";
|
||||
|
||||
import type {
|
||||
ProcessScenario,
|
||||
ProtocolEvent,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
/** Minimal recorder boundary shared by the legacy queue replay adapter. */
|
||||
export interface QueueReplayRecorder {
|
||||
readonly scenario: ProcessScenario;
|
||||
truncated: boolean;
|
||||
atMs(): number;
|
||||
record(event: Omit<ProtocolEvent, "sequence">): number | null;
|
||||
}
|
||||
|
||||
export interface QueueHttpRequest {
|
||||
readonly request: IncomingMessage;
|
||||
readonly response: ServerResponse;
|
||||
readonly method: string;
|
||||
readonly path: string;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
/** Execute one request against the existing bounded HTTP response queue. */
|
||||
export const handleQueueHttp = async (
|
||||
input: QueueHttpRequest,
|
||||
recorder: QueueReplayRecorder,
|
||||
calls: Map<number, number>,
|
||||
): Promise<void> => {
|
||||
const index = recorder.scenario.replay.http.findIndex((route) => {
|
||||
if (route.method !== input.method || route.path !== input.path)
|
||||
return false;
|
||||
if (route.request_body !== undefined && route.request_body !== input.body)
|
||||
return false;
|
||||
return Object.entries(route.request_headers).every(
|
||||
([name, value]) => input.request.headers[name.toLowerCase()] === value,
|
||||
);
|
||||
});
|
||||
const route = recorder.scenario.replay.http[index];
|
||||
const used = index < 0 ? 0 : (calls.get(index) ?? 0);
|
||||
const outcome =
|
||||
route === undefined
|
||||
? "unmatched"
|
||||
: used >= route.max_calls
|
||||
? "script_exhausted"
|
||||
: "matched";
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
data: input.body.length === 0 ? "" : "<redacted-request-body>",
|
||||
outcome,
|
||||
});
|
||||
if (route === undefined || outcome === "script_exhausted") {
|
||||
input.response.statusCode = route === undefined ? 404 : 409;
|
||||
input.response.end();
|
||||
return;
|
||||
}
|
||||
calls.set(index, used + 1);
|
||||
if (route.delay_ms > 0)
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, route.delay_ms),
|
||||
);
|
||||
if (route.disconnect) {
|
||||
input.response.destroy();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
return;
|
||||
}
|
||||
input.response.statusCode = route.status;
|
||||
for (const [name, value] of Object.entries(route.response_headers))
|
||||
input.response.setHeader(name, value);
|
||||
input.response.end(route.body);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
data: route.body,
|
||||
outcome: "matched",
|
||||
});
|
||||
};
|
||||
|
||||
/** Send the existing bounded per-connection WebSocket queue. */
|
||||
export const sendWebSocketScript = async (
|
||||
client: WebSocket,
|
||||
connection: number,
|
||||
recorder: QueueReplayRecorder,
|
||||
): Promise<void> => {
|
||||
const scripts = recorder.scenario.replay.websocket_connections;
|
||||
const script = scripts[connection - 1];
|
||||
if (scripts.length > 0 && script === undefined) {
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "script_exhausted",
|
||||
});
|
||||
client.terminate();
|
||||
return;
|
||||
}
|
||||
const messages =
|
||||
script?.messages ??
|
||||
recorder.scenario.replay.websocket_messages.map((data) => ({
|
||||
data,
|
||||
delay_ms: 0,
|
||||
}));
|
||||
for (const message of messages) {
|
||||
if (message.delay_ms > 0)
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, message.delay_ms),
|
||||
);
|
||||
if (client.readyState !== 1) return;
|
||||
client.send(message.data);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: message.data,
|
||||
outcome: "matched",
|
||||
});
|
||||
}
|
||||
if (script?.disconnect_after === true) {
|
||||
client.close();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
}
|
||||
};
|
||||
+269
-113
@@ -8,19 +8,28 @@ import { WebSocketServer, type WebSocket } from "ws";
|
||||
import type {
|
||||
ProcessScenario,
|
||||
ProtocolEvent,
|
||||
ReplayTransitionEvent,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
ReplayMachineRuntime,
|
||||
type ReplayMachineDecision,
|
||||
type ReplayMachineEvent,
|
||||
} from "../domain/replayMachineRuntime.js";
|
||||
import { handleQueueHttp, sendWebSocketScript } from "./LoopbackQueueReplay.js";
|
||||
|
||||
/** Owned loopback replay endpoints and their bounded protocol observations. */
|
||||
export interface LoopbackReplay {
|
||||
readonly httpUrl: string;
|
||||
readonly websocketUrl: string;
|
||||
readonly events: ProtocolEvent[];
|
||||
readonly transitions: ReplayTransitionEvent[];
|
||||
readonly truncated: boolean;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
class ReplayRecorder {
|
||||
readonly events: ProtocolEvent[] = [];
|
||||
readonly transitions: ReplayTransitionEvent[] = [];
|
||||
readonly started = Date.now();
|
||||
truncated = false;
|
||||
|
||||
@@ -35,13 +44,106 @@ class ReplayRecorder {
|
||||
);
|
||||
}
|
||||
|
||||
record(event: Omit<ProtocolEvent, "sequence">): void {
|
||||
if (this.events.length < this.scenario.limits.protocol_events)
|
||||
this.events.push({ sequence: this.events.length, ...event });
|
||||
else this.truncated = true;
|
||||
record(event: Omit<ProtocolEvent, "sequence">): number | null {
|
||||
if (this.events.length >= this.scenario.limits.protocol_events) {
|
||||
this.truncated = true;
|
||||
return null;
|
||||
}
|
||||
const sequence = this.events.length;
|
||||
this.events.push({ sequence, ...event });
|
||||
return sequence;
|
||||
}
|
||||
|
||||
recordTransition(
|
||||
decision: Extract<ReplayMachineDecision, { readonly outcome: "matched" }>,
|
||||
protocolEventSequence: number | null,
|
||||
): void {
|
||||
if (protocolEventSequence === null) {
|
||||
this.truncated = true;
|
||||
return;
|
||||
}
|
||||
this.transitions.push({
|
||||
...decision.transition,
|
||||
at_ms: this.atMs(),
|
||||
protocol_event_sequence: protocolEventSequence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SerializedReplayMachine {
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(readonly runtime: ReplayMachineRuntime) {}
|
||||
|
||||
run<T>(operation: (runtime: ReplayMachineRuntime) => Promise<T>): Promise<T> {
|
||||
const result = this.#tail.then(
|
||||
() => operation(this.runtime),
|
||||
() => operation(this.runtime),
|
||||
);
|
||||
this.#tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const requestHeaders = (
|
||||
request: IncomingMessage,
|
||||
): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(request.headers).flatMap(([name, value]) =>
|
||||
value === undefined
|
||||
? []
|
||||
: [
|
||||
[
|
||||
name.toLowerCase(),
|
||||
Array.isArray(value) ? value.join(", ") : value,
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
const machineEvent = (
|
||||
protocol: ReplayMachineEvent["protocol"],
|
||||
path: string,
|
||||
body: string,
|
||||
connection: ReplayMachineEvent["connection"] = "not_applicable",
|
||||
request?: IncomingMessage,
|
||||
): ReplayMachineEvent => ({
|
||||
protocol,
|
||||
connection,
|
||||
at_ms: 0,
|
||||
method: protocol === "http" ? (request?.method ?? "GET") : null,
|
||||
path,
|
||||
headers: request === undefined ? {} : requestHeaders(request),
|
||||
body,
|
||||
});
|
||||
|
||||
const applyHttpActions = async (
|
||||
decision: Extract<ReplayMachineDecision, { readonly outcome: "matched" }>,
|
||||
response: ServerResponse,
|
||||
): Promise<{ readonly disconnected: boolean; readonly body: string }> => {
|
||||
let body = "";
|
||||
for (const action of decision.actions) {
|
||||
if (action.type === "delay")
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, action.duration_ms),
|
||||
);
|
||||
else if (action.type === "disconnect") {
|
||||
response.destroy();
|
||||
return { disconnected: true, body };
|
||||
} else if (action.type === "http_response") {
|
||||
response.statusCode = action.status;
|
||||
for (const [name, value] of Object.entries(action.headers))
|
||||
response.setHeader(name, value);
|
||||
body = action.body;
|
||||
}
|
||||
}
|
||||
response.end(body);
|
||||
return { disconnected: false, body };
|
||||
};
|
||||
|
||||
const readRequestBody = async (
|
||||
request: IncomingMessage,
|
||||
limit: number,
|
||||
@@ -57,8 +159,66 @@ const readRequestBody = async (
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
};
|
||||
|
||||
interface HttpReplayRequest {
|
||||
readonly request: IncomingMessage;
|
||||
readonly response: ServerResponse;
|
||||
readonly method: string;
|
||||
readonly path: string;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
const handleMachineHttp = async (
|
||||
input: HttpReplayRequest,
|
||||
recorder: ReplayRecorder,
|
||||
machine: SerializedReplayMachine,
|
||||
): Promise<void> =>
|
||||
machine.run(async (runtime) => {
|
||||
const decision = runtime.dispatch({
|
||||
...machineEvent(
|
||||
"http",
|
||||
input.path,
|
||||
input.body,
|
||||
"not_applicable",
|
||||
input.request,
|
||||
),
|
||||
at_ms: recorder.atMs(),
|
||||
});
|
||||
const protocolSequence = recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
data: input.body.length === 0 ? "" : "<redacted-request-body>",
|
||||
outcome: decision.outcome,
|
||||
transition_id: decision.transition?.transition_id ?? null,
|
||||
state_before: decision.transition?.state_before ?? runtime.state,
|
||||
state_after: decision.transition?.state_after ?? runtime.state,
|
||||
});
|
||||
if (decision.outcome !== "matched") {
|
||||
input.response.statusCode = decision.outcome === "unmatched" ? 404 : 409;
|
||||
input.response.end();
|
||||
return;
|
||||
}
|
||||
recorder.recordTransition(decision, protocolSequence);
|
||||
const applied = await applyHttpActions(decision, input.response);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
data: runtime.redact(applied.body),
|
||||
outcome: applied.disconnected ? "disconnected" : "matched",
|
||||
transition_id: decision.transition.transition_id,
|
||||
state_before: decision.transition.state_before,
|
||||
state_after: decision.transition.state_after,
|
||||
});
|
||||
});
|
||||
|
||||
const createHttpHandler = (
|
||||
recorder: ReplayRecorder,
|
||||
machine: SerializedReplayMachine | null,
|
||||
): ((request: IncomingMessage, response: ServerResponse) => Promise<void>) => {
|
||||
const calls = new Map<number, number>();
|
||||
return async (request, response) => {
|
||||
@@ -83,130 +243,97 @@ const createHttpHandler = (
|
||||
});
|
||||
return;
|
||||
}
|
||||
const index = recorder.scenario.replay.http.findIndex((route) => {
|
||||
if (route.method !== method || route.path !== path) return false;
|
||||
if (route.request_body !== undefined && route.request_body !== body)
|
||||
return false;
|
||||
return Object.entries(route.request_headers).every(
|
||||
([name, value]) => request.headers[name.toLowerCase()] === value,
|
||||
);
|
||||
});
|
||||
const route = recorder.scenario.replay.http[index];
|
||||
const used = index < 0 ? 0 : (calls.get(index) ?? 0);
|
||||
const outcome =
|
||||
route === undefined
|
||||
? "unmatched"
|
||||
: used >= route.max_calls
|
||||
? "script_exhausted"
|
||||
: "matched";
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method,
|
||||
path,
|
||||
data: body.length === 0 ? "" : "<redacted-request-body>",
|
||||
outcome,
|
||||
});
|
||||
if (route === undefined || outcome === "script_exhausted") {
|
||||
response.statusCode = route === undefined ? 404 : 409;
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
calls.set(index, used + 1);
|
||||
if (route.delay_ms > 0)
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, route.delay_ms),
|
||||
);
|
||||
if (route.disconnect) {
|
||||
response.destroy();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method,
|
||||
path,
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
return;
|
||||
}
|
||||
response.statusCode = route.status;
|
||||
for (const [name, value] of Object.entries(route.response_headers))
|
||||
response.setHeader(name, value);
|
||||
response.end(route.body);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method,
|
||||
path,
|
||||
data: route.body,
|
||||
outcome: "matched",
|
||||
});
|
||||
const input = { request, response, method, path, body };
|
||||
if (machine === null) await handleQueueHttp(input, recorder, calls);
|
||||
else await handleMachineHttp(input, recorder, machine);
|
||||
};
|
||||
};
|
||||
|
||||
const sendWebSocketScript = async (
|
||||
const applyWebSocketActions = async (
|
||||
client: WebSocket,
|
||||
connection: number,
|
||||
decision: Extract<ReplayMachineDecision, { readonly outcome: "matched" }>,
|
||||
recorder: ReplayRecorder,
|
||||
machine: ReplayMachineRuntime,
|
||||
): Promise<void> => {
|
||||
const scripts = recorder.scenario.replay.websocket_connections;
|
||||
const script = scripts[connection - 1];
|
||||
if (scripts.length > 0 && script === undefined) {
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "script_exhausted",
|
||||
});
|
||||
client.terminate();
|
||||
return;
|
||||
}
|
||||
const messages =
|
||||
script?.messages ??
|
||||
recorder.scenario.replay.websocket_messages.map((data) => ({
|
||||
data,
|
||||
delay_ms: 0,
|
||||
}));
|
||||
for (const message of messages) {
|
||||
if (message.delay_ms > 0)
|
||||
for (const action of decision.actions) {
|
||||
if (action.type === "delay")
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, message.delay_ms),
|
||||
setTimeout(resolveDelay, action.duration_ms),
|
||||
);
|
||||
if (client.readyState !== 1) return;
|
||||
client.send(message.data);
|
||||
recorder.record({
|
||||
else if (action.type === "disconnect") {
|
||||
client.close();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
transition_id: decision.transition.transition_id,
|
||||
state_before: decision.transition.state_before,
|
||||
state_after: decision.transition.state_after,
|
||||
});
|
||||
return;
|
||||
} else if (action.type === "websocket_send" && client.readyState === 1) {
|
||||
client.send(action.data);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: machine.redact(action.data),
|
||||
outcome: "matched",
|
||||
transition_id: decision.transition.transition_id,
|
||||
state_before: decision.transition.state_before,
|
||||
state_after: decision.transition.state_after,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const dispatchWebSocketMachine = async (input: {
|
||||
readonly client: WebSocket;
|
||||
readonly machine: SerializedReplayMachine;
|
||||
readonly recorder: ReplayRecorder;
|
||||
readonly protocol: "websocket_connect" | "websocket_message";
|
||||
readonly connection: ReplayMachineEvent["connection"];
|
||||
readonly body: string;
|
||||
readonly request?: IncomingMessage;
|
||||
}): Promise<void> => {
|
||||
const { client, machine, recorder, protocol, connection, body, request } =
|
||||
input;
|
||||
await machine.run(async (runtime) => {
|
||||
const decision = runtime.dispatch({
|
||||
...machineEvent(protocol, "/ws", body, connection, request),
|
||||
at_ms: recorder.atMs(),
|
||||
});
|
||||
const protocolSequence = recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
direction: protocol === "websocket_connect" ? "request" : "received",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: message.data,
|
||||
outcome: "matched",
|
||||
data: protocol === "websocket_connect" ? "" : runtime.redact(body),
|
||||
outcome: decision.outcome,
|
||||
transition_id: decision.transition?.transition_id ?? null,
|
||||
state_before: decision.transition?.state_before ?? runtime.state,
|
||||
state_after: decision.transition?.state_after ?? runtime.state,
|
||||
});
|
||||
}
|
||||
if (script?.disconnect_after === true) {
|
||||
client.close();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
}
|
||||
if (decision.outcome !== "matched") {
|
||||
client.close();
|
||||
return;
|
||||
}
|
||||
recorder.recordTransition(decision, protocolSequence);
|
||||
await applyWebSocketActions(client, decision, recorder, runtime);
|
||||
});
|
||||
};
|
||||
|
||||
const createWebSocketReplay = (
|
||||
server: Server,
|
||||
recorder: ReplayRecorder,
|
||||
machine: SerializedReplayMachine | null,
|
||||
): WebSocketServer => {
|
||||
let connections = 0;
|
||||
const websocket = new WebSocketServer({
|
||||
@@ -223,7 +350,7 @@ const createWebSocketReplay = (
|
||||
websocket.emit("connection", client, request),
|
||||
);
|
||||
});
|
||||
websocket.on("connection", (client: WebSocket) => {
|
||||
websocket.on("connection", (client: WebSocket, request: IncomingMessage) => {
|
||||
connections += 1;
|
||||
if (connections > recorder.scenario.limits.connections) {
|
||||
recorder.truncated = true;
|
||||
@@ -231,6 +358,28 @@ const createWebSocketReplay = (
|
||||
return;
|
||||
}
|
||||
client.on("error", () => undefined);
|
||||
if (machine !== null) {
|
||||
client.on("message", (value) => {
|
||||
void dispatchWebSocketMachine({
|
||||
client,
|
||||
machine,
|
||||
recorder,
|
||||
protocol: "websocket_message",
|
||||
connection: "not_applicable",
|
||||
body: value.toString(),
|
||||
});
|
||||
});
|
||||
void dispatchWebSocketMachine({
|
||||
client,
|
||||
machine,
|
||||
recorder,
|
||||
protocol: "websocket_connect",
|
||||
connection: connections === 1 ? "initial" : "reconnect",
|
||||
body: "",
|
||||
request,
|
||||
});
|
||||
return;
|
||||
}
|
||||
client.on("message", (value) =>
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
@@ -273,8 +422,14 @@ export const startLoopbackReplay = async (
|
||||
scenario: ProcessScenario,
|
||||
): Promise<LoopbackReplay> => {
|
||||
const recorder = new ReplayRecorder(scenario);
|
||||
const server = createServer(createHttpHandler(recorder));
|
||||
const websocket = createWebSocketReplay(server, recorder);
|
||||
const machine =
|
||||
scenario.replay.machine === null
|
||||
? null
|
||||
: new SerializedReplayMachine(
|
||||
new ReplayMachineRuntime(scenario.replay.machine),
|
||||
);
|
||||
const server = createServer(createHttpHandler(recorder, machine));
|
||||
const websocket = createWebSocketReplay(server, recorder, machine);
|
||||
let port: number;
|
||||
try {
|
||||
port = await listen(server);
|
||||
@@ -286,6 +441,7 @@ export const startLoopbackReplay = async (
|
||||
httpUrl: `http://127.0.0.1:${String(port)}`,
|
||||
websocketUrl: `ws://127.0.0.1:${String(port)}/ws`,
|
||||
events: recorder.events,
|
||||
transitions: recorder.transitions,
|
||||
get truncated() {
|
||||
return recorder.truncated;
|
||||
},
|
||||
|
||||
@@ -145,13 +145,11 @@ export class PermissionAuthority {
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
const canonical = await canonicalizePermissionRequest(request, access);
|
||||
if (!canonical.ok) return canonical;
|
||||
const evaluated = this.evaluateCanonical(canonical.value, options);
|
||||
const evaluated = await this.evaluateRequest(request, access, options);
|
||||
if (!evaluated.ok) return evaluated;
|
||||
const { decision, owner } = evaluated.value;
|
||||
const { decision, owner, request: canonicalRequest } = evaluated.value;
|
||||
owner.policy = consumePermission(owner.policy, decision);
|
||||
return ok({ ...decision, request: canonical.value });
|
||||
return ok({ ...decision, request: canonicalRequest });
|
||||
}
|
||||
|
||||
/** Dry-run the exact shared evaluation without consuming a once grant. */
|
||||
@@ -170,12 +168,38 @@ export class PermissionAuthority {
|
||||
},
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
const evaluated = await this.evaluateRequest(request, access, options);
|
||||
return evaluated.ok
|
||||
? ok({ ...evaluated.value.decision, request: evaluated.value.request })
|
||||
: evaluated;
|
||||
}
|
||||
|
||||
private async evaluateRequest(
|
||||
request: PermissionRequest,
|
||||
access: "read" | "write",
|
||||
options: {
|
||||
readonly elicitationSupported?: boolean;
|
||||
readonly restartRequired?: boolean;
|
||||
},
|
||||
): Promise<
|
||||
Result<
|
||||
{
|
||||
readonly decision: Extract<
|
||||
PermissionDecision,
|
||||
{ readonly allowed: true }
|
||||
>;
|
||||
readonly owner: PermissionAuthority;
|
||||
readonly request: PermissionRequest;
|
||||
},
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
const canonical = await canonicalizePermissionRequest(request, access);
|
||||
if (!canonical.ok) return canonical;
|
||||
const evaluated = this.evaluateCanonical(canonical.value, options);
|
||||
return evaluated.ok
|
||||
? ok({ ...evaluated.value.decision, request: canonical.value })
|
||||
? ok({ ...evaluated.value, request: canonical.value })
|
||||
: evaluated;
|
||||
}
|
||||
|
||||
@@ -256,13 +280,13 @@ export class PermissionAuthority {
|
||||
const denied = evaluatePermission(effective, request);
|
||||
if (denied.allowed) return ok({ decision: denied, owner: this });
|
||||
return err(
|
||||
new PermissionRequiredError(
|
||||
request,
|
||||
denied.missing,
|
||||
ceilingFor(effective, request.capability),
|
||||
options.elicitationSupported ?? false,
|
||||
options.restartRequired ?? false,
|
||||
),
|
||||
new PermissionRequiredError({
|
||||
requested: request,
|
||||
missing: denied.missing,
|
||||
ceiling: ceilingFor(effective, request.capability),
|
||||
elicitationSupported: options.elicitationSupported ?? false,
|
||||
restartRequired: options.restartRequired ?? false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -270,48 +294,29 @@ export class PermissionAuthority {
|
||||
async replaceProjectGrants(
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
let candidate: PermissionPolicy = {
|
||||
...this.policy,
|
||||
grants: this.policy.grants.filter(
|
||||
({ lifetime }) => lifetime !== "project",
|
||||
),
|
||||
};
|
||||
for (const grant of grants) {
|
||||
const canonical = await canonicalizeGrant(grant);
|
||||
if (!canonical.ok) return canonical;
|
||||
const added = grantPermission(candidate, canonical.value);
|
||||
if (!added.ok)
|
||||
return err(
|
||||
new PermissionPathError(grant.grant_id, "io", {
|
||||
cause: added.error,
|
||||
}),
|
||||
);
|
||||
candidate = added.value;
|
||||
}
|
||||
this.policy = candidate;
|
||||
return ok(null);
|
||||
return this.replaceGrantsForLifetime("project", grants);
|
||||
}
|
||||
|
||||
/** Replace grants derived from the currently loaded administrator ceiling. */
|
||||
async replaceAdministratorGrants(
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
return this.replaceGrantsForLifetime("administrator", grants);
|
||||
}
|
||||
|
||||
private async replaceGrantsForLifetime(
|
||||
lifetime: Extract<PermissionGrant["lifetime"], "administrator" | "project">,
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
let candidate: PermissionPolicy = {
|
||||
...this.policy,
|
||||
grants: this.policy.grants.filter(
|
||||
({ lifetime }) => lifetime !== "administrator",
|
||||
),
|
||||
grants: this.policy.grants.filter((grant) => grant.lifetime !== lifetime),
|
||||
};
|
||||
for (const grant of grants) {
|
||||
const canonical = await canonicalizeGrant(grant);
|
||||
if (!canonical.ok) return canonical;
|
||||
const added = grantPermission(candidate, canonical.value);
|
||||
if (!added.ok)
|
||||
return err(
|
||||
new PermissionPathError(grant.grant_id, "io", {
|
||||
cause: added.error,
|
||||
}),
|
||||
);
|
||||
const added = addGrant(candidate, canonical.value);
|
||||
if (!added.ok) return added;
|
||||
candidate = added.value;
|
||||
}
|
||||
this.policy = candidate;
|
||||
@@ -345,13 +350,8 @@ export class PermissionAuthority {
|
||||
),
|
||||
};
|
||||
for (const grant of grants) {
|
||||
const added = grantPermission(candidate, grant);
|
||||
if (!added.ok)
|
||||
return err(
|
||||
new PermissionPathError(grant.grant_id, "io", {
|
||||
cause: added.error,
|
||||
}),
|
||||
);
|
||||
const added = addGrant(candidate, grant);
|
||||
if (!added.ok) return added;
|
||||
candidate = added.value;
|
||||
}
|
||||
this.policy = candidate;
|
||||
@@ -380,11 +380,8 @@ export const createPermissionAuthority = async (
|
||||
for (const grant of grants) {
|
||||
const canonicalGrant = await canonicalizeGrant(grant);
|
||||
if (!canonicalGrant.ok) return canonicalGrant;
|
||||
const added = grantPermission(policy, canonicalGrant.value);
|
||||
if (!added.ok)
|
||||
return err(
|
||||
new PermissionPathError(grant.grant_id, "io", { cause: added.error }),
|
||||
);
|
||||
const added = addGrant(policy, canonicalGrant.value);
|
||||
if (!added.ok) return added;
|
||||
policy = added.value;
|
||||
}
|
||||
return ok(new PermissionAuthority(policy));
|
||||
@@ -397,6 +394,20 @@ const canonicalizeGrant = async (
|
||||
return scope.ok ? ok({ ...grant, ...scope.value }) : scope;
|
||||
};
|
||||
|
||||
const addGrant = (
|
||||
policy: PermissionPolicy,
|
||||
grant: PermissionGrant,
|
||||
): Result<PermissionPolicy, PermissionPathError> => {
|
||||
const added = grantPermission(policy, grant);
|
||||
return added.ok
|
||||
? added
|
||||
: err(
|
||||
new PermissionPathError(grant.grant_id, "io", {
|
||||
cause: added.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const ceilingFor = (
|
||||
policy: PermissionPolicy,
|
||||
capability: PermissionRequest["capability"],
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessLifecycleEvent,
|
||||
ProcessPolicyDecision,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
assertRealPathAuthority,
|
||||
} from "./ProcessCaptureAuthority.js";
|
||||
import {
|
||||
normalizeProcessEvents,
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessText,
|
||||
redactProtocolEvents,
|
||||
@@ -66,6 +68,7 @@ interface CaptureResultOptions {
|
||||
readonly reason: "exited" | "timeout" | "idle_timeout";
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly processEvents: readonly ProcessLifecycleEvent[];
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly before: SnapshotResult;
|
||||
readonly after: SnapshotResult;
|
||||
@@ -81,6 +84,11 @@ interface CaptureResultOptions {
|
||||
readonly manifest: ProcessCapture["manifest"];
|
||||
}
|
||||
|
||||
type ProcessSignal = NonNullable<ProcessLifecycleEvent["signal"]>;
|
||||
|
||||
const isProcessSignal = (value: string): value is ProcessSignal =>
|
||||
value === "SIGINT" || value === "SIGTERM" || value === "SIGKILL";
|
||||
|
||||
export const buildCaptureResult = (
|
||||
options: CaptureResultOptions,
|
||||
): ProcessCapture => ({
|
||||
@@ -109,12 +117,40 @@ export const buildCaptureResult = (
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
process_events: normalizeProcessEvents(
|
||||
[
|
||||
...options.processEvents,
|
||||
...options.interactions
|
||||
.filter(
|
||||
(event) => event.type === "signal" && event.outcome === "dispatched",
|
||||
)
|
||||
.flatMap((event) =>
|
||||
isProcessSignal(event.data)
|
||||
? [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: event.dispatched_at_ms,
|
||||
type: "signal_dispatched" as const,
|
||||
pid: options.rootPid,
|
||||
parent_pid: null,
|
||||
previous_parent_pid: null,
|
||||
signal: event.data,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
].sort((left, right) => left.at_ms - right.at_ms),
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
filesystem_checkpoints: options.checkpoints,
|
||||
shim_events: options.shimEvents,
|
||||
protocol_events: redactProtocolEvents(
|
||||
options.replay.events,
|
||||
options.scenario,
|
||||
),
|
||||
replay_transitions: options.replay.transitions,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
filesystem_effects: classifyFilesystemEffects(
|
||||
|
||||
@@ -82,7 +82,7 @@ export const compareProcessEvidenceFiles = async (
|
||||
const right = parseCaptureEvidence(await readJson(rightPath));
|
||||
const comparison = compareProcessCaptures(left.capture, right.capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
predicateType: "rea.process-comparison/v4",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.id,
|
||||
|
||||
@@ -11,7 +11,7 @@ import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
export const PROCESS_PROVIDER = {
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
version: "4",
|
||||
} as const;
|
||||
|
||||
/** Project one process scenario into secret-free Evidence parameters. */
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessLifecycleEvent,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
TerminalFrame,
|
||||
@@ -192,6 +193,7 @@ const startCaptureRuntime = async (options: {
|
||||
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
|
||||
readonly frames: TerminalFrame[];
|
||||
readonly samples: ProcessSample[];
|
||||
readonly processEvents: ProcessLifecycleEvent[];
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly timers: Set<NodeJS.Timeout>;
|
||||
readonly dispatchedEventIndexes: Set<number>;
|
||||
@@ -252,6 +254,7 @@ const startCaptureRuntime = async (options: {
|
||||
started,
|
||||
limit: scenario.limits.processes,
|
||||
samples: options.samples,
|
||||
events: options.processEvents,
|
||||
});
|
||||
return {
|
||||
replay,
|
||||
@@ -362,6 +365,7 @@ const completeCapture = async (options: {
|
||||
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly processEvents: readonly ProcessLifecycleEvent[];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly exit: Awaited<ReturnType<typeof awaitTerminalExit>>;
|
||||
readonly signal?: AbortSignal;
|
||||
@@ -400,6 +404,7 @@ const completeCapture = async (options: {
|
||||
frames: options.frames,
|
||||
exit: { ...options.exit, reason },
|
||||
samples: options.samples,
|
||||
processEvents: options.processEvents,
|
||||
replay: runtime.replay,
|
||||
before: options.before,
|
||||
after,
|
||||
@@ -429,6 +434,7 @@ const runProcessScenario = async (
|
||||
);
|
||||
const frames: TerminalFrame[] = [];
|
||||
const samples: ProcessSample[] = [];
|
||||
const processEvents: ProcessLifecycleEvent[] = [];
|
||||
let runtime: StartedCaptureRuntime | undefined;
|
||||
const timers = new Set<NodeJS.Timeout>();
|
||||
let capture: ProcessCapture | undefined;
|
||||
@@ -446,6 +452,7 @@ const runProcessScenario = async (
|
||||
before,
|
||||
frames,
|
||||
samples,
|
||||
processEvents,
|
||||
interactions,
|
||||
timers,
|
||||
dispatchedEventIndexes,
|
||||
@@ -470,6 +477,7 @@ const runProcessScenario = async (
|
||||
before,
|
||||
frames,
|
||||
samples,
|
||||
processEvents,
|
||||
interactions,
|
||||
exit,
|
||||
initiallyTruncated: before.truncated,
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type {
|
||||
ProcessLifecycleEvent,
|
||||
ProcessSample,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
/** Mutable observation state owned by one bounded process sampler. */
|
||||
export interface ProcessLifecycleState {
|
||||
readonly previous: Map<number, ProcessSample>;
|
||||
readonly misses: Map<number, number>;
|
||||
}
|
||||
|
||||
/** Record spawn, reparent, and confirmed-exit transitions for one sample. */
|
||||
export const recordProcessLifecycle = (options: {
|
||||
readonly values: readonly ProcessSample[];
|
||||
readonly events: ProcessLifecycleEvent[];
|
||||
readonly state: ProcessLifecycleState;
|
||||
readonly limit: number;
|
||||
readonly elapsedMs: number;
|
||||
}): boolean => {
|
||||
const { values, events, state, limit, elapsedMs } = options;
|
||||
const current = new Set(values.map(({ pid }) => pid));
|
||||
let complete = true;
|
||||
for (const value of values) {
|
||||
const prior = state.previous.get(value.pid);
|
||||
if (prior === undefined)
|
||||
complete =
|
||||
appendEvent(events, limit, {
|
||||
at_ms: value.at_ms,
|
||||
type: "spawned",
|
||||
pid: value.pid,
|
||||
parent_pid: value.parent_pid,
|
||||
previous_parent_pid: null,
|
||||
signal: null,
|
||||
}) && complete;
|
||||
else if (prior.parent_pid !== value.parent_pid)
|
||||
complete =
|
||||
appendEvent(events, limit, {
|
||||
at_ms: value.at_ms,
|
||||
type: "reparented",
|
||||
pid: value.pid,
|
||||
parent_pid: value.parent_pid,
|
||||
previous_parent_pid: prior.parent_pid,
|
||||
signal: null,
|
||||
}) && complete;
|
||||
state.previous.set(value.pid, value);
|
||||
state.misses.delete(value.pid);
|
||||
}
|
||||
for (const [pid, prior] of state.previous) {
|
||||
if (current.has(pid)) continue;
|
||||
const missed = (state.misses.get(pid) ?? 0) + 1;
|
||||
state.misses.set(pid, missed);
|
||||
if (missed < 2) continue;
|
||||
complete =
|
||||
appendEvent(events, limit, {
|
||||
at_ms: elapsedMs,
|
||||
type: "exited",
|
||||
pid,
|
||||
parent_pid: null,
|
||||
previous_parent_pid: prior.parent_pid,
|
||||
signal: null,
|
||||
}) && complete;
|
||||
state.previous.delete(pid);
|
||||
state.misses.delete(pid);
|
||||
}
|
||||
return complete;
|
||||
};
|
||||
|
||||
const appendEvent = (
|
||||
events: ProcessLifecycleEvent[],
|
||||
limit: number,
|
||||
event: Omit<ProcessLifecycleEvent, "sequence">,
|
||||
): boolean => {
|
||||
if (events.length >= limit) return false;
|
||||
events.push({ ...event, sequence: events.length });
|
||||
return true;
|
||||
};
|
||||
@@ -1,9 +1,23 @@
|
||||
import type {
|
||||
ProcessCapture,
|
||||
ProcessLifecycleEvent,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
const localProcessIdentifiers = (
|
||||
identifiers: readonly number[],
|
||||
): ReadonlyMap<number, number> => {
|
||||
const mapping = new Map<number, number>();
|
||||
for (const identifier of identifiers)
|
||||
if (identifier > 0 && !mapping.has(identifier))
|
||||
mapping.set(identifier, mapping.size + 1);
|
||||
return mapping;
|
||||
};
|
||||
|
||||
const bucketProcessTime = (atMs: number, bucketMs: number): number =>
|
||||
Math.floor(atMs / bucketMs) * bucketMs;
|
||||
|
||||
/** Normalize and redact one terminal/protocol payload under scenario rules. */
|
||||
export const normalizeProcessText = (
|
||||
value: string,
|
||||
@@ -53,10 +67,7 @@ export const normalizeProcessSamples = (
|
||||
sample.session_id ?? 0,
|
||||
]),
|
||||
];
|
||||
const mapping = new Map<number, number>();
|
||||
for (const identifier of identifiers)
|
||||
if (identifier > 0 && !mapping.has(identifier))
|
||||
mapping.set(identifier, mapping.size + 1);
|
||||
const mapping = localProcessIdentifiers(identifiers);
|
||||
const normalizeCommand = (command: string): string => {
|
||||
const normalized = normalizeProcessText(
|
||||
command,
|
||||
@@ -69,9 +80,10 @@ export const normalizeProcessSamples = (
|
||||
: normalized;
|
||||
};
|
||||
return samples.map((sample) => ({
|
||||
at_ms:
|
||||
Math.floor(sample.at_ms / scenario.normalization.time_bucket_ms) *
|
||||
at_ms: bucketProcessTime(
|
||||
sample.at_ms,
|
||||
scenario.normalization.time_bucket_ms,
|
||||
),
|
||||
pid: mapping.get(sample.pid) ?? 1,
|
||||
parent_pid: mapping.get(sample.parent_pid) ?? 0,
|
||||
process_group_id:
|
||||
@@ -84,6 +96,40 @@ export const normalizeProcessSamples = (
|
||||
}));
|
||||
};
|
||||
|
||||
/** Normalize lifecycle coordinates with stable capture-local PID identities. */
|
||||
export const normalizeProcessEvents = (
|
||||
events: readonly ProcessLifecycleEvent[],
|
||||
samples: readonly ProcessSample[],
|
||||
scenario: ProcessScenario,
|
||||
rootPid: number,
|
||||
): readonly ProcessLifecycleEvent[] => {
|
||||
const identifiers = [
|
||||
rootPid,
|
||||
...samples.flatMap(({ pid, parent_pid }) => [pid, parent_pid]),
|
||||
...events.flatMap(({ pid, parent_pid, previous_parent_pid }) => [
|
||||
pid,
|
||||
parent_pid ?? 0,
|
||||
previous_parent_pid ?? 0,
|
||||
]),
|
||||
];
|
||||
const mapping = localProcessIdentifiers(identifiers);
|
||||
return events.map((event, sequence) => ({
|
||||
...event,
|
||||
sequence,
|
||||
at_ms: bucketProcessTime(
|
||||
event.at_ms,
|
||||
scenario.normalization.time_bucket_ms,
|
||||
),
|
||||
pid: mapping.get(event.pid) ?? 1,
|
||||
parent_pid:
|
||||
event.parent_pid === null ? null : (mapping.get(event.parent_pid) ?? 0),
|
||||
previous_parent_pid:
|
||||
event.previous_parent_pid === null
|
||||
? null
|
||||
: (mapping.get(event.previous_parent_pid) ?? 0),
|
||||
}));
|
||||
};
|
||||
|
||||
const normalizePidTokens = (
|
||||
value: string,
|
||||
identifiers: readonly number[],
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
processCaptureCancelled,
|
||||
type ProcessCaptureError,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
import type {
|
||||
ProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
import { compareProcessCaptures } from "../domain/processComparison.js";
|
||||
import {
|
||||
analyzeProcessRepeatability,
|
||||
bindProcessScenario,
|
||||
type ProcessPairedExperiment,
|
||||
} from "../domain/processPairedExperiment.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
export interface ProcessCapturePort {
|
||||
capture(
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<ProcessCapture, ProcessCaptureError>>;
|
||||
}
|
||||
|
||||
export interface PairedProcessExperimentResult {
|
||||
readonly authority_runs: readonly ProcessCapture[];
|
||||
readonly candidate_runs: readonly ProcessCapture[];
|
||||
readonly authority_repeatability: ReturnType<
|
||||
typeof analyzeProcessRepeatability
|
||||
>;
|
||||
readonly candidate_repeatability: ReturnType<
|
||||
typeof analyzeProcessRepeatability
|
||||
>;
|
||||
readonly cross_side: ReturnType<typeof compareProcessCaptures> | null;
|
||||
readonly cross_side_blocked_reason: string | null;
|
||||
}
|
||||
|
||||
const productionCapturePort: ProcessCapturePort = {
|
||||
capture: captureProcessScenario,
|
||||
};
|
||||
|
||||
const captureRepeats = async (
|
||||
scenario: ProcessScenario,
|
||||
repeatCount: number,
|
||||
policy: ProcessExecutionPolicy,
|
||||
port: ProcessCapturePort,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<readonly ProcessCapture[], ProcessCaptureError>> => {
|
||||
const captures: ProcessCapture[] = [];
|
||||
for (let index = 0; index < repeatCount; index += 1) {
|
||||
if (signal?.aborted === true) return err(processCaptureCancelled());
|
||||
const capture = await port.capture(scenario, policy, signal);
|
||||
if (!capture.ok) return err(capture.error);
|
||||
captures.push(capture.value);
|
||||
}
|
||||
return ok(captures);
|
||||
};
|
||||
|
||||
/** Execute repeatability-first authority/candidate captures under one contract. */
|
||||
export const runPairedProcessExperiment = async (
|
||||
experiment: ProcessPairedExperiment,
|
||||
policy: ProcessExecutionPolicy,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly capturePort?: ProcessCapturePort;
|
||||
readonly now?: () => number;
|
||||
} = {},
|
||||
): Promise<Result<PairedProcessExperimentResult, ProcessCaptureError>> => {
|
||||
const port = options.capturePort ?? productionCapturePort;
|
||||
const authorityScenario = bindProcessScenario(
|
||||
experiment.shared_scenario,
|
||||
experiment.authority,
|
||||
);
|
||||
const candidateScenario = bindProcessScenario(
|
||||
experiment.shared_scenario,
|
||||
experiment.candidate,
|
||||
);
|
||||
const authorityRuns = await captureRepeats(
|
||||
authorityScenario,
|
||||
experiment.repeat_count,
|
||||
policy,
|
||||
port,
|
||||
options.signal,
|
||||
);
|
||||
if (!authorityRuns.ok) return authorityRuns;
|
||||
const candidateRuns = await captureRepeats(
|
||||
candidateScenario,
|
||||
experiment.repeat_count,
|
||||
policy,
|
||||
port,
|
||||
options.signal,
|
||||
);
|
||||
if (!candidateRuns.ok) return candidateRuns;
|
||||
const authorityRepeatability = analyzeProcessRepeatability(
|
||||
authorityRuns.value,
|
||||
experiment.required_dimensions,
|
||||
);
|
||||
const candidateRepeatability = analyzeProcessRepeatability(
|
||||
candidateRuns.value,
|
||||
experiment.required_dimensions,
|
||||
);
|
||||
const stable = authorityRepeatability.stable && candidateRepeatability.stable;
|
||||
return ok({
|
||||
authority_runs: authorityRuns.value,
|
||||
candidate_runs: candidateRuns.value,
|
||||
authority_repeatability: authorityRepeatability,
|
||||
candidate_repeatability: candidateRepeatability,
|
||||
cross_side: stable
|
||||
? compareProcessCaptures(
|
||||
authorityRuns.value[0]!,
|
||||
candidateRuns.value[0]!,
|
||||
{
|
||||
maxCaptureAgeMs: experiment.freshness_policy.max_capture_age_ms,
|
||||
...(options.now === undefined ? {} : { now: options.now }),
|
||||
},
|
||||
)
|
||||
: null,
|
||||
cross_side_blocked_reason: stable
|
||||
? null
|
||||
: "Cross-side comparison is blocked because a required same-side dimension is unstable.",
|
||||
});
|
||||
};
|
||||
@@ -1,8 +1,12 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import type { ProcessSample } from "../domain/processCapture.js";
|
||||
import type {
|
||||
ProcessLifecycleEvent,
|
||||
ProcessSample,
|
||||
} from "../domain/processCapture.js";
|
||||
import { readProcessRunId } from "../process/ProcessOwnership.js";
|
||||
import { recordProcessLifecycle } from "./ProcessLifecycleTracking.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const PROC_READ_CONCURRENCY = 64;
|
||||
@@ -261,16 +265,17 @@ const sampleLinux = async (
|
||||
if (limit <= 0) return [];
|
||||
|
||||
const rootStat = await readProcessStat(rootPid, signal);
|
||||
if (rootStat === undefined) return [];
|
||||
const rootChildren = await readLinuxChildren(rootPid, signal);
|
||||
if (rootChildren === undefined) return samplePs(context);
|
||||
if (rootStat !== undefined && rootChildren === undefined)
|
||||
return samplePs(context);
|
||||
|
||||
const rows: ProcessRow[] = [];
|
||||
const visited = new Set<number>([rootPid]);
|
||||
let level: Array<{
|
||||
readonly pid: number;
|
||||
readonly expectedParent: number | undefined;
|
||||
}> = [{ pid: rootPid, expectedParent: undefined }];
|
||||
}> =
|
||||
rootStat === undefined ? [] : [{ pid: rootPid, expectedParent: undefined }];
|
||||
|
||||
while (level.length > 0 && rows.length < limit) {
|
||||
const batchSize = Math.min(level.length, PROC_READ_CONCURRENCY);
|
||||
@@ -302,6 +307,12 @@ const sampleLinux = async (
|
||||
level.push(...nextLevel);
|
||||
}
|
||||
|
||||
for (const pid of identities.keys()) {
|
||||
if (rows.length >= limit || visited.has(pid)) continue;
|
||||
const node = await inspectProcess(pid, undefined, signal, identities);
|
||||
if (node !== undefined) rows.push(node);
|
||||
}
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
@@ -452,10 +463,13 @@ export const startProcessSampler = (options: {
|
||||
readonly started: number;
|
||||
readonly limit: number;
|
||||
readonly samples: ProcessSample[];
|
||||
readonly events: ProcessLifecycleEvent[];
|
||||
}): (() => Promise<{ readonly partial: boolean }>) => {
|
||||
const { rootPid, runId, started, limit, samples } = options;
|
||||
const { rootPid, runId, started, limit, samples, events } = options;
|
||||
const identities = new Map<number, string>();
|
||||
const lastObservations = new Map<number, string>();
|
||||
const previous = new Map<number, ProcessSample>();
|
||||
const misses = new Map<number, number>();
|
||||
let pending: Promise<void> | undefined;
|
||||
let stopped = false;
|
||||
let abortCurrent: (() => void) | undefined;
|
||||
@@ -488,6 +502,16 @@ export const startProcessSampler = (options: {
|
||||
});
|
||||
})()
|
||||
.then((values) => {
|
||||
if (
|
||||
!recordProcessLifecycle({
|
||||
values,
|
||||
events,
|
||||
state: { previous, misses },
|
||||
limit,
|
||||
elapsedMs: Date.now() - started,
|
||||
})
|
||||
)
|
||||
partial = true;
|
||||
for (const value of values) {
|
||||
const observation = JSON.stringify({
|
||||
parent_pid: value.parent_pid,
|
||||
|
||||
@@ -55,4 +55,11 @@ export const writeReconstructionCoverageWorkspace = (
|
||||
{ readonly path: string; readonly bytes: number },
|
||||
InvestigationWorkspaceError
|
||||
>
|
||||
> => writeRevisionedWorkspace(workspace, path, expectedRevision, policy, codec);
|
||||
> =>
|
||||
writeRevisionedWorkspace({
|
||||
document: workspace,
|
||||
path,
|
||||
expectedRevision,
|
||||
policy,
|
||||
codec,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
identifyRuntimes,
|
||||
runtimeIdentificationInputSchema,
|
||||
} from "../domain/runtimeIdentification.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { RUNTIME_IDENTIFICATION_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { projectInventoryEvidence } from "./InventoryProjectionEvidence.js";
|
||||
|
||||
const OPERATION = "identify_runtime" as const;
|
||||
|
||||
/** Identify runtime families from authenticated artifact inventory Evidence. */
|
||||
export const identifyRuntimeEvidence = (
|
||||
rawInput: unknown,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
return projectInventoryEvidence({
|
||||
rawInput,
|
||||
schema: runtimeIdentificationInputSchema,
|
||||
project: identifyRuntimes,
|
||||
operation: OPERATION,
|
||||
predicateType: "rea.runtime-identification/v1",
|
||||
provider: RUNTIME_IDENTIFICATION_PROVIDER,
|
||||
subjectFormat: (first) => first.subject?.format ?? "unknown",
|
||||
protocolError: "Runtime identification produced an invalid result",
|
||||
});
|
||||
};
|
||||
@@ -564,24 +564,20 @@ export interface WindowsOwnedProcessInput
|
||||
readonly limits: WindowsOwnedProcessLimits;
|
||||
}
|
||||
|
||||
const parseAdmittedFileObservation = (
|
||||
const parseAdmittedObservation = <
|
||||
TObservation extends Omit<
|
||||
WindowsAdmittedPathObservation<"file" | "directory">,
|
||||
"stableIdentity"
|
||||
>,
|
||||
>(
|
||||
schema: z.ZodType<TObservation>,
|
||||
value: unknown,
|
||||
requestedPath: string,
|
||||
): Result<WindowsAdmittedFileObservation, WindowsNativeAuthorityError> => {
|
||||
const parsed = admittedFileObservationSchema.safeParse(value);
|
||||
if (!parsed.success || parsed.data.requestedPath !== requestedPath)
|
||||
return malformedAdmissionObservation();
|
||||
return ok({
|
||||
...parsed.data,
|
||||
stableIdentity: stablePathIdentity(parsed.data),
|
||||
});
|
||||
};
|
||||
|
||||
const parseAdmittedDirectoryObservation = (
|
||||
value: unknown,
|
||||
requestedPath: string,
|
||||
): Result<WindowsAdmittedDirectoryObservation, WindowsNativeAuthorityError> => {
|
||||
const parsed = admittedDirectoryObservationSchema.safeParse(value);
|
||||
): Result<
|
||||
TObservation & { readonly stableIdentity: string },
|
||||
WindowsNativeAuthorityError
|
||||
> => {
|
||||
const parsed = schema.safeParse(value);
|
||||
if (!parsed.success || parsed.data.requestedPath !== requestedPath)
|
||||
return malformedAdmissionObservation();
|
||||
return ok({
|
||||
@@ -683,6 +679,57 @@ const malformedAdmissionObservation = <T>(): Result<
|
||||
),
|
||||
);
|
||||
|
||||
const completePathAdmission = async <
|
||||
TObservation extends Omit<
|
||||
WindowsAdmittedPathObservation<"file" | "directory">,
|
||||
"stableIdentity"
|
||||
>,
|
||||
>(
|
||||
input: Readonly<{
|
||||
authority: WindowsNativeAuthority;
|
||||
admitted: Result<
|
||||
WindowsNativeAdmittedFile | WindowsNativeAdmittedDirectory,
|
||||
WindowsNativeAuthorityError
|
||||
>;
|
||||
schema: z.ZodType<TObservation>;
|
||||
requestedPath: string;
|
||||
}>,
|
||||
): Promise<
|
||||
Result<
|
||||
TObservation & {
|
||||
readonly stableIdentity: string;
|
||||
close(): Promise<Result<void, WindowsNativeAuthorityError>>;
|
||||
},
|
||||
WindowsNativeAuthorityError
|
||||
>
|
||||
> => {
|
||||
const admitted = input.admitted;
|
||||
if (!admitted.ok) return admitted;
|
||||
const observation = parseAdmittedObservation(
|
||||
input.schema,
|
||||
admitted.value.observation,
|
||||
input.requestedPath,
|
||||
);
|
||||
if (!observation.ok) {
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return observation;
|
||||
}
|
||||
const resource = createResource({
|
||||
authority: input.authority,
|
||||
operation: "admit_path",
|
||||
kind: observation.value.kind,
|
||||
observation: observation.value,
|
||||
backend: admitted.value.resource,
|
||||
});
|
||||
if (!resource.ok)
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return resource;
|
||||
};
|
||||
|
||||
/** Application-owned authority wrapper that scopes every native resource. */
|
||||
export class WindowsNativeAuthority {
|
||||
constructor(readonly backend: WindowsNativeAuthorityBackend) {}
|
||||
@@ -719,60 +766,24 @@ export class WindowsNativeAuthority {
|
||||
};
|
||||
|
||||
if (input.kind === "file") {
|
||||
const admitted = await this.backend.admitFile(
|
||||
admissionInput as WindowsPathAdmissionInput<"file">,
|
||||
);
|
||||
if (!admitted.ok) return admitted;
|
||||
const observation = parseAdmittedFileObservation(
|
||||
admitted.value.observation,
|
||||
admissionInput.path,
|
||||
);
|
||||
if (!observation.ok) {
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return observation;
|
||||
}
|
||||
const resource = createResource({
|
||||
return completePathAdmission({
|
||||
authority: this,
|
||||
operation: "admit_path",
|
||||
kind: "file",
|
||||
observation: observation.value,
|
||||
backend: admitted.value.resource,
|
||||
admitted: await this.backend.admitFile(
|
||||
admissionInput as WindowsPathAdmissionInput<"file">,
|
||||
),
|
||||
schema: admittedFileObservationSchema,
|
||||
requestedPath: admissionInput.path,
|
||||
});
|
||||
if (!resource.ok)
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return resource;
|
||||
}
|
||||
|
||||
const admitted = await this.backend.admitDirectory(
|
||||
admissionInput as WindowsPathAdmissionInput<"directory">,
|
||||
);
|
||||
if (!admitted.ok) return admitted;
|
||||
const observation = parseAdmittedDirectoryObservation(
|
||||
admitted.value.observation,
|
||||
admissionInput.path,
|
||||
);
|
||||
if (!observation.ok) {
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return observation;
|
||||
}
|
||||
const resource = createResource({
|
||||
return completePathAdmission({
|
||||
authority: this,
|
||||
operation: "admit_path",
|
||||
kind: "directory",
|
||||
observation: observation.value,
|
||||
backend: admitted.value.resource,
|
||||
admitted: await this.backend.admitDirectory(
|
||||
admissionInput as WindowsPathAdmissionInput<"directory">,
|
||||
),
|
||||
schema: admittedDirectoryObservationSchema,
|
||||
requestedPath: admissionInput.path,
|
||||
});
|
||||
if (!resource.ok)
|
||||
await poisonAliasedToken(admitted.value.resource, () =>
|
||||
admitted.value.resource.close(),
|
||||
);
|
||||
return resource;
|
||||
}
|
||||
|
||||
/** Create and verify a protected runtime root beneath owned authority. */
|
||||
@@ -907,19 +918,21 @@ export class WindowsNativeAuthority {
|
||||
}
|
||||
|
||||
const registerBackend = (
|
||||
authority: WindowsNativeAuthority,
|
||||
kind: ResourceKind,
|
||||
backend: WindowsNativeBackendResource,
|
||||
operation: WindowsNativeAuthorityOperation,
|
||||
closeBackend: ResourceState["closeBackend"],
|
||||
input: Readonly<{
|
||||
authority: WindowsNativeAuthority;
|
||||
kind: ResourceKind;
|
||||
backend: WindowsNativeBackendResource;
|
||||
operation: WindowsNativeAuthorityOperation;
|
||||
closeBackend: ResourceState["closeBackend"];
|
||||
}>,
|
||||
): Result<ResourceState, WindowsNativeAuthorityError> => {
|
||||
const existing = backendTokenStates.get(backend);
|
||||
const existing = backendTokenStates.get(input.backend);
|
||||
if (existing !== undefined) {
|
||||
return err(
|
||||
new WindowsNativeAuthorityError(
|
||||
operation,
|
||||
input.operation,
|
||||
"native_contract_mismatch",
|
||||
existing.kind === kind
|
||||
existing.kind === input.kind
|
||||
? "Windows native backend token is already registered"
|
||||
: "Windows native backend token is registered with a different kind",
|
||||
),
|
||||
@@ -927,14 +940,14 @@ const registerBackend = (
|
||||
}
|
||||
|
||||
const state: ResourceState = {
|
||||
owner: authority,
|
||||
backend,
|
||||
closeBackend,
|
||||
kind,
|
||||
owner: input.authority,
|
||||
backend: input.backend,
|
||||
closeBackend: input.closeBackend,
|
||||
kind: input.kind,
|
||||
status: "open",
|
||||
leaseCount: 0,
|
||||
};
|
||||
backendTokenStates.set(backend, state);
|
||||
backendTokenStates.set(input.backend, state);
|
||||
return ok(state);
|
||||
};
|
||||
|
||||
@@ -1173,13 +1186,13 @@ const createResource = <TObservation extends object>(
|
||||
},
|
||||
WindowsNativeAuthorityError
|
||||
> => {
|
||||
const stateResult = registerBackend(
|
||||
input.authority,
|
||||
input.kind,
|
||||
input.backend,
|
||||
input.operation,
|
||||
() => input.backend.close(),
|
||||
);
|
||||
const stateResult = registerBackend({
|
||||
authority: input.authority,
|
||||
kind: input.kind,
|
||||
backend: input.backend,
|
||||
operation: input.operation,
|
||||
closeBackend: () => input.backend.close(),
|
||||
});
|
||||
if (!stateResult.ok) return stateResult;
|
||||
const resource = {
|
||||
...input.observation,
|
||||
@@ -1213,16 +1226,16 @@ const createOwnedProcess = (
|
||||
...ownership.data,
|
||||
policySha256: jobOwnershipPolicySha256(ownership.data),
|
||||
};
|
||||
const stateResult = registerBackend(
|
||||
const stateResult = registerBackend({
|
||||
authority,
|
||||
"process",
|
||||
kind: "process",
|
||||
backend,
|
||||
"spawn_owned_process",
|
||||
() =>
|
||||
operation: "spawn_owned_process",
|
||||
closeBackend: () =>
|
||||
closeOwnedProcess(backend).then((result) =>
|
||||
result.ok ? ok(undefined) : result,
|
||||
),
|
||||
);
|
||||
});
|
||||
if (!stateResult.ok) return stateResult;
|
||||
const state = stateResult.value;
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ export class ArtifactProvider implements AnalysisProvider {
|
||||
timeoutMs: 120_000,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"DMG child inventory is macOS-only and requires per-call approval plus operator policy; PKG remains root-hash-only.",
|
||||
"DMG child inventory and extraction are macOS-only and require per-call approval plus operator policy; PKG remains root-hash-only.",
|
||||
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
|
||||
]),
|
||||
}),
|
||||
@@ -122,6 +122,10 @@ class ArtifactClient implements AnalysisClient {
|
||||
offset: parsed.offset,
|
||||
limit: parsed.limit,
|
||||
limits: limitsFrom(parsed),
|
||||
nativeMount: {
|
||||
nativeMountApproved: parsed.native_mount_approved === true,
|
||||
nativeMountEnabled: this.nativeMountEnabled,
|
||||
},
|
||||
},
|
||||
options?.signal,
|
||||
);
|
||||
|
||||
@@ -28,6 +28,7 @@ const attachOutputSchema = z.object({
|
||||
|
||||
/** Narrow host seam for tested, shell-free hdiutil lifecycle operations. */
|
||||
export interface NativeDmgHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
run(
|
||||
arguments_: readonly string[],
|
||||
signal?: AbortSignal,
|
||||
@@ -35,6 +36,7 @@ export interface NativeDmgHost {
|
||||
}
|
||||
|
||||
const systemHost: NativeDmgHost = {
|
||||
platform: process.platform,
|
||||
async run(arguments_, signal) {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
@@ -76,7 +78,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
signal?: AbortSignal,
|
||||
host: NativeDmgHost = systemHost,
|
||||
): Promise<NativeDmgArtifactReader> {
|
||||
if (process.platform !== "darwin")
|
||||
if (host.platform !== "darwin")
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Native DMG traversal is available only on macOS",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
@@ -30,11 +31,11 @@ export const openCdpTargetSession = async (
|
||||
);
|
||||
if (webSocket.scope === "page") return { connection, sessionId: undefined };
|
||||
try {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
const attached = await connection.send(
|
||||
"Target.attachToTarget",
|
||||
{ targetId: target.id, flatten: true },
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
return { connection, sessionId: attachedSessionId(attached, operation) };
|
||||
} catch (cause: unknown) {
|
||||
|
||||
+67
-19
@@ -9,6 +9,9 @@ import {
|
||||
} from "./application/DirectAnalysis.js";
|
||||
import { compareManagedMemberPaths } from "./application/ManagedMemberComparisonService.js";
|
||||
import { projectManagedApplicationGraphEvidence } from "./application/ManagedApplicationGraphService.js";
|
||||
import { projectAppleApplicationEvidence } from "./application/AppleApplicationService.js";
|
||||
import { projectAndroidApplicationEvidence } from "./application/AndroidApplicationService.js";
|
||||
import { identifyRuntimeEvidence } from "./application/RuntimeIdentificationService.js";
|
||||
import { verifyManagedNativeBoundariesEvidence } from "./application/ManagedNativeVerificationService.js";
|
||||
import { importManagedReconstructionEvidence } from "./application/ManagedReconstructionService.js";
|
||||
import { planManagedRuntimeCorrelationEvidence } from "./application/ManagedRuntimeCorrelationService.js";
|
||||
@@ -38,9 +41,10 @@ import { registerApplicationCommands } from "./cliApplicationCommands.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "./cliJsonInput.js";
|
||||
import {
|
||||
analysisProviderSelectorSchema,
|
||||
type AnalysisProviderSelector,
|
||||
} from "./contracts/providerSelection.js";
|
||||
directAnalysisOptions,
|
||||
providerSelectionOption,
|
||||
} from "./cliDirectAnalysisOptions.js";
|
||||
import { registerEnhancedAnalysisCommands } from "./cliEnhancedCommands.js";
|
||||
import { createSystemDoctorHost } from "./doctorRuntime.js";
|
||||
import {
|
||||
conciseSetupResult,
|
||||
@@ -86,6 +90,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
registerSearchCommand(cli, logger);
|
||||
registerXrefsCommand(cli, logger);
|
||||
registerTraceCommand(cli, logger);
|
||||
registerEnhancedAnalysisCommands(cli, logger);
|
||||
registerCapabilityCommands(cli, logger);
|
||||
registerNativeCommands(cli, logger);
|
||||
registerArtifactCommands(cli, logger);
|
||||
@@ -1183,6 +1188,65 @@ const registerManagedCommands = (
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.projectAppleApplicationGraph, {
|
||||
description:
|
||||
"Project authenticated IPA inventory Evidence into an Apple application graph",
|
||||
args: z.object({
|
||||
inputJson: z
|
||||
.string()
|
||||
.describe("Inline Apple application projection JSON or JSON file path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "project-apple-application-graph", async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.inputJson,
|
||||
"project-apple-application-graph",
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const result = projectAppleApplicationEvidence(input.value);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.projectAndroidApplicationGraph, {
|
||||
description:
|
||||
"Project authenticated APK inventory Evidence into an Android application graph",
|
||||
args: z.object({
|
||||
inputJson: z
|
||||
.string()
|
||||
.describe(
|
||||
"Inline Android application projection JSON or JSON file path",
|
||||
),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "project-android-application-graph", async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.inputJson,
|
||||
"project-android-application-graph",
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const result = projectAndroidApplicationEvidence(input.value);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.identifyRuntime, {
|
||||
description:
|
||||
"Identify runtime families from authenticated artifact inventory Evidence",
|
||||
args: z.object({
|
||||
inputJson: z
|
||||
.string()
|
||||
.describe("Inline runtime-identification JSON or JSON file path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "identify-runtime", async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.inputJson,
|
||||
"identify-runtime",
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const result = identifyRuntimeEvidence(input.value);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const registerNativeCommands = (
|
||||
@@ -1244,19 +1308,3 @@ const registerNativeCommands = (
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const providerSelectionOption = analysisProviderSelectorSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Bind deep analysis to a provider ID or use deterministic auto selection",
|
||||
);
|
||||
|
||||
const directAnalysisOptions = (
|
||||
logger: Logger,
|
||||
snapshotPath: string | undefined,
|
||||
providerId: AnalysisProviderSelector | undefined,
|
||||
) => ({
|
||||
logger,
|
||||
snapshotPath,
|
||||
...(providerId === undefined ? {} : { providerId }),
|
||||
});
|
||||
|
||||
@@ -9,6 +9,13 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
upgrade: "upgrade",
|
||||
xrefs: "xrefs",
|
||||
trace: "trace",
|
||||
swiftClasses: "swift-classes",
|
||||
objcClasses: "objc-classes",
|
||||
objcProtocols: "objc-protocols",
|
||||
batchDecompile: "batch-decompile",
|
||||
callGraph: "call-graph",
|
||||
analyzeSwiftTypes: "analyze-swift-types",
|
||||
xrefsToName: "xrefs-to-name",
|
||||
capabilities: "capabilities",
|
||||
providers: "providers",
|
||||
function: "function",
|
||||
@@ -24,6 +31,9 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
importManagedReconstruction: "import-managed-reconstruction",
|
||||
planManagedRuntimeCorrelation: "plan-managed-runtime-correlation",
|
||||
projectManagedApplicationGraph: "project-managed-application-graph",
|
||||
projectAppleApplicationGraph: "project-apple-application-graph",
|
||||
projectAndroidApplicationGraph: "project-android-application-graph",
|
||||
identifyRuntime: "identify-runtime",
|
||||
inspectMacho: "inspect-macho",
|
||||
inspectSignature: "inspect-signature",
|
||||
listArchitectures: "list-architectures",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { z } from "incur";
|
||||
|
||||
import type { Logger } from "./logger.js";
|
||||
import {
|
||||
analysisProviderSelectorSchema,
|
||||
type AnalysisProviderSelector,
|
||||
} from "./contracts/providerSelection.js";
|
||||
|
||||
/** Shared provider selector used by every one-shot deep-analysis command. */
|
||||
export const providerSelectionOption = analysisProviderSelectorSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Bind deep analysis to a provider ID or use deterministic auto selection",
|
||||
);
|
||||
|
||||
/** Project parsed CLI options into the direct-analysis application boundary. */
|
||||
export const directAnalysisOptions = (
|
||||
logger: Logger,
|
||||
snapshotPath: string | undefined,
|
||||
providerId: AnalysisProviderSelector | undefined,
|
||||
): {
|
||||
readonly logger: Logger;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly providerId?: z.output<typeof analysisProviderSelectorSchema>;
|
||||
} => ({
|
||||
logger,
|
||||
snapshotPath,
|
||||
...(providerId === undefined ? {} : { providerId }),
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import { runDirectAnalysis } from "./application/DirectAnalysis.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
providerSelectionOption,
|
||||
} from "./cliDirectAnalysisOptions.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const sharedOptions = z.object({
|
||||
snapshot: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
provider: providerSelectionOption,
|
||||
});
|
||||
|
||||
const registerEnhancedDiscoveryCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.swiftClasses, {
|
||||
description: "Discover bounded Swift classes from analyzed procedures",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
pattern: z.string().default("").describe("Optional literal class filter"),
|
||||
}),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.swiftClasses,
|
||||
path: args.path,
|
||||
operation: "swift_classes",
|
||||
parameters: {
|
||||
pattern: args.pattern,
|
||||
},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.objcClasses, {
|
||||
description: "Discover bounded Objective-C classes from analyzed names",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
pattern: z.string().default("").describe("Optional literal class filter"),
|
||||
}),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.objcClasses,
|
||||
path: args.path,
|
||||
operation: "get_objc_classes",
|
||||
parameters: {
|
||||
pattern: args.pattern,
|
||||
},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.objcProtocols, {
|
||||
description: "Discover bounded Objective-C and Swift protocols",
|
||||
args: z.object({ path: z.string().describe("App or program path") }),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.objcProtocols,
|
||||
path: args.path,
|
||||
operation: "get_objc_protocols",
|
||||
parameters: {},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.batchDecompile, {
|
||||
description: "Decompile up to twenty explicit procedures concurrently",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
addresses: z
|
||||
.array(z.string().describe("Procedure symbol or address"))
|
||||
.max(20)
|
||||
.describe("Procedures to decompile"),
|
||||
}),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.batchDecompile,
|
||||
path: args.path,
|
||||
operation: "batch_decompile",
|
||||
parameters: {
|
||||
addresses: [...args.addresses],
|
||||
},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const registerEnhancedRelationshipCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.callGraph, {
|
||||
description: "Traverse bounded caller or callee relationships",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
address: z.string().describe("Starting procedure symbol or address"),
|
||||
}),
|
||||
options: sharedOptions.extend({
|
||||
direction: z
|
||||
.enum(["forward", "backward"])
|
||||
.default("forward")
|
||||
.describe("Traverse callees forward or callers backward"),
|
||||
depth: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(5)
|
||||
.default(2)
|
||||
.describe("Maximum relationship depth"),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.callGraph,
|
||||
path: args.path,
|
||||
operation: "get_call_graph",
|
||||
parameters: {
|
||||
address: args.address,
|
||||
direction: options.direction,
|
||||
depth: options.depth,
|
||||
},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.analyzeSwiftTypes, {
|
||||
description: "Categorize bounded Swift type symbols",
|
||||
args: z.object({ path: z.string().describe("App or program path") }),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.analyzeSwiftTypes,
|
||||
path: args.path,
|
||||
operation: "analyze_swift_types",
|
||||
parameters: {},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.xrefsToName, {
|
||||
description: "Resolve an exact analyzed name to bounded references",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
name: z.string().describe("Exact analyzed name to resolve"),
|
||||
}),
|
||||
options: sharedOptions,
|
||||
run: ({ args, options }) =>
|
||||
runEnhanced({
|
||||
logger,
|
||||
command: CLI_COMMANDS.xrefsToName,
|
||||
path: args.path,
|
||||
operation: "find_xrefs_to_name",
|
||||
parameters: {
|
||||
name: args.name,
|
||||
},
|
||||
options,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Register one-shot CLI adapters for every enhanced workflow not otherwise exposed. */
|
||||
export const registerEnhancedAnalysisCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerEnhancedDiscoveryCommands(cli, logger);
|
||||
registerEnhancedRelationshipCommands(cli, logger);
|
||||
};
|
||||
|
||||
type SharedOptions = {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly provider?: z.output<typeof providerSelectionOption>;
|
||||
};
|
||||
|
||||
type EnhancedRun = {
|
||||
readonly logger: Logger;
|
||||
readonly command: string;
|
||||
readonly path: string;
|
||||
readonly operation:
|
||||
| "swift_classes"
|
||||
| "get_objc_classes"
|
||||
| "get_objc_protocols"
|
||||
| "batch_decompile"
|
||||
| "get_call_graph"
|
||||
| "analyze_swift_types"
|
||||
| "find_xrefs_to_name";
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly options: SharedOptions;
|
||||
};
|
||||
|
||||
const runEnhanced = ({
|
||||
logger,
|
||||
command,
|
||||
path,
|
||||
operation,
|
||||
parameters,
|
||||
options,
|
||||
}: EnhancedRun) =>
|
||||
logCliCommand(logger, command, () =>
|
||||
runDirectAnalysis(
|
||||
path,
|
||||
operation,
|
||||
parameters,
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
),
|
||||
);
|
||||
@@ -12,25 +12,15 @@ import {
|
||||
PermissionRequiredError,
|
||||
projectAnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import type { PermissionCapability } from "./domain/permissionPolicy.js";
|
||||
import {
|
||||
PERMISSION_CAPABILITIES,
|
||||
type PermissionCapability,
|
||||
} from "./domain/permissionPolicy.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
|
||||
const capabilitySchema = z.enum([
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"electron_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
]);
|
||||
/** CLI parser derived from the canonical permission-capability inventory. */
|
||||
export const policyCapabilitySchema = z.enum(PERMISSION_CAPABILITIES);
|
||||
|
||||
type PolicyRevocationApproval =
|
||||
| { readonly approved: true }
|
||||
@@ -155,7 +145,7 @@ export const registerPolicyCommands = (
|
||||
? { error: "Grant was not found", grant_id: args.value }
|
||||
: { error: revoked.error.message };
|
||||
}
|
||||
const capability = capabilitySchema.safeParse(args.value);
|
||||
const capability = policyCapabilitySchema.safeParse(args.value);
|
||||
if (!capability.success)
|
||||
return {
|
||||
error: "A registered capability is required for policy explain",
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface AppConfig {
|
||||
readonly ghidraInstallDir: string | undefined;
|
||||
readonly ghidraJavaHome: string | undefined;
|
||||
readonly ilspyCmdPath: string | undefined;
|
||||
readonly jadxCmdPath: string | undefined;
|
||||
readonly hopperLauncherPath: string;
|
||||
readonly hopperTargetPath: string | undefined;
|
||||
readonly hopperTargetKind: "executable" | "database";
|
||||
@@ -90,6 +91,11 @@ const environmentSchema = z
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_ILSPY_CMD_PATH must be absolute")
|
||||
.optional(),
|
||||
REA_JADX_CMD_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_JADX_CMD_PATH must be absolute")
|
||||
.optional(),
|
||||
HOPPER_LAUNCHER_PATH: z.string().min(1).optional(),
|
||||
HOPPER_TARGET_PATH: z.string().min(1).optional(),
|
||||
HOPPER_TARGET_KIND: z
|
||||
@@ -491,6 +497,7 @@ export const parseConfig = (
|
||||
ghidraInstallDir: parsedEnvironment.data.GHIDRA_INSTALL_DIR,
|
||||
ghidraJavaHome: parsedEnvironment.data.JAVA_HOME,
|
||||
ilspyCmdPath: parsedEnvironment.data.REA_ILSPY_CMD_PATH,
|
||||
jadxCmdPath: parsedEnvironment.data.REA_JADX_CMD_PATH,
|
||||
hopperLauncherPath:
|
||||
parsedEnvironment.data.HOPPER_LAUNCHER_PATH ??
|
||||
defaultHopperLauncherPath(),
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { androidApplicationOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
|
||||
/** Session references for one bounded Android application projection. */
|
||||
export const androidApplicationReferenceInputSchema = z.strictObject({
|
||||
inventory_evidence_ids: z
|
||||
.array(z.string().regex(/^ev_[a-f0-9]{64}$/u))
|
||||
.min(1)
|
||||
.max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_components: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_components: 1_000 }),
|
||||
});
|
||||
|
||||
const outputSchema =
|
||||
androidApplicationOutputSchemas.project_android_application_graph;
|
||||
if (outputSchema === undefined)
|
||||
throw new Error("Missing Android application graph output schema");
|
||||
|
||||
/** Provider-neutral Android application workflow contract. */
|
||||
export const ANDROID_APPLICATION_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "project_android_application_graph",
|
||||
...toolContractMetadata("project_android_application_graph"),
|
||||
description:
|
||||
"Project authenticated, bounded APK inventory Evidence into deterministic Android components, runtime-family observations, and explicit managed-to-native bridge hypotheses. Reports exact artifact paths and hashes without executing code or decoding Android binary formats.",
|
||||
kind: "application",
|
||||
inputSchema: androidApplicationReferenceInputSchema,
|
||||
outputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Project an APK inventory into Android application components",
|
||||
input: {
|
||||
inventory_evidence_ids: [`ev_${"1".repeat(64)}`],
|
||||
limits: { max_components: 1_000 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { appleApplicationOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
|
||||
/** Session references for one bounded Apple application projection. */
|
||||
export const appleApplicationReferenceInputSchema = z.strictObject({
|
||||
inventory_evidence_ids: z
|
||||
.array(z.string().regex(/^ev_[a-f0-9]{64}$/u))
|
||||
.min(1)
|
||||
.max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_components: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_components: 1_000 }),
|
||||
});
|
||||
|
||||
const outputSchema =
|
||||
appleApplicationOutputSchemas.project_apple_application_graph;
|
||||
if (outputSchema === undefined)
|
||||
throw new Error("Missing Apple application graph output schema");
|
||||
|
||||
/** Provider-neutral Apple application workflow contract. */
|
||||
export const APPLE_APPLICATION_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "project_apple_application_graph",
|
||||
...toolContractMetadata("project_apple_application_graph"),
|
||||
description:
|
||||
"Project authenticated, bounded IPA inventory Evidence into deterministic Apple application components, runtime-family observations, and explicit cross-language bridge hypotheses. Reports exact artifact paths and hashes without executing code or parsing provisioning-profile signing material.",
|
||||
kind: "application",
|
||||
inputSchema: appleApplicationReferenceInputSchema,
|
||||
outputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Project an IPA inventory into Apple application components",
|
||||
input: {
|
||||
inventory_evidence_ids: [`ev_${"1".repeat(64)}`],
|
||||
limits: { max_components: 1_000 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -58,6 +58,7 @@ export const artifactInventoryInputSchema = z
|
||||
/** Exact caller boundary for approved artifact extraction. */
|
||||
export const artifactExtractionInputSchema = z.object({
|
||||
approved: z.literal(true),
|
||||
native_mount_approved: z.boolean().default(false),
|
||||
output_root: z.string().min(1).max(4_096),
|
||||
occurrence_ids: z
|
||||
.array(z.string().regex(/^occ_[a-f0-9]{64}$/u))
|
||||
@@ -73,6 +74,7 @@ const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
|
||||
inventory_artifact: {},
|
||||
extract_artifact: {
|
||||
approved: true,
|
||||
native_mount_approved: false,
|
||||
output_root: "/tmp/rea-extracted",
|
||||
occurrence_ids: [`occ_${"0".repeat(64)}`],
|
||||
},
|
||||
@@ -111,7 +113,7 @@ export const ARTIFACT_TOOL_CONTRACTS = [
|
||||
),
|
||||
artifact(
|
||||
"extract_artifact",
|
||||
"Extract selected graph artifacts beneath an explicit output root. Requires approval, rejects traversal and symlink escapes, never overwrites, enforces bomb limits, and verifies cleanup.",
|
||||
"Extract selected graph artifacts beneath an explicit output root. Requires extraction approval; DMG inputs additionally require per-call native-mount approval and operator enablement. Rejects traversal and symlink escapes, never overwrites, enforces bomb limits, and verifies cleanup.",
|
||||
artifactExtractionInputSchema,
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -44,7 +44,7 @@ export const FUNCTION_COMPARISON_EVIDENCE = createEvidence(
|
||||
const PROCESS_PROVIDER = {
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
version: "4",
|
||||
} as const;
|
||||
const capture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const captureEvidence = (scenario: string) =>
|
||||
@@ -68,7 +68,7 @@ export const PROCESS_COMPARISON_EVIDENCE = createEvidence(
|
||||
undefined,
|
||||
PROCESS_PROVIDER,
|
||||
{
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
predicateType: "rea.process-comparison/v4",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: PROCESS_CAPTURE_REFERENCE.evidence_id,
|
||||
|
||||
@@ -18,7 +18,7 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "1.1.0",
|
||||
provider_version: "3",
|
||||
provider_version: "4",
|
||||
platform: "fixture",
|
||||
architecture: "fixture",
|
||||
pty_backend: "node-pty",
|
||||
@@ -46,6 +46,7 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
process_events: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { runtimeIdentificationOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
|
||||
/** Session Evidence references accepted by runtime identification. */
|
||||
export const runtimeIdentificationReferenceInputSchema = z.strictObject({
|
||||
inventory_evidence_ids: z
|
||||
.array(z.string().regex(/^ev_[a-f0-9]{64}$/u))
|
||||
.min(1)
|
||||
.max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_observations: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_observations: 1_000 }),
|
||||
});
|
||||
|
||||
const outputSchema = runtimeIdentificationOutputSchemas.identify_runtime;
|
||||
if (outputSchema === undefined)
|
||||
throw new Error("Missing runtime-identification output schema");
|
||||
|
||||
/** Provider-neutral runtime-identification tool contract. */
|
||||
export const RUNTIME_IDENTIFICATION_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "identify_runtime",
|
||||
...toolContractMetadata("identify_runtime"),
|
||||
description:
|
||||
"Identify runtime families from authenticated artifact inventory Evidence and report whether semantic tooling is available, missing, or requires provider selection. This classifies exact formats and paths without executing or decoding target bytecode.",
|
||||
inputSchema: runtimeIdentificationReferenceInputSchema,
|
||||
outputSchema,
|
||||
kind: "application",
|
||||
examples: [
|
||||
{
|
||||
title: "Identify runtimes in an artifact inventory",
|
||||
input: {
|
||||
inventory_evidence_ids: [`ev_${"1".repeat(64)}`],
|
||||
limits: { max_observations: 1_000 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -25,6 +25,9 @@ import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { APPLE_APPLICATION_TOOL_CONTRACTS } from "./appleApplicationToolContracts.js";
|
||||
import { ANDROID_APPLICATION_TOOL_CONTRACTS } from "./androidApplicationToolContracts.js";
|
||||
import { RUNTIME_IDENTIFICATION_TOOL_CONTRACTS } from "./runtimeIdentificationToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
@@ -514,6 +517,9 @@ export const TOOL_CONTRACTS = [
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
...APPLE_APPLICATION_TOOL_CONTRACTS,
|
||||
...ANDROID_APPLICATION_TOOL_CONTRACTS,
|
||||
...RUNTIME_IDENTIFICATION_TOOL_CONTRACTS,
|
||||
...BROWSER_TOOL_CONTRACTS,
|
||||
...ELECTRON_TOOL_CONTRACTS,
|
||||
...APPLICATION_TOOL_CONTRACTS,
|
||||
|
||||
@@ -102,6 +102,9 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
import_managed_reconstruction: sessionEvidence,
|
||||
plan_managed_runtime_correlation: sessionEvidence,
|
||||
project_managed_application_graph: sessionEvidence,
|
||||
project_apple_application_graph: sessionEvidence,
|
||||
project_android_application_graph: sessionEvidence,
|
||||
identify_runtime: sessionEvidence,
|
||||
list_browser_targets: browserEvidence,
|
||||
inspect_web_page: browserEvidence,
|
||||
analyze_web_bundle: browserEvidence,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { runtimeIdentificationResultSchema } from "../domain/runtimeIdentification.js";
|
||||
import {
|
||||
processCaptureComparisonSchema,
|
||||
processCaptureSchema,
|
||||
@@ -28,6 +29,8 @@ import {
|
||||
managedMemberInspectionSchema,
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
} from "../domain/managedArtifact.js";
|
||||
import { appleApplicationProjectionResultSchema } from "../domain/appleApplication.js";
|
||||
import { androidApplicationProjectionResultSchema } from "../domain/androidApplication.js";
|
||||
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
|
||||
import { managedNativeVerificationResultSchema } from "../domain/managedNativeVerification.js";
|
||||
import { managedReconstructionImportResultSchema } from "../domain/managedReconstruction.js";
|
||||
@@ -582,6 +585,31 @@ export const managedWorkflowOutputSchemas: Readonly<
|
||||
),
|
||||
};
|
||||
|
||||
/** Exact Evidence v2 schema for Apple application workflows. */
|
||||
export const appleApplicationOutputSchemas: Readonly<
|
||||
Record<string, z.ZodObject>
|
||||
> = {
|
||||
project_apple_application_graph: resultOf(
|
||||
appleApplicationProjectionResultSchema,
|
||||
),
|
||||
};
|
||||
|
||||
/** Exact Evidence v2 schema for Android application workflows. */
|
||||
export const androidApplicationOutputSchemas: Readonly<
|
||||
Record<string, z.ZodObject>
|
||||
> = {
|
||||
project_android_application_graph: resultOf(
|
||||
androidApplicationProjectionResultSchema,
|
||||
),
|
||||
};
|
||||
|
||||
/** Exact Evidence v2 schema for provider-neutral runtime identification. */
|
||||
export const runtimeIdentificationOutputSchemas: Readonly<
|
||||
Record<string, z.ZodObject>
|
||||
> = {
|
||||
identify_runtime: resultOf(runtimeIdentificationResultSchema),
|
||||
};
|
||||
|
||||
/** Exact structured-content schemas for target lifecycle operations. */
|
||||
export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
open_binary: lifecycleResultOf(
|
||||
|
||||
@@ -57,6 +57,11 @@ const subjectSchema = z.object({
|
||||
"mach-o-universal",
|
||||
"javascript-bundle",
|
||||
"entitlements",
|
||||
"dex",
|
||||
"jvm-class",
|
||||
"webassembly",
|
||||
"android-manifest",
|
||||
"android-resources",
|
||||
]),
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const pathSchema = z.string().min(1).max(4_096);
|
||||
const componentSchema = z.strictObject({
|
||||
path: pathSchema,
|
||||
artifact_id: z.string().regex(/^art_[a-f0-9]{64}$/u),
|
||||
sha256: digestSchema,
|
||||
format: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
/** Authenticated APK inventory pages projected as one Android application. */
|
||||
export const androidApplicationProjectionInputSchema = z.strictObject({
|
||||
inventory_evidence: z.array(evidenceSchema).min(1).max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_components: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_components: 1_000 }),
|
||||
});
|
||||
|
||||
/** Deterministic, execution-free Android application inventory projection. */
|
||||
export const androidApplicationProjectionResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
projection_id: z.string().regex(/^adp_[a-f0-9]{64}$/u),
|
||||
root_sha256: digestSchema,
|
||||
root_format: z.literal("apk"),
|
||||
source_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
components: z.strictObject({
|
||||
manifests: z.array(componentSchema),
|
||||
resources: z.array(componentSchema),
|
||||
dex: z.array(componentSchema),
|
||||
jvm_classes: z.array(componentSchema),
|
||||
native_libraries: z.array(componentSchema),
|
||||
javascript: z.array(componentSchema),
|
||||
signing: z.array(componentSchema),
|
||||
}),
|
||||
runtime_families: z.array(
|
||||
z.enum([
|
||||
"dalvik-art",
|
||||
"java-kotlin",
|
||||
"native",
|
||||
"javascript",
|
||||
"react-native",
|
||||
"flutter",
|
||||
"unity",
|
||||
]),
|
||||
),
|
||||
bridge_candidates: z.array(
|
||||
z.strictObject({
|
||||
managed_path: pathSchema,
|
||||
native_path: pathSchema,
|
||||
basis: z.enum([
|
||||
"managed-and-native-content",
|
||||
"jni-library-convention",
|
||||
"react-native-convention",
|
||||
"flutter-convention",
|
||||
"unity-convention",
|
||||
]),
|
||||
}),
|
||||
),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inventory", "partial", "truncated"]),
|
||||
inventory_complete: z.boolean(),
|
||||
omitted_components: z.number().int().min(0),
|
||||
omitted_bridge_candidates: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1).max(4_096)).max(100),
|
||||
});
|
||||
|
||||
export type AndroidApplicationProjectionInput = z.infer<
|
||||
typeof androidApplicationProjectionInputSchema
|
||||
>;
|
||||
export type AndroidApplicationProjectionResult = z.infer<
|
||||
typeof androidApplicationProjectionResultSchema
|
||||
>;
|
||||
type Component = z.infer<typeof componentSchema>;
|
||||
|
||||
/** Project exact APK paths and hashes without decoding or executing target code. */
|
||||
export const projectAndroidApplication = (
|
||||
input: AndroidApplicationProjectionInput,
|
||||
): AndroidApplicationProjectionResult => {
|
||||
const parsed = androidApplicationProjectionInputSchema.parse(input);
|
||||
const { evidence, inventory } = parseArtifactInventoryEvidence(
|
||||
parsed.inventory_evidence,
|
||||
);
|
||||
if (inventory.manifest.root_format !== "apk")
|
||||
throw new TypeError("Android application projection requires APK Evidence");
|
||||
const nodes = new Map(
|
||||
inventory.nodes.map((node) => [node.artifact_id, node]),
|
||||
);
|
||||
const all = inventory.occurrences
|
||||
.filter(
|
||||
(occurrence) =>
|
||||
occurrence.artifact_id !== null && occurrence.logical_path !== ".",
|
||||
)
|
||||
.map((occurrence) => {
|
||||
const node = nodes.get(occurrence.artifact_id ?? "");
|
||||
if (node === undefined)
|
||||
throw new TypeError(
|
||||
"Android application occurrence has no artifact node",
|
||||
);
|
||||
return {
|
||||
path: occurrence.logical_path,
|
||||
artifact_id: node.artifact_id,
|
||||
sha256: node.sha256,
|
||||
format: node.format,
|
||||
} satisfies Component;
|
||||
});
|
||||
const classified = classify(all);
|
||||
const components = retain(classified, parsed.limits.max_components);
|
||||
const omittedComponents = count(classified) - count(components);
|
||||
const bridgeProjection = bridgeCandidates(
|
||||
[...components.dex, ...components.jvm_classes],
|
||||
components.native_libraries,
|
||||
parsed.limits.max_components,
|
||||
);
|
||||
const limitations = [
|
||||
...(!inventory.complete
|
||||
? ["Source inventory pages are incomplete; absence is unknown."]
|
||||
: []),
|
||||
...(omittedComponents > 0
|
||||
? [
|
||||
`${String(omittedComponents)} component observations were omitted by the projection limit.`,
|
||||
]
|
||||
: []),
|
||||
...(bridgeProjection.omitted > 0
|
||||
? [
|
||||
`${String(bridgeProjection.omitted)} bridge hypotheses were omitted by the projection limit.`,
|
||||
]
|
||||
: []),
|
||||
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
|
||||
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
|
||||
];
|
||||
const withoutId = {
|
||||
schema_version: 1 as const,
|
||||
root_sha256: inventory.manifest.root_sha256,
|
||||
root_format: "apk" as const,
|
||||
source_evidence_ids: evidence
|
||||
.map(({ evidence_id: id }) => id)
|
||||
.sort(compare),
|
||||
components,
|
||||
runtime_families: runtimeFamilies(all),
|
||||
bridge_candidates: bridgeProjection.candidates,
|
||||
coverage: {
|
||||
status:
|
||||
omittedComponents > 0 || bridgeProjection.omitted > 0
|
||||
? ("truncated" as const)
|
||||
: inventory.complete
|
||||
? ("complete-within-inventory" as const)
|
||||
: ("partial" as const),
|
||||
inventory_complete: inventory.complete,
|
||||
omitted_components: omittedComponents,
|
||||
omitted_bridge_candidates: bridgeProjection.omitted,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
return androidApplicationProjectionResultSchema.parse({
|
||||
...withoutId,
|
||||
projection_id: `adp_${digest(withoutId)}`,
|
||||
});
|
||||
};
|
||||
|
||||
const classify = (all: readonly Component[]) => ({
|
||||
manifests: all.filter(
|
||||
({ path, format }) =>
|
||||
format === "android-manifest" ||
|
||||
/(?:^|\/)AndroidManifest\.xml$/u.test(path),
|
||||
),
|
||||
resources: all.filter(
|
||||
({ path, format }) =>
|
||||
format === "android-resources" || /(?:^|\/)resources\.arsc$/u.test(path),
|
||||
),
|
||||
dex: all.filter(({ format }) => format === "dex"),
|
||||
jvm_classes: all.filter(({ format }) => format === "jvm-class"),
|
||||
native_libraries: all.filter(
|
||||
({ path, format }) =>
|
||||
format === "elf" || /(?:^|\/)lib\/[^/]+\/[^/]+\.so$/iu.test(path),
|
||||
),
|
||||
javascript: all.filter(({ format }) => format === "javascript-bundle"),
|
||||
signing: all.filter(({ path }) =>
|
||||
/^META-INF\/[^/]+\.(?:MF|RSA|DSA|EC|SF)$/iu.test(path),
|
||||
),
|
||||
});
|
||||
|
||||
const retain = <Groups extends Record<string, readonly Component[]>>(
|
||||
groups: Groups,
|
||||
maximum: number,
|
||||
): { [Key in keyof Groups]: Component[] } => {
|
||||
let remaining = maximum;
|
||||
return Object.fromEntries(
|
||||
Object.entries(groups).map(([key, values]) => {
|
||||
const selected = [...values]
|
||||
.sort((left, right) => compare(left.path, right.path))
|
||||
.slice(0, remaining);
|
||||
remaining -= selected.length;
|
||||
return [key, selected];
|
||||
}),
|
||||
) as { [Key in keyof Groups]: Component[] };
|
||||
};
|
||||
|
||||
const count = (groups: Record<string, readonly Component[]>): number =>
|
||||
Object.values(groups).reduce((total, values) => total + values.length, 0);
|
||||
|
||||
const runtimeFamilies = (all: readonly Component[]) => {
|
||||
const paths = all.map(({ path }) => path.toLowerCase());
|
||||
const families = new Set<
|
||||
AndroidApplicationProjectionResult["runtime_families"][number]
|
||||
>();
|
||||
if (all.some(({ format }) => format === "dex")) families.add("dalvik-art");
|
||||
if (all.some(({ format }) => format === "jvm-class"))
|
||||
families.add("java-kotlin");
|
||||
if (all.some(({ format }) => format === "elf")) families.add("native");
|
||||
if (all.some(({ format }) => format === "javascript-bundle"))
|
||||
families.add("javascript");
|
||||
if (
|
||||
paths.some(
|
||||
(path) => path.includes("reactnative") || path.includes("hermes"),
|
||||
)
|
||||
)
|
||||
families.add("react-native");
|
||||
if (paths.some((path) => path.includes("libflutter.so")))
|
||||
families.add("flutter");
|
||||
if (paths.some((path) => path.includes("libunity.so"))) families.add("unity");
|
||||
return [...families].sort(compare);
|
||||
};
|
||||
|
||||
const bridgeCandidates = (
|
||||
managed: readonly Component[],
|
||||
native: readonly Component[],
|
||||
maximum: number,
|
||||
) => {
|
||||
const candidates = managed.flatMap((source) =>
|
||||
native.map((target) => ({
|
||||
managed_path: source.path,
|
||||
native_path: target.path,
|
||||
basis: bridgeBasis(target.path),
|
||||
})),
|
||||
);
|
||||
return {
|
||||
candidates: candidates.slice(0, maximum),
|
||||
omitted: Math.max(0, candidates.length - maximum),
|
||||
};
|
||||
};
|
||||
|
||||
const bridgeBasis = (
|
||||
path: string,
|
||||
): AndroidApplicationProjectionResult["bridge_candidates"][number]["basis"] => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.includes("react") || lower.includes("hermes"))
|
||||
return "react-native-convention";
|
||||
if (lower.includes("flutter")) return "flutter-convention";
|
||||
if (lower.includes("unity")) return "unity-convention";
|
||||
if (/lib\/[^/]+\/lib[^/]+\.so$/u.test(lower)) return "jni-library-convention";
|
||||
return "managed-and-native-content";
|
||||
};
|
||||
|
||||
const compare = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Android application projection is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,315 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const boundedPathSchema = z.string().min(1).max(4_096);
|
||||
|
||||
const componentSchema = z.strictObject({
|
||||
path: boundedPathSchema,
|
||||
artifact_id: z.string().regex(/^art_[a-f0-9]{64}$/u),
|
||||
sha256: digestSchema,
|
||||
format: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
/** Authenticated artifact inventory pages projected as one Apple application. */
|
||||
export const appleApplicationProjectionInputSchema = z.strictObject({
|
||||
inventory_evidence: z.array(evidenceSchema).min(1).max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_components: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_components: 1_000 }),
|
||||
});
|
||||
|
||||
/** Deterministic, execution-free Apple application inventory projection. */
|
||||
export const appleApplicationProjectionResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
projection_id: z.string().regex(/^aap_[a-f0-9]{64}$/u),
|
||||
root_sha256: digestSchema,
|
||||
root_format: z.literal("ipa"),
|
||||
source_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
application_roots: z.array(boundedPathSchema),
|
||||
components: z.strictObject({
|
||||
bundle_metadata: z.array(componentSchema),
|
||||
executables: z.array(componentSchema),
|
||||
frameworks: z.array(componentSchema),
|
||||
native_libraries: z.array(componentSchema),
|
||||
javascript: z.array(componentSchema),
|
||||
signing: z.array(componentSchema),
|
||||
}),
|
||||
runtime_families: z.array(
|
||||
z.enum([
|
||||
"native",
|
||||
"swift-objective-c",
|
||||
"javascript",
|
||||
"react-native",
|
||||
"flutter",
|
||||
"unity",
|
||||
]),
|
||||
),
|
||||
bridge_candidates: z.array(
|
||||
z.strictObject({
|
||||
source_path: boundedPathSchema,
|
||||
native_path: boundedPathSchema,
|
||||
basis: z.enum([
|
||||
"javascript-and-native-content",
|
||||
"react-native-convention",
|
||||
"flutter-convention",
|
||||
"unity-convention",
|
||||
]),
|
||||
}),
|
||||
),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inventory", "partial", "truncated"]),
|
||||
inventory_complete: z.boolean(),
|
||||
omitted_components: z.number().int().min(0),
|
||||
omitted_bridge_candidates: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1).max(4_096)).max(100),
|
||||
});
|
||||
|
||||
export type AppleApplicationProjectionInput = z.infer<
|
||||
typeof appleApplicationProjectionInputSchema
|
||||
>;
|
||||
export type AppleApplicationProjectionResult = z.infer<
|
||||
typeof appleApplicationProjectionResultSchema
|
||||
>;
|
||||
|
||||
type Component = z.infer<typeof componentSchema>;
|
||||
|
||||
/** Project exact IPA paths and hashes without parsing or executing target code. */
|
||||
export const projectAppleApplication = (
|
||||
input: AppleApplicationProjectionInput,
|
||||
): AppleApplicationProjectionResult => {
|
||||
const parsed = appleApplicationProjectionInputSchema.parse(input);
|
||||
const { evidence, inventory } = parseArtifactInventoryEvidence(
|
||||
parsed.inventory_evidence,
|
||||
);
|
||||
if (inventory.manifest.root_format !== "ipa")
|
||||
throw new TypeError("Apple application projection requires IPA Evidence");
|
||||
const nodes = new Map(
|
||||
inventory.nodes.map((node) => [node.artifact_id, node]),
|
||||
);
|
||||
const all = inventory.occurrences
|
||||
.filter(
|
||||
(occurrence) =>
|
||||
occurrence.artifact_id !== null && occurrence.logical_path !== ".",
|
||||
)
|
||||
.map((occurrence) => {
|
||||
const node = nodes.get(occurrence.artifact_id ?? "");
|
||||
if (node === undefined)
|
||||
throw new TypeError(
|
||||
"Apple application occurrence has no artifact node",
|
||||
);
|
||||
return {
|
||||
path: occurrence.logical_path,
|
||||
artifact_id: node.artifact_id,
|
||||
sha256: node.sha256,
|
||||
format: node.format,
|
||||
} satisfies Component;
|
||||
});
|
||||
const roots = inventory.occurrences
|
||||
.filter(
|
||||
({ logical_path: path, entry_kind: kind }) =>
|
||||
kind === "directory" && /^Payload\/[^/]+\.app$/u.test(path),
|
||||
)
|
||||
.map(({ logical_path: path }) => path)
|
||||
.sort(compare);
|
||||
const classified = classifyComponents(all, roots);
|
||||
const retained = retainComponents(classified, parsed.limits.max_components);
|
||||
const omitted = componentCount(classified) - componentCount(retained);
|
||||
const runtimeFamilies = identifyRuntimeFamilies(all);
|
||||
const bridgeProjection = identifyBridgeCandidates(
|
||||
retained.javascript,
|
||||
[...retained.frameworks, ...retained.native_libraries],
|
||||
parsed.limits.max_components,
|
||||
);
|
||||
const limitations = projectionLimitations(
|
||||
inventory.complete,
|
||||
omitted,
|
||||
bridgeProjection.omitted,
|
||||
roots,
|
||||
);
|
||||
const withoutId = {
|
||||
schema_version: 1 as const,
|
||||
root_sha256: inventory.manifest.root_sha256,
|
||||
root_format: "ipa" as const,
|
||||
source_evidence_ids: evidence
|
||||
.map(({ evidence_id: id }) => id)
|
||||
.sort(compare),
|
||||
application_roots: roots,
|
||||
components: retained,
|
||||
runtime_families: runtimeFamilies,
|
||||
bridge_candidates: bridgeProjection.candidates,
|
||||
coverage: {
|
||||
status:
|
||||
omitted > 0 || bridgeProjection.omitted > 0
|
||||
? ("truncated" as const)
|
||||
: inventory.complete
|
||||
? ("complete-within-inventory" as const)
|
||||
: ("partial" as const),
|
||||
inventory_complete: inventory.complete,
|
||||
omitted_components: omitted,
|
||||
omitted_bridge_candidates: bridgeProjection.omitted,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
return appleApplicationProjectionResultSchema.parse({
|
||||
...withoutId,
|
||||
projection_id: `aap_${digest(withoutId)}`,
|
||||
});
|
||||
};
|
||||
|
||||
const classifyComponents = (
|
||||
all: readonly Component[],
|
||||
roots: readonly string[],
|
||||
) => {
|
||||
const withinApp = (path: string): boolean =>
|
||||
roots.some((root) => path.startsWith(`${root}/`));
|
||||
return {
|
||||
bundle_metadata: all.filter(({ path }) =>
|
||||
/(?:^|\/)Info\.plist$/u.test(path),
|
||||
),
|
||||
executables: all.filter(
|
||||
({ path, format }) =>
|
||||
withinApp(path) && ["mach-o", "mach-o-universal"].includes(format),
|
||||
),
|
||||
frameworks: all.filter(({ path }) => /\.framework\//u.test(path)),
|
||||
native_libraries: all.filter(({ path }) => /\.(?:dylib|so)$/iu.test(path)),
|
||||
javascript: all.filter(({ format }) => format === "javascript-bundle"),
|
||||
signing: all.filter(({ path }) =>
|
||||
/(?:^|\/)(?:embedded\.mobileprovision|_CodeSignature\/CodeResources)$/u.test(
|
||||
path,
|
||||
),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const retainComponents = <Groups extends Record<string, readonly Component[]>>(
|
||||
groups: Groups,
|
||||
maximum: number,
|
||||
): { [Key in keyof Groups]: Component[] } => {
|
||||
let remaining = maximum;
|
||||
return Object.fromEntries(
|
||||
Object.entries(groups).map(([key, values]) => {
|
||||
const retained = [...values]
|
||||
.sort((left, right) => compare(left.path, right.path))
|
||||
.slice(0, remaining);
|
||||
remaining -= retained.length;
|
||||
return [key, retained];
|
||||
}),
|
||||
) as { [Key in keyof Groups]: Component[] };
|
||||
};
|
||||
|
||||
const componentCount = (groups: Record<string, readonly Component[]>): number =>
|
||||
Object.values(groups).reduce((total, values) => total + values.length, 0);
|
||||
|
||||
const identifyRuntimeFamilies = (all: readonly Component[]) => {
|
||||
const paths = all.map(({ path }) => path.toLowerCase());
|
||||
const families = new Set<
|
||||
z.infer<
|
||||
typeof appleApplicationProjectionResultSchema
|
||||
>["runtime_families"][number]
|
||||
>();
|
||||
if (all.some(({ format }) => ["mach-o", "mach-o-universal"].includes(format)))
|
||||
families.add("native");
|
||||
if (paths.some((path) => /\.(?:dylib|framework\/[^/]+)$/u.test(path)))
|
||||
families.add("swift-objective-c");
|
||||
if (all.some(({ format }) => format === "javascript-bundle"))
|
||||
families.add("javascript");
|
||||
if (
|
||||
paths.some(
|
||||
(path) =>
|
||||
path.includes("reactnative") ||
|
||||
path.includes("react.framework") ||
|
||||
path.includes("hermes"),
|
||||
)
|
||||
)
|
||||
families.add("react-native");
|
||||
if (
|
||||
paths.some(
|
||||
(path) =>
|
||||
path.includes("flutter.framework") || path.includes("app.framework"),
|
||||
)
|
||||
)
|
||||
families.add("flutter");
|
||||
if (paths.some((path) => path.includes("unityframework.framework")))
|
||||
families.add("unity");
|
||||
return [...families].sort(compare);
|
||||
};
|
||||
|
||||
const identifyBridgeCandidates = (
|
||||
scripts: readonly Component[],
|
||||
native: readonly Component[],
|
||||
maximum: number,
|
||||
) => {
|
||||
const candidates = scripts.flatMap((script) =>
|
||||
native.map((item) => ({
|
||||
source_path: script.path,
|
||||
native_path: item.path,
|
||||
basis: bridgeBasis(item.path),
|
||||
})),
|
||||
);
|
||||
return {
|
||||
candidates: candidates.slice(0, maximum),
|
||||
omitted: Math.max(0, candidates.length - maximum),
|
||||
};
|
||||
};
|
||||
|
||||
const bridgeBasis = (
|
||||
path: string,
|
||||
):
|
||||
| "javascript-and-native-content"
|
||||
| "react-native-convention"
|
||||
| "flutter-convention"
|
||||
| "unity-convention" => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.includes("react")) return "react-native-convention";
|
||||
if (lower.includes("flutter") || lower.includes("app.framework"))
|
||||
return "flutter-convention";
|
||||
if (lower.includes("unity")) return "unity-convention";
|
||||
return "javascript-and-native-content";
|
||||
};
|
||||
|
||||
const projectionLimitations = (
|
||||
complete: boolean,
|
||||
omitted: number,
|
||||
omittedBridges: number,
|
||||
roots: readonly string[],
|
||||
): string[] => [
|
||||
...(!complete
|
||||
? ["Source inventory pages are incomplete; absence is unknown."]
|
||||
: []),
|
||||
...(omitted > 0
|
||||
? [
|
||||
`${String(omitted)} component observations were omitted by the projection limit.`,
|
||||
]
|
||||
: []),
|
||||
...(omittedBridges > 0
|
||||
? [
|
||||
`${String(omittedBridges)} bridge hypotheses were omitted by the projection limit.`,
|
||||
]
|
||||
: []),
|
||||
...(roots.length === 0
|
||||
? [
|
||||
"No Payload/*.app directory was present in the supplied inventory pages.",
|
||||
]
|
||||
: []),
|
||||
"Bundle identifiers and signing claims require dedicated plist and CMS parsing; this projection reports only exact paths and hashes.",
|
||||
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
|
||||
];
|
||||
|
||||
const compare = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Apple application projection is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -223,40 +223,26 @@ const classifyPath = (input: {
|
||||
readonly complete: boolean;
|
||||
readonly evidenceLinks: readonly string[];
|
||||
}): ArtifactChange | null => {
|
||||
const base = {
|
||||
logical_path: input.path,
|
||||
left_occurrence_id: input.leftOccurrence?.occurrence_id ?? null,
|
||||
right_occurrence_id: input.rightOccurrence?.occurrence_id ?? null,
|
||||
left_artifact_id: input.leftOccurrence?.artifact_id ?? null,
|
||||
right_artifact_id: input.rightOccurrence?.artifact_id ?? null,
|
||||
evidence_links: [...input.evidenceLinks],
|
||||
};
|
||||
if (input.leftOccurrence === undefined)
|
||||
return {
|
||||
...base,
|
||||
classification: input.complete ? "added" : "unknown",
|
||||
dimensions: [input.complete ? "content" : "availability"],
|
||||
};
|
||||
if (input.rightOccurrence === undefined)
|
||||
return {
|
||||
...base,
|
||||
classification: input.complete ? "removed" : "unknown",
|
||||
dimensions: [input.complete ? "content" : "availability"],
|
||||
};
|
||||
if (
|
||||
input.leftOccurrence.hash_status === "mismatched" ||
|
||||
input.rightOccurrence.hash_status === "mismatched"
|
||||
)
|
||||
const base = artifactChangeBase(input);
|
||||
const leftOccurrence = input.leftOccurrence;
|
||||
const rightOccurrence = input.rightOccurrence;
|
||||
if (leftOccurrence === undefined)
|
||||
return missingOccurrenceChange(base, "added", input.complete);
|
||||
if (rightOccurrence === undefined)
|
||||
return missingOccurrenceChange(base, "removed", input.complete);
|
||||
if (hasIntegrityContradiction(leftOccurrence, rightOccurrence))
|
||||
return {
|
||||
...base,
|
||||
classification: "contradiction",
|
||||
dimensions: ["integrity"],
|
||||
};
|
||||
if (
|
||||
input.leftOccurrence.hash_status !== "verified" ||
|
||||
input.rightOccurrence.hash_status !== "verified" ||
|
||||
input.leftNode === undefined ||
|
||||
input.rightNode === undefined
|
||||
hasUnavailableComparisonInput({
|
||||
leftOccurrence,
|
||||
rightOccurrence,
|
||||
leftNode: input.leftNode,
|
||||
rightNode: input.rightNode,
|
||||
})
|
||||
)
|
||||
return { ...base, classification: "unknown", dimensions: ["availability"] };
|
||||
const dimensions = changedDimensions(input);
|
||||
@@ -265,6 +251,49 @@ const classifyPath = (input: {
|
||||
: { ...base, classification: "changed", dimensions };
|
||||
};
|
||||
|
||||
type ArtifactChangeBase = Omit<ArtifactChange, "classification" | "dimensions">;
|
||||
|
||||
const artifactChangeBase = (input: {
|
||||
readonly path: string;
|
||||
readonly leftOccurrence: ArtifactOccurrence | undefined;
|
||||
readonly rightOccurrence: ArtifactOccurrence | undefined;
|
||||
readonly evidenceLinks: readonly string[];
|
||||
}): ArtifactChangeBase => ({
|
||||
logical_path: input.path,
|
||||
left_occurrence_id: input.leftOccurrence?.occurrence_id ?? null,
|
||||
right_occurrence_id: input.rightOccurrence?.occurrence_id ?? null,
|
||||
left_artifact_id: input.leftOccurrence?.artifact_id ?? null,
|
||||
right_artifact_id: input.rightOccurrence?.artifact_id ?? null,
|
||||
evidence_links: [...input.evidenceLinks],
|
||||
});
|
||||
|
||||
const missingOccurrenceChange = (
|
||||
base: ArtifactChangeBase,
|
||||
completeClassification: "added" | "removed",
|
||||
complete: boolean,
|
||||
): ArtifactChange => ({
|
||||
...base,
|
||||
classification: complete ? completeClassification : "unknown",
|
||||
dimensions: [complete ? "content" : "availability"],
|
||||
});
|
||||
|
||||
const hasIntegrityContradiction = (
|
||||
left: ArtifactOccurrence,
|
||||
right: ArtifactOccurrence,
|
||||
): boolean =>
|
||||
left.hash_status === "mismatched" || right.hash_status === "mismatched";
|
||||
|
||||
const hasUnavailableComparisonInput = (input: {
|
||||
readonly leftOccurrence: ArtifactOccurrence;
|
||||
readonly rightOccurrence: ArtifactOccurrence;
|
||||
readonly leftNode: ArtifactNode | undefined;
|
||||
readonly rightNode: ArtifactNode | undefined;
|
||||
}): boolean =>
|
||||
input.leftOccurrence.hash_status !== "verified" ||
|
||||
input.rightOccurrence.hash_status !== "verified" ||
|
||||
input.leftNode === undefined ||
|
||||
input.rightNode === undefined;
|
||||
|
||||
const changedDimensions = (input: {
|
||||
readonly leftNode: ArtifactNode | undefined;
|
||||
readonly rightNode: ArtifactNode | undefined;
|
||||
|
||||
@@ -33,6 +33,7 @@ const artifactKindSchema = z.enum([
|
||||
"resource",
|
||||
"universal-slice",
|
||||
"package-metadata",
|
||||
"bytecode",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
@@ -52,6 +53,11 @@ const artifactFormatSchema = z.enum([
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
"apk",
|
||||
"dex",
|
||||
"jvm-class",
|
||||
"webassembly",
|
||||
"android-manifest",
|
||||
"android-resources",
|
||||
"plist",
|
||||
"entitlements",
|
||||
"directory",
|
||||
|
||||
@@ -84,10 +84,10 @@ type RuntimeStatus = z.infer<typeof processCaptureComparisonSchema>["status"];
|
||||
|
||||
const EXPECTED_PROVIDERS = {
|
||||
compare_process_captures: {
|
||||
predicate: "rea.process-comparison/v3",
|
||||
predicate: "rea.process-comparison/v4",
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
version: "4",
|
||||
},
|
||||
compare_artifacts: {
|
||||
predicate: "rea.artifact-comparison/v1",
|
||||
|
||||
+28
-7
@@ -433,6 +433,7 @@ export class HopperProtocolError extends HopperError {
|
||||
|
||||
export type HopperDiagnosticType =
|
||||
| "remote"
|
||||
| "analysis_in_progress"
|
||||
| "authorization"
|
||||
| "invalid_request"
|
||||
| "bridge_exception";
|
||||
@@ -542,19 +543,39 @@ export interface AnalysisErrorProjection
|
||||
readonly details?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Exact denied authority used by both CLI and MCP remediation. */
|
||||
export interface PermissionRequiredErrorInput {
|
||||
readonly requested: PermissionRequest;
|
||||
readonly missing: MissingPermissionScope;
|
||||
readonly ceiling: PermissionScope | null;
|
||||
readonly elicitationSupported: boolean;
|
||||
readonly restartRequired: boolean;
|
||||
}
|
||||
|
||||
/** Exact denied authority used by both CLI and MCP remediation. */
|
||||
export class PermissionRequiredError extends AnalysisError {
|
||||
readonly _tag = "PermissionRequiredError" as const;
|
||||
|
||||
constructor(
|
||||
readonly requested: PermissionRequest,
|
||||
readonly missing: MissingPermissionScope,
|
||||
readonly ceiling: PermissionScope | null,
|
||||
readonly elicitationSupported: boolean,
|
||||
readonly restartRequired: boolean,
|
||||
) {
|
||||
constructor({
|
||||
requested,
|
||||
missing,
|
||||
ceiling,
|
||||
elicitationSupported,
|
||||
restartRequired,
|
||||
}: PermissionRequiredErrorInput) {
|
||||
super(`Permission required for ${requested.capability}`);
|
||||
this.requested = requested;
|
||||
this.missing = missing;
|
||||
this.ceiling = ceiling;
|
||||
this.elicitationSupported = elicitationSupported;
|
||||
this.restartRequired = restartRequired;
|
||||
}
|
||||
|
||||
readonly requested: PermissionRequest;
|
||||
readonly missing: MissingPermissionScope;
|
||||
readonly ceiling: PermissionScope | null;
|
||||
readonly elicitationSupported: boolean;
|
||||
readonly restartRequired: boolean;
|
||||
}
|
||||
|
||||
/** Approved replay commitment no longer matches the immediately rebuilt plan. */
|
||||
|
||||
@@ -41,6 +41,11 @@ const subjectSchema = z.object({
|
||||
"mach-o-universal",
|
||||
"javascript-bundle",
|
||||
"entitlements",
|
||||
"dex",
|
||||
"jvm-class",
|
||||
"webassembly",
|
||||
"android-manifest",
|
||||
"android-resources",
|
||||
]),
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
|
||||
local_path: z.string(),
|
||||
|
||||
@@ -250,36 +250,44 @@ const relationshipSignature = (
|
||||
const signatures = graph.edges.flatMap((edge) => {
|
||||
if (edge.source_node_id === node.node_id)
|
||||
return [
|
||||
edgeSignature(
|
||||
"out",
|
||||
edge.relation,
|
||||
edge.target_node_id,
|
||||
edgeSignature({
|
||||
direction: "out",
|
||||
relation: edge.relation,
|
||||
neighborId: edge.target_node_id,
|
||||
paired,
|
||||
nodeById,
|
||||
),
|
||||
}),
|
||||
];
|
||||
if (edge.target_node_id === node.node_id)
|
||||
return [
|
||||
edgeSignature(
|
||||
"in",
|
||||
edge.relation,
|
||||
edge.source_node_id,
|
||||
edgeSignature({
|
||||
direction: "in",
|
||||
relation: edge.relation,
|
||||
neighborId: edge.source_node_id,
|
||||
paired,
|
||||
nodeById,
|
||||
),
|
||||
}),
|
||||
];
|
||||
return [];
|
||||
});
|
||||
return canonical(signatures.sort(compareCodePoints));
|
||||
};
|
||||
|
||||
const edgeSignature = (
|
||||
direction: "in" | "out",
|
||||
relation: ApplicationEdge["relation"],
|
||||
neighborId: string,
|
||||
paired: ReadonlyMap<string, string>,
|
||||
nodeById: ReadonlyMap<string, ApplicationNode>,
|
||||
): string => {
|
||||
interface EdgeSignatureInput {
|
||||
readonly direction: "in" | "out";
|
||||
readonly relation: ApplicationEdge["relation"];
|
||||
readonly neighborId: string;
|
||||
readonly paired: ReadonlyMap<string, string>;
|
||||
readonly nodeById: ReadonlyMap<string, ApplicationNode>;
|
||||
}
|
||||
|
||||
const edgeSignature = ({
|
||||
direction,
|
||||
relation,
|
||||
neighborId,
|
||||
paired,
|
||||
nodeById,
|
||||
}: EdgeSignatureInput): string => {
|
||||
const mapped = paired.get(neighborId);
|
||||
const neighbor = nodeById.get(neighborId);
|
||||
return `${direction}\0${relation}\0${mapped ?? `unmatched:${neighbor?.kind ?? "unknown"}`}`;
|
||||
|
||||
@@ -54,7 +54,14 @@ export const matchJavaScriptApplicationVersions = (
|
||||
const rightCandidates = new Map<string, Set<string>>();
|
||||
const pairs: ApplicationVersionNodePair[] = [];
|
||||
for (const tier of matchTiers())
|
||||
applyTier(left, right, pairs, leftCandidates, rightCandidates, tier);
|
||||
applyTier({
|
||||
left,
|
||||
right,
|
||||
pairs,
|
||||
leftCandidates,
|
||||
rightCandidates,
|
||||
tier,
|
||||
});
|
||||
const remainingLeft = sortedNodes(left.values());
|
||||
const remainingRight = sortedNodes(right.values());
|
||||
const leftIds = new Set(remainingLeft.map(({ node_id: id }) => id));
|
||||
@@ -73,14 +80,23 @@ export const matchJavaScriptApplicationVersions = (
|
||||
};
|
||||
};
|
||||
|
||||
const applyTier = (
|
||||
left: Map<string, ApplicationNode>,
|
||||
right: Map<string, ApplicationNode>,
|
||||
pairs: ApplicationVersionNodePair[],
|
||||
leftCandidates: Map<string, Set<string>>,
|
||||
rightCandidates: Map<string, Set<string>>,
|
||||
tier: MatchTier,
|
||||
): void => {
|
||||
interface MatchTierContext {
|
||||
readonly left: Map<string, ApplicationNode>;
|
||||
readonly right: Map<string, ApplicationNode>;
|
||||
readonly pairs: ApplicationVersionNodePair[];
|
||||
readonly leftCandidates: Map<string, Set<string>>;
|
||||
readonly rightCandidates: Map<string, Set<string>>;
|
||||
readonly tier: MatchTier;
|
||||
}
|
||||
|
||||
const applyTier = ({
|
||||
left,
|
||||
right,
|
||||
pairs,
|
||||
leftCandidates,
|
||||
rightCandidates,
|
||||
tier,
|
||||
}: MatchTierContext): void => {
|
||||
const leftByKey = nodesByKey(left.values(), tier.key);
|
||||
const rightByKey = nodesByKey(right.values(), tier.key);
|
||||
for (const key of [...leftByKey.keys()].sort(compareCodePoints)) {
|
||||
|
||||
@@ -41,6 +41,12 @@ export const traverseApplicationFeature = (
|
||||
const omittedNodes = new Set<string>();
|
||||
const omittedEdges = new Set<string>();
|
||||
const frontier = new Set<string>();
|
||||
const recordOmission = (entry: AdjacencyEntry, current: string): void => {
|
||||
omittedNodes.add(entry.nextNodeId);
|
||||
omittedEdges.add(entry.edge.edge_id);
|
||||
frontier.add(current);
|
||||
frontier.add(entry.nextNodeId);
|
||||
};
|
||||
const depths = new Map(seedNodeIds.map((nodeId) => [nodeId, 0]));
|
||||
const predecessors = new Map<string, Predecessor>();
|
||||
const queue = [...seedNodeIds];
|
||||
@@ -50,11 +56,11 @@ export const traverseApplicationFeature = (
|
||||
const depth = depths.get(current) ?? 0;
|
||||
for (const entry of adjacency.get(current) ?? []) {
|
||||
if (depth >= limits.max_depth) {
|
||||
recordOmission(entry, current, omittedNodes, omittedEdges, frontier);
|
||||
recordOmission(entry, current);
|
||||
continue;
|
||||
}
|
||||
if (!visited.has(entry.nextNodeId) && visited.size >= limits.max_nodes) {
|
||||
recordOmission(entry, current, omittedNodes, omittedEdges, frontier);
|
||||
recordOmission(entry, current);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
@@ -128,16 +134,3 @@ const addAdjacency = (
|
||||
): void => {
|
||||
adjacency.set(nodeId, [...(adjacency.get(nodeId) ?? []), entry]);
|
||||
};
|
||||
|
||||
const recordOmission = (
|
||||
entry: AdjacencyEntry,
|
||||
current: string,
|
||||
omittedNodes: Set<string>,
|
||||
omittedEdges: Set<string>,
|
||||
frontier: Set<string>,
|
||||
): void => {
|
||||
omittedNodes.add(entry.nextNodeId);
|
||||
omittedEdges.add(entry.edge.edge_id);
|
||||
frontier.add(current);
|
||||
frontier.add(entry.nextNodeId);
|
||||
};
|
||||
|
||||
@@ -2,23 +2,27 @@ import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Local capabilities governed by the shared REA permission policy. */
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "browser_observe"
|
||||
| "electron_observe"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
| "investigation_workspace_read"
|
||||
| "investigation_workspace_write"
|
||||
| "snapshot_read"
|
||||
| "snapshot_write"
|
||||
| "artifact_extract"
|
||||
| "native_mount"
|
||||
| "reference_read"
|
||||
| "javascript_replay"
|
||||
| "managed_runtime";
|
||||
/** Canonical local capabilities governed by the shared REA permission policy. */
|
||||
export const PERMISSION_CAPABILITIES = [
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"electron_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
"javascript_replay",
|
||||
"managed_runtime",
|
||||
] as const;
|
||||
|
||||
/** Local capability governed by the shared REA permission policy. */
|
||||
export type PermissionCapability = (typeof PERMISSION_CAPABILITIES)[number];
|
||||
|
||||
/** Ordered network authority; each mode includes the modes before it. */
|
||||
type PermissionNetwork = "none" | "loopback" | "external";
|
||||
|
||||
@@ -65,6 +65,17 @@ export interface ProcessSample {
|
||||
readonly session_id: number | null;
|
||||
}
|
||||
|
||||
/** One bounded lifecycle transition for a proven owned process identity. */
|
||||
export interface ProcessLifecycleEvent {
|
||||
readonly sequence: number;
|
||||
readonly at_ms: number;
|
||||
readonly type: "spawned" | "reparented" | "exited" | "signal_dispatched";
|
||||
readonly pid: number;
|
||||
readonly parent_pid: number | null;
|
||||
readonly previous_parent_pid: number | null;
|
||||
readonly signal: "SIGINT" | "SIGTERM" | "SIGKILL" | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Named filesystem state whose effects are relative to the prior checkpoint.
|
||||
*/
|
||||
@@ -100,7 +111,27 @@ export interface ProtocolEvent {
|
||||
| "matched"
|
||||
| "unmatched"
|
||||
| "script_exhausted"
|
||||
| "disconnected";
|
||||
| "disconnected"
|
||||
| "invalid_state"
|
||||
| "guard_failed"
|
||||
| "transition_exhausted"
|
||||
| "invalid_capture"
|
||||
| "unexpected_reconnect"
|
||||
| "limit_exhausted";
|
||||
readonly transition_id?: string | null | undefined;
|
||||
readonly state_before?: string | null | undefined;
|
||||
readonly state_after?: string | null | undefined;
|
||||
}
|
||||
|
||||
/** Secret-safe state transition linked to its triggering protocol event. */
|
||||
export interface ReplayTransitionEvent {
|
||||
readonly sequence: number;
|
||||
readonly at_ms: number;
|
||||
readonly protocol_event_sequence: number;
|
||||
readonly transition_id: string;
|
||||
readonly state_before: string;
|
||||
readonly state_after: string;
|
||||
readonly sensitive_aliases: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,9 +176,11 @@ export interface ProcessCapture {
|
||||
readonly cleanup_outcome: "not_required" | "cleaned" | "failed";
|
||||
};
|
||||
readonly process_samples: readonly ProcessSample[];
|
||||
readonly process_events: readonly ProcessLifecycleEvent[];
|
||||
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
|
||||
readonly shim_events: readonly ShimEvent[];
|
||||
readonly protocol_events: readonly ProtocolEvent[];
|
||||
readonly replay_transitions?: readonly ReplayTransitionEvent[] | undefined;
|
||||
readonly files_before: readonly FileState[];
|
||||
readonly files_after: readonly FileState[];
|
||||
readonly filesystem_effects: readonly FileEffect[];
|
||||
@@ -161,6 +194,7 @@ export interface ProcessCapture {
|
||||
| "process"
|
||||
| "filesystem"
|
||||
| "protocol"
|
||||
| "replay_transition"
|
||||
| "shim"
|
||||
| "cleanup"
|
||||
| "network";
|
||||
@@ -265,6 +299,17 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
session_id: z.number().int().nonnegative().nullable(),
|
||||
}),
|
||||
),
|
||||
process_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
type: z.enum(["spawned", "reparented", "exited", "signal_dispatched"]),
|
||||
pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().nonnegative().nullable(),
|
||||
previous_parent_pid: z.number().int().nonnegative().nullable(),
|
||||
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]).nullable(),
|
||||
}),
|
||||
),
|
||||
filesystem_checkpoints: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
@@ -299,9 +344,32 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
"unmatched",
|
||||
"script_exhausted",
|
||||
"disconnected",
|
||||
"invalid_state",
|
||||
"guard_failed",
|
||||
"transition_exhausted",
|
||||
"invalid_capture",
|
||||
"unexpected_reconnect",
|
||||
"limit_exhausted",
|
||||
]),
|
||||
transition_id: z.string().nullable().optional(),
|
||||
state_before: z.string().nullable().optional(),
|
||||
state_after: z.string().nullable().optional(),
|
||||
}),
|
||||
),
|
||||
replay_transitions: z
|
||||
.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
protocol_event_sequence: z.number().int().nonnegative(),
|
||||
transition_id: z.string(),
|
||||
state_before: z.string(),
|
||||
state_after: z.string(),
|
||||
sensitive_aliases: z.array(z.string()),
|
||||
}),
|
||||
)
|
||||
.max(100_000)
|
||||
.optional(),
|
||||
files_before: z.array(fileStateSchema),
|
||||
files_after: z.array(fileStateSchema),
|
||||
filesystem_effects: z.array(fileEffectSchema),
|
||||
@@ -316,6 +384,7 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
"process",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"replay_transition",
|
||||
"shim",
|
||||
"cleanup",
|
||||
"network",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
|
||||
import { digestProcessCommitment } from "./processScenario.js";
|
||||
|
||||
/** One pure semantic validation failure in an otherwise shaped v4 capture. */
|
||||
@@ -52,8 +53,10 @@ const validateOrdering = (
|
||||
["frames", capture.frames],
|
||||
["rendered_frames", capture.rendered_frames],
|
||||
["interaction_events", capture.interaction_events],
|
||||
["process_events", capture.process_events],
|
||||
["shim_events", capture.shim_events],
|
||||
["protocol_events", capture.protocol_events],
|
||||
["replay_transitions", capture.replay_transitions ?? []],
|
||||
] as const)
|
||||
require(values.every(
|
||||
({ sequence }, index) => sequence === index,
|
||||
@@ -62,9 +65,11 @@ const validateOrdering = (
|
||||
["frames", capture.frames],
|
||||
["rendered_frames", capture.rendered_frames],
|
||||
["process_samples", capture.process_samples],
|
||||
["process_events", capture.process_events],
|
||||
["filesystem_checkpoints", capture.filesystem_checkpoints],
|
||||
["shim_events", capture.shim_events],
|
||||
["protocol_events", capture.protocol_events],
|
||||
["replay_transitions", capture.replay_transitions ?? []],
|
||||
] as const)
|
||||
require(orderedTimestamps(values), name, "timestamps must be ordered");
|
||||
};
|
||||
@@ -144,11 +149,77 @@ const validateShimEvents = (
|
||||
}
|
||||
};
|
||||
|
||||
const validateReplayEvents = (
|
||||
const machineTriggerMatches = (
|
||||
transition: ReplayMachine["transitions"][number],
|
||||
event: ProcessCapture["protocol_events"][number],
|
||||
): boolean =>
|
||||
transition.trigger.path === event.path &&
|
||||
(transition.trigger.protocol === "http"
|
||||
? event.protocol === "http" &&
|
||||
event.direction === "request" &&
|
||||
transition.trigger.method === event.method
|
||||
: event.protocol === "websocket" &&
|
||||
((transition.trigger.protocol === "websocket_connect" &&
|
||||
event.direction === "request") ||
|
||||
(transition.trigger.protocol === "websocket_message" &&
|
||||
event.direction === "received")));
|
||||
|
||||
const validateMachineTimeline = (
|
||||
machine: ReplayMachine,
|
||||
capture: ProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const { replay_plan: replayPlan } = capture.manifest;
|
||||
const timeline = capture.replay_transitions;
|
||||
require(timeline !==
|
||||
undefined, "replay_transitions", "machine replay capture has no transition timeline");
|
||||
if (timeline === undefined) return;
|
||||
let expectedState = machine.initial_state;
|
||||
for (const entry of timeline) {
|
||||
const event = capture.protocol_events[entry.protocol_event_sequence];
|
||||
const declared = machine.transitions.find(
|
||||
({ id }) => id === entry.transition_id,
|
||||
);
|
||||
require(event?.transition_id ===
|
||||
entry.transition_id, "replay_transitions", "transition does not link to its triggering protocol event");
|
||||
require(declared?.from === entry.state_before &&
|
||||
declared.to ===
|
||||
entry.state_after, "replay_transitions", "transition timeline entry is not declared by the replay machine");
|
||||
require(expectedState ===
|
||||
entry.state_before, "replay_transitions", "transition timeline state chain is discontinuous");
|
||||
require(event !== undefined &&
|
||||
declared !== undefined &&
|
||||
machineTriggerMatches(
|
||||
declared,
|
||||
event,
|
||||
), "replay_transitions", "transition trigger does not match its protocol event");
|
||||
const aliases =
|
||||
declared?.captures
|
||||
.filter(({ sensitive }) => sensitive)
|
||||
.map(({ variable }) => variable)
|
||||
.sort() ?? [];
|
||||
require(JSON.stringify(aliases) ===
|
||||
JSON.stringify(
|
||||
[...entry.sensitive_aliases].sort(),
|
||||
), "replay_transitions", "transition secret aliases disagree with declared captures");
|
||||
expectedState = entry.state_after;
|
||||
}
|
||||
for (const event of capture.protocol_events) {
|
||||
const triggeringDirection =
|
||||
event.direction === "request" || event.direction === "received";
|
||||
if (event.outcome !== "matched" || !triggeringDirection) continue;
|
||||
require(timeline.some(
|
||||
({ protocol_event_sequence, transition_id }) =>
|
||||
protocol_event_sequence === event.sequence &&
|
||||
transition_id === event.transition_id,
|
||||
), "protocol_events", "matched machine event has no transition timeline entry");
|
||||
}
|
||||
};
|
||||
|
||||
const validateQueueReplayEvents = (
|
||||
capture: ProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const replayPlan = capture.manifest.replay_plan;
|
||||
const routes =
|
||||
"http" in replayPlan && Array.isArray(replayPlan.http)
|
||||
? replayPlan.http
|
||||
@@ -160,7 +231,7 @@ const validateReplayEvents = (
|
||||
event.outcome !== "matched"
|
||||
)
|
||||
continue;
|
||||
const declared = routes.some(
|
||||
require(routes.some(
|
||||
(route) =>
|
||||
typeof route === "object" &&
|
||||
route !== null &&
|
||||
@@ -168,11 +239,25 @@ const validateReplayEvents = (
|
||||
route.method === event.method &&
|
||||
"path" in route &&
|
||||
route.path === event.path,
|
||||
);
|
||||
require(declared, "protocol_events", "matched HTTP event has no declared replay route");
|
||||
), "protocol_events", "matched HTTP event has no declared replay route");
|
||||
}
|
||||
};
|
||||
|
||||
const validateReplayEvents = (
|
||||
capture: ProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const replayPlan = capture.manifest.replay_plan;
|
||||
const hasMachine = "machine" in replayPlan && replayPlan.machine !== null;
|
||||
if (!hasMachine) {
|
||||
validateQueueReplayEvents(capture, require);
|
||||
return;
|
||||
}
|
||||
const parsed = replayMachineSchema.safeParse(replayPlan.machine);
|
||||
require(parsed.success, "manifest.replay_plan.machine", "replay machine commitment is not a valid machine contract");
|
||||
if (parsed.success) validateMachineTimeline(parsed.data, capture, require);
|
||||
};
|
||||
|
||||
/** Recompute v4 commitments and cross-field invariants without side effects. */
|
||||
export const validateProcessCapture = (
|
||||
capture: ProcessCapture,
|
||||
|
||||
@@ -23,6 +23,7 @@ export const PROCESS_COMPARISON_DIMENSIONS = [
|
||||
"exit",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"replay_transition",
|
||||
"process",
|
||||
"shim",
|
||||
] as const;
|
||||
@@ -50,6 +51,7 @@ export const processCaptureComparisonSchema = z
|
||||
exit: comparisonStatusSchema,
|
||||
filesystem: comparisonStatusSchema,
|
||||
protocol: comparisonStatusSchema,
|
||||
replay_transition: comparisonStatusSchema,
|
||||
process: comparisonStatusSchema,
|
||||
shim: comparisonStatusSchema,
|
||||
first_divergence: z.discriminatedUnion("status", [
|
||||
@@ -63,6 +65,7 @@ export const processCaptureComparisonSchema = z
|
||||
"exit",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"replay_transition",
|
||||
"process",
|
||||
"shim",
|
||||
]),
|
||||
@@ -86,7 +89,9 @@ export const processCaptureComparisonSchema = z
|
||||
path: ["status"],
|
||||
});
|
||||
});
|
||||
type ProcessCaptureComparison = z.infer<typeof processCaptureComparisonSchema>;
|
||||
export type ProcessCaptureComparison = z.infer<
|
||||
typeof processCaptureComparisonSchema
|
||||
>;
|
||||
|
||||
const terminalObservations = (capture: ProcessCapture): readonly unknown[] =>
|
||||
[
|
||||
@@ -113,6 +118,47 @@ const filesystemObservations = (
|
||||
},
|
||||
];
|
||||
|
||||
const replayTransitionObservations = (
|
||||
capture: ProcessCapture,
|
||||
): readonly unknown[] =>
|
||||
(capture.replay_transitions ?? []).map(
|
||||
({
|
||||
at_ms: _atMs,
|
||||
protocol_event_sequence: _eventSequence,
|
||||
...transition
|
||||
}) => transition,
|
||||
);
|
||||
|
||||
/** Canonical observations for one process-comparison dimension. */
|
||||
export const processDimensionObservations = (
|
||||
capture: ProcessCapture,
|
||||
dimension: (typeof PROCESS_COMPARISON_DIMENSIONS)[number],
|
||||
): readonly unknown[] => {
|
||||
switch (dimension) {
|
||||
case "terminal":
|
||||
return terminalObservations(capture);
|
||||
case "interaction":
|
||||
return capture.interaction_events;
|
||||
case "exit":
|
||||
return [{ ...capture.exit, settlement: capture.settlement }];
|
||||
case "filesystem":
|
||||
return filesystemObservations(capture);
|
||||
case "protocol":
|
||||
return capture.protocol_events;
|
||||
case "replay_transition":
|
||||
return replayTransitionObservations(capture);
|
||||
case "process":
|
||||
return processObservations(capture);
|
||||
case "shim":
|
||||
return capture.shim_events;
|
||||
}
|
||||
};
|
||||
|
||||
const processObservations = (capture: ProcessCapture): readonly unknown[] => [
|
||||
...capture.process_samples.map((value) => ({ kind: "sample", value })),
|
||||
...capture.process_events.map((value) => ({ kind: "event", value })),
|
||||
];
|
||||
|
||||
const classifyCollection = (
|
||||
left: readonly unknown[],
|
||||
right: readonly unknown[],
|
||||
@@ -235,6 +281,7 @@ const truncatedComparison = (): ProcessCaptureComparison => ({
|
||||
exit: "truncated",
|
||||
filesystem: "truncated",
|
||||
protocol: "truncated",
|
||||
replay_transition: "truncated",
|
||||
process: "truncated",
|
||||
shim: "truncated",
|
||||
first_divergence: {
|
||||
@@ -251,6 +298,7 @@ type ComparisonDimensions = Pick<
|
||||
| "exit"
|
||||
| "filesystem"
|
||||
| "protocol"
|
||||
| "replay_transition"
|
||||
| "process"
|
||||
| "shim"
|
||||
>;
|
||||
@@ -292,7 +340,16 @@ const compareDimensions = (
|
||||
filesystemObservations(right),
|
||||
),
|
||||
protocol: classify("protocol", left.protocol_events, right.protocol_events),
|
||||
process: classify("process", left.process_samples, right.process_samples),
|
||||
replay_transition: classify(
|
||||
"replay_transition",
|
||||
replayTransitionObservations(left),
|
||||
replayTransitionObservations(right),
|
||||
),
|
||||
process: classify(
|
||||
"process",
|
||||
processObservations(left),
|
||||
processObservations(right),
|
||||
),
|
||||
shim: classify("shim", left.shim_events, right.shim_events),
|
||||
};
|
||||
};
|
||||
@@ -343,10 +400,15 @@ export const compareProcessCaptures = (
|
||||
left.protocol_events,
|
||||
right.protocol_events,
|
||||
),
|
||||
firstCollectionDivergence(
|
||||
"replay_transition",
|
||||
replayTransitionObservations(left),
|
||||
replayTransitionObservations(right),
|
||||
),
|
||||
firstCollectionDivergence(
|
||||
"process",
|
||||
left.process_samples,
|
||||
right.process_samples,
|
||||
processObservations(left),
|
||||
processObservations(right),
|
||||
),
|
||||
firstCollectionDivergence("shim", left.shim_events, right.shim_events),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
PROCESS_COMPARISON_DIMENSIONS,
|
||||
compareProcessCaptures,
|
||||
processDimensionObservations,
|
||||
type ProcessCaptureComparison,
|
||||
} from "./processComparison.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
processScenarioSchema,
|
||||
type ProcessScenario,
|
||||
} from "./processScenario.js";
|
||||
|
||||
const sideIdentifierSchema = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u);
|
||||
const environmentNameSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
|
||||
const processDimensionSchema = z.enum(PROCESS_COMPARISON_DIMENSIONS);
|
||||
|
||||
const sideBindingSchema = z
|
||||
.object({
|
||||
id: sideIdentifierSchema,
|
||||
executable: z.string().startsWith("/"),
|
||||
arguments: z.array(z.string()).max(256).optional(),
|
||||
environment: z.record(environmentNameSchema, z.string()).default({}),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Boundary contract for one bounded authority/candidate process experiment. */
|
||||
export const processPairedExperimentSchema = z
|
||||
.object({
|
||||
approved: z.literal(true),
|
||||
shared_scenario: processScenarioSchema,
|
||||
authority: sideBindingSchema,
|
||||
candidate: sideBindingSchema,
|
||||
repeat_count: z.number().int().min(2).max(10).default(3),
|
||||
freshness_policy: z
|
||||
.object({
|
||||
max_capture_age_ms: z.number().int().positive().max(86_400_000),
|
||||
})
|
||||
.strict(),
|
||||
required_dimensions: z
|
||||
.array(processDimensionSchema)
|
||||
.min(1)
|
||||
.max(PROCESS_COMPARISON_DIMENSIONS.length)
|
||||
.default([...PROCESS_COMPARISON_DIMENSIONS]),
|
||||
reconstruction_claims: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: sideIdentifierSchema,
|
||||
predicate: z.string().min(1).max(256),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.max(64)
|
||||
.default([]),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((experiment, context) => {
|
||||
if (experiment.authority.id === experiment.candidate.id)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "authority and candidate identities must differ",
|
||||
path: ["candidate", "id"],
|
||||
});
|
||||
if (
|
||||
new Set(experiment.required_dimensions).size !==
|
||||
experiment.required_dimensions.length
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "required process dimensions must be unique",
|
||||
path: ["required_dimensions"],
|
||||
});
|
||||
});
|
||||
|
||||
export type ProcessPairedExperiment = z.infer<
|
||||
typeof processPairedExperimentSchema
|
||||
>;
|
||||
export type ProcessSideBinding = ProcessPairedExperiment[
|
||||
| "authority"
|
||||
| "candidate"];
|
||||
|
||||
type ProcessRepeatabilityClassification =
|
||||
| "stable"
|
||||
| "timing_variance"
|
||||
| "nondeterministic_output"
|
||||
| "flaky_exit"
|
||||
| "environmental_drift"
|
||||
| "insufficient_samples";
|
||||
|
||||
export interface ProcessSideRepeatability {
|
||||
readonly classification: ProcessRepeatabilityClassification;
|
||||
readonly stable: boolean;
|
||||
readonly digest: string;
|
||||
readonly comparisons: readonly ProcessCaptureComparison[];
|
||||
readonly unstable_dimensions: readonly (typeof PROCESS_COMPARISON_DIMENSIONS)[number][];
|
||||
}
|
||||
|
||||
/** Apply a side binding without changing the shared observation contract. */
|
||||
export const bindProcessScenario = (
|
||||
shared: ProcessScenario,
|
||||
side: ProcessSideBinding,
|
||||
): ProcessScenario =>
|
||||
processScenarioSchema.parse({
|
||||
...shared,
|
||||
executable: side.executable,
|
||||
arguments: side.arguments ?? shared.arguments,
|
||||
environment: { ...shared.environment, ...side.environment },
|
||||
});
|
||||
|
||||
const classifyInstability = (
|
||||
dimensions: ReadonlySet<(typeof PROCESS_COMPARISON_DIMENSIONS)[number]>,
|
||||
): ProcessRepeatabilityClassification => {
|
||||
if (dimensions.has("exit")) return "flaky_exit";
|
||||
if (dimensions.has("filesystem") || dimensions.has("process"))
|
||||
return "environmental_drift";
|
||||
return "nondeterministic_output";
|
||||
};
|
||||
|
||||
const timingKeys = new Set([
|
||||
"at_ms",
|
||||
"scheduled_at_ms",
|
||||
"dispatched_at_ms",
|
||||
"elapsed_ms",
|
||||
]);
|
||||
|
||||
const withoutTiming = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(withoutTiming);
|
||||
if (typeof value !== "object" || value === null) return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => !timingKeys.has(key))
|
||||
.map(([key, entry]) => [key, withoutTiming(entry)]),
|
||||
);
|
||||
};
|
||||
|
||||
const hasOnlyTimingVariance = (
|
||||
captures: readonly ProcessCapture[],
|
||||
dimensions: readonly (typeof PROCESS_COMPARISON_DIMENSIONS)[number][],
|
||||
): boolean =>
|
||||
dimensions.every((dimension) => {
|
||||
const baseline = JSON.stringify(
|
||||
withoutTiming(processDimensionObservations(captures[0]!, dimension)),
|
||||
);
|
||||
return captures
|
||||
.slice(1)
|
||||
.every(
|
||||
(capture) =>
|
||||
JSON.stringify(
|
||||
withoutTiming(processDimensionObservations(capture, dimension)),
|
||||
) === baseline,
|
||||
);
|
||||
});
|
||||
|
||||
/** Compare same-side repeats before permitting a cross-side claim. */
|
||||
export const analyzeProcessRepeatability = (
|
||||
captures: readonly ProcessCapture[],
|
||||
requiredDimensions: readonly (typeof PROCESS_COMPARISON_DIMENSIONS)[number][],
|
||||
): ProcessSideRepeatability => {
|
||||
if (captures.length < 2)
|
||||
return {
|
||||
classification: "insufficient_samples",
|
||||
stable: false,
|
||||
digest: digestProcessCommitment({ captures: [], requiredDimensions }),
|
||||
comparisons: [],
|
||||
unstable_dimensions: [],
|
||||
};
|
||||
const comparisons = captures
|
||||
.slice(1)
|
||||
.map((capture, index) => compareProcessCaptures(captures[index]!, capture));
|
||||
const unstable = new Set(
|
||||
requiredDimensions.filter((dimension) =>
|
||||
comparisons.some((comparison) => comparison[dimension] !== "unchanged"),
|
||||
),
|
||||
);
|
||||
const unstableDimensions = PROCESS_COMPARISON_DIMENSIONS.filter((dimension) =>
|
||||
unstable.has(dimension),
|
||||
);
|
||||
return {
|
||||
classification:
|
||||
unstable.size === 0
|
||||
? "stable"
|
||||
: hasOnlyTimingVariance(captures, unstableDimensions)
|
||||
? "timing_variance"
|
||||
: classifyInstability(unstable),
|
||||
stable: unstable.size === 0,
|
||||
digest: digestProcessCommitment({
|
||||
requiredDimensions,
|
||||
comparisons,
|
||||
}),
|
||||
comparisons,
|
||||
unstable_dimensions: unstableDimensions,
|
||||
};
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
import { replayMachineSchema } from "./replayMachine.js";
|
||||
|
||||
const positiveBudget = z.number().int().positive();
|
||||
const timedEventBase = { at_ms: z.number().int().nonnegative() };
|
||||
@@ -241,6 +242,7 @@ export const processScenarioSchema = z
|
||||
}),
|
||||
replay: z
|
||||
.object({
|
||||
machine: replayMachineSchema.nullable().default(null),
|
||||
http: z
|
||||
.array(
|
||||
z.object({
|
||||
@@ -285,6 +287,7 @@ export const processScenarioSchema = z
|
||||
.default([]),
|
||||
})
|
||||
.default({
|
||||
machine: null,
|
||||
http: [],
|
||||
websocket_messages: [],
|
||||
websocket_connections: [],
|
||||
|
||||
@@ -46,7 +46,7 @@ const MAX_CANONICAL_BYTES = 32 * 1024 * 1024;
|
||||
const providers = {
|
||||
behavioral: {
|
||||
operation: "compare_process_captures",
|
||||
predicate: "rea.process-comparison/v3",
|
||||
predicate: "rea.process-comparison/v4",
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
},
|
||||
@@ -232,7 +232,7 @@ const validateComparisonIdentity = (claim: Claim, evidence: Evidence): void => {
|
||||
evidence.predicate_type !== expected.predicate ||
|
||||
evidence.provider.id !== expected.id ||
|
||||
evidence.provider.name !== expected.name ||
|
||||
evidence.provider.version !== (claim.kind === "behavioral" ? "3" : "1") ||
|
||||
evidence.provider.version !== (claim.kind === "behavioral" ? "4" : "1") ||
|
||||
evidence.confidence !== "derived" ||
|
||||
evidence.authority !== "analyst-inference" ||
|
||||
evidence.subject !== null
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
import { MultiDirectedGraph } from "graphology";
|
||||
import { singleSource } from "graphology-shortest-path";
|
||||
import { z } from "zod";
|
||||
|
||||
const replayIdentifierSchema = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u);
|
||||
const replayPathSchema = z
|
||||
.array(z.union([z.string().max(256), z.number().int().nonnegative()]))
|
||||
.max(32);
|
||||
const sensitiveHeaderNames = new Set([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
const replayHeaderMatchersSchema = z
|
||||
.record(z.string().min(1).max(256), z.string().max(8_192))
|
||||
.superRefine((headers, context) => {
|
||||
const names = Object.keys(headers).map((name) => name.toLowerCase());
|
||||
if (new Set(names).size !== names.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay header matchers must be unique ignoring case",
|
||||
input: headers,
|
||||
});
|
||||
if (names.some((name) => sensitiveHeaderNames.has(name)))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"replay header matchers cannot persist authorization or cookie values; capture and guard through a secret alias instead",
|
||||
input: headers,
|
||||
});
|
||||
})
|
||||
.transform((headers) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(headers).map(([name, value]) => [
|
||||
name.toLowerCase(),
|
||||
value,
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
const replayValueSourceSchema = z.discriminatedUnion("source", [
|
||||
z.object({
|
||||
source: z.literal("request_header"),
|
||||
name: z
|
||||
.string()
|
||||
.min(1)
|
||||
.transform((name) => name.toLowerCase()),
|
||||
}),
|
||||
z.object({ source: z.literal("request_json"), path: replayPathSchema }),
|
||||
z.object({ source: z.literal("websocket_json"), path: replayPathSchema }),
|
||||
z.object({ source: z.literal("action_json"), path: replayPathSchema }),
|
||||
]);
|
||||
|
||||
const replayTriggerSchema = z.discriminatedUnion("protocol", [
|
||||
z.object({
|
||||
protocol: z.literal("http"),
|
||||
method: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16)
|
||||
.transform((method) => method.toUpperCase()),
|
||||
path: z.string().startsWith("/"),
|
||||
headers: replayHeaderMatchersSchema.default({}),
|
||||
body: z.string().max(1_000_000).nullable().default(null),
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal("websocket_connect"),
|
||||
path: z.string().startsWith("/"),
|
||||
headers: replayHeaderMatchersSchema.default({}),
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal("websocket_message"),
|
||||
path: z.string().startsWith("/"),
|
||||
body: z.string().max(1_000_000).nullable().default(null),
|
||||
}),
|
||||
]);
|
||||
|
||||
const replayActionSchema = z.discriminatedUnion("type", [
|
||||
z.object({
|
||||
type: z.literal("http_response"),
|
||||
status: z.number().int().min(100).max(599),
|
||||
headers: z.record(z.string(), z.string()).default({}),
|
||||
body: z.string().max(1_000_000),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("websocket_send"),
|
||||
data: z.string().max(1_000_000),
|
||||
}),
|
||||
z.object({ type: z.literal("disconnect") }),
|
||||
z.object({
|
||||
type: z.literal("delay"),
|
||||
duration_ms: z.number().int().nonnegative().max(30_000),
|
||||
}),
|
||||
]);
|
||||
|
||||
const replayTransitionSchema = z.object({
|
||||
id: replayIdentifierSchema,
|
||||
from: replayIdentifierSchema,
|
||||
to: replayIdentifierSchema,
|
||||
priority: z.number().int().min(0).max(1_000).default(100),
|
||||
trigger: replayTriggerSchema,
|
||||
guards: z
|
||||
.array(
|
||||
z.object({
|
||||
variable: replayIdentifierSchema,
|
||||
value: replayValueSourceSchema,
|
||||
}),
|
||||
)
|
||||
.max(32)
|
||||
.default([]),
|
||||
captures: z
|
||||
.array(
|
||||
z.object({
|
||||
variable: replayIdentifierSchema,
|
||||
value: replayValueSourceSchema,
|
||||
sensitive: z.boolean().default(false),
|
||||
}),
|
||||
)
|
||||
.max(32)
|
||||
.default([]),
|
||||
actions: z.array(replayActionSchema).min(1).max(32),
|
||||
max_uses: z.number().int().min(1).max(10_000),
|
||||
});
|
||||
|
||||
const transitionSignature = (
|
||||
transition: z.infer<typeof replayTransitionSchema>,
|
||||
): string =>
|
||||
JSON.stringify({
|
||||
from: transition.from,
|
||||
priority: transition.priority,
|
||||
trigger: transition.trigger,
|
||||
});
|
||||
|
||||
const replayMachineBaseSchema = z.object({
|
||||
initial_state: replayIdentifierSchema,
|
||||
states: z
|
||||
.array(
|
||||
z.object({
|
||||
name: replayIdentifierSchema,
|
||||
terminal: z.boolean().default(false),
|
||||
max_visits: z.number().int().min(1).max(100_000).default(100_000),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(256),
|
||||
transitions: z.array(replayTransitionSchema).min(1).max(2_000),
|
||||
max_transitions: z.number().int().min(1).max(100_000),
|
||||
limits: z
|
||||
.object({
|
||||
connections: z.number().int().min(1).max(1_000).default(100),
|
||||
messages: z.number().int().min(1).max(100_000).default(10_000),
|
||||
bytes: z.number().int().min(1).max(10_000_000).default(1_000_000),
|
||||
duration_ms: z.number().int().min(1).max(300_000).default(30_000),
|
||||
})
|
||||
.default({
|
||||
connections: 100,
|
||||
messages: 10_000,
|
||||
bytes: 1_000_000,
|
||||
duration_ms: 30_000,
|
||||
}),
|
||||
});
|
||||
type ReplayMachineInput = z.infer<typeof replayMachineBaseSchema>;
|
||||
type ReplayMachineContext = z.core.$RefinementCtx<ReplayMachineInput>;
|
||||
|
||||
const validateReplayIdentities = (
|
||||
machine: ReplayMachineInput,
|
||||
context: ReplayMachineContext,
|
||||
): ReadonlySet<string> => {
|
||||
const names = machine.states.map(({ name }) => name);
|
||||
const nameSet = new Set(names);
|
||||
if (nameSet.size !== names.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine state names must be unique",
|
||||
path: ["states"],
|
||||
input: machine,
|
||||
});
|
||||
if (!nameSet.has(machine.initial_state))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine initial state is not declared",
|
||||
path: ["initial_state"],
|
||||
input: machine,
|
||||
});
|
||||
const transitionIds = machine.transitions.map(({ id }) => id);
|
||||
if (new Set(transitionIds).size !== transitionIds.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine transition IDs must be unique",
|
||||
path: ["transitions"],
|
||||
input: machine,
|
||||
});
|
||||
const signatures = machine.transitions.map(transitionSignature);
|
||||
if (new Set(signatures).size !== signatures.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"replay machine transitions with the same state, trigger, and priority are ambiguous",
|
||||
path: ["transitions"],
|
||||
input: machine,
|
||||
});
|
||||
return nameSet;
|
||||
};
|
||||
|
||||
const validateReplayVariables = (
|
||||
machine: ReplayMachineInput,
|
||||
context: ReplayMachineContext,
|
||||
): void => {
|
||||
const capturedVariables = new Map<string, boolean>();
|
||||
for (const [transitionIndex, transition] of machine.transitions.entries()) {
|
||||
for (const capture of transition.captures) {
|
||||
const sensitivity = capturedVariables.get(capture.variable);
|
||||
if (sensitivity !== undefined && sensitivity !== capture.sensitive)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"a replay variable cannot change secret classification between captures",
|
||||
path: ["transitions", transitionIndex, "captures"],
|
||||
input: machine,
|
||||
});
|
||||
capturedVariables.set(capture.variable, capture.sensitive);
|
||||
}
|
||||
}
|
||||
for (const [transitionIndex, transition] of machine.transitions.entries())
|
||||
for (const [guardIndex, guard] of transition.guards.entries())
|
||||
if (!capturedVariables.has(guard.variable))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay guard references a variable that is never captured",
|
||||
path: ["transitions", transitionIndex, "guards", guardIndex],
|
||||
input: machine,
|
||||
});
|
||||
};
|
||||
|
||||
const validateReplayActions = (
|
||||
machine: ReplayMachineInput,
|
||||
context: ReplayMachineContext,
|
||||
): void => {
|
||||
for (const [index, transition] of machine.transitions.entries()) {
|
||||
const httpResponses = transition.actions.filter(
|
||||
({ type }) => type === "http_response",
|
||||
).length;
|
||||
const websocketSends = transition.actions.some(
|
||||
({ type }) => type === "websocket_send",
|
||||
);
|
||||
const invalid =
|
||||
transition.trigger.protocol === "http"
|
||||
? httpResponses !== 1 || websocketSends
|
||||
: httpResponses !== 0;
|
||||
if (invalid)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"replay actions must match the transition protocol and HTTP transitions require exactly one response",
|
||||
path: ["transitions", index, "actions"],
|
||||
input: machine,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const validateReplayGraph = (
|
||||
machine: ReplayMachineInput,
|
||||
names: ReadonlySet<string>,
|
||||
context: ReplayMachineContext,
|
||||
): void => {
|
||||
const graph = new MultiDirectedGraph();
|
||||
for (const name of names) graph.addNode(name);
|
||||
for (const [index, transition] of machine.transitions.entries()) {
|
||||
if (!names.has(transition.from) || !names.has(transition.to)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine transition references an unknown state",
|
||||
path: ["transitions", index],
|
||||
input: machine,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
graph.addDirectedEdgeWithKey(transition.id, transition.from, transition.to);
|
||||
}
|
||||
if (!graph.hasNode(machine.initial_state)) return;
|
||||
if (!machine.states.some(({ terminal }) => terminal))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine must declare at least one terminal state",
|
||||
path: ["states"],
|
||||
input: machine,
|
||||
});
|
||||
const reachable = new Set(
|
||||
Object.keys(singleSource(graph, machine.initial_state)),
|
||||
);
|
||||
reachable.add(machine.initial_state);
|
||||
for (const [index, state] of machine.states.entries()) {
|
||||
if (!reachable.has(state.name))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay machine state is unreachable from the initial state",
|
||||
path: ["states", index],
|
||||
input: machine,
|
||||
});
|
||||
if (state.terminal && graph.outDegree(state.name) > 0)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"terminal replay machine state cannot have outgoing transitions",
|
||||
path: ["states", index],
|
||||
input: machine,
|
||||
});
|
||||
if (!state.terminal && graph.outDegree(state.name) === 0)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "non-terminal replay machine state has no outgoing transition",
|
||||
path: ["states", index],
|
||||
input: machine,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** Portable finite replay machine with no executable callbacks. */
|
||||
export const replayMachineSchema = z
|
||||
.object(replayMachineBaseSchema.shape)
|
||||
.strict()
|
||||
.superRefine((machine, context) => {
|
||||
const names = validateReplayIdentities(machine, context);
|
||||
validateReplayVariables(machine, context);
|
||||
validateReplayActions(machine, context);
|
||||
validateReplayGraph(machine, names, context);
|
||||
});
|
||||
|
||||
export type ReplayMachine = z.infer<typeof replayMachineSchema>;
|
||||
@@ -0,0 +1,264 @@
|
||||
import type { ReplayMachine } from "./replayMachine.js";
|
||||
|
||||
type ReplayTransition = ReplayMachine["transitions"][number];
|
||||
type ReplayValueSource = ReplayTransition["captures"][number]["value"];
|
||||
|
||||
export interface ReplayMachineEvent {
|
||||
readonly protocol: "http" | "websocket_connect" | "websocket_message";
|
||||
readonly connection: "not_applicable" | "initial" | "reconnect";
|
||||
readonly at_ms: number;
|
||||
readonly method: string | null;
|
||||
readonly path: string;
|
||||
readonly headers: Readonly<Record<string, string>>;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
export interface ReplayTransitionRecord {
|
||||
readonly sequence: number;
|
||||
readonly transition_id: string;
|
||||
readonly state_before: string;
|
||||
readonly state_after: string;
|
||||
readonly sensitive_aliases: readonly string[];
|
||||
}
|
||||
|
||||
export type ReplayMachineDecision =
|
||||
| {
|
||||
readonly outcome: "matched";
|
||||
readonly actions: ReplayTransition["actions"];
|
||||
readonly transition: ReplayTransitionRecord;
|
||||
}
|
||||
| {
|
||||
readonly outcome:
|
||||
| "unmatched"
|
||||
| "invalid_state"
|
||||
| "guard_failed"
|
||||
| "transition_exhausted"
|
||||
| "invalid_capture"
|
||||
| "unexpected_reconnect"
|
||||
| "limit_exhausted";
|
||||
readonly actions: readonly [];
|
||||
readonly transition: null;
|
||||
};
|
||||
|
||||
const parseJson = (value: string): unknown => {
|
||||
try {
|
||||
return JSON.parse(value) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const atPath = (
|
||||
value: unknown,
|
||||
path: readonly (string | number)[],
|
||||
): unknown => {
|
||||
let current = value;
|
||||
for (const segment of path) {
|
||||
if (typeof segment === "number") {
|
||||
if (!Array.isArray(current)) return undefined;
|
||||
current = current[segment];
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof current !== "object" ||
|
||||
current === null ||
|
||||
!(segment in current)
|
||||
)
|
||||
return undefined;
|
||||
current = (current as Readonly<Record<string, unknown>>)[segment];
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
const actionJsonBody = (transition: ReplayTransition): string | undefined => {
|
||||
for (const action of transition.actions)
|
||||
if (action.type === "http_response") return action.body;
|
||||
else if (action.type === "websocket_send") return action.data;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const readValue = (
|
||||
source: ReplayValueSource,
|
||||
event: ReplayMachineEvent,
|
||||
transition: ReplayTransition,
|
||||
): unknown => {
|
||||
switch (source.source) {
|
||||
case "request_header":
|
||||
return event.headers[source.name.toLowerCase()];
|
||||
case "request_json":
|
||||
return atPath(parseJson(event.body), source.path);
|
||||
case "websocket_json":
|
||||
return atPath(parseJson(event.body), source.path);
|
||||
case "action_json": {
|
||||
const body = actionJsonBody(transition);
|
||||
return body === undefined
|
||||
? undefined
|
||||
: atPath(parseJson(body), source.path);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const triggerMatches = (
|
||||
transition: ReplayTransition,
|
||||
event: ReplayMachineEvent,
|
||||
): boolean => {
|
||||
const trigger = transition.trigger;
|
||||
if (trigger.protocol !== event.protocol || trigger.path !== event.path)
|
||||
return false;
|
||||
if (
|
||||
"headers" in trigger &&
|
||||
Object.entries(trigger.headers).some(
|
||||
([name, value]) => event.headers[name.toLowerCase()] !== value,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
if (trigger.protocol === "http")
|
||||
return (
|
||||
trigger.method === event.method &&
|
||||
(trigger.body === null || trigger.body === event.body)
|
||||
);
|
||||
if (trigger.protocol === "websocket_message")
|
||||
return trigger.body === null || trigger.body === event.body;
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Stateful evaluator for one validated replay-machine instance. */
|
||||
export class ReplayMachineRuntime {
|
||||
readonly #variables = new Map<string, unknown>();
|
||||
readonly #sensitiveVariables = new Set<string>();
|
||||
readonly #uses = new Map<string, number>();
|
||||
readonly #stateVisits = new Map<string, number>();
|
||||
readonly #timeline: ReplayTransitionRecord[] = [];
|
||||
#state: string;
|
||||
#connections = 0;
|
||||
#messages = 0;
|
||||
#bytes = 0;
|
||||
|
||||
constructor(readonly machine: ReplayMachine) {
|
||||
this.#state = machine.initial_state;
|
||||
this.#stateVisits.set(machine.initial_state, 1);
|
||||
}
|
||||
|
||||
get state(): string {
|
||||
return this.#state;
|
||||
}
|
||||
|
||||
get timeline(): readonly ReplayTransitionRecord[] {
|
||||
return this.#timeline;
|
||||
}
|
||||
|
||||
/** Replace captured secret values with stable aliases before persistence. */
|
||||
redact(value: string): string {
|
||||
let redacted = value;
|
||||
for (const variable of [...this.#sensitiveVariables].sort()) {
|
||||
const secret = this.#variables.get(variable);
|
||||
if (typeof secret === "string" && secret.length > 0)
|
||||
redacted = redacted.replaceAll(secret, `<secret:${variable}>`);
|
||||
}
|
||||
return redacted;
|
||||
}
|
||||
|
||||
dispatch(event: ReplayMachineEvent): ReplayMachineDecision {
|
||||
if (!this.#admitEvent(event)) return this.#refusal("limit_exhausted");
|
||||
const matching = this.machine.transitions
|
||||
.map((transition, declarationOrder) => ({
|
||||
transition,
|
||||
declarationOrder,
|
||||
}))
|
||||
.filter(({ transition }) => triggerMatches(transition, event));
|
||||
const eligible = matching
|
||||
.filter(({ transition }) => transition.from === this.#state)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.transition.priority - right.transition.priority ||
|
||||
left.declarationOrder - right.declarationOrder,
|
||||
);
|
||||
if (eligible.length === 0)
|
||||
return this.#refusal(
|
||||
matching.length === 0
|
||||
? "unmatched"
|
||||
: event.protocol === "websocket_connect" &&
|
||||
event.connection === "reconnect"
|
||||
? "unexpected_reconnect"
|
||||
: "invalid_state",
|
||||
);
|
||||
const guarded = eligible.find(({ transition }) =>
|
||||
transition.guards.every(
|
||||
(guard) =>
|
||||
this.#variables.has(guard.variable) &&
|
||||
Object.is(
|
||||
this.#variables.get(guard.variable),
|
||||
readValue(guard.value, event, transition),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (guarded === undefined) return this.#refusal("guard_failed");
|
||||
const transition = guarded.transition;
|
||||
const used = this.#uses.get(transition.id) ?? 0;
|
||||
if (
|
||||
used >= transition.max_uses ||
|
||||
this.#timeline.length >= this.machine.max_transitions
|
||||
)
|
||||
return this.#refusal("transition_exhausted");
|
||||
const nextState = this.machine.states.find(
|
||||
({ name }) => name === transition.to,
|
||||
);
|
||||
const nextVisits = (this.#stateVisits.get(transition.to) ?? 0) + 1;
|
||||
if (nextState === undefined || nextVisits > nextState.max_visits)
|
||||
return this.#refusal("limit_exhausted");
|
||||
const captures = transition.captures.map((capture) => ({
|
||||
...capture,
|
||||
captured: readValue(capture.value, event, transition),
|
||||
}));
|
||||
if (captures.some(({ captured }) => captured === undefined))
|
||||
return this.#refusal("invalid_capture");
|
||||
for (const capture of captures) {
|
||||
this.#variables.set(capture.variable, capture.captured);
|
||||
if (capture.sensitive) this.#sensitiveVariables.add(capture.variable);
|
||||
}
|
||||
const record = {
|
||||
sequence: this.#timeline.length,
|
||||
transition_id: transition.id,
|
||||
state_before: this.#state,
|
||||
state_after: transition.to,
|
||||
sensitive_aliases: captures
|
||||
.filter(({ sensitive }) => sensitive)
|
||||
.map(({ variable }) => variable)
|
||||
.sort(),
|
||||
} satisfies ReplayTransitionRecord;
|
||||
this.#uses.set(transition.id, used + 1);
|
||||
this.#stateVisits.set(transition.to, nextVisits);
|
||||
this.#state = transition.to;
|
||||
this.#timeline.push(record);
|
||||
return {
|
||||
outcome: "matched",
|
||||
actions: transition.actions,
|
||||
transition: record,
|
||||
};
|
||||
}
|
||||
|
||||
#admitEvent(event: ReplayMachineEvent): boolean {
|
||||
const connections =
|
||||
this.#connections + (event.protocol === "websocket_connect" ? 1 : 0);
|
||||
const messages =
|
||||
this.#messages + (event.protocol === "websocket_message" ? 1 : 0);
|
||||
const bytes = this.#bytes + Buffer.byteLength(event.body);
|
||||
if (
|
||||
event.at_ms > this.machine.limits.duration_ms ||
|
||||
connections > this.machine.limits.connections ||
|
||||
messages > this.machine.limits.messages ||
|
||||
bytes > this.machine.limits.bytes
|
||||
)
|
||||
return false;
|
||||
this.#connections = connections;
|
||||
this.#messages = messages;
|
||||
this.#bytes = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
#refusal(
|
||||
outcome: Exclude<ReplayMachineDecision["outcome"], "matched">,
|
||||
): ReplayMachineDecision {
|
||||
return { outcome, actions: [], transition: null };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const runtimeFamilySchema = z.enum([
|
||||
"android",
|
||||
"apple",
|
||||
"javascript",
|
||||
"jvm",
|
||||
"native",
|
||||
"webassembly",
|
||||
]);
|
||||
const observationSchema = z.strictObject({
|
||||
path: z.string().min(1).max(4_096),
|
||||
artifact_id: z.string().regex(/^art_[a-f0-9]{64}$/u),
|
||||
sha256: digestSchema,
|
||||
format: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
/** Authenticated artifact inventory pages to classify by runtime family. */
|
||||
export const runtimeIdentificationInputSchema = z.strictObject({
|
||||
inventory_evidence: z.array(evidenceSchema).min(1).max(100),
|
||||
limits: z
|
||||
.strictObject({
|
||||
max_observations: z.number().int().min(1).max(10_000).default(1_000),
|
||||
})
|
||||
.default({ max_observations: 1_000 }),
|
||||
});
|
||||
|
||||
/** Provider-neutral runtime identification with explicit tooling availability. */
|
||||
export const runtimeIdentificationResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
identification_id: z.string().regex(/^rid_[a-f0-9]{64}$/u),
|
||||
root_sha256: digestSchema,
|
||||
root_format: z.string().min(1).max(100),
|
||||
source_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
runtimes: z.array(
|
||||
z.strictObject({
|
||||
family: runtimeFamilySchema,
|
||||
inspection: z.enum([
|
||||
"available",
|
||||
"provider-missing",
|
||||
"provider-selection-required",
|
||||
]),
|
||||
provider_id: z.string().min(1).max(200).nullable(),
|
||||
reason: z.string().min(1).max(1_000).nullable(),
|
||||
observations: z.array(observationSchema),
|
||||
omitted_observations: z.number().int().min(0),
|
||||
}),
|
||||
),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inventory", "partial", "truncated"]),
|
||||
inventory_complete: z.boolean(),
|
||||
omitted_observations: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1).max(4_096)).max(100),
|
||||
});
|
||||
|
||||
export type RuntimeIdentificationInput = z.input<
|
||||
typeof runtimeIdentificationInputSchema
|
||||
>;
|
||||
export type RuntimeIdentificationResult = z.infer<
|
||||
typeof runtimeIdentificationResultSchema
|
||||
>;
|
||||
type RuntimeFamily = z.infer<typeof runtimeFamilySchema>;
|
||||
type Observation = z.infer<typeof observationSchema>;
|
||||
type RuntimeProvider = {
|
||||
readonly inspection:
|
||||
| "available"
|
||||
| "provider-missing"
|
||||
| "provider-selection-required";
|
||||
readonly id: string | null;
|
||||
readonly reason: string | null;
|
||||
};
|
||||
|
||||
const PROVIDERS: Readonly<Record<RuntimeFamily, RuntimeProvider>> = {
|
||||
android: {
|
||||
inspection: "provider-missing",
|
||||
id: null,
|
||||
reason: "Install or configure an Android semantic-analysis provider.",
|
||||
},
|
||||
apple: { inspection: "available", id: "rea-apple-application", reason: null },
|
||||
javascript: {
|
||||
inspection: "available",
|
||||
id: "rea-javascript-application",
|
||||
reason: null,
|
||||
},
|
||||
jvm: {
|
||||
inspection: "provider-missing",
|
||||
id: null,
|
||||
reason: "Install or configure a JVM bytecode-analysis provider.",
|
||||
},
|
||||
native: {
|
||||
inspection: "provider-selection-required",
|
||||
id: null,
|
||||
reason:
|
||||
"Select an available native deep-analysis provider for this target and host.",
|
||||
},
|
||||
webassembly: {
|
||||
inspection: "provider-missing",
|
||||
id: null,
|
||||
reason: "Install or configure a WebAssembly semantic-analysis provider.",
|
||||
},
|
||||
};
|
||||
|
||||
/** Identify runtime families without executing or semantically decoding target bytes. */
|
||||
export const identifyRuntimes = (
|
||||
input: RuntimeIdentificationInput,
|
||||
): RuntimeIdentificationResult => {
|
||||
const parsed = runtimeIdentificationInputSchema.parse(input);
|
||||
const { evidence, inventory } = parseArtifactInventoryEvidence(
|
||||
parsed.inventory_evidence,
|
||||
);
|
||||
const nodes = new Map(
|
||||
inventory.nodes.map((node) => [node.artifact_id, node]),
|
||||
);
|
||||
const grouped = new Map<RuntimeFamily, Observation[]>();
|
||||
const add = (family: RuntimeFamily, observation: Observation): void => {
|
||||
const observations = grouped.get(family) ?? [];
|
||||
observations.push(observation);
|
||||
grouped.set(family, observations);
|
||||
};
|
||||
for (const occurrence of inventory.occurrences) {
|
||||
if (occurrence.artifact_id === null) continue;
|
||||
const node = nodes.get(occurrence.artifact_id);
|
||||
if (node === undefined)
|
||||
throw new TypeError("Runtime observation has no artifact node");
|
||||
const observation = {
|
||||
path: occurrence.logical_path,
|
||||
artifact_id: node.artifact_id,
|
||||
sha256: node.sha256,
|
||||
format: node.format,
|
||||
};
|
||||
for (const family of familiesFor(node.format, occurrence.logical_path))
|
||||
add(family, observation);
|
||||
}
|
||||
const rootObservation = inventory.nodes.find(
|
||||
({ sha256 }) => sha256 === inventory.manifest.root_sha256,
|
||||
);
|
||||
if (rootObservation !== undefined)
|
||||
for (const family of familiesFor(inventory.manifest.root_format, "."))
|
||||
add(family, {
|
||||
path: ".",
|
||||
artifact_id: rootObservation.artifact_id,
|
||||
sha256: rootObservation.sha256,
|
||||
format: rootObservation.format,
|
||||
});
|
||||
let remaining = parsed.limits.max_observations;
|
||||
let omitted = 0;
|
||||
const runtimes = [...grouped.entries()]
|
||||
.sort(([left], [right]) => compare(left, right))
|
||||
.map(([family, values]) => {
|
||||
const unique = deduplicate(values);
|
||||
const observations = unique.slice(0, remaining);
|
||||
remaining -= observations.length;
|
||||
const omittedObservations = unique.length - observations.length;
|
||||
omitted += omittedObservations;
|
||||
const provider = PROVIDERS[family];
|
||||
return {
|
||||
family,
|
||||
inspection: provider.inspection,
|
||||
provider_id: provider.id,
|
||||
reason: provider.reason,
|
||||
observations,
|
||||
omitted_observations: omittedObservations,
|
||||
};
|
||||
});
|
||||
const limitations = [
|
||||
...(!inventory.complete
|
||||
? [
|
||||
"Source inventory pages are incomplete; absent runtimes remain unknown.",
|
||||
]
|
||||
: []),
|
||||
...(omitted > 0
|
||||
? [`${String(omitted)} runtime observations were omitted by the limit.`]
|
||||
: []),
|
||||
"Runtime families are identified from exact artifact formats and paths; semantic claims require the named provider.",
|
||||
];
|
||||
const withoutId = {
|
||||
schema_version: 1 as const,
|
||||
root_sha256: inventory.manifest.root_sha256,
|
||||
root_format: inventory.manifest.root_format,
|
||||
source_evidence_ids: evidence
|
||||
.map(({ evidence_id: id }) => id)
|
||||
.sort(compare),
|
||||
runtimes,
|
||||
coverage: {
|
||||
status:
|
||||
omitted > 0
|
||||
? ("truncated" as const)
|
||||
: inventory.complete
|
||||
? ("complete-within-inventory" as const)
|
||||
: ("partial" as const),
|
||||
inventory_complete: inventory.complete,
|
||||
omitted_observations: omitted,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
return runtimeIdentificationResultSchema.parse({
|
||||
...withoutId,
|
||||
identification_id: `rid_${digest(withoutId)}`,
|
||||
});
|
||||
};
|
||||
|
||||
const familiesFor = (format: string, path: string): RuntimeFamily[] => {
|
||||
const families = new Set<RuntimeFamily>();
|
||||
if (
|
||||
format === "apk" ||
|
||||
format === "dex" ||
|
||||
/(?:^|\/)AndroidManifest\.xml$/u.test(path)
|
||||
)
|
||||
families.add("android");
|
||||
if (format === "ipa") families.add("apple");
|
||||
if (format === "javascript-bundle") families.add("javascript");
|
||||
if (format === "jvm-class") families.add("jvm");
|
||||
if (["elf", "mach-o", "mach-o-universal", "pe"].includes(format))
|
||||
families.add("native");
|
||||
if (format === "webassembly") families.add("webassembly");
|
||||
return [...families];
|
||||
};
|
||||
|
||||
const deduplicate = (values: readonly Observation[]): Observation[] =>
|
||||
[
|
||||
...new Map(
|
||||
values.map((value) => [`${value.path}\0${value.artifact_id}`, value]),
|
||||
).values(),
|
||||
].sort((left, right) => compare(left.path, right.path));
|
||||
const compare = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Runtime identification is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -160,7 +160,7 @@ const EXPECTED = {
|
||||
"REA function comparison",
|
||||
],
|
||||
compare_process_captures: [
|
||||
"rea.process-comparison/v3",
|
||||
"rea.process-comparison/v4",
|
||||
"rea-process",
|
||||
"REA deterministic process harness",
|
||||
],
|
||||
@@ -409,7 +409,7 @@ const assertComparisonIdentity = (evidence: Evidence): void => {
|
||||
evidence.provider.id !== expected[1] ||
|
||||
evidence.provider.name !== expected[2] ||
|
||||
evidence.provider.version !==
|
||||
(evidence.operation === "compare_process_captures" ? "3" : "1") ||
|
||||
(evidence.operation === "compare_process_captures" ? "4" : "1") ||
|
||||
evidence.confidence !== "derived" ||
|
||||
evidence.authority !== "analyst-inference" ||
|
||||
evidence.subject !== null ||
|
||||
|
||||
+184
-59
@@ -51,6 +51,11 @@ export const webCaptureDiffSchema = z.object({
|
||||
resources: dimensionSchema,
|
||||
network: dimensionSchema,
|
||||
metadata: dimensionSchema,
|
||||
accessibility: dimensionSchema,
|
||||
storage: dimensionSchema,
|
||||
console_errors: dimensionSchema,
|
||||
current_route: dimensionSchema,
|
||||
lifecycle: dimensionSchema,
|
||||
webmcp: dimensionSchema,
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
@@ -59,73 +64,23 @@ export type WebCaptureDiff = z.infer<typeof webCaptureDiffSchema>;
|
||||
type Dimension =
|
||||
WebCaptureDiff["dimensions"][keyof WebCaptureDiff["dimensions"]];
|
||||
type Change = Dimension["changes"][number];
|
||||
type DimensionBuilder = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
complete: boolean,
|
||||
reason: string,
|
||||
) => Dimension;
|
||||
|
||||
/** Compare normalized observations without treating incomplete absence as proof. */
|
||||
export const compareWebCaptures = (
|
||||
input: CompareWebCapturesInput,
|
||||
): WebCaptureDiff => {
|
||||
let remaining = input.max_changes;
|
||||
const dimension = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
complete: boolean,
|
||||
reason: string,
|
||||
): Dimension => {
|
||||
const all = compareIdentities(before, after);
|
||||
const retained = all.slice(0, remaining);
|
||||
remaining -= retained.length;
|
||||
return {
|
||||
status: all.length > 0 ? "changed" : complete ? "unchanged" : "unknown",
|
||||
total_changes: all.length,
|
||||
changes: retained,
|
||||
omitted_changes: all.length - retained.length,
|
||||
reason: all.length === 0 && !complete ? reason : null,
|
||||
};
|
||||
};
|
||||
const dimension = createDimensionBuilder(input.max_changes);
|
||||
const before = input.before.inspection;
|
||||
const after = input.after.inspection;
|
||||
const dimensions = {
|
||||
dom_structure: dimension(
|
||||
singleton("document", digest(domProjection(before))),
|
||||
singleton("document", digest(domProjection(after))),
|
||||
sectionsComplete(before, ["frames", "dom"]) &&
|
||||
sectionsComplete(after, ["frames", "dom"]),
|
||||
"DOM or frame capture was incomplete in at least one observation.",
|
||||
),
|
||||
scripts: dimension(
|
||||
keyed(
|
||||
before.scripts.items.map(scriptProjection),
|
||||
(item) => item.script_key,
|
||||
),
|
||||
keyed(
|
||||
after.scripts.items.map(scriptProjection),
|
||||
(item) => item.script_key,
|
||||
),
|
||||
sectionsComplete(before, ["scripts"]) &&
|
||||
sectionsComplete(after, ["scripts"]),
|
||||
"Script inventory was incomplete in at least one observation.",
|
||||
),
|
||||
resources: dimension(
|
||||
keyed(before.resources, (item) => item.resource_key),
|
||||
keyed(after.resources, (item) => item.resource_key),
|
||||
sectionsComplete(before, ["resources"]) &&
|
||||
sectionsComplete(after, ["resources"]),
|
||||
"Resource inventory was incomplete in at least one observation.",
|
||||
),
|
||||
network: dimension(
|
||||
networkMap(before),
|
||||
networkMap(after),
|
||||
sectionsComplete(before, ["network_requests"]) &&
|
||||
sectionsComplete(after, ["network_requests"]),
|
||||
"Network capture is attach-window limited or incomplete.",
|
||||
),
|
||||
metadata: dimension(
|
||||
singleton("metadata", digest(metadataProjection(before))),
|
||||
singleton("metadata", digest(metadataProjection(after))),
|
||||
sectionsComplete(before, ["metadata"]) &&
|
||||
sectionsComplete(after, ["metadata"]),
|
||||
"Safe metadata capture was incomplete in at least one observation.",
|
||||
),
|
||||
...contentDimensions(before, after, dimension),
|
||||
...runtimeDimensions(before, after, dimension),
|
||||
webmcp: dimension(
|
||||
webMcpMap(input.before.webmcp),
|
||||
webMcpMap(input.after.webmcp),
|
||||
@@ -153,10 +108,118 @@ export const compareWebCaptures = (
|
||||
limitations: [
|
||||
"A changed status proves an observed difference; an unknown status means absence could not be established from capture completeness.",
|
||||
"Network comparison covers only activity observed after each CDP attachment.",
|
||||
"Current-route comparison covers the observed final page URL; complete history alignment requires a session capture.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const createDimensionBuilder = (maxChanges: number): DimensionBuilder => {
|
||||
let remaining = maxChanges;
|
||||
return (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
complete: boolean,
|
||||
reason: string,
|
||||
): Dimension => {
|
||||
const all = compareIdentities(before, after);
|
||||
const retained = all.slice(0, remaining);
|
||||
remaining -= retained.length;
|
||||
return {
|
||||
status: all.length > 0 ? "changed" : complete ? "unchanged" : "unknown",
|
||||
total_changes: all.length,
|
||||
changes: retained,
|
||||
omitted_changes: all.length - retained.length,
|
||||
reason: all.length === 0 && !complete ? reason : null,
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
const contentDimensions = (
|
||||
before: WebPageInspection,
|
||||
after: WebPageInspection,
|
||||
dimension: DimensionBuilder,
|
||||
) => ({
|
||||
dom_structure: dimension(
|
||||
singleton("document", digest(domProjection(before))),
|
||||
singleton("document", digest(domProjection(after))),
|
||||
sectionsComplete(before, ["frames", "dom"]) &&
|
||||
sectionsComplete(after, ["frames", "dom"]),
|
||||
"DOM or frame capture was incomplete in at least one observation.",
|
||||
),
|
||||
scripts: dimension(
|
||||
keyed(
|
||||
before.scripts.items.map(scriptProjection),
|
||||
(item) => item.script_key,
|
||||
),
|
||||
keyed(after.scripts.items.map(scriptProjection), (item) => item.script_key),
|
||||
sectionsComplete(before, ["scripts"]) &&
|
||||
sectionsComplete(after, ["scripts"]),
|
||||
"Script inventory was incomplete in at least one observation.",
|
||||
),
|
||||
resources: dimension(
|
||||
keyed(before.resources, (item) => item.resource_key),
|
||||
keyed(after.resources, (item) => item.resource_key),
|
||||
sectionsComplete(before, ["resources"]) &&
|
||||
sectionsComplete(after, ["resources"]),
|
||||
"Resource inventory was incomplete in at least one observation.",
|
||||
),
|
||||
network: dimension(
|
||||
networkMap(before),
|
||||
networkMap(after),
|
||||
sectionsComplete(before, ["network_requests"]) &&
|
||||
sectionsComplete(after, ["network_requests"]),
|
||||
"Network capture is attach-window limited or incomplete.",
|
||||
),
|
||||
metadata: dimension(
|
||||
singleton("metadata", digest(metadataProjection(before))),
|
||||
singleton("metadata", digest(metadataProjection(after))),
|
||||
sectionsComplete(before, ["metadata"]) &&
|
||||
sectionsComplete(after, ["metadata"]),
|
||||
"Safe metadata capture was incomplete in at least one observation.",
|
||||
),
|
||||
});
|
||||
|
||||
const runtimeDimensions = (
|
||||
before: WebPageInspection,
|
||||
after: WebPageInspection,
|
||||
dimension: DimensionBuilder,
|
||||
) => ({
|
||||
accessibility: dimension(
|
||||
singleton("accessibility", digest(accessibilityProjection(before))),
|
||||
singleton("accessibility", digest(accessibilityProjection(after))),
|
||||
sectionsComplete(before, ["accessibility"]) &&
|
||||
sectionsComplete(after, ["accessibility"]),
|
||||
"Accessibility capture was unavailable or incomplete in at least one observation.",
|
||||
),
|
||||
storage: dimension(
|
||||
singleton("storage", digest(storageProjection(before))),
|
||||
singleton("storage", digest(storageProjection(after))),
|
||||
sectionsComplete(before, ["storage", "storage_keys"]) &&
|
||||
sectionsComplete(after, ["storage", "storage_keys"]),
|
||||
"Storage capture was unavailable or incomplete in at least one observation.",
|
||||
),
|
||||
console_errors: dimension(
|
||||
consoleErrorMap(before),
|
||||
consoleErrorMap(after),
|
||||
sectionsComplete(before, ["console_events"]) &&
|
||||
sectionsComplete(after, ["console_events"]),
|
||||
"Console-event capture is attach-window limited or incomplete.",
|
||||
),
|
||||
current_route: dimension(
|
||||
singleton("route", digest(before.target.url)),
|
||||
singleton("route", digest(after.target.url)),
|
||||
true,
|
||||
"",
|
||||
),
|
||||
lifecycle: dimension(
|
||||
singleton("lifecycle", digest(lifecycleProjection(before))),
|
||||
singleton("lifecycle", digest(lifecycleProjection(after))),
|
||||
sectionsComplete(before, ["frames", "workers"]) &&
|
||||
sectionsComplete(after, ["frames", "workers"]),
|
||||
"Frame or worker lifecycle capture was unavailable or incomplete.",
|
||||
),
|
||||
});
|
||||
|
||||
const compareIdentities = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
@@ -276,6 +339,68 @@ const metadataProjection = (inspection: WebPageInspection) => ({
|
||||
headers_allowlisted: inspection.metadata.headers_allowlisted,
|
||||
});
|
||||
|
||||
const accessibilityProjection = (inspection: WebPageInspection) => {
|
||||
const indexById = new Map(
|
||||
inspection.accessibility.nodes.map(({ node_id: id }, index) => [id, index]),
|
||||
);
|
||||
return {
|
||||
total_nodes: inspection.accessibility.total_nodes,
|
||||
text_capture: inspection.accessibility.text_capture,
|
||||
nodes: inspection.accessibility.nodes.map(
|
||||
({ node_id: _nodeId, parent_id: parentId, ...node }) => ({
|
||||
...node,
|
||||
parent_index:
|
||||
parentId === null ? null : (indexById.get(parentId) ?? -1),
|
||||
}),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const storageProjection = (inspection: WebPageInspection) => ({
|
||||
...inspection.storage,
|
||||
local_storage_keys: [...inspection.storage.local_storage_keys].sort(),
|
||||
session_storage_keys: [...inspection.storage.session_storage_keys].sort(),
|
||||
indexed_db_names: [...inspection.storage.indexed_db_names].sort(),
|
||||
cache_names: [...inspection.storage.cache_names].sort(),
|
||||
});
|
||||
|
||||
const consoleErrorMap = (
|
||||
inspection: WebPageInspection,
|
||||
): ReadonlyMap<string, string> => {
|
||||
const errors = inspection.console.events
|
||||
.filter(({ type }) => type === "error" || type === "assert")
|
||||
.map(({ timestamp: _timestamp, ...event }) => event);
|
||||
const counts = new Map<string, number>();
|
||||
for (const error of errors) {
|
||||
const fingerprint = digest(error);
|
||||
counts.set(fingerprint, (counts.get(fingerprint) ?? 0) + 1);
|
||||
}
|
||||
return new Map(
|
||||
[...counts].map(([fingerprint, count]) => [fingerprint, String(count)]),
|
||||
);
|
||||
};
|
||||
|
||||
const lifecycleProjection = (inspection: WebPageInspection) => ({
|
||||
frames: inspection.frames
|
||||
.map(
|
||||
({ frame_id: _frameId, parent_frame_id: _parentFrameId, ...frame }) =>
|
||||
frame,
|
||||
)
|
||||
.map((frame) => digest(frame))
|
||||
.sort(),
|
||||
workers: inspection.workers
|
||||
.map(
|
||||
({
|
||||
target_id: _targetId,
|
||||
opener_target_id: _openerTargetId,
|
||||
parent_frame_id: _parentFrameId,
|
||||
...worker
|
||||
}) => worker,
|
||||
)
|
||||
.map((worker) => digest(worker))
|
||||
.sort(),
|
||||
});
|
||||
|
||||
const singleton = (key: string, value: string): ReadonlyMap<string, string> =>
|
||||
new Map([[key, value]]);
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const responseSchema = z.union([
|
||||
type: z
|
||||
.enum([
|
||||
"remote",
|
||||
"analysis_in_progress",
|
||||
"authorization",
|
||||
"invalid_request",
|
||||
"bridge_exception",
|
||||
|
||||
@@ -15,6 +15,9 @@ import { registerNativeTools } from "./registerNativeTools.js";
|
||||
import { registerArtifactTools } from "./registerArtifactTools.js";
|
||||
import { registerManagedTools } from "./registerManagedTools.js";
|
||||
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
|
||||
import { registerAppleApplicationTools } from "./registerAppleApplicationTools.js";
|
||||
import { registerAndroidApplicationTools } from "./registerAndroidApplicationTools.js";
|
||||
import { registerRuntimeIdentificationTools } from "./registerRuntimeIdentificationTools.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
@@ -210,6 +213,24 @@ export const createServer = (
|
||||
authority: permissionAuthority,
|
||||
},
|
||||
});
|
||||
if (session !== undefined) {
|
||||
registerAppleApplicationTools(server, {
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
session,
|
||||
});
|
||||
registerAndroidApplicationTools(server, {
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
session,
|
||||
});
|
||||
}
|
||||
if (session !== undefined)
|
||||
registerRuntimeIdentificationTools(server, {
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
session,
|
||||
});
|
||||
registerBrowserTools(server, {
|
||||
logger: toolLogger,
|
||||
browser: options.browserObservation,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { projectAndroidApplicationEvidence } from "../application/AndroidApplicationService.js";
|
||||
import {
|
||||
ANDROID_APPLICATION_TOOL_CONTRACTS,
|
||||
androidApplicationReferenceInputSchema,
|
||||
} from "../contracts/androidApplicationToolContracts.js";
|
||||
import {
|
||||
registerInventoryEvidenceTool,
|
||||
type InventoryEvidenceToolRegistration,
|
||||
} from "./registerInventoryEvidenceTool.js";
|
||||
|
||||
/** Register the authenticated APK application projection workflow. */
|
||||
export const registerAndroidApplicationTools = (
|
||||
server: McpServer,
|
||||
options: InventoryEvidenceToolRegistration,
|
||||
): void =>
|
||||
registerInventoryEvidenceTool(server, options, {
|
||||
contract: ANDROID_APPLICATION_TOOL_CONTRACTS[0],
|
||||
inputSchema: androidApplicationReferenceInputSchema,
|
||||
derive: projectAndroidApplicationEvidence,
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { projectAppleApplicationEvidence } from "../application/AppleApplicationService.js";
|
||||
import {
|
||||
APPLE_APPLICATION_TOOL_CONTRACTS,
|
||||
appleApplicationReferenceInputSchema,
|
||||
} from "../contracts/appleApplicationToolContracts.js";
|
||||
import {
|
||||
registerInventoryEvidenceTool,
|
||||
type InventoryEvidenceToolRegistration,
|
||||
} from "./registerInventoryEvidenceTool.js";
|
||||
|
||||
/** Register the authenticated IPA application projection workflow. */
|
||||
export const registerAppleApplicationTools = (
|
||||
server: McpServer,
|
||||
options: InventoryEvidenceToolRegistration,
|
||||
): void =>
|
||||
registerInventoryEvidenceTool(server, options, {
|
||||
contract: APPLE_APPLICATION_TOOL_CONTRACTS[0],
|
||||
inputSchema: appleApplicationReferenceInputSchema,
|
||||
derive: projectAppleApplicationEvidence,
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
|
||||
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
|
||||
import { resolveSessionEvidenceIds } from "./sessionEvidence.js";
|
||||
import { resolveSessionEvidencePair } from "./sessionEvidence.js";
|
||||
import { ARTIFACT_COMPARISON_PROVIDER } from "./sessionToolPolicies.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
@@ -38,20 +38,22 @@ export const registerArtifactComparisonTool = (
|
||||
operation: "inventory_artifact",
|
||||
predicate: "rea.analysis/v2",
|
||||
};
|
||||
const left = resolveSessionEvidenceIds(
|
||||
const evidencePair = resolveSessionEvidencePair(
|
||||
session,
|
||||
parsed.left_evidence_ids,
|
||||
{
|
||||
left: parsed.left_evidence_ids,
|
||||
right: parsed.right_evidence_ids,
|
||||
},
|
||||
expected,
|
||||
);
|
||||
if (!left.ok) return toCallToolResult(left, contract);
|
||||
const right = resolveSessionEvidenceIds(
|
||||
session,
|
||||
parsed.right_evidence_ids,
|
||||
expected,
|
||||
);
|
||||
if (!right.ok) return toCallToolResult(right, contract);
|
||||
if (!evidencePair.ok) return toCallToolResult(evidencePair, contract);
|
||||
const computed = await runDerivedOperation(context, contract.name, () =>
|
||||
compareArtifacts(left.value, right.value, parsed.offset, parsed.limit),
|
||||
compareArtifacts(
|
||||
evidencePair.value.left,
|
||||
evidencePair.value.right,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
),
|
||||
);
|
||||
if (!computed.ok) return toCallToolResult(computed, contract);
|
||||
const comparison = computed.value;
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { RecordUnknownInput } from "../domain/residualUnknown.js";
|
||||
import { FUNCTION_COMPARISON_PROVIDER } from "./sessionToolPolicies.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
|
||||
import { resolveSessionEvidenceIds } from "./sessionEvidence.js";
|
||||
import { resolveSessionEvidencePair } from "./sessionEvidence.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { runDerivedOperation } from "./runDerivedOperation.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
@@ -38,22 +38,26 @@ export const registerFunctionComparisonTool = (
|
||||
operation: "analyze_function",
|
||||
predicate: "rea.analysis/v2",
|
||||
};
|
||||
const left = resolveSessionEvidenceIds(
|
||||
const evidencePair = resolveSessionEvidencePair(
|
||||
session,
|
||||
parsed.left_evidence_ids,
|
||||
{
|
||||
left: parsed.left_evidence_ids,
|
||||
right: parsed.right_evidence_ids,
|
||||
},
|
||||
expected,
|
||||
);
|
||||
if (!left.ok) return toCallToolResult(left, contract);
|
||||
const right = resolveSessionEvidenceIds(
|
||||
session,
|
||||
parsed.right_evidence_ids,
|
||||
expected,
|
||||
if (!evidencePair.ok) return toCallToolResult(evidencePair, contract);
|
||||
const leftIds = evidencePair.value.left.map(({ evidence_id: id }) => id);
|
||||
const rightIds = evidencePair.value.right.map(
|
||||
({ evidence_id: id }) => id,
|
||||
);
|
||||
if (!right.ok) return toCallToolResult(right, contract);
|
||||
const leftIds = left.value.map(({ evidence_id: id }) => id);
|
||||
const rightIds = right.value.map(({ evidence_id: id }) => id);
|
||||
const computed = await runDerivedOperation(context, contract.name, () =>
|
||||
compareFunctions(left.value, right.value, parsed.offset, parsed.limit),
|
||||
compareFunctions(
|
||||
evidencePair.value.left,
|
||||
evidencePair.value.right,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
),
|
||||
);
|
||||
if (!computed.ok) return toCallToolResult(computed, contract);
|
||||
const comparison = computed.value;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { resolveSessionEvidenceIds } from "./sessionEvidence.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
interface InventoryEvidenceReference {
|
||||
readonly inventory_evidence_ids: readonly string[];
|
||||
readonly limits: JsonValue;
|
||||
}
|
||||
|
||||
export interface InventoryEvidenceToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly session: BinarySessionPort;
|
||||
}
|
||||
|
||||
interface InventoryEvidenceToolDefinition {
|
||||
readonly contract: ToolContract;
|
||||
readonly inputSchema: z.ZodType<InventoryEvidenceReference>;
|
||||
readonly derive: (input: {
|
||||
readonly inventory_evidence: readonly Evidence[];
|
||||
readonly limits: JsonValue;
|
||||
}) => Result<Evidence, AnalysisError>;
|
||||
}
|
||||
|
||||
/** Register one pure workflow derived from session-owned artifact inventory Evidence. */
|
||||
export const registerInventoryEvidenceTool = (
|
||||
server: McpServer,
|
||||
options: InventoryEvidenceToolRegistration,
|
||||
definition: InventoryEvidenceToolDefinition,
|
||||
): void => {
|
||||
const { contract, inputSchema, derive } = definition;
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input) => {
|
||||
const parsed = safeParseToolInput(inputSchema, input, contract.name);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, contract);
|
||||
const resolved = resolveSessionEvidenceIds(
|
||||
options.session,
|
||||
parsed.value.inventory_evidence_ids,
|
||||
{ operation: "inventory_artifact", predicate: "rea.analysis/v2" },
|
||||
);
|
||||
if (!resolved.ok) return toCallToolResult(resolved, contract);
|
||||
const result = await logToolExecution(options.logger, contract.name, () =>
|
||||
Promise.resolve(
|
||||
derive({
|
||||
inventory_evidence: resolved.value,
|
||||
limits: parsed.value.limits,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
for (const source of resolved.value) {
|
||||
const recordedSource = options.recordEvidence?.(source);
|
||||
if (recordedSource !== undefined && !recordedSource.ok)
|
||||
return toCallToolResult(recordedSource, contract);
|
||||
}
|
||||
const recorded = options.recordEvidence?.(result.value);
|
||||
if (recorded !== undefined && !recorded.ok)
|
||||
return toCallToolResult(recorded, contract);
|
||||
return toCallToolResult(result, contract, {
|
||||
evidenceResourcesAvailable: recorded !== undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -20,7 +20,7 @@ import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { runDerivedOperation } from "./runDerivedOperation.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { resolveSessionEvidenceIds } from "./sessionEvidence.js";
|
||||
import { resolveSessionEvidencePair } from "./sessionEvidence.js";
|
||||
|
||||
/** Register deterministic process-capture comparison and contradiction tracking. */
|
||||
export const registerProcessComparisonTool = (
|
||||
@@ -44,27 +44,24 @@ export const registerProcessComparisonTool = (
|
||||
operation: "capture_process_scenario",
|
||||
predicate: "rea.process-capture/v4",
|
||||
};
|
||||
const leftRecord = resolveSessionEvidenceIds(
|
||||
const evidencePair = resolveSessionEvidencePair(
|
||||
session,
|
||||
[parsed.left_evidence_id],
|
||||
{
|
||||
left: [parsed.left_evidence_id],
|
||||
right: [parsed.right_evidence_id],
|
||||
},
|
||||
expected,
|
||||
);
|
||||
if (!leftRecord.ok) return toCallToolResult(leftRecord, contract);
|
||||
const rightRecord = resolveSessionEvidenceIds(
|
||||
session,
|
||||
[parsed.right_evidence_id],
|
||||
expected,
|
||||
);
|
||||
if (!rightRecord.ok) return toCallToolResult(rightRecord, contract);
|
||||
if (!evidencePair.ok) return toCallToolResult(evidencePair, contract);
|
||||
let comparison: ReturnType<typeof compareProcessCaptures>;
|
||||
let leftCapture: ReturnType<typeof parseProcessCapture>;
|
||||
let rightCapture: ReturnType<typeof parseProcessCapture>;
|
||||
try {
|
||||
leftCapture = parseProcessCapture(
|
||||
leftRecord.value[0]?.normalized_result,
|
||||
evidencePair.value.left[0]?.normalized_result,
|
||||
);
|
||||
rightCapture = parseProcessCapture(
|
||||
rightRecord.value[0]?.normalized_result,
|
||||
evidencePair.value.right[0]?.normalized_result,
|
||||
);
|
||||
const computed = await runDerivedOperation(context, contract.name, () =>
|
||||
compareProcessCaptures(leftCapture, rightCapture, {
|
||||
@@ -89,7 +86,7 @@ export const registerProcessComparisonTool = (
|
||||
);
|
||||
}
|
||||
const evidence = createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
predicateType: "rea.process-comparison/v4",
|
||||
operation: contract.name,
|
||||
parameters: {
|
||||
left_evidence_id: parsed.left_evidence_id,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { identifyRuntimeEvidence } from "../application/RuntimeIdentificationService.js";
|
||||
import {
|
||||
RUNTIME_IDENTIFICATION_TOOL_CONTRACTS,
|
||||
runtimeIdentificationReferenceInputSchema,
|
||||
} from "../contracts/runtimeIdentificationToolContracts.js";
|
||||
import {
|
||||
registerInventoryEvidenceTool,
|
||||
type InventoryEvidenceToolRegistration,
|
||||
} from "./registerInventoryEvidenceTool.js";
|
||||
|
||||
/** Register provider-neutral runtime identification over session Evidence. */
|
||||
export const registerRuntimeIdentificationTools = (
|
||||
server: McpServer,
|
||||
options: InventoryEvidenceToolRegistration,
|
||||
): void =>
|
||||
registerInventoryEvidenceTool(server, options, {
|
||||
contract: RUNTIME_IDENTIFICATION_TOOL_CONTRACTS[0],
|
||||
inputSchema: runtimeIdentificationReferenceInputSchema,
|
||||
derive: identifyRuntimeEvidence,
|
||||
});
|
||||
@@ -12,21 +12,29 @@ import { buildCapabilityInventory } from "../application/CapabilityInventory.js"
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
|
||||
/** Register the read-only provider and target status operation. */
|
||||
export const registerSessionStatusTool = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
contract: (typeof SESSION_TOOL_CONTRACTS)[2],
|
||||
startedAt: string,
|
||||
availabilityPolicy: () => {
|
||||
interface SessionStatusToolRegistration {
|
||||
readonly server: McpServer;
|
||||
readonly session: BinarySessionPort;
|
||||
readonly contract: (typeof SESSION_TOOL_CONTRACTS)[2];
|
||||
readonly startedAt: string;
|
||||
readonly availabilityPolicy: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
readonly javascriptReplayEnabled?: boolean;
|
||||
readonly managedRuntimeEnabled?: boolean;
|
||||
},
|
||||
): void => {
|
||||
};
|
||||
}
|
||||
|
||||
/** Register the read-only provider and target status operation. */
|
||||
export const registerSessionStatusTool = ({
|
||||
server,
|
||||
session,
|
||||
contract,
|
||||
startedAt,
|
||||
availabilityPolicy,
|
||||
}: SessionStatusToolRegistration): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
|
||||
@@ -582,13 +582,13 @@ const registerLifecycleTools = ({
|
||||
return toCallToolResult(closed, closeContract);
|
||||
},
|
||||
);
|
||||
registerSessionStatusTool(
|
||||
registerSessionStatusTool({
|
||||
server,
|
||||
session,
|
||||
statusContract,
|
||||
contract: statusContract,
|
||||
startedAt,
|
||||
availabilityPolicy,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
/** Register MCP-only target lifecycle operations on a long-lived session. */
|
||||
|
||||
@@ -8,6 +8,11 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type EvidenceAuthorityResult = Result<Evidence[], EvidenceIntegrityError>;
|
||||
|
||||
type EvidencePairAuthorityResult = Result<
|
||||
{ readonly left: Evidence[]; readonly right: Evidence[] },
|
||||
EvidenceIntegrityError
|
||||
>;
|
||||
|
||||
/** Resolve bounded IDs to authoritative records with exact semantic identity. */
|
||||
export const resolveSessionEvidenceIds = (
|
||||
session: BinarySessionPort,
|
||||
@@ -48,3 +53,19 @@ export const resolveSessionEvidenceIds = (
|
||||
}
|
||||
return ok(records);
|
||||
};
|
||||
|
||||
/** Resolve both sides of a comparison under one semantic authority contract. */
|
||||
export const resolveSessionEvidencePair = (
|
||||
session: BinarySessionPort,
|
||||
evidenceIds: {
|
||||
readonly left: readonly string[];
|
||||
readonly right: readonly string[];
|
||||
},
|
||||
expected: { readonly operation: string; readonly predicate: string },
|
||||
): EvidencePairAuthorityResult => {
|
||||
const left = resolveSessionEvidenceIds(session, evidenceIds.left, expected);
|
||||
if (!left.ok) return left;
|
||||
const right = resolveSessionEvidenceIds(session, evidenceIds.right, expected);
|
||||
if (!right.ok) return right;
|
||||
return ok({ left: left.value, right: right.value });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user