refactor: remove abandoned test-only analysis scaffolding

This commit is contained in:
morluto
2026-10-08 04:03:23 +08:00
parent 984fc27ce1
commit c93422a898
30 changed files with 8 additions and 3932 deletions
@@ -1,16 +0,0 @@
import { realpath } from "node:fs/promises";
import {
scanCanonicalArtifactInventory,
type ArtifactInventoryOptions,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
/** Resolve, authorize, and scan one artifact without a second path resolution. */
export const scanAuthorizedArtifactInventory = async (
inputPath: string,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(path, options);
};
-144
View File
@@ -1,144 +0,0 @@
import { randomUUID } from "node:crypto";
import {
lstat,
mkdtemp,
open,
readdir,
rename,
rm,
rmdir,
unlink,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
/** One acquired store transaction lock with cleanup bound to its unique owner. */
export interface StoreFileLock {
readonly release: () => Promise<void>;
}
class StoreFileLockOccupied extends Error {
readonly code = "EEXIST";
constructor(cause?: unknown) {
super("Store transaction lock is occupied", { cause });
}
}
/** Atomically publish a populated directory so another owner cannot replace a live lock. */
export const createStoreFileLock = async (
path: string,
): Promise<StoreFileLock> => {
if (await exists(path)) throw new StoreFileLockOccupied();
const staged = await mkdtemp(join(dirname(path), ".rea-store-lock-"));
const owner = `owner-${randomUUID()}`;
try {
const handle = await open(join(staged, owner), "wx", 0o600);
try {
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
await handle.sync();
} finally {
await handle.close();
}
try {
// Rename cannot replace a nonempty directory: the owner entry is present before publication.
await rename(staged, path);
} catch (cause: unknown) {
if (await exists(path)) throw new StoreFileLockOccupied(cause);
throw cause;
}
return {
release: async () => {
await removeOwner(path, owner).catch((cause: unknown) => {
// best-effort cleanup: lock release must not reject unhandled.
void cause;
});
},
};
} finally {
await rm(staged, { recursive: true, force: true });
}
};
/** Recover a dead owner's directory lock or a legacy PID file; leave live and unknown owners intact. */
export const removeStaleStoreFileLock = async (
path: string,
): Promise<boolean> => {
try {
const stats = await lstat(path);
if (stats.isFile()) {
if (!(await ownerIsDead(path))) return false;
await unlink(path);
return true;
}
if (!stats.isDirectory()) return false;
const entries = await readdir(path);
if (entries.length === 0) {
await rmdir(path);
return true;
}
const owner = entries[0];
if (
entries.length !== 1 ||
owner === undefined ||
!/^owner-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(owner) ||
!(await ownerIsDead(join(path, owner)))
)
return false;
await removeOwner(path, owner);
return true;
} catch (cause: unknown) {
// best-effort cleanup: stale lock probing; failure means the lock stands.
void cause;
return false;
}
};
const removeOwner = async (path: string, owner: string): Promise<void> => {
// A successor has a different entry, so stale cleanup cannot make its directory empty.
await unlink(join(path, owner));
await rmdir(path);
};
const ownerIsDead = async (path: string): Promise<boolean> => {
const stats = await lstat(path);
if (!stats.isFile() || stats.size > 32) return false;
const handle = await open(path, "r");
let bytes: Buffer | undefined;
try {
bytes = await readBoundedFileBytes(handle, 32);
} finally {
await handle.close();
}
const encoded = bytes?.toString("utf8").trim();
return (
encoded !== undefined &&
/^[1-9][0-9]{0,9}$/u.test(encoded) &&
!processIsAlive(Number(encoded))
);
};
const exists = async (path: string): Promise<boolean> => {
try {
await lstat(path);
return true;
} catch (cause: unknown) {
if (errorCode(cause) === "ENOENT") return false;
throw cause;
}
};
const processIsAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
return errorCode(cause) !== "ESRCH";
}
};
const errorCode = (cause: unknown): unknown =>
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
-160
View File
@@ -1,160 +0,0 @@
import { describe, expect, it } from "vitest";
import {
analyzeBytecodeArtifacts,
bytecodeAnalysisSchema,
classifyProvenance,
detectArtifactFormat,
detectBytecodeFamily,
type BytecodeArtifact,
} from "./bytecodeProvider.js";
describe("bytecode provider", () => {
it("detects JVM family from extensions", () => {
expect(detectBytecodeFamily("App.class")).toBe("jvm");
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
});
it("detects Python family from extensions", () => {
expect(detectBytecodeFamily("module.pyc")).toBe("python");
expect(detectBytecodeFamily("module.pyo")).toBe("python");
expect(detectBytecodeFamily("package.whl")).toBe("python");
expect(detectBytecodeFamily("app.pyz")).toBe("python");
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
});
it("returns null for unknown extensions", () => {
expect(detectBytecodeFamily("readme.txt")).toBeNull();
expect(detectBytecodeFamily("script.js")).toBeNull();
});
it("detects artifact format from path", () => {
expect(detectArtifactFormat("App.class")).toBe("class");
expect(detectArtifactFormat("lib.jar")).toBe("jar");
expect(detectArtifactFormat("web.war")).toBe("war");
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
});
it("classifies standard library provenance", () => {
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
"standard_library",
);
expect(
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
).toBe("standard_library");
});
it("classifies generated provenance", () => {
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
"generated",
);
expect(
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
).toBe("generated");
});
it("classifies vendored provenance", () => {
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
"vendored",
);
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
"vendored",
);
});
it("classifies application provenance", () => {
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
"application",
);
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
});
it("analyzes bytecode artifacts and computes summary", () => {
const artifacts: BytecodeArtifact[] = [
{
path: "src/App.class",
family: "jvm",
format: "class",
size: 1000,
digest: "a".repeat(64),
symbols: [
{
name: "com.example.App",
raw_location: "0x1000",
kind: "class",
bytecode_version: 52,
provenance: "application",
is_public: true,
},
{
name: "java.lang.String",
raw_location: "0x2000",
kind: "class",
bytecode_version: 52,
provenance: "standard_library",
is_public: true,
},
],
is_standard_library: false,
is_generated: false,
is_vendored: false,
},
{
path: "lib/generated/Generated.class",
family: "jvm",
format: "class",
size: 500,
digest: "b".repeat(64),
symbols: [
{
name: "GeneratedClass",
raw_location: "0x3000",
kind: "class",
bytecode_version: 52,
provenance: "generated",
is_public: false,
},
],
is_standard_library: false,
is_generated: true,
is_vendored: false,
},
];
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.family).toBe("jvm");
expect(result.total_symbols).toBe(3);
expect(result.application_symbols).toBe(1);
expect(result.standard_library_symbols).toBe(1);
expect(result.generated_symbols).toBe(1);
expect(result.vendored_symbols).toBe(0);
// Validate schema
const parsed = bytecodeAnalysisSchema.safeParse(result);
expect(parsed.success).toBe(true);
});
it("returns every artifact when the inventory exceeds ten thousand entries", () => {
const artifacts = Array.from({ length: 10_001 }, (_, index) => ({
path: `classes/${index}.class`,
family: "jvm" as const,
format: "class" as const,
size: 1,
digest: "a".repeat(64),
symbols: [],
is_standard_library: false,
is_generated: false,
is_vendored: false,
}));
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.artifacts).toHaveLength(artifacts.length);
expect(bytecodeAnalysisSchema.parse(result).artifacts).toHaveLength(
artifacts.length,
);
});
});
-204
View File
@@ -1,204 +0,0 @@
import { z } from "zod";
/** Supported managed-runtime bytecode families. */
export const bytecodeFamilySchema = z.enum(["jvm", "python"]);
export type BytecodeFamily = z.infer<typeof bytecodeFamilySchema>;
/** Classification of bytecode provenance. */
export const bytecodeProvenanceSchema = z.enum([
"application",
"generated",
"vendored",
"bundled",
"standard_library",
]);
export type BytecodeProvenance = z.infer<typeof bytecodeProvenanceSchema>;
/** A bytecode symbol discovered through static analysis. */
export const bytecodeSymbolSchema = z.strictObject({
/** Fully qualified name. */
name: z.string().min(1),
/** Raw bytecode location or offset. */
raw_location: z.string().min(1),
/** Normalized symbol type. */
kind: z.enum([
"class",
"interface",
"method",
"field",
"function",
"module",
"variable",
]),
/** Bytecode version if known. */
bytecode_version: z.number().int().nullable(),
/** Provenance classification. */
provenance: bytecodeProvenanceSchema,
/** Whether the symbol is accessible (public). */
is_public: z.boolean().default(false),
});
/** A discovered bytecode artifact (class file, wheel, etc). */
export const bytecodeArtifactSchema = z.strictObject({
/** Artifact path relative to the analysis root. */
path: z.string().min(1),
/** Bytecode family. */
family: bytecodeFamilySchema,
/** Artifact format. */
format: z.enum(["class", "jar", "war", "ear", "pyc", "pyo", "whl", "zipapp"]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z.string().regex(/^[a-f0-9]{64}$/u),
/** Discovered symbols. */
symbols: z.array(bytecodeSymbolSchema).default([]),
/** Whether this is a standard library artifact. */
is_standard_library: z.boolean().default(false),
/** Whether this is a generated artifact. */
is_generated: z.boolean().default(false),
/** Whether this is a vendored artifact. */
is_vendored: z.boolean().default(false),
});
export type BytecodeArtifact = z.infer<typeof bytecodeArtifactSchema>;
/** Static bytecode analysis result. */
export const bytecodeAnalysisSchema = z.strictObject({
/** Bytecode family. */
family: bytecodeFamilySchema,
/** All discovered artifacts. */
artifacts: z.array(bytecodeArtifactSchema),
/** Total symbols across all artifacts. */
total_symbols: z.number().int().nonnegative(),
/** Symbols classified as application code. */
application_symbols: z.number().int().nonnegative(),
/** Symbols classified as generated code. */
generated_symbols: z.number().int().nonnegative(),
/** Symbols classified as vendored code. */
vendored_symbols: z.number().int().nonnegative(),
/** Symbols classified as standard library. */
standard_library_symbols: z.number().int().nonnegative(),
});
export type BytecodeAnalysis = z.infer<typeof bytecodeAnalysisSchema>;
/** Detect bytecode family from file extension. */
export function detectBytecodeFamily(path: string): BytecodeFamily | null {
const lower = path.toLowerCase();
if (
lower.endsWith(".class") ||
lower.endsWith(".jar") ||
lower.endsWith(".war") ||
lower.endsWith(".ear")
) {
return "jvm";
}
if (
lower.endsWith(".pyc") ||
lower.endsWith(".pyo") ||
lower.endsWith(".whl") ||
lower.endsWith(".pyz") ||
lower.endsWith(".zipapp")
) {
return "python";
}
return null;
}
/** Detect artifact format from file path. */
export function detectArtifactFormat(
path: string,
): `class` | `jar` | `war` | `ear` | `pyc` | `pyo` | `whl` | `zipapp` | null {
const lower = path.toLowerCase();
if (lower.endsWith(".class")) return "class";
if (lower.endsWith(".jar")) return "jar";
if (lower.endsWith(".war")) return "war";
if (lower.endsWith(".ear")) return "ear";
if (lower.endsWith(".pyc")) return "pyc";
if (lower.endsWith(".pyo")) return "pyo";
if (lower.endsWith(".whl")) return "whl";
if (lower.endsWith(".pyz") || lower.endsWith(".zipapp")) return "zipapp";
return null;
}
const STANDARD_LIBRARY_PATH_MARKERS = [
"/stdlib/",
"/site-packages/",
"java/",
"javax/",
"sun/",
];
const STANDARD_LIBRARY_SYMBOL_MARKERS = ["java.", "javax.", "sun.", "__"];
const GENERATED_PATH_MARKERS = [
"/generated/",
"_generated",
"/build/",
"/target/",
"/dist-packages/",
"/__pycache__/",
];
const GENERATED_SYMBOL_MARKERS = ["Generated", "_generated"];
const VENDORED_PATH_MARKERS = [
"/vendor/",
"/vendored/",
"/third_party/",
"/3rdparty/",
"/node_modules/",
];
const BUNDLED_PATH_MARKERS = ["/bundle/", "/bundled/", ".jar!", ".war!"];
const includesAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.includes(marker));
const startsWithAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.startsWith(marker));
/** Classify bytecode symbol provenance. */
export function classifyProvenance(
path: string,
symbolName: string,
): BytecodeProvenance {
const lower = path.toLowerCase();
if (
includesAny(lower, STANDARD_LIBRARY_PATH_MARKERS) ||
startsWithAny(symbolName, STANDARD_LIBRARY_SYMBOL_MARKERS)
)
return "standard_library";
if (
includesAny(lower, GENERATED_PATH_MARKERS) ||
includesAny(symbolName, GENERATED_SYMBOL_MARKERS)
)
return "generated";
if (includesAny(lower, VENDORED_PATH_MARKERS)) return "vendored";
if (includesAny(lower, BUNDLED_PATH_MARKERS)) return "bundled";
return "application";
}
/** Analyze a set of bytecode artifacts and produce a summary. */
export function analyzeBytecodeArtifacts(
artifacts: readonly BytecodeArtifact[],
family: BytecodeFamily,
): BytecodeAnalysis {
const totals = artifacts.reduce(
(counts, artifact) => {
counts.total += artifact.symbols.length;
for (const symbol of artifact.symbols) counts[symbol.provenance] += 1;
return counts;
},
{
total: 0,
application: 0,
generated: 0,
vendored: 0,
standard_library: 0,
bundled: 0,
},
);
return {
family,
artifacts: [...artifacts],
total_symbols: totals.total,
application_symbols: totals.application,
generated_symbols: totals.generated,
vendored_symbols: totals.vendored,
standard_library_symbols: totals.standard_library,
};
}
-86
View File
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vitest";
import {
bundleClassificationToCanonical,
comparisonConclusionSchema,
comparisonStatusSchema,
functionStatusToCanonical,
scenarioArtifactStatusToCanonical,
sourceToBundleStatusToCanonical,
} from "./comparisonStatus.js";
describe("comparison status vocabulary", () => {
it("owns the canonical unchanged/changed/unknown triple", () => {
expect(comparisonStatusSchema.options).toEqual([
"unchanged",
"changed",
"unknown",
]);
expect(comparisonConclusionSchema.options).toEqual([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
});
it("projects every bundle classification", () => {
expect(
(
[
"added",
"removed",
"changed",
"unknown",
"history_advanced",
"history_diverged",
] as const
).map(bundleClassificationToCanonical),
).toEqual([
"changed",
"changed",
"changed",
"unknown",
"changed",
"changed",
]);
});
it("projects every source-to-bundle item status", () => {
expect(
(
[
"unchanged",
"modified",
"removed",
"split",
"merged",
"duplicated",
"unknown",
] as const
).map(sourceToBundleStatusToCanonical),
).toEqual([
"unchanged",
"changed",
"changed",
"changed",
"changed",
"changed",
"unknown",
]);
});
it("projects every function dimension status without claiming truncated work", () => {
expect(
(["unchanged", "changed", "truncated", "unknown"] as const).map(
functionStatusToCanonical,
),
).toEqual(["unchanged", "changed", "unknown", "unknown"]);
});
it("projects every scenario artifact status", () => {
expect(
(["changed", "unknown"] as const).map(scenarioArtifactStatusToCanonical),
).toEqual(["changed", "unknown"]);
});
});
+2 -60
View File
@@ -2,69 +2,11 @@ import { z } from "zod";
/**
* Canonical top-level comparison outcome shared by every comparison
* pipeline. Pipeline-native detail enums (bundle classifications,
* source-to-bundle split/merge kinds, scenario alignment states, function
* truncation) keep their wire schemas; the mappers below project each of
* them onto this triple without changing any pipeline result.
* pipeline. Pipeline-native detail enums keep their wire schemas, while
* shared result contracts use this canonical triple.
*/
export const comparisonStatusSchema = z.enum([
"unchanged",
"changed",
"unknown",
]);
export type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
/** Canonical comparison conclusion shared by every comparison pipeline. */
export const comparisonConclusionSchema = z.enum([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
/** Project a bundle change classification onto the canonical triple. */
export const bundleClassificationToCanonical = (
classification:
| "added"
| "removed"
| "changed"
| "unknown"
| "history_advanced"
| "history_diverged",
): ComparisonStatus => (classification === "unknown" ? "unknown" : "changed");
/** Project a source-to-bundle item status onto the canonical triple. */
export const sourceToBundleStatusToCanonical = (
status:
| "unchanged"
| "modified"
| "removed"
| "split"
| "merged"
| "duplicated"
| "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "unknown"
? "unknown"
: "changed";
/**
* Project a function dimension status onto the canonical triple. A
* truncated dimension cannot support an unchanged/changed claim.
*/
export const functionStatusToCanonical = (
status: "unchanged" | "changed" | "truncated" | "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "changed"
? "changed"
: "unknown";
/** Project a browser-scenario artifact status onto the canonical triple. */
export const scenarioArtifactStatusToCanonical = (
status: "changed" | "unknown",
): ComparisonStatus => status;
-18
View File
@@ -51,19 +51,6 @@ const VOLATILE_DIMENSIONS = new Set([
"updated_at",
]);
/** Dimension that carries semantic content. */
const SEMANTIC_DIMENSIONS = new Set([
"exit_code",
"stdout",
"stderr",
"filesystem",
"process",
"process_tree",
"shim_events",
"protocol_events",
"event_journal",
]);
type IncompleteStatus = "unknown" | "truncated";
type EvidenceView = {
@@ -214,11 +201,6 @@ export function isVolatileDimension(name: string): boolean {
return VOLATILE_DIMENSIONS.has(name);
}
/** Check if a dimension name carries semantic content. */
export function isSemanticDimension(name: string): boolean {
return SEMANTIC_DIMENSIONS.has(name);
}
/**
* Compare two values for a dimension, classifying semantic diffs
* from timing/normalization noise.
-158
View File
@@ -1,158 +0,0 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
authEventsByProtocol,
authFlowDuration,
customProtocolCaptureSchema,
correlateProcessIdentity,
failedAuthEvents,
framesByTransport,
looksLikeCredentialFrame,
successfulAuthEvents,
type AuthFlowEvent,
type ProtocolFrame,
} from "./customProtocolCapture.js";
const sampleFrames: ProtocolFrame[] = [
{
sequence: 0,
at_ms: 100,
transport: "tcp",
direction: "sent",
source_pid: 100,
dest_pid: 200,
source_endpoint: "127.0.0.1:8080",
dest_endpoint: "127.0.0.1:9090",
raw_data: "hello",
decoded_content: "hello",
size: 5,
truncated: false,
},
{
sequence: 1,
at_ms: 200,
transport: "udp",
direction: "received",
source_pid: 200,
dest_pid: 100,
source_endpoint: "127.0.0.1:9090",
dest_endpoint: "127.0.0.1:8080",
raw_data: "world",
decoded_content: "world",
size: 5,
truncated: false,
},
];
const sampleAuthEvents: AuthFlowEvent[] = [
{
sequence: 0,
at_ms: 100,
stage: "init",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: false,
error: null,
},
{
sequence: 1,
at_ms: 500,
stage: "success",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: true,
error: null,
},
];
describe("custom protocol capture", () => {
it("rejects a capture with an unknown transport", () => {
const result = customProtocolCaptureSchema.safeParse({
transport: "carrier-pigeon",
frames: sampleFrames,
auth_events: sampleAuthEvents,
has_truncated: false,
credentials_detected: false,
});
expect(result.success).toBe(false);
});
it("retains every captured frame at any size", () => {
fc.assert(
fc.property(
// The bound must sit well above any ceiling a future change would
// plausibly introduce. A generated length of 40 would pass unnoticed
// against a cap at 100, so the generated arrays cross 1,000.
fc.array(fc.constant(sampleFrames[0]!), {
minLength: 300,
maxLength: 1_000,
}),
(frames) => {
const parsed = customProtocolCaptureSchema.parse({
transport: "tcp",
frames: frames.map((frame, sequence) => ({ ...frame, sequence })),
});
expect(parsed.frames).toHaveLength(frames.length);
},
),
{ numRuns: 25 },
);
});
it("correlates process identity", () => {
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
});
it("filters frames by transport", () => {
const tcpFrames = framesByTransport(sampleFrames, "tcp");
expect(tcpFrames).toHaveLength(1);
const udpFrames = framesByTransport(sampleFrames, "udp");
expect(udpFrames).toHaveLength(1);
});
it("detects credential-like frames", () => {
const credFrame: ProtocolFrame = {
...sampleFrames[0]!,
decoded_content: { password: "secret" },
};
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
});
it("filters auth events by protocol", () => {
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
expect(oauthEvents).toHaveLength(2);
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
expect(otherEvents).toHaveLength(0);
});
it("gets successful auth events", () => {
const success = successfulAuthEvents(sampleAuthEvents);
expect(success).toHaveLength(1);
expect(success[0]!.succeeded).toBe(true);
});
it("gets failed auth events", () => {
const failed = failedAuthEvents(sampleAuthEvents);
expect(failed).toHaveLength(1);
expect(failed[0]!.succeeded).toBe(false);
});
it("computes auth flow duration", () => {
const duration = authFlowDuration(sampleAuthEvents);
expect(duration).toBe(400);
});
it("returns null for empty auth events", () => {
expect(authFlowDuration([])).toBeNull();
});
});
-169
View File
@@ -1,169 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Supported transport types for custom protocol capture. */
export const transportTypeSchema = z.enum([
"tcp",
"udp",
"ipc",
"unix-socket",
"named-pipe",
"xpc",
]);
export type TransportType = z.infer<typeof transportTypeSchema>;
/** Direction of a protocol frame. */
export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
/** A captured protocol frame. */
export const protocolFrameSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Transport type. */
transport: transportTypeSchema,
/** Direction of the frame. */
direction: frameDirectionSchema,
/** Source process identity. */
source_pid: z.number().int().nullable(),
/** Destination process identity. */
dest_pid: z.number().int().nullable(),
/** Endpoint address (IP:port, socket path, pipe name). */
source_endpoint: z.string().nullable(),
/** Destination endpoint. */
dest_endpoint: z.string().nullable(),
/** Raw frame data as base64. */
raw_data: z.string().nullable(),
/** Decoded/parsed frame content if known. */
decoded_content: jsonValueSchema.nullable(),
/** Frame size in bytes. */
size: z.number().int().nonnegative(),
/** Whether the frame was truncated. */
truncated: z.boolean().default(false),
});
export type ProtocolFrame = z.infer<typeof protocolFrameSchema>;
/** Authentication flow stage. */
export const authStageSchema = z.enum([
"init",
"challenge",
"response",
"token_exchange",
"renewal",
"revocation",
"failure",
"success",
]);
/** Token lifecycle event. */
export const tokenLifecycleEventSchema = z.enum([
"issued",
"refreshed",
"expired",
"revoked",
"renewed",
]);
/** A captured authentication flow event. */
export const authFlowEventSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Authentication stage. */
stage: authStageSchema,
/** Protocol used. */
protocol: z.string().min(1),
/** Token type if applicable. */
token_type: z.string().nullable(),
/** Token lifecycle event. */
token_lifecycle: tokenLifecycleEventSchema.nullable(),
/** Correlation ID linking challenge-response pairs. */
correlation_id: z.string().nullable(),
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
/** Whether the authentication succeeded. */
succeeded: z.boolean().default(false),
/** Error message if authentication failed. */
error: z.string().nullable(),
});
export type AuthFlowEvent = z.infer<typeof authFlowEventSchema>;
/** A captured protocol session. */
export const customProtocolCaptureSchema = z.strictObject({
/** Transport type for this session. */
transport: transportTypeSchema,
/** Captured frames in order. */
frames: z.array(protocolFrameSchema),
/** Authentication flow events. */
auth_events: z.array(authFlowEventSchema).default([]),
/** Whether any frame was truncated. */
has_truncated: z.boolean().default(false),
/** Whether the capture producer detected credential content. */
credentials_detected: z.boolean().default(false),
});
/** Correlate a frame with process identity. */
export function correlateProcessIdentity(
frame: ProtocolFrame,
pid: number,
): boolean {
return frame.source_pid === pid || frame.dest_pid === pid;
}
/** Check if a frame contains credential-like content. */
export function looksLikeCredentialFrame(frame: ProtocolFrame): boolean {
const patterns = [
"password",
"token",
"secret",
"api_key",
"apikey",
"authorization",
"credential",
];
const content = JSON.stringify(frame.decoded_content ?? "").toLowerCase();
return patterns.some((p) => content.includes(p));
}
/** Filter frames by transport type. */
export function framesByTransport(
frames: readonly ProtocolFrame[],
transport: TransportType,
): ProtocolFrame[] {
return frames.filter((f) => f.transport === transport);
}
/** Get all authentication flow events for a specific protocol. */
export function authEventsByProtocol(
events: readonly AuthFlowEvent[],
protocol: string,
): AuthFlowEvent[] {
return events.filter((e) => e.protocol === protocol);
}
/** Get successful authentication events. */
export function successfulAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => e.succeeded);
}
/** Get failed authentication events. */
export function failedAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => !e.succeeded);
}
/** Compute the duration of an authentication flow in milliseconds. */
export function authFlowDuration(
events: readonly AuthFlowEvent[],
): number | null {
const first = events.at(0);
const last = events.at(-1);
if (first === undefined || last === undefined) return null;
return last.at_ms - first.at_ms;
}
@@ -1,131 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyMobileResource,
detectMobileFormat,
detectPlatform,
getAllArchitectures,
hasInternetPermission,
mobileArtifactManifestSchema,
nativeLibsByArchitecture,
type MobileArtifactManifest,
type AndroidManifest,
type SigningInfo,
type NativeLibrary,
type MobileResource,
} from "./mobileApplicationInvestigation.js";
describe("mobile application investigation", () => {
it("detects mobile format from extension", () => {
expect(detectMobileFormat("app.apk")).toBe("apk");
expect(detectMobileFormat("app.aab")).toBe("aab");
expect(detectMobileFormat("app.ipa")).toBe("ipa");
expect(detectMobileFormat("classes.dex")).toBe("dex");
expect(detectMobileFormat("lib.so")).toBe("native_lib");
expect(detectMobileFormat("readme.txt")).toBeNull();
});
it("detects platform from format", () => {
expect(detectPlatform("apk")).toBe("android");
expect(detectPlatform("aab")).toBe("android");
expect(detectPlatform("dex")).toBe("android");
expect(detectPlatform("ipa")).toBe("ios");
expect(detectPlatform("native_lib")).toBe("cross_platform");
});
it("classifies resources by path", () => {
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
expect(classifyMobileResource("assets/data.json")).toBe("asset");
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
"native_lib",
);
expect(classifyMobileResource("unknown.xyz")).toBe("other");
});
const androidManifest: AndroidManifest = {
package_name: "com.example.app",
version_name: "1.0.0",
version_code: 1,
min_sdk: 21,
target_sdk: 34,
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
activities: ["MainActivity"],
services: ["BackgroundService"],
receivers: [],
providers: [],
};
const signing: SigningInfo = {
is_signed: true,
signer_identity: "CN=TestSigner",
certificate_fingerprint: "abc123",
signature_scheme: "v2",
is_debuggable: false,
};
const nativeLibs: NativeLibrary[] = [
{
path: "lib/arm64-v8a/libnative.so",
architecture: "arm64-v8a",
size: 100000,
digest: "a".repeat(64),
},
{
path: "lib/armeabi-v7a/libnative.so",
architecture: "armeabi-v7a",
size: 90000,
digest: "b".repeat(64),
},
];
const resources: MobileResource[] = [
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
];
const validManifest: MobileArtifactManifest = {
format: "apk",
platform: "android",
app_name: "TestApp",
android_manifest: androidManifest,
ios_manifest: null,
signing,
resources,
native_libraries: nativeLibs,
total_size: 5000000,
architectures: ["arm64-v8a", "armeabi-v7a"],
};
it("rejects a manifest with a negative total size", () => {
const result = mobileArtifactManifestSchema.safeParse({
...validManifest,
total_size: -1,
});
expect(result.success).toBe(false);
});
it("filters native libs by architecture", () => {
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
expect(arm64).toHaveLength(1);
expect(arm64[0]!.architecture).toBe("arm64-v8a");
});
it("checks internet permission", () => {
expect(hasInternetPermission(validManifest)).toBe(true);
const noInternet: MobileArtifactManifest = {
...validManifest,
android_manifest: { ...androidManifest, permissions: [] },
};
expect(hasInternetPermission(noInternet)).toBe(false);
});
it("gets all architectures", () => {
const archs = getAllArchitectures(validManifest);
expect(archs).toHaveLength(2);
expect(archs).toContain("arm64-v8a");
expect(archs).toContain("armeabi-v7a");
});
});
@@ -1,177 +0,0 @@
import { z } from "zod";
/** Supported mobile artifact formats. */
export const mobileArtifactFormatSchema = z.enum([
"apk",
"aab",
"ipa",
"dex",
"native_lib",
]);
export type MobileArtifactFormat = z.infer<typeof mobileArtifactFormatSchema>;
/** Mobile platform. */
export const mobilePlatformSchema = z.enum([
"android",
"ios",
"cross_platform",
]);
export type MobilePlatform = z.infer<typeof mobilePlatformSchema>;
/** Android manifest entry. */
export const androidManifestSchema = z.strictObject({
package_name: z.string().min(1),
version_name: z.string().nullable(),
version_code: z.number().int().nullable(),
min_sdk: z.number().int().nullable(),
target_sdk: z.number().int().nullable(),
permissions: z.array(z.string()).default([]),
activities: z.array(z.string()).default([]),
services: z.array(z.string()).default([]),
receivers: z.array(z.string()).default([]),
providers: z.array(z.string()).default([]),
});
export type AndroidManifest = z.infer<typeof androidManifestSchema>;
/** iOS app manifest (Info.plist). */
export const iosManifestSchema = z.strictObject({
bundle_identifier: z.string().min(1),
bundle_version: z.string().nullable(),
short_version: z.string().nullable(),
minimum_os_version: z.string().nullable(),
supported_platforms: z.array(z.string()).default([]),
ui_required_device_capabilities: z.array(z.string()).default([]),
app_permissions: z.array(z.string()).default([]),
});
/** Signing information. */
export const signingInfoSchema = z.strictObject({
is_signed: z.boolean().default(false),
signer_identity: z.string().nullable(),
certificate_fingerprint: z.string().nullable(),
signature_scheme: z.string().nullable(),
is_debuggable: z.boolean().default(false),
});
export type SigningInfo = z.infer<typeof signingInfoSchema>;
/** Native library entry. */
export const nativeLibrarySchema = z.strictObject({
path: z.string().min(1),
architecture: z.string().nullable(),
size: z.number().int().nonnegative(),
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type NativeLibrary = z.infer<typeof nativeLibrarySchema>;
/** Resource entry within a mobile artifact. */
export const mobileResourceSchema = z.strictObject({
path: z.string().min(1),
type: z.enum([
"layout",
"drawable",
"string",
"asset",
"raw",
"native_lib",
"manifest",
"entitlements",
"provisioning",
"other",
]),
size: z.number().int().nonnegative(),
});
export type MobileResource = z.infer<typeof mobileResourceSchema>;
/** Static analysis result for a mobile artifact. */
export const mobileArtifactManifestSchema = z.strictObject({
format: mobileArtifactFormatSchema,
platform: mobilePlatformSchema,
app_name: z.string().nullable(),
android_manifest: androidManifestSchema.nullable(),
ios_manifest: iosManifestSchema.nullable(),
signing: signingInfoSchema,
resources: z.array(mobileResourceSchema).default([]),
native_libraries: z.array(nativeLibrarySchema).default([]),
total_size: z.number().int().nonnegative(),
architectures: z.array(z.string()).default([]),
});
export type MobileArtifactManifest = z.infer<
typeof mobileArtifactManifestSchema
>;
/** Detect mobile artifact format from file extension. */
export function detectMobileFormat(path: string): MobileArtifactFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".apk")) return "apk";
if (lower.endsWith(".aab")) return "aab";
if (lower.endsWith(".ipa")) return "ipa";
if (lower.endsWith(".dex")) return "dex";
if (lower.endsWith(".so") || lower.endsWith(".dylib") || lower.endsWith(".a"))
return "native_lib";
return null;
}
/** Detect platform from format. */
export function detectPlatform(format: MobileArtifactFormat): MobilePlatform {
switch (format) {
case "apk":
case "aab":
case "dex":
return "android";
case "ipa":
return "ios";
case "native_lib":
return "cross_platform";
}
}
/** Classify a resource by its path. */
export function classifyMobileResource(path: string): MobileResource["type"] {
const lower = path.toLowerCase();
if (lower.includes("androidmanifest.xml")) return "manifest";
if (lower.includes(".entitlements")) return "entitlements";
if (lower.includes("provisioning") || lower.includes(".mobileprovision"))
return "provisioning";
if (lower.includes("/layout/")) return "layout";
if (lower.includes("/drawable/") || lower.includes("/mipmap/"))
return "drawable";
if (lower.includes("/values/")) return "string";
if (lower.includes("assets/") || lower.includes("raw/")) return "asset";
if (lower.endsWith(".so") || lower.endsWith(".dylib")) return "native_lib";
if (lower.endsWith(".xml")) return "layout";
return "other";
}
/** Get all native libraries for a specific architecture. */
export function nativeLibsByArchitecture(
manifest: MobileArtifactManifest,
arch: string,
): NativeLibrary[] {
return manifest.native_libraries.filter((l) => l.architecture === arch);
}
/** Check if an Android artifact has internet permission. */
export function hasInternetPermission(
manifest: MobileArtifactManifest,
): boolean {
if (!manifest.android_manifest) return false;
return manifest.android_manifest.permissions.some(
(p) => p.includes("INTERNET") || p.includes("android.permission.INTERNET"),
);
}
/** Get all unique architectures across native libraries. */
export function getAllArchitectures(
manifest: MobileArtifactManifest,
): string[] {
const archs = new Set<string>();
for (const lib of manifest.native_libraries) {
if (lib.architecture) archs.add(lib.architecture);
}
for (const arch of manifest.architectures) {
archs.add(arch);
}
return [...archs];
}
+1 -143
View File
@@ -1,150 +1,8 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
countMethodsByType,
isDbSaveComplete,
isGetterSelector,
isSetterSelector,
inspectNativeDispatchMetadata,
propertyNameFromSelector,
swiftDeclsByKind,
type ObjcMethod,
type SwiftDecl,
type DbSaveResult,
} from "./objcSwiftMetadata.js";
import { inspectNativeDispatchMetadata } from "./objcSwiftMetadata.js";
describe("ObjC/Swift metadata", () => {
it("identifies getter selectors", () => {
expect(isGetterSelector("name")).toBe(true);
expect(isGetterSelector("setName:")).toBe(false);
expect(isGetterSelector("set")).toBe(true);
});
it("identifies setter selectors", () => {
expect(isSetterSelector("setName:")).toBe(true);
expect(isSetterSelector("name")).toBe(false);
});
it("extracts property name from selector", () => {
expect(propertyNameFromSelector("name")).toBe("name");
expect(propertyNameFromSelector("setName:")).toBe("name");
expect(propertyNameFromSelector("set")).toBe("set");
});
it("counts methods by type", () => {
const methods: ObjcMethod[] = [
{
selector: "init",
method_type: "instance",
address: 0x1000,
is_required: false,
is_optional: false,
},
{
selector: "alloc",
method_type: "class",
address: 0x2000,
is_required: false,
is_optional: false,
},
];
const counts = countMethodsByType(methods);
expect(counts.instance).toBe(1);
expect(counts.class).toBe(1);
expect(counts.ivar_getter).toBe(0);
expect(counts.ivar_setter).toBe(0);
});
it("filters Swift declarations by kind", () => {
const decls: SwiftDecl[] = [
{
kind: "class",
name: "Foo",
module: null,
access_level: "public",
super_class: null,
protocols: [],
is_final: false,
is_required: false,
is_convenience_init: false,
is_override: false,
},
];
const classes = swiftDeclsByKind(decls, "class");
expect(classes).toHaveLength(1);
expect(classes[0]!.name).toBe("Foo");
});
it("checks database save completeness", () => {
const result: DbSaveResult = {
operation: "save",
succeeded: true,
preserved_names: 10,
preserved_comments: 5,
preserved_bookmarks: 3,
database_path: "/tmp/db.hop",
error: null,
};
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
});
it("is monotone in every expected count and total at the observed count", () => {
fc.assert(
fc.property(
fc.record({
operation: fc.constantFrom(
"save",
"readback",
"open_database",
"close_database",
"export",
"import",
),
succeeded: fc.boolean(),
preserved_names: fc.nat({ max: 50 }),
preserved_comments: fc.nat({ max: 50 }),
preserved_bookmarks: fc.nat({ max: 50 }),
database_path: fc.option(fc.string(), { nil: null }),
error: fc.option(fc.string(), { nil: null }),
}),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
(result, names, comments, bookmarks) => {
// Completeness is downward closed: if demanding more was met,
// demanding less must also be met.
if (isDbSaveComplete(result, names + 1, comments, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments + 1, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments, bookmarks + 1)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
// Expecting exactly what was preserved is complete iff the save worked.
expect(
isDbSaveComplete(
result,
result.preserved_names,
result.preserved_comments,
result.preserved_bookmarks,
),
).toBe(result.succeeded);
},
),
{ numRuns: 200 },
);
});
it("bounds symbol projections and labels symbol-only metadata as partial", () => {
const result = inspectNativeDispatchMetadata(
[
+4 -65
View File
@@ -7,7 +7,6 @@ export const objcMethodTypeSchema = z.enum([
"ivar_getter",
"ivar_setter",
]);
export type ObjcMethodType = z.infer<typeof objcMethodTypeSchema>;
/** Objective-C property attribute. */
export const objcPropertyAttributeSchema = z.strictObject({
@@ -27,7 +26,7 @@ export const objcMethodSchema = z.strictObject({
is_required: z.boolean().default(false),
is_optional: z.boolean().default(false),
});
export type ObjcMethod = z.infer<typeof objcMethodSchema>;
type ObjcMethod = z.infer<typeof objcMethodSchema>;
/** Objective-C property metadata. */
export const objcPropertySchema = z.strictObject({
@@ -87,7 +86,7 @@ export const objcClassSchema = z.strictObject({
)
.optional(),
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
type ObjcClass = z.infer<typeof objcClassSchema>;
/** Exact location of a decoded native metadata value when the provider knows it. */
export const nativeMetadataLocationSchema = z.strictObject({
@@ -162,7 +161,7 @@ export const objcDispatchImplementationSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcDispatchImplementation = z.infer<
type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
@@ -224,7 +223,7 @@ export const swiftSymbolSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
/** Per-facet coverage; empty arrays are meaningful only with this record. */
export const nativeMetadataCoverageSchema = z.strictObject({
@@ -246,7 +245,6 @@ export const swiftDeclKindSchema = z.enum([
"global_var",
"global_func",
]);
export type SwiftDeclKind = z.infer<typeof swiftDeclKindSchema>;
/** Swift access level. */
export const swiftAccessLevelSchema = z.enum([
@@ -269,7 +267,6 @@ export const swiftDeclSchema = z.strictObject({
is_convenience_init: z.boolean().default(false),
is_override: z.boolean().default(false),
});
export type SwiftDecl = z.infer<typeof swiftDeclSchema>;
/** Database save/read operation type. */
export const dbOperationSchema = z.enum([
@@ -290,7 +287,6 @@ export const dbSaveResultSchema = z.strictObject({
database_path: z.string().nullable(),
error: z.string().nullable(),
});
export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
/** Result of deeper ObjC/Swift metadata extraction. */
export const objcSwiftMetadataSchema = z.strictObject({
@@ -479,60 +475,3 @@ const parseMetadataAddress = (address: string | null): number | null => {
const value = Number.parseInt(match[1], 16);
return Number.isSafeInteger(value) ? value : null;
};
/** Check if a selector name looks like a getter. */
export function isGetterSelector(selector: string): boolean {
return /^[a-z][a-zA-Z0-9_]*$/u.test(selector) && !selector.includes(":");
}
/** Check if a selector name looks like a setter. */
export function isSetterSelector(selector: string): boolean {
return selector.startsWith("set") && selector.endsWith(":");
}
/** Extract property name from a getter/setter selector. */
export function propertyNameFromSelector(selector: string): string | null {
if (isSetterSelector(selector)) {
const inner = selector.slice(3, -1);
return inner.charAt(0).toLowerCase() + inner.slice(1);
}
if (isGetterSelector(selector)) {
return selector;
}
return null;
}
/** Count ObjC methods by type. */
export function countMethodsByType(
methods: readonly ObjcMethod[],
): Record<ObjcMethodType, number> {
return {
instance: methods.filter((m) => m.method_type === "instance").length,
class: methods.filter((m) => m.method_type === "class").length,
ivar_getter: methods.filter((m) => m.method_type === "ivar_getter").length,
ivar_setter: methods.filter((m) => m.method_type === "ivar_setter").length,
};
}
/** Get all Swift declarations of a specific kind. */
export function swiftDeclsByKind(
decls: readonly SwiftDecl[],
kind: SwiftDeclKind,
): SwiftDecl[] {
return decls.filter((d) => d.kind === kind);
}
/** Check if a database save preserved all expected items. */
export function isDbSaveComplete(
result: DbSaveResult,
expectedNames: number,
expectedComments: number,
expectedBookmarks: number,
): boolean {
return (
result.succeeded &&
result.preserved_names >= expectedNames &&
result.preserved_comments >= expectedComments &&
result.preserved_bookmarks >= expectedBookmarks
);
}
-95
View File
@@ -1,95 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyResource,
detectPackageFormat,
hasValidSignature,
isConfigurationResource,
isManifestResource,
resourcesByType,
totalResourceSize,
type PackageManifest,
} from "./packageAnalysis.js";
describe("package analysis", () => {
it("detects package format from extension", () => {
expect(detectPackageFormat("app.msix")).toBe("msix");
expect(detectPackageFormat("installer.msi")).toBe("msi");
expect(detectPackageFormat("app.appx")).toBe("appx");
expect(detectPackageFormat("app.zip")).toBeNull();
});
it("identifies manifest resources", () => {
expect(isManifestResource("AppXManifest.xml")).toBe(true);
expect(isManifestResource("resources.pri")).toBe(false);
});
it("identifies configuration resources", () => {
expect(isConfigurationResource("settings.xml")).toBe(true);
expect(isConfigurationResource("config.json")).toBe(true);
expect(isConfigurationResource("app.exe")).toBe(false);
});
it("classifies resources by path", () => {
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
expect(classifyResource("icon.png")).toBe("icon");
expect(classifyResource("settings.xml")).toBe("configuration");
expect(classifyResource("cert.cer")).toBe("certificate");
expect(classifyResource("app.exe")).toBe("executable");
expect(classifyResource("lib.dll")).toBe("library");
expect(classifyResource("data.bin")).toBe("other");
});
const validManifest: PackageManifest = {
format: "msix",
name: "TestApp",
publisher: "CN=TestPublisher",
version: "1.0.0.0",
architecture: "x64",
resources: [
{
path: "AppXManifest.xml",
type: "manifest",
size: 1000,
digest: "a".repeat(64),
},
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
{
path: "app.exe",
type: "executable",
size: 50000,
digest: "c".repeat(64),
},
],
signature: {
is_signed: true,
signer_subject: "CN=TestPublisher",
certificate_thumbprint: "abc123",
is_valid: true,
is_timestamped: true,
timestamp_signer: "CN=Timestamp",
},
is_framework: false,
dependencies: ["Microsoft.VCLibs.14.00"],
capabilities: ["internetClient", "localNetwork"],
};
it("filters resources by type", () => {
const icons = resourcesByType(validManifest, "icon");
expect(icons).toHaveLength(1);
expect(icons[0]!.path).toBe("icon.png");
});
it("computes total resource size", () => {
expect(totalResourceSize(validManifest)).toBe(56000);
});
it("checks valid signature", () => {
expect(hasValidSignature(validManifest)).toBe(true);
const unsigned: PackageManifest = {
...validManifest,
signature: { ...validManifest.signature, is_valid: false },
};
expect(hasValidSignature(unsigned)).toBe(false);
});
});
-143
View File
@@ -1,143 +0,0 @@
import { z } from "zod";
/** Supported Windows package formats. */
export const packageFormatSchema = z.enum(["msix", "msi", "appx"]);
export type PackageFormat = z.infer<typeof packageFormatSchema>;
/** A resource entry within a package. */
export const packageResourceSchema = z.strictObject({
/** Resource path within the package. */
path: z.string().min(1),
/** Resource type. */
type: z.enum([
"manifest",
"icon",
"configuration",
"certificate",
"executable",
"library",
"data",
"other",
]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type PackageResource = z.infer<typeof packageResourceSchema>;
/** Digital signature information. */
export const digitalSignatureSchema = z.strictObject({
/** Whether the package is signed. */
is_signed: z.boolean(),
/** Signer subject name. */
signer_subject: z.string().nullable(),
/** Certificate thumbprint. */
certificate_thumbprint: z.string().nullable(),
/** Whether the signature is valid. */
is_valid: z.boolean().default(false),
/** Whether the signature is timestamped. */
is_timestamped: z.boolean().default(false),
/** Timestamp signer if present. */
timestamp_signer: z.string().nullable(),
});
/** A Windows package manifest for static analysis. */
export const packageManifestSchema = z.strictObject({
/** Package format. */
format: packageFormatSchema,
/** Package identity name. */
name: z.string().min(1),
/** Package publisher. */
publisher: z.string().nullable(),
/** Package version. */
version: z.string().nullable(),
/** Architecture. */
architecture: z.enum(["x86", "x64", "arm", "arm64", "neutral", "unknown"]),
/** Package resources. */
resources: z.array(packageResourceSchema).default([]),
/** Digital signature. */
signature: digitalSignatureSchema,
/** Whether the package is a framework. */
is_framework: z.boolean().default(false),
/** Package dependencies. */
dependencies: z.array(z.string()).default([]),
/** Capabilities declared in the manifest. */
capabilities: z.array(z.string()).default([]),
});
export type PackageManifest = z.infer<typeof packageManifestSchema>;
/** Detect package format from file extension. */
export function detectPackageFormat(path: string): PackageFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".msix")) return "msix";
if (lower.endsWith(".msi")) return "msi";
if (lower.endsWith(".appx")) return "appx";
return null;
}
/** Check if a resource path looks like a manifest. */
export function isManifestResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.includes("appxmanifest.xml") ||
lower.includes("appxmanifest") ||
lower.includes("manifest.xml") ||
lower.endsWith("_manifest.xml")
);
}
/** Check if a resource path looks like a configuration file. */
export function isConfigurationResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.endsWith(".xml") ||
lower.endsWith(".json") ||
lower.endsWith(".ini") ||
lower.endsWith(".config")
);
}
/** Classify a resource by its path. */
export function classifyResource(path: string): PackageResource["type"] {
if (isManifestResource(path)) return "manifest";
const lower = path.toLowerCase();
if (
lower.endsWith(".ico") ||
lower.endsWith(".png") ||
lower.endsWith(".jpg") ||
lower.endsWith(".jpeg")
)
return "icon";
if (isConfigurationResource(path)) return "configuration";
if (
lower.endsWith(".cer") ||
lower.endsWith(".pfx") ||
lower.endsWith(".p12")
)
return "certificate";
if (lower.endsWith(".exe") || lower.endsWith(".dll"))
return lower.endsWith(".exe") ? "executable" : "library";
return "other";
}
/** Get all resources of a specific type. */
export function resourcesByType(
manifest: PackageManifest,
type: PackageResource["type"],
): PackageResource[] {
return manifest.resources.filter((r) => r.type === type);
}
/** Get the total size of all resources. */
export function totalResourceSize(manifest: PackageManifest): number {
return manifest.resources.reduce((sum, r) => sum + r.size, 0);
}
/** Check if a package has a valid signature. */
export function hasValidSignature(manifest: PackageManifest): boolean {
return manifest.signature.is_signed && manifest.signature.is_valid;
}
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
countExecutableSections,
getExportedFunctions,
getImportedDlls,
hasPdbInfo,
parseDebugType,
parseImageCharacteristics,
parseMachineType,
parseSectionCharacteristics,
peManifestSchema,
type PeManifest,
} from "./peInspection.js";
const validManifest: PeManifest = {
dos_magic: 0x5a4d,
pe_signature: 0x00004550,
machine: "x64",
number_of_sections: 3,
timestamp: 0x12345678,
is_dll: false,
is_executable: true,
is_console: true,
entry_point: 0x1000,
image_base: 0x400000,
section_alignment: 0x1000,
subsystem_version: "10.0",
sections: [
{
name: ".text",
virtual_size: 0x1000,
virtual_address: 0x1000,
raw_size: 0x1000,
raw_offset: 0x400,
characteristics: {
has_code: true,
has_initialized_data: false,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: true,
},
},
{
name: ".data",
virtual_size: 0x500,
virtual_address: 0x2000,
raw_size: 0x500,
raw_offset: 0x1400,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: true,
executable: false,
},
},
{
name: ".rdata",
virtual_size: 0x200,
virtual_address: 0x3000,
raw_size: 0x200,
raw_offset: 0x1900,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: false,
},
},
],
imports: [
{
dll: "KERNEL32.DLL",
function_name: "CreateFileW",
ordinal: null,
is_delay_import: false,
},
{
dll: "KERNEL32.DLL",
function_name: "WriteFile",
ordinal: null,
is_delay_import: false,
},
{
dll: "USER32.DLL",
function_name: "MessageBoxW",
ordinal: 100,
is_delay_import: false,
},
],
exports: [
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
],
resources: [
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
],
debug_entries: [
{
type: "CODEVIEW",
rva: 0x5000,
size: 100,
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
pdb_age: 1,
pdb_path: "C:\\src\\app.pdb",
},
],
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
relocations_count: 50,
image_characteristics: ["Executable", "Console"],
};
describe("PE/COFF static inspection", () => {
it("parses machine types", () => {
expect(parseMachineType(0x014c)).toBe("x86");
expect(parseMachineType(0x8664)).toBe("x64");
expect(parseMachineType(0x01c0)).toBe("arm");
expect(parseMachineType(0xaa64)).toBe("arm64");
expect(parseMachineType(0x0200)).toBe("ia64");
expect(parseMachineType(0xffff)).toBe("unknown");
});
it("parses section characteristics", () => {
const CODE = 0x00000020;
const READ = 0x40000000;
const EXECUTE = 0x20000000;
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
expect(result.has_code).toBe(true);
expect(result.readable).toBe(true);
expect(result.executable).toBe(true);
expect(result.writable).toBe(false);
});
it("parses image characteristics", () => {
const DLL = 0x2000;
const EXEC = 0x0002;
const flags = parseImageCharacteristics(DLL | EXEC);
expect(flags).toContain("DLL");
expect(flags).toContain("Executable");
});
it("parses debug types", () => {
expect(parseDebugType(2)).toBe("CODEVIEW");
expect(parseDebugType(1)).toBe("COFF");
expect(parseDebugType(99)).toBe("UNKNOWN");
});
it("rejects a manifest whose section table is malformed", () => {
const malformed = {
...validManifest,
sections: [{ ...validManifest.sections[0]!, name: 7 }],
};
const result = peManifestSchema.safeParse(malformed);
expect(result.success).toBe(false);
});
it("accepts static manifests with more than 96 PE sections", () => {
const section = validManifest.sections[0];
if (section === undefined) throw new Error("Expected PE section fixture");
const sections = Array.from({ length: 97 }, (_, index) => ({
...section,
name: `section-${String(index)}`,
}));
expect(
peManifestSchema.parse({
...validManifest,
number_of_sections: sections.length,
sections,
}).sections,
).toHaveLength(97);
});
it("detects PDB info", () => {
expect(hasPdbInfo(validManifest)).toBe(true);
const withoutPdb: PeManifest = {
...validManifest,
debug_entries: [
{
type: "COFF",
rva: 0x5000,
size: 100,
pdb_guid: null,
pdb_age: null,
pdb_path: null,
},
],
};
expect(hasPdbInfo(withoutPdb)).toBe(false);
});
it("gets imported DLLs", () => {
const dlls = getImportedDlls(validManifest);
expect(dlls).toHaveLength(2);
expect(dlls).toContain("KERNEL32.DLL");
expect(dlls).toContain("USER32.DLL");
});
it("gets exported functions", () => {
const exports = getExportedFunctions(validManifest);
expect(exports).toHaveLength(2);
expect(exports).toContain("DllMain");
expect(exports).toContain("MyFunction");
});
it("counts executable sections", () => {
expect(countExecutableSections(validManifest)).toBe(1);
});
});
-220
View File
@@ -1,220 +0,0 @@
import { z } from "zod";
/** PE/COFF section characteristics flags. */
export const sectionCharacteristicsSchema = z.object({
/** Section contains executable code. */
has_code: z.boolean().default(false),
/** Section contains initialized data. */
has_initialized_data: z.boolean().default(false),
/** Section contains uninitialized data. */
has_uninitialized_data: z.boolean().default(false),
/** Section can be read. */
readable: z.boolean().default(false),
/** Section can be written. */
writable: z.boolean().default(false),
/** Section can be executed. */
executable: z.boolean().default(false),
});
/** PE/COFF section header. */
export const peSectionSchema = z.strictObject({
name: z.string().min(1),
virtual_size: z.number().int().nonnegative(),
virtual_address: z.number().int().nonnegative(),
raw_size: z.number().int().nonnegative(),
raw_offset: z.number().int().nonnegative(),
characteristics: sectionCharacteristicsSchema,
});
/** PE import entry. */
export const peImportSchema = z.strictObject({
dll: z.string().min(1),
function_name: z.string().min(1),
ordinal: z.number().int().nullable(),
is_delay_import: z.boolean().default(false),
});
/** PE export entry. */
export const peExportSchema = z.strictObject({
name: z.string().min(1),
ordinal: z.number().int().nonnegative(),
rva: z.number().int().nonnegative(),
forwarder: z.string().nullable(),
});
/** PE/COFF resource entry. */
export const peResourceSchema = z.strictObject({
type: z.string().min(1),
name: z.string().nullable(),
language: z.number().int().nullable(),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
});
/** PE debug directory entry. */
export const peDebugEntrySchema = z.strictObject({
type: z.string().min(1),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
/** PDB GUID if this is a CodeView entry. */
pdb_guid: z.string().nullable(),
/** PDB age if this is a CodeView entry. */
pdb_age: z.number().int().nullable(),
/** PDB path if this is a CodeView entry. */
pdb_path: z.string().nullable(),
});
/** TLS callback entry. */
export const peTlsCallbackSchema = z.strictObject({
callback_rva: z.number().int().nonnegative(),
index: z.number().int().nonnegative(),
});
/** Architecture/machine type. */
export const peMachineTypeSchema = z.enum([
"x86",
"x64",
"arm",
"arm64",
"ia64",
"unknown",
]);
export type PeMachineType = z.infer<typeof peMachineTypeSchema>;
/** PE/COFF manifest for static inspection. */
export const peManifestSchema = z.strictObject({
/** DOS header magic. */
dos_magic: z.literal(0x5a4d),
/** PE signature. */
pe_signature: z.literal(0x00004550),
/** Machine type. */
machine: peMachineTypeSchema,
/** Number of sections. */
number_of_sections: z.number().int().positive(),
/** Timestamp from the COFF header. */
timestamp: z.number().int().nullable(),
/** PE characteristics flags. */
is_dll: z.boolean().default(false),
is_executable: z.boolean().default(false),
is_console: z.boolean().default(true),
/** Entry point RVA. */
entry_point: z.number().int().nonnegative(),
/** Image base. */
image_base: z.number().int().nonnegative(),
/** Section alignment. */
section_alignment: z.number().int().positive(),
/** Subsystem version. */
subsystem_version: z.string().nullable(),
/** Sections. */
sections: z.array(peSectionSchema),
/** Imports. */
imports: z.array(peImportSchema).default([]),
/** Exports. */
exports: z.array(peExportSchema).default([]),
/** Resources. */
resources: z.array(peResourceSchema).default([]),
/** Debug directory entries. */
debug_entries: z.array(peDebugEntrySchema).default([]),
/** TLS callbacks. */
tls_callbacks: z.array(peTlsCallbackSchema).default([]),
/** Relocations count (not all entries). */
relocations_count: z.number().int().nonnegative().default(0),
/** Image file characteristics. */
image_characteristics: z.array(z.string()).default([]),
});
export type PeManifest = z.infer<typeof peManifestSchema>;
/** Parse machine type from COFF machine field. */
export function parseMachineType(machine: number): PeMachineType {
switch (machine) {
case 0x014c:
return "x86";
case 0x8664:
return "x64";
case 0x01c0:
case 0x01c2:
case 0x01c4:
return "arm";
case 0xaa64:
return "arm64";
case 0x0200:
return "ia64";
default:
return "unknown";
}
}
/** Parse section characteristics flags. */
export function parseSectionCharacteristics(
characteristics: number,
): z.infer<typeof sectionCharacteristicsSchema> {
const IMAGE_SCN_CNT_CODE = 0x00000020;
const IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040;
const IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080;
const IMAGE_SCN_MEM_READ = 0x40000000;
const IMAGE_SCN_MEM_WRITE = 0x80000000;
const IMAGE_SCN_MEM_EXECUTE = 0x20000000;
return {
has_code: (characteristics & IMAGE_SCN_CNT_CODE) !== 0,
has_initialized_data:
(characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) !== 0,
has_uninitialized_data:
(characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) !== 0,
readable: (characteristics & IMAGE_SCN_MEM_READ) !== 0,
writable: (characteristics & IMAGE_SCN_MEM_WRITE) !== 0,
executable: (characteristics & IMAGE_SCN_MEM_EXECUTE) !== 0,
};
}
/** Parse image characteristics flags. */
export function parseImageCharacteristics(characteristics: number): string[] {
const IMAGE_DLL = 0x2000;
const IMAGE_EXECUTABLE = 0x0002;
const IMAGE_CONSOLE = 0x0003;
const flags: string[] = [];
if (characteristics & IMAGE_DLL) flags.push("DLL");
if (characteristics & IMAGE_EXECUTABLE) flags.push("Executable");
if ((characteristics & 0x0000000f) === IMAGE_CONSOLE) flags.push("Console");
return flags;
}
/** Parse a PE debug directory type. */
export function parseDebugType(type: number): string {
switch (type) {
case 0:
return "UNKNOWN";
case 1:
return "COFF";
case 2:
return "CODEVIEW";
case 3:
return "POGO";
case 4:
return "MISC";
default:
return "UNKNOWN";
}
}
/** Check if a PE manifest has PDB debug info. */
export function hasPdbInfo(manifest: PeManifest): boolean {
return manifest.debug_entries.some(
(e) => e.pdb_guid !== null && e.pdb_path !== null,
);
}
/** Get all imported DLLs from a PE manifest. */
export function getImportedDlls(manifest: PeManifest): string[] {
return [...new Set(manifest.imports.map((i) => i.dll))];
}
/** Get all exported function names from a PE manifest. */
export function getExportedFunctions(manifest: PeManifest): string[] {
return manifest.exports.map((e) => e.name);
}
/** Count executable sections. */
export function countExecutableSections(manifest: PeManifest): number {
return manifest.sections.filter((s) => s.characteristics.executable).length;
}
@@ -1,112 +0,0 @@
import type { ProcessNode, ProcessTreeEvent } from "./eventProcessTree.js";
/**
* Defaults shared by every fixture event. Tests vary only the fields they are
* actually asserting on, so a tree reads as the sequence of transitions under
* test rather than thirteen repeated literal fields per event.
*/
const eventDefaults: {
arguments: string[];
previous_pid: number | null;
previous_ppid: number | null;
exit_code: number | null;
signal: number | null;
tid: number | null;
} = {
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
};
/** One `spawn` event, numbering itself from the sequence given. */
export const spawnEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable?: string | null;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "spawn",
executable: event.executable ?? `/${event.process_name}`,
...event,
});
/** One `exit` event. */
export const exitEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number | null;
process_name: string | null;
exit_code?: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "exit",
executable: null,
exit_code: 0,
...event,
});
/** One `re_exec` event, which keeps the pid and replaces the executable. */
export const reExecEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable: string;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "re_exec",
previous_pid: null,
...event,
});
/** One `reparent` event, which records the pid the process was adopted from. */
export const reparentEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
previous_ppid: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "reparent",
executable: null,
...event,
});
/** A reconstructed node, defaulting to a childless process with no lifecycle. */
export const processNode = (node: {
pid: number;
ppid: number | null;
process_name: string;
children?: number[];
}): ProcessNode => ({
executable: null,
arguments: [],
spawn_time_ms: null,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
...node,
children: node.children ?? [],
});
/** The common `spawn` of a root process at pid 1. */
export const rootSpawn = (sequence = 0): ProcessTreeEvent =>
spawnEvent({ sequence, pid: 1, ppid: 0, process_name: "root" });
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
containsProcess,
getDescendants,
maxTreeDepth,
reconstructProcessTree,
type ProcessTreeEvent,
} from "./eventProcessTree.js";
import {
exitEvent,
processNode,
reExecEvent,
reparentEvent,
rootSpawn,
spawnEvent,
} from "./eventProcessTree.fixture.js";
describe("event-backed process tree reconstruction", () => {
it("walks trees larger than ten thousand nodes", () => {
const childPids = Array.from({ length: 10_001 }, (_, index) => index + 2);
const root = processNode({
pid: 1,
ppid: null,
process_name: "root",
children: childPids,
});
const children = childPids.map((pid) =>
processNode({ pid, ppid: 1, process_name: "root" }),
);
expect(maxTreeDepth([root, ...children], 1)).toBe(1);
expect(getDescendants([root, ...children], 1)).toHaveLength(
childPids.length,
);
});
it("reconstructs a simple process tree", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
exitEvent({
sequence: 2,
at_ms: 20,
pid: 2,
ppid: 1,
process_name: "child",
}),
exitEvent({
sequence: 3,
at_ms: 30,
pid: 1,
ppid: 0,
process_name: "root",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.processes).toHaveLength(2);
expect(result.events_consumed).toBe(4);
expect(result.events_unmatched).toBe(0);
expect(result.short_lived_descendants).toBe(2);
});
});
describe("short-lived process descendants", () => {
it("detects short-lived descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "short",
executable: "/short",
}),
exitEvent({
sequence: 2,
at_ms: 11,
pid: 2,
ppid: 1,
process_name: "short",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.short_lived_descendants).toBe(1);
});
});
describe("event-backed process tree transitions", () => {
it("detects re-exec", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
reExecEvent({
sequence: 1,
pid: 1,
ppid: 0,
process_name: "root",
executable: "/newroot",
arguments: ["--new"],
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_re_exec).toBe(true);
const root = result.processes.find((p) => p.pid === 1);
expect(root?.is_re_exec).toBe(true);
expect(root?.executable).toBe("/newroot");
});
it("detects reparenting", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
reparentEvent({
sequence: 2,
pid: 2,
ppid: 0,
process_name: "child",
previous_ppid: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_reparenting).toBe(true);
const child = result.processes.find((p) => p.pid === 2);
expect(child?.is_reparented).toBe(true);
expect(child?.previous_ppid).toBe(1);
expect(child?.ppid).toBe(0);
});
it("reports unmatched events for unknown exits", () => {
const events: ProcessTreeEvent[] = [
exitEvent({
sequence: 0,
at_ms: 0,
pid: 999,
ppid: null,
process_name: null,
exit_code: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.events_unmatched).toBe(1);
expect(result.processes).toHaveLength(0);
});
});
describe("event-backed process tree queries", () => {
it("gets descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child1",
executable: "/c1",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "grandchild",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
const descendants = getDescendants(result.processes, 1);
expect(descendants).toHaveLength(2);
expect(descendants).toContain(2);
expect(descendants).toContain(3);
});
it("checks process containment", () => {
const events: ProcessTreeEvent[] = [rootSpawn(0)];
const result = reconstructProcessTree(events, 1);
expect(containsProcess(result.processes, 1)).toBe(true);
expect(containsProcess(result.processes, 999)).toBe(false);
});
});
describe("event-backed process tree depth and types", () => {
it("computes max tree depth", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/c",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "gc",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
expect(maxTreeDepth(result.processes, 1)).toBe(2);
});
});
-262
View File
@@ -1,262 +0,0 @@
import { z } from "zod";
/** Event types for event-backed process-tree capture. */
export const processEventTypeSchema = z.enum([
"spawn",
"exit",
"re_exec",
"reparent",
"signal",
"name_change",
"thread_create",
"thread_exit",
]);
/** A single event-backed process-tree event. */
export const processTreeEventSchema = z.strictObject({
/** Monotonic event sequence number. */
sequence: z.number().int().nonnegative(),
/** Event timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Event type. */
type: processEventTypeSchema,
/** Process ID. */
pid: z.number().int().positive(),
/** Parent process ID. */
ppid: z.number().int().nullable(),
/** Process name if known. */
process_name: z.string().nullable(),
/** Executable path if known. */
executable: z.string().nullable(),
/** Command line arguments. */
arguments: z.array(z.string()).default([]),
/** Previous PID (for reparent events). */
previous_pid: z.number().int().nullable(),
/** Previous PPID (for reparent events). */
previous_ppid: z.number().int().nullable(),
/** Exit code (for exit events). */
exit_code: z.number().int().nullable(),
/** Signal number (for signal events). */
signal: z.number().int().nullable(),
/** Thread ID (for thread events). */
tid: z.number().int().nullable(),
});
export type ProcessTreeEvent = z.infer<typeof processTreeEventSchema>;
/** Process node in a reconstructed tree. */
export const processNodeSchema = z.strictObject({
pid: z.number().int().positive(),
ppid: z.number().int().nullable(),
process_name: z.string().nullable(),
executable: z.string().nullable(),
arguments: z.array(z.string()).default([]),
children: z.array(z.number().int()).default([]),
spawn_time_ms: z.number().int().nullable(),
exit_time_ms: z.number().int().nullable(),
exit_code: z.number().int().nullable(),
is_re_exec: z.boolean().default(false),
is_reparented: z.boolean().default(false),
previous_ppid: z.number().int().nullable(),
});
export type ProcessNode = z.infer<typeof processNodeSchema>;
/** Result of event-backed process-tree reconstruction. */
export const processTreeReconstructionSchema = z.strictObject({
/** Root PID of the process tree. */
root_pid: z.number().int().positive(),
/** All reconstructed process nodes. */
processes: z.array(processNodeSchema).min(0),
/** Events that were consumed. */
events_consumed: z.number().int().nonnegative(),
/** Events that could not be matched. */
events_unmatched: z.number().int().nonnegative(),
/** Short-lived descendants that were missed by sampling. */
short_lived_descendants: z.number().int().nonnegative(),
/** Whether any re-exec was detected. */
has_re_exec: z.boolean().default(false),
/** Whether any reparenting was detected. */
has_reparenting: z.boolean().default(false),
});
export type ProcessTreeReconstruction = z.infer<
typeof processTreeReconstructionSchema
>;
type ProcessTreeAccumulator = {
readonly nodes: Map<number, ProcessNode>;
readonly children: Map<number, number[]>;
eventsUnmatched: number;
hasReExec: boolean;
hasReparenting: boolean;
shortLivedDescendants: number;
};
const applyProcessTreeEvent = (
event: ProcessTreeEvent,
state: ProcessTreeAccumulator,
): void => {
let node = state.nodes.get(event.pid);
switch (event.type) {
case "spawn": {
if (!node) {
node = {
pid: event.pid,
ppid: event.ppid,
process_name: event.process_name,
executable: event.executable,
arguments: event.arguments,
children: [],
spawn_time_ms: event.at_ms,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
};
state.nodes.set(event.pid, node);
}
if (event.ppid !== null) {
const parentChildren = state.children.get(event.ppid) ?? [];
parentChildren.push(event.pid);
state.children.set(event.ppid, parentChildren);
}
break;
}
case "exit":
if (node) {
node.exit_time_ms = event.at_ms;
node.exit_code = event.exit_code;
if (
node.spawn_time_ms !== null &&
event.at_ms - node.spawn_time_ms < 100
)
state.shortLivedDescendants++;
} else state.eventsUnmatched++;
break;
case "re_exec":
if (node) {
node.is_re_exec = true;
node.executable = event.executable ?? node.executable;
node.arguments = event.arguments;
state.hasReExec = true;
} else state.eventsUnmatched++;
break;
case "reparent":
if (node) {
node.previous_ppid = node.ppid;
node.ppid = event.ppid;
node.is_reparented = true;
state.hasReparenting = true;
} else state.eventsUnmatched++;
break;
case "signal":
case "name_change":
case "thread_create":
case "thread_exit":
// These events are recorded but don't modify the tree structure.
break;
}
};
/** Reconstruct a process tree from event-backed capture. */
export function reconstructProcessTree(
events: readonly ProcessTreeEvent[],
rootPid: number,
): ProcessTreeReconstruction {
const nodes = new Map<number, ProcessNode>();
const children = new Map<number, number[]>();
let eventsConsumed = 0;
const state: ProcessTreeAccumulator = {
nodes,
children,
eventsUnmatched: 0,
hasReExec: false,
hasReparenting: false,
shortLivedDescendants: 0,
};
const sorted = [...events].sort((a, b) => a.at_ms - b.at_ms);
for (const event of sorted) {
eventsConsumed++;
applyProcessTreeEvent(event, state);
}
// Attach children to nodes
for (const [pid, childPids] of children) {
const node = nodes.get(pid);
if (node) node.children = childPids;
}
return {
root_pid: rootPid,
processes: [...nodes.values()],
events_consumed: eventsConsumed,
events_unmatched: state.eventsUnmatched,
short_lived_descendants: state.shortLivedDescendants,
has_re_exec: state.hasReExec,
has_reparenting: state.hasReparenting,
};
}
/** Get all descendant PIDs of a given root PID. */
export function getDescendants(
processes: readonly ProcessNode[],
rootPid: number,
): number[] {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const visited = new Set<number>();
const result: number[] = [];
const queue: number[] = [rootPid];
for (let head = 0; head < queue.length; head += 1) {
const pid = queue[head];
if (pid === undefined) continue;
if (visited.has(pid)) continue;
visited.add(pid);
const node = byPid.get(pid);
if (node) {
for (const child of node.children) {
if (!visited.has(child)) {
result.push(child);
queue.push(child);
}
}
}
}
return result;
}
/** Check if a process tree contains a specific PID. */
export function containsProcess(
processes: readonly ProcessNode[],
pid: number,
): boolean {
return processes.some((p) => p.pid === pid);
}
/** Get the maximum tree depth from the root. */
export function maxTreeDepth(
processes: readonly ProcessNode[],
rootPid: number,
): number {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const pending = [{ pid: rootPid, depth: 0 }];
const visited = new Set<number>();
let maximumDepth = 0;
while (pending.length > 0) {
const current = pending.pop();
if (!current || visited.has(current.pid)) continue;
visited.add(current.pid);
const node = byPid.get(current.pid);
if (!node || node.children.length === 0) continue;
const childDepth = current.depth + 1;
maximumDepth = Math.max(maximumDepth, childDepth);
for (const childPid of node.children)
if (!visited.has(childPid))
pending.push({ pid: childPid, depth: childDepth });
}
return maximumDepth;
}
-259
View File
@@ -1,259 +0,0 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
classifyProtocolFamily,
decodeGrpcFrame,
decodeJsonRpc,
decodeMessagePack,
inferMessageSchema,
protocolCaptureSchema,
type ProtocolMessage,
} from "./protocolCapture.js";
describe("protocol capture", () => {
it("accepts every captured message", () => {
const message: ProtocolMessage = {
sequence: 0,
at_ms: 0,
family: "json-rpc",
direction: "request",
endpoint: null,
content_type: null,
raw_payload: null,
decoded_fields: [],
schema_hypotheses: [],
truncated: false,
credentials_redacted: false,
};
expect(
protocolCaptureSchema.parse({
family: "json-rpc",
messages: Array.from({ length: 10_001 }, (_, sequence) => ({
...message,
sequence,
})),
}).messages,
).toHaveLength(10_001);
});
it("classifies gRPC from content type", () => {
expect(classifyProtocolFamily("application/grpc+proto", null)).toBe("grpc");
});
it("classifies protobuf from content type", () => {
expect(classifyProtocolFamily("application/x-protobuf", null)).toBe(
"protobuf",
);
});
it("classifies json-rpc from content type", () => {
expect(classifyProtocolFamily("application/json-rpc", null)).toBe(
"json-rpc",
);
});
it("classifies msgpack from content type", () => {
expect(classifyProtocolFamily("application/msgpack", null)).toBe(
"messagepack",
);
});
it("classifies from path when content type is null", () => {
expect(classifyProtocolFamily(null, "/some/grpc/method")).toBe("grpc");
expect(classifyProtocolFamily(null, "/api/json-rpc/2.0")).toBe("json-rpc");
});
it("returns null for unknown protocols", () => {
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
expect(classifyProtocolFamily(null, null)).toBeNull();
});
});
describe("JSON-RPC decoding", () => {
it("decodes the captured MCP SDK initialize request with exact field values", async () => {
const payload = await readFile(
new URL(
"../../tests/fixtures/golden/mcp-initialize.json",
import.meta.url,
),
);
expect(decodeJsonRpc(payload)).toEqual({
decoded_fields: [
{
path: "method",
wire_type: "json",
value: "initialize",
inferred: false,
},
{
path: "params",
wire_type: "json",
inferred: false,
value: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "rea-protocol-golden", version: "1" },
},
},
{ path: "jsonrpc", wire_type: "json", value: "2.0", inferred: false },
{ path: "id", wire_type: "json", value: 0, inferred: false },
],
truncated: false,
});
});
it("preserves decoded fields whose names resemble credentials", () => {
const payload = new TextEncoder().encode(
JSON.stringify({
password: "observed-value",
authorization: { scheme: "custom", value: "observed-header" },
username: "admin",
}),
);
const result = decodeJsonRpc(payload);
expect(result.decoded_fields).toEqual([
{
path: "password",
wire_type: "json",
value: "observed-value",
inferred: false,
},
{
path: "authorization",
wire_type: "json",
value: { scheme: "custom", value: "observed-header" },
inferred: false,
},
{
path: "username",
wire_type: "json",
value: "admin",
inferred: false,
},
]);
});
});
describe("MessagePack decoding", () => {
it("does not report unobserved payload bytes as truncation", () => {
const result = decodeMessagePack(new Uint8Array(10_001).fill(0x82));
expect(result.truncated).toBe(false);
});
it("detects map type", () => {
const payload = new Uint8Array([0x82]);
const result = decodeMessagePack(payload);
expect(result.decoded_fields[0]?.value).toBe("map");
});
it("detects array type", () => {
const payload = new Uint8Array([0x92]);
const result = decodeMessagePack(payload);
expect(result.decoded_fields[0]?.value).toBe("array");
});
it("reports unknown type for other tags", () => {
const payload = new Uint8Array([0xff]);
const result = decodeMessagePack(payload);
expect(result.decoded_fields[0]?.value).toBe("unknown");
expect(result.decoded_fields[0]?.inferred).toBe(true);
});
});
describe("gRPC frame decoding", () => {
it("decodes a valid gRPC frame header", () => {
const payload = new Uint8Array([
0x00, 0x00, 0x00, 0x00, 0x05, 1, 2, 3, 4, 5,
]);
const result = decodeGrpcFrame(payload);
expect(result.decoded_fields).toHaveLength(2);
expect(result.decoded_fields[0]?.path).toBe("compressed");
expect(result.decoded_fields[0]?.value).toBe(false);
expect(result.decoded_fields[1]?.path).toBe("message_length");
expect(result.decoded_fields[1]?.value).toBe(5);
});
it("detects compressed flag", () => {
const payload = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x0a]);
const result = decodeGrpcFrame(payload);
expect(result.decoded_fields[0]?.value).toBe(true);
});
it("handles too-short frames", () => {
const payload = new Uint8Array([0x00, 0x01]);
const result = decodeGrpcFrame(payload);
expect(result.decoded_fields[0]?.path).toBe("error");
});
});
describe("schema inference", () => {
it("infers schema from repeated messages", () => {
const messages: ProtocolMessage[] = [
{
sequence: 0,
at_ms: 0,
family: "json-rpc",
direction: "request",
endpoint: "/api",
content_type: "application/json",
raw_payload: null,
decoded_fields: [
{ path: "method", wire_type: "json", value: "add", inferred: false },
{ path: "id", wire_type: "json", value: 1, inferred: false },
],
schema_hypotheses: [],
truncated: false,
credentials_redacted: false,
},
{
sequence: 1,
at_ms: 10,
family: "json-rpc",
direction: "response",
endpoint: "/api",
content_type: "application/json",
raw_payload: null,
decoded_fields: [
{ path: "result", wire_type: "json", value: 3, inferred: false },
{ path: "id", wire_type: "json", value: 1, inferred: false },
],
schema_hypotheses: [],
truncated: false,
credentials_redacted: false,
},
];
const hypotheses = inferMessageSchema(messages);
expect(hypotheses).toHaveLength(3);
const idHypothesis = hypotheses.find((h) => h.field_name === "id");
expect(idHypothesis).toBeDefined();
expect(idHypothesis!.evidence_count).toBe(2);
expect(idHypothesis!.confidence).toBe(1);
});
});
describe("protocol capture schema validation", () => {
it("rejects a capture with an unknown protocol family", () => {
const result = protocolCaptureSchema.safeParse({
family: "smtp",
messages: [],
inferred_schema: [],
has_truncated: false,
credentials_detected: false,
});
expect(result.success).toBe(false);
});
it("rejects a capture that declares a non-boolean truncation flag", () => {
const result = protocolCaptureSchema.safeParse({
family: "grpc",
messages: [],
inferred_schema: [],
has_truncated: "no",
credentials_detected: false,
});
expect(result.success).toBe(false);
});
});
-243
View File
@@ -1,243 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Supported protocol families for structured protocol capture. */
export const protocolFamilySchema = z.enum([
"grpc",
"protobuf",
"json-rpc",
"messagepack",
]);
export type ProtocolFamily = z.infer<typeof protocolFamilySchema>;
/** A decoded field from a protocol message. */
export const decodedFieldSchema = z.strictObject({
/** Field name or path within the message structure. */
path: z.string().min(1),
/** Wire type or encoding hint. */
wire_type: z.string().nullable(),
/** Decoded field value. */
value: jsonValueSchema.nullable(),
/** Whether this field value was inferred rather than decoded. */
inferred: z.boolean().default(false),
});
export type DecodedField = z.infer<typeof decodedFieldSchema>;
/** Schema inference hypothesis for a repeated message pattern. */
export const schemaHypothesisSchema = z.strictObject({
/** Hypothesized field name. */
field_name: z.string().min(1),
/** Inferred type. */
inferred_type: z.string().min(1),
/** Confidence: 0-1 */
confidence: z.number().min(0).max(1),
/** Supporting evidence count. */
evidence_count: z.number().int().nonnegative(),
});
export type SchemaHypothesis = z.infer<typeof schemaHypothesisSchema>;
/** Result of decoding a single protocol message. */
export const protocolMessageSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Protocol family. */
family: protocolFamilySchema,
/** Direction of the message. */
direction: z.enum(["request", "response"]),
/** Transport endpoint or path (e.g. gRPC method path). */
endpoint: z.string().nullable(),
/** Content type of the raw payload. */
content_type: z.string().nullable(),
/** Raw payload bytes as base64. */
raw_payload: z.string().nullable(),
/** Decoded fields from the payload. */
decoded_fields: z.array(decodedFieldSchema).default([]),
/** Inferred schema hypotheses. */
schema_hypotheses: z.array(schemaHypothesisSchema).default([]),
/** Whether decoding was truncated. */
truncated: z.boolean().default(false),
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
});
export type ProtocolMessage = z.infer<typeof protocolMessageSchema>;
/** A captured protocol session with messages and inferred schemas. */
export const protocolCaptureSchema = z.strictObject({
/** Protocol family for this capture. */
family: protocolFamilySchema,
/** Captured messages in order. */
messages: z.array(protocolMessageSchema).min(0),
/** Aggregated schema hypotheses across all messages. */
inferred_schema: z.array(schemaHypothesisSchema).default([]),
/** Whether any message was truncated. */
has_truncated: z.boolean().default(false),
/** Whether the capture producer marked credential content as redacted. */
credentials_detected: z.boolean().default(false),
});
/** Classification of a byte sequence as a known protocol family. */
export function classifyProtocolFamily(
contentType: string | null,
path: string | null,
): ProtocolFamily | null {
if (contentType) {
if (contentType.includes("application/grpc")) return "grpc";
if (contentType.includes("application/x-protobuf")) return "protobuf";
if (contentType.includes("application/json-rpc")) return "json-rpc";
if (
contentType.includes("application/msgpack") ||
contentType.includes("application/x-msgpack")
)
return "messagepack";
}
if (path) {
if (path.startsWith("/grpc.") || path.includes("/grpc/")) return "grpc";
if (path.includes("/json-rpc") || path.includes("/jsonrpc"))
return "json-rpc";
}
return null;
}
/** Decode a JSON-RPC message from raw payload bytes. */
export function decodeJsonRpc(rawPayload: Uint8Array): {
decoded_fields: DecodedField[];
truncated: boolean;
} {
const text = new TextDecoder().decode(rawPayload);
const parsed = jsonValueSchema.parse(JSON.parse(text));
const fields: DecodedField[] = [];
if (typeof parsed === "object" && parsed !== null) {
for (const [key, value] of Object.entries(parsed)) {
fields.push({
path: key,
wire_type: "json",
value,
inferred: false,
});
}
}
return { decoded_fields: fields, truncated: false };
}
/** Decode a MessagePack message (simplified: only checks basic structure). */
export function decodeMessagePack(rawPayload: Uint8Array): {
decoded_fields: DecodedField[];
truncated: boolean;
} {
const fields: DecodedField[] = [];
// MessagePack uses a single-byte type tag
if (rawPayload.length === 0) {
return { decoded_fields: [], truncated: false };
}
const tag = rawPayload[0];
if (tag === undefined) return { decoded_fields: [], truncated: false };
// Map type: 0x80-0x8f (fixmap), 0xde (map16), 0xdf (map32)
if ((tag >= 0x80 && tag <= 0x8f) || tag === 0xde || tag === 0xdf) {
fields.push({
path: "type",
wire_type: "msgpack",
value: "map",
inferred: false,
});
}
// Array type: 0x90-0x9f (fixarray), 0xdc (array16), 0xdd (array32)
else if ((tag >= 0x90 && tag <= 0x9f) || tag === 0xdc || tag === 0xdd) {
fields.push({
path: "type",
wire_type: "msgpack",
value: "array",
inferred: false,
});
} else {
fields.push({
path: "type",
wire_type: "msgpack",
value: "unknown",
inferred: true,
});
}
return {
decoded_fields: fields,
truncated: false,
};
}
/** Decode a gRPC frame (5-byte header + protobuf payload). */
export function decodeGrpcFrame(rawPayload: Uint8Array): {
decoded_fields: DecodedField[];
truncated: boolean;
} {
// gRPC uses a 5-byte prefix: 1 byte compressed flag + 4 byte length
if (rawPayload.length < 5) {
return {
decoded_fields: [
{
path: "error",
wire_type: "grpc",
value: "frame too short",
inferred: false,
},
],
truncated: false,
};
}
const compressed = rawPayload[0] !== 0;
const length =
((rawPayload[1] ?? 0) << 24) |
((rawPayload[2] ?? 0) << 16) |
((rawPayload[3] ?? 0) << 8) |
(rawPayload[4] ?? 0);
return {
decoded_fields: [
{
path: "compressed",
wire_type: "grpc",
value: compressed,
inferred: false,
},
{
path: "message_length",
wire_type: "grpc",
value: length,
inferred: false,
},
],
truncated: false,
};
}
/** Infer schema hypotheses from a set of decoded messages. */
export function inferMessageSchema(
messages: readonly ProtocolMessage[],
): SchemaHypothesis[] {
const fieldCounts = new Map<string, { count: number; types: Set<string> }>();
for (const msg of messages) {
for (const field of msg.decoded_fields) {
const existing = fieldCounts.get(field.path);
if (existing) {
existing.count++;
if (field.wire_type) existing.types.add(field.wire_type);
} else {
fieldCounts.set(field.path, {
count: 1,
types: new Set(field.wire_type ?? "unknown"),
});
}
}
}
const hypotheses: SchemaHypothesis[] = [];
for (const [field_name, data] of fieldCounts) {
hypotheses.push({
field_name,
inferred_type: [...data.types].join("|"),
confidence: Math.min(1, data.count / messages.length || 0),
evidence_count: data.count,
});
}
return hypotheses;
}
-265
View File
@@ -1,265 +0,0 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
import { evidenceSchema } from "./evidence.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const runtimeFamilySchema = z.enum([
"android",
"apple",
"javascript",
"jvm",
"native",
"webassembly",
]);
const observationSchema = z.strictObject({
path: z.string().min(1),
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
const runtimeObservationShape = {
family: runtimeFamilySchema,
observations: z.array(observationSchema),
};
const identifiedRuntimeSchema = z.discriminatedUnion("inspection", [
z.strictObject({
...runtimeObservationShape,
inspection: z.literal("available"),
provider_id: z.string().min(1),
reason: z.null(),
}),
z.strictObject({
...runtimeObservationShape,
inspection: z.literal("provider-missing"),
provider_id: z.null(),
reason: z.string().min(1),
}),
z.strictObject({
...runtimeObservationShape,
inspection: z.literal("provider-selection-required"),
provider_id: z.null(),
reason: z.string().min(1),
}),
]);
/** Authenticated artifact inventory pages to classify by runtime family. */
const runtimeIdentificationInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Provider-neutral runtime identification with explicit tooling availability. */
export const runtimeIdentificationResultSchema = z.strictObject({
identification_id: prefixedDigestSchema("rid"),
root_sha256: digestSchema,
root_format: z.string().min(1),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
runtimes: z.array(identifiedRuntimeSchema),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
});
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";
readonly id: string;
readonly reason: null;
}
| {
readonly inspection: "provider-missing" | "provider-selection-required";
readonly id: null;
readonly reason: string;
};
const PROVIDERS: Readonly<Record<RuntimeFamily, RuntimeProvider>> = {
android: {
inspection: "available",
id: "rea-android-application",
reason: null,
},
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,
});
const runtimes = [...grouped.entries()]
.sort(([left], [right]) => compare(left, right))
.map(([family, values]) => {
const unique = deduplicate(values);
const provider = providerFor(family, inventory.manifest.root_format);
return {
family,
...runtimeInspection(provider),
observations: unique,
};
});
const limitations = [
...(!inventory.complete
? [
"Source inventory pages are incomplete; absent runtimes remain unknown.",
]
: []),
"Runtime families are identified from exact artifact formats and paths; semantic claims require the named provider.",
];
const withoutId = {
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: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
},
limitations,
};
return runtimeIdentificationResultSchema.parse({
...withoutId,
identification_id: `rid_${digest(withoutId)}`,
});
};
const providerFor = (
family: RuntimeFamily,
rootFormat: string,
): RuntimeProvider =>
family === "android" && rootFormat !== "apk"
? {
inspection: "provider-selection-required",
id: null,
reason:
"Extract or select an APK root before using the Android application provider.",
}
: PROVIDERS[family];
const runtimeInspection = (provider: RuntimeProvider) =>
provider.inspection === "available"
? {
inspection: provider.inspection,
provider_id: provider.id,
reason: null,
}
: {
inspection: provider.inspection,
provider_id: null,
reason: provider.reason,
};
const familiesFor = (format: string, path: string): RuntimeFamily[] => {
const families = new Set<RuntimeFamily>();
if (
format === "apk" ||
format === "dex" ||
/(?:^|\/)[^/]+\.dex$/iu.test(path) ||
/(?:^|\/)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" || /(?:^|\/)[^/]+\.class$/iu.test(path))
families.add("jvm");
if (
["elf", "mach-o", "mach-o-universal", "pe", "dos-mz", "dos-com"].includes(
format,
)
)
families.add("native");
if (format === "webassembly" || /(?:^|\/)[^/]+\.wasm$/iu.test(path))
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");
};
@@ -9,9 +9,6 @@ import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../../src/artifacts/Art
import { scanCanonicalArtifactInventory } from "../../../src/application/ArtifactInventory/scanCanonical.js";
import { targetFormatSchema } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { identifyRuntimes } from "../../../src/domain/runtimeIdentification.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("MZ artifact classification", () => {
@@ -62,7 +59,7 @@ describe("MZ artifact classification", () => {
expect(targetFormatSchema.parse("dos-mz")).toBe("dos-mz");
});
it("keeps standalone and embedded DOS identities through inventory and runtime evidence", async () => {
it("keeps standalone and embedded DOS identities through inventory", async () => {
const directory = await createTestTempDirectory("rea-mz-inventory-");
const dosPath = join(directory, "LEGACY.EXE");
const pePath = join(directory, "NATIVE.EXE");
@@ -88,30 +85,6 @@ describe("MZ artifact classification", () => {
expect(inventory.nodes.map(({ format }) => format)).toEqual(
expect.arrayContaining(["dos-mz", "pe"]),
);
const evidence = createEvidence(
{
path: tree,
sha256: inventory.manifest.root_sha256,
format: "directory",
},
{ id: "inventory-fixture", name: "Inventory fixture", version: null },
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(inventory),
},
);
const runtimes = identifyRuntimes({ inventory_evidence: [evidence] });
expect(runtimes.runtimes).toContainEqual(
expect.objectContaining({
family: "native",
inspection: "provider-selection-required",
observations: expect.arrayContaining([
expect.objectContaining({ path: "LEGACY.EXE", format: "dos-mz" }),
expect.objectContaining({ path: "NATIVE.EXE", format: "pe" }),
]),
}),
);
});
});
@@ -1,18 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { scanAuthorizedArtifactInventory } from "../../../src/application/AuthorizedArtifactInventory.js";
describe("authorized artifact inventory", () => {
it("scans a local artifact without configured input roots", async () => {
const root = await createTestTempDirectory("rea-artifact-roots-");
const path = join(root, "artifact.js");
await writeFile(path, "export const value = 1;\n");
const inventory = await scanAuthorizedArtifactInventory(path);
expect(inventory.manifest.root_format).toBe("javascript-bundle");
});
});
@@ -1,191 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { runProviderAnalysis } from "../../../src/composition/directAnalysis.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
identifyRuntimes,
runtimeIdentificationResultSchema,
} from "../../../src/domain/runtimeIdentification.js";
describe("runtime identification", () => {
it("identifies APK runtime families and exposes missing semantic providers", async () => {
const root = await createTestTempDirectory("rea-runtime-");
const path = join(root, "Fixture.apk");
await writeApkRuntimeFixture(path);
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const first = identifyRuntimes({ inventory_evidence: [inventory] });
const second = identifyRuntimes({ inventory_evidence: [inventory] });
expect(first).toEqual(second);
expect(runtimeIdentificationResultSchema.parse(first)).toMatchObject({
root_format: "apk",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(first.runtimes.map(({ family }) => family)).toEqual([
"android",
"javascript",
"jvm",
"native",
"webassembly",
]);
expect(first.runtimes).toEqual(
expect.arrayContaining([
expect.objectContaining({
family: "android",
inspection: "available",
provider_id: "rea-android-application",
}),
expect.objectContaining({
family: "jvm",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "webassembly",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "javascript",
inspection: "available",
provider_id: "rea-javascript-application",
}),
expect.objectContaining({
family: "native",
inspection: "provider-selection-required",
provider_id: null,
}),
]),
);
const widened = runtimeIdentificationResultSchema.parse({
...first,
root_format: "x".repeat(101),
source_evidence_ids: Array.from(
{ length: 101 },
() => inventory.evidence_id,
),
limitations: Array.from({ length: 101 }, () => "x".repeat(4_097)),
runtimes: first.runtimes.map((runtime) => ({
...runtime,
...(runtime.provider_id === null
? { reason: "x".repeat(1_001) }
: { provider_id: `provider-${"x".repeat(200)}` }),
observations: runtime.observations.map((observation) => ({
...observation,
path: "x".repeat(4_097),
format: "x".repeat(101),
})),
})),
});
expect(widened.limitations).toHaveLength(101);
expect(widened.runtimes[0]?.observations[0]?.path).toHaveLength(4_097);
const available = first.runtimes.find(
({ inspection }) => inspection === "available",
);
if (available === undefined)
throw new TypeError("Expected an available runtime provider");
expect(
runtimeIdentificationResultSchema.safeParse({
...first,
runtimes: [{ ...available, provider_id: null, reason: "Missing." }],
}).success,
).toBe(false);
});
it("accepts more than 100 supplied inventory Evidence records", async () => {
const root = await createTestTempDirectory("rea-runtime-pages-");
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("one.js", new TextReader("one"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = identifyRuntimes({
inventory_evidence: Array.from({ length: 101 }, () => inventory),
});
expect(result.source_evidence_ids).toHaveLength(101);
expect(result.coverage.status).toBe("complete-within-inventory");
expect(result.runtimes).toContainEqual(
expect.objectContaining({
family: "javascript",
observations: expect.arrayContaining([
expect.objectContaining({ path: "one.js" }),
]),
}),
);
});
it("does not route nested DEX content to the APK-only provider", async () => {
const root = await createTestTempDirectory("rea-runtime-dex-");
const path = join(root, "Fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = identifyRuntimes({ inventory_evidence: [inventory] });
expect(result.runtimes).toContainEqual(
expect.objectContaining({
family: "android",
inspection: "provider-selection-required",
provider_id: null,
}),
);
});
});
const writeApkRuntimeFixture = async (path: string): Promise<void> => {
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0, 8, 0, 0, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
),
);
await writer.add(
"assets/Fixture.class",
new Uint8ArrayReader(
Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]),
),
);
await writer.add(
"assets/module.wasm",
new Uint8ArrayReader(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])),
);
await writer.add("assets/main.js", new TextReader("bridge.call();"));
await writer.add(
"lib/arm64-v8a/libfixture.so",
new Uint8ArrayReader(Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0])),
);
await writeFile(path, await writer.close());
};
@@ -1,81 +0,0 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { lstat, readdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
createStoreFileLock,
removeStaleStoreFileLock,
} from "../../../src/application/StoreFileLock.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("store lock cleanup ownership", () => {
it.each(["released", "replaced"] as const)(
"preserves a successor lock when an old %s owner cleans up",
async (state) => {
const root = await createTestTempDirectory("rea-store-lock-owner-");
const path = join(root, "transaction.lock");
const previous = await createStoreFileLock(path);
if (state === "released") await previous.release();
else await rm(path, { recursive: true });
const successor = await createStoreFileLock(path);
try {
await previous.release();
await expect(lstat(path)).resolves.toBeDefined();
await expect(createStoreFileLock(path)).rejects.toMatchObject({
code: "EEXIST",
});
} finally {
await successor.release();
}
},
);
});
describe("store lock acquisition and recovery", () => {
it("admits one concurrent owner and removes all preparation directories", async () => {
const root = await createTestTempDirectory("rea-store-lock-contenders-");
const path = join(root, "transaction.lock");
const results = await Promise.allSettled(
Array.from({ length: 8 }, () => createStoreFileLock(path)),
);
try {
expect(
results.filter((result) => result.status === "fulfilled"),
).toHaveLength(1);
for (const result of results)
if (result.status === "rejected")
expect(result.reason).toMatchObject({ code: "EEXIST" });
expect(await readdir(root)).toEqual(["transaction.lock"]);
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await Promise.all(
results.map((result) =>
result.status === "fulfilled" ? result.value.release() : undefined,
),
);
}
expect(await readdir(root)).toEqual([]);
});
it("recovers a directory lock abandoned by an exited process", async () => {
const root = await createTestTempDirectory("rea-store-lock-exited-");
const path = join(root, "transaction.lock");
await promisify(execFile)(
process.execPath,
["tests/fixtures/abandonStoreFileLock.mjs", path],
{ timeout: 5_000 },
);
expect((await lstat(path)).isDirectory()).toBe(true);
expect(await removeStaleStoreFileLock(path)).toBe(true);
const successor = await createStoreFileLock(path);
try {
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await successor.release();
}
expect(await readdir(root)).toEqual([]);
});
});
@@ -3,7 +3,6 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { parseMachineType } from "../../../../src/domain/peInspection.js";
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
import { ManagedStaticProvider } from "../../../../src/dotnet/ManagedStaticProvider.js";
@@ -24,7 +23,6 @@ it.each([0x01c0, 0x01c2, 0x01c4])(
architecture: "arm",
managed: true,
});
expect(parseMachineType(machine)).toBe("arm");
const client = new ManagedStaticProvider().createClient(parsed.value);
try {
for (const operation of [
@@ -4,8 +4,6 @@ import type { VerifierContract } from "../../../src/domain/conformancePackage.js
import {
compareDimension,
evaluateTrustGate,
isSemanticDimension,
isVolatileDimension,
trustGateResultSchema,
} from "../../../src/domain/conformanceTrustGate.js";
@@ -35,52 +33,6 @@ const expectDivergenceRejected = (
};
describe("conformance trust gates", () => {
it("classifies volatile dimensions correctly", () => {
expect(isVolatileDimension("timing")).toBe(true);
expect(isVolatileDimension("timestamp")).toBe(true);
expect(isVolatileDimension("pid")).toBe(true);
expect(isVolatileDimension("exit_code")).toBe(false);
});
it("classifies semantic dimensions correctly", () => {
expect(isSemanticDimension("exit_code")).toBe(true);
expect(isSemanticDimension("stdout")).toBe(true);
expect(isSemanticDimension("timing")).toBe(false);
});
it("matches identical values", () => {
const result = compareDimension("exit_code", 0, 0);
expect(result.status).toBe("match");
});
it("detects mismatches", () => {
const result = compareDimension("exit_code", 0, 1);
expect(result.status).toBe("mismatch");
});
it("ignores volatile dimensions", () => {
const result = compareDimension("timing", 100, 200);
expect(result.status).toBe("match");
expect(result.message).toContain("volatile");
});
it("handles truncated evidence", () => {
const result = compareDimension("exit_code", 0, null, {
truncated: true,
});
expect(result.status).toBe("truncated");
});
it("handles undefined values", () => {
const result = compareDimension("exit_code", undefined, undefined);
expect(result.status).toBe("unknown");
});
it("handles missing actual", () => {
const result = compareDimension("exit_code", 0, undefined);
expect(result.status).toBe("unknown");
});
it("keeps semantic unknown and truncated values out of equivalence", () => {
expect(
compareDimension(
-6
View File
@@ -1,6 +0,0 @@
import { createStoreFileLock } from "../../dist/application/StoreFileLock.js";
const path = process.argv[2];
if (path === undefined) throw new Error("A lock path is required");
await createStoreFileLock(path);
// Exit without invoking release so the parent can exercise dead-owner recovery.