Merge remote-tracking branch 'origin/main'

This commit is contained in:
morluto
2026-10-13 14:51:59 +08:00
36 changed files with 1047 additions and 96 deletions
+2 -1
View File
@@ -144,7 +144,8 @@ const projectHar = (
(literal) =>
item.includes(literal) ||
contentBase64.includes(literal) ||
sha256.includes(literal),
sha256.includes(literal) ||
String(bytes.length).includes(literal),
);
binary_fields.push(
hidden
+12
View File
@@ -3,6 +3,18 @@ import { describe, expect, it } from "vitest";
import { parseConfig } from "./config/parseConfig.js";
import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
it("reports a configuration failure for a NUL in Hopper loader arguments", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: JSON.stringify(["--option", "value\0suffix"]),
});
if (result.ok)
throw new Error("NUL argv cannot be passed to a child process");
expect(result.error).toMatchObject({
settings: [{ setting: "HOPPER_LOADER_ARGS_JSON" }],
});
expect(result.error.message).toContain("NUL");
});
describe("runtime configuration", () => {
it("allows target-free startup and applies runtime defaults", () => {
const empty = parseConfig({});
+5 -8
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { nulFreeStringSchema } from "../domain/localPath.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
@@ -20,7 +21,8 @@ export const parseLoaderArgs = (
return parseConfiguredStringArray(
encoded,
"HOPPER_LOADER_ARGS_JSON",
z.string(),
nulFreeStringSchema,
"must encode an array of strings without NUL bytes",
);
};
@@ -28,6 +30,7 @@ const parseConfiguredStringArray = (
encoded: string,
setting: string,
itemSchema: z.ZodString,
requirement = "must encode an array of strings",
): Result<readonly string[], ConfigurationError> => {
const decoded = safeParseJson(encoded);
if (!decoded.ok)
@@ -37,13 +40,7 @@ const parseConfiguredStringArray = (
const parsed = z.array(itemSchema).safeParse(decoded.value);
return parsed.success
? ok(parsed.data)
: err(
configuredArrayError(
setting,
"must encode an array of strings",
parsed.error,
),
);
: err(configuredArrayError(setting, requirement, parsed.error));
};
const configuredArrayError = (
+130
View File
@@ -597,6 +597,136 @@ describe("dyld load order", () => {
});
});
describe("loader-relative dylib resolution", () => {
it("does not reuse already loaded images by install name for @loader_path dependencies", async () => {
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
const helperA = "Contents/PlugIns/A/libhelper.dylib";
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
],
}),
[pluginA]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperA]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
[pluginB]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
}),
{ roots: [MAIN] },
);
const edgeA = edgeFor(trace, pluginA, "@loader_path/libhelper.dylib");
expect(edgeA.resolution).toEqual({
status: "resolved",
image: helperA,
});
expect(edgeA.candidates).toEqual([
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperA,
}),
]);
const edgeB = edgeFor(trace, pluginB, "@loader_path/libhelper.dylib");
expect(edgeB.resolution).toEqual({
status: "unresolved",
image: null,
});
expect(edgeB.candidates).toEqual([
expect.objectContaining({
path: "Contents/PlugIns/B/libhelper.dylib",
source: "loader_path",
outcome: "absent",
resolved_path: null,
}),
]);
expect(trace.findings).toContainEqual(
expect.objectContaining({
kind: "required-load-unresolved",
image: pluginB,
}),
);
});
it("resolves @loader_path dependencies to the loader's own directory when multiple helpers exist", async () => {
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
const helperA = "Contents/PlugIns/A/libhelper.dylib";
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
const helperB = "Contents/PlugIns/B/libhelper.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
],
}),
[pluginA]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperA]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
[pluginB]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperB]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, pluginA, "@loader_path/libhelper.dylib"),
).toMatchObject({
resolution: { status: "resolved", image: helperA },
candidates: [
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperA,
}),
],
});
expect(
edgeFor(trace, pluginB, "@loader_path/libhelper.dylib"),
).toMatchObject({
resolution: { status: "resolved", image: helperB },
candidates: [
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperB,
}),
],
});
});
});
describe("dyld slice compatibility and coverage", () => {
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
const files = {
+8 -2
View File
@@ -427,7 +427,9 @@ const resolveDependency = async (
): Promise<Edge> => {
const current = context.loaded.get(loader);
const chain = current?.chain ?? [loader];
const loaded = context.byInstallName.get(dependency.install_name);
const loaded = dependency.install_name.startsWith("@rpath/")
? context.byInstallName.get(dependency.install_name)
: undefined;
const candidates: Candidate[] = [];
if (loaded !== undefined)
candidates.push({
@@ -506,7 +508,10 @@ const traceProcess = async (
chain: [context.root],
conditional: false,
});
if (rootSlice.install_name !== null)
if (
rootSlice.install_name !== null &&
rootSlice.install_name.startsWith("@rpath/")
)
context.byInstallName.set(rootSlice.install_name, context.root);
const pending = [context.root];
while (pending.length > 0) {
@@ -537,6 +542,7 @@ const traceProcess = async (
});
if (
slice.install_name !== null &&
slice.install_name.startsWith("@rpath/") &&
!context.byInstallName.has(slice.install_name)
)
context.byInstallName.set(slice.install_name, image);
+1 -1
View File
@@ -91,7 +91,7 @@ export const DYLIB_RESOLUTION_LIMITATIONS = [
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later @rpath request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
@@ -116,6 +116,24 @@ it("keeps unsupported profile reasons distinct from malformed input", () => {
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("preserves a retryable capability failure through explicit-value redaction", () => {
// Retryability is a semantic field of the error, not presentation: dropping
// it turns a transient admission failure into a permanent one and changes
// the remediation the caller is shown.
const error = new AnalysisCapabilityUnavailableError(
"mitmproxy",
"inspect_web_network_capture",
"Runtime admission for /targets/private/capture failed transiently",
{ retryable: true },
);
expect(projectAnalysisError(error).retryable).toBe(true);
const result = redactExplicitFailure(error, ["private"]);
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
expect((result as AnalysisCapabilityUnavailableError).retryable).toBe(true);
expect(projectAnalysisError(result).retryable).toBe(true);
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("coarsens format issue pointers without creating replacement coordinates", () => {
const error = new AnalysisInputError(
"inspect_web_network_capture",
+1
View File
@@ -154,6 +154,7 @@ export const redactExplicitFailure = (
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
...(error.retryable ? { retryable: true } : {}),
},
);
if (error instanceof AnalysisResourceConstraintError)
@@ -1,4 +1,4 @@
import { posix, relative, win32 } from "node:path";
import { posix, win32 } from "node:path";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
@@ -216,7 +216,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
const remainder =
rootStyle === "windows"
? win32.relative(root, value)
: relative(root, value);
: posix.relative(root, value);
const portableRemainder = remainder.replaceAll("\\", "/");
if (
remainder === "" ||
+42 -17
View File
@@ -37,10 +37,19 @@ export const parserPluginsForPath = (sourcePath?: string): ParserPlugin[] => {
: ["decorators-legacy", typescript];
};
/** `.mjs` and `.mts` are modules by extension; other paths leave the mode to syntax. */
/** `.mjs` and `.mts` explicitly select module mode. */
export const isExplicitModuleSourcePath = (path?: string): boolean =>
/\.m[jt]s$/iu.test(path ?? "");
const runtimeSourceTypeForPath = (
path?: string,
): "commonjs" | "module" | "unambiguous" =>
/\.cjs$/iu.test(path ?? "")
? "commonjs"
: isExplicitModuleSourcePath(path)
? "module"
: "unambiguous";
export interface RecoveredJavaScriptParse {
readonly file: ParsedJavaScriptSource;
/** Errors that apply only if a source of unknown mode is an ES module. */
@@ -58,25 +67,25 @@ export const parseRecoveredJavaScript = (
sourcePath: string | undefined,
options: Omit<ParserOptions, "sourceType" | "errorRecovery">,
): RecoveredJavaScriptParse => {
// `.cjs` is CommonJS by extension, so module-only errors cannot apply.
if (/\.cjs$/iu.test(sourcePath ?? ""))
const sourceType = runtimeSourceTypeForPath(sourcePath);
if (sourceType !== "unambiguous") {
const normalizedOptions = { ...options };
if (sourceType === "commonjs") {
// Babel owns these wrapper semantics in CommonJS mode and rejects
// explicit script overrides, including the reference-import options.
delete normalizedOptions.allowAwaitOutsideFunction;
delete normalizedOptions.allowReturnOutsideFunction;
delete normalizedOptions.allowNewTargetOutsideFunction;
}
return {
file: parse(source, {
...options,
sourceType: "script",
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
if (isExplicitModuleSourcePath(sourcePath))
return {
file: parse(source, {
...options,
sourceType: "module",
...normalizedOptions,
sourceType,
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
}
const file = parse(source, {
...options,
sourceType: "unambiguous",
@@ -98,18 +107,34 @@ export const parseRecoveredJavaScript = (
};
};
/** Parse JavaScript or TypeScript once without attaching comments to AST nodes. */
/** Parse inert JavaScript or TypeScript facts without attaching comments to AST nodes. */
export const parseJavaScriptSource = (
source: string,
sourcePath?: string,
): ParsedJavaScriptSource | null => {
try {
return parse(source, {
sourceType: "unambiguous",
const runtimeSourceType = runtimeSourceTypeForPath(sourcePath);
const commonjs = runtimeSourceType === "commonjs";
const options = {
errorRecovery: true,
attachComment: false,
plugins: parserPluginsForPath(sourcePath),
};
const file = parse(source, {
...options,
// Inert artifact analysis retains module declarations even in .cjs assets.
// Infer their syntax here; reference imports keep filename-mode diagnostics.
sourceType: commonjs ? "unambiguous" : runtimeSourceType,
allowReturnOutsideFunction: commonjs,
allowNewTargetOutsideFunction: commonjs,
});
// Unambiguous mode retains module-only diagnostics after choosing a script.
// The .cjs extension establishes wrapper mode, so obtain its own diagnostics.
return commonjs &&
file.program.sourceType === "script" &&
file.errors.length > 0
? parse(source, { ...options, sourceType: "commonjs" })
: file;
} catch (cause: unknown) {
// Unparseable source is represented by the null return.
void cause;
+21
View File
@@ -33,3 +33,24 @@ it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
expect(readPngHeaderDimensions(zero)).toBeUndefined();
}
});
it.each([0, 12, 14, 0xffff_ffff])("rejects IHDR data length %s", (length) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(length, 8);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it.each([16, 20])("rejects out-of-range PNG dimension at %s", (offset) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x8000_0000, offset);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it("accepts the largest dimension representable by the PNG specification", () => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x7fff_ffff, 16);
expect(readPngHeaderDimensions(bytes)).toEqual({
width: 0x7fff_ffff,
height: 1,
});
});
+7 -1
View File
@@ -8,10 +8,16 @@ export const readPngHeaderDimensions = (
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.readUInt32BE(8) !== 13 ||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
)
return undefined;
const width = bytes.readUInt32BE(16);
const height = bytes.readUInt32BE(20);
return width === 0 || height === 0 ? undefined : { width, height };
return width === 0 ||
height === 0 ||
width > 0x7fff_ffff ||
height > 0x7fff_ffff
? undefined
: { width, height };
};
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { parseProcessCapture } from "./processCaptureParsing.js";
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
import { processTraceSpecificationSchema as specificationSchema } from "./processTraceSpecification.js";
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
import {
capture,
@@ -100,6 +101,33 @@ describe("generic capture trace comparison", () => {
right: { matched_variant: "two" },
});
});
it("compares a declared identifier the comparison result can represent", () => {
// The specification owns the trace identifier vocabulary and the result
// echoes those identifiers verbatim, so both must accept the same values
// rather than handing the caller a raw schema error for its own input.
const eventId = `e${"0".repeat(64)}`;
const specification: ProcessTraceSpecification = {
events: [
{
id: eventId,
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "only", trace: [eventId] }],
},
};
expect(specificationSchema.safeParse(specification).success).toBe(true);
const left = capture(values(["terminal", "process"]));
expect(compareProcessTraces(left, left, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "only", raw_trace: [{ event_id: eventId }] },
});
});
});
describe("process trace constraints and evidence sufficiency", () => {
+4 -5
View File
@@ -13,13 +13,12 @@ import {
import {
canonicalTraceJson,
processTraceCardinalityBounds,
processTraceIdentifierSchema,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._\x2d]{0,63}$/u);
const matchedEventSchema = z.strictObject({
event_id: identifierSchema,
event_id: processTraceIdentifierSchema,
location: processObservationLocationSchema,
});
@@ -32,7 +31,7 @@ const sideResultSchema = z.union([
z.strictObject({
...sideResultShape,
status: z.literal("pass"),
matched_variant: identifierSchema.nullable(),
matched_variant: processTraceIdentifierSchema.nullable(),
}),
z.strictObject({
...sideResultShape,
@@ -53,7 +52,7 @@ const diagnosticSchema = z.strictObject({
]),
side: z.enum(["left", "right"]),
message: z.string(),
event_ids: z.array(identifierSchema),
event_ids: z.array(processTraceIdentifierSchema),
locations: z.array(processObservationLocationSchema),
});
+23 -12
View File
@@ -9,7 +9,16 @@ import {
processObservationSourceSchema,
} from "./processObservation.js";
const identifierSchema = z.string().regex(IDENTIFIER_PATTERN);
/**
* A declared trace, event or variant identifier. The specification owns this
* vocabulary and the comparison result echoes those identifiers verbatim, so
* the result module must reuse this schema rather than restate the pattern:
* two bounds on the same identifier would reject the result of an accepted
* specification.
*/
export const processTraceIdentifierSchema = z
.string()
.regex(IDENTIFIER_PATTERN);
const cardinalitySchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("required") }),
@@ -31,7 +40,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
]);
const eventDeclarationSchema = z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
source: processObservationSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
@@ -56,29 +65,31 @@ const partialOrderLanguageSchema = z.strictObject({
happens_before: z
.array(
z.strictObject({
before: identifierSchema,
after: identifierSchema,
before: processTraceIdentifierSchema,
after: processTraceIdentifierSchema,
}),
)
.default([]),
not_before: z
.array(
z.strictObject({
event: identifierSchema,
anchor: identifierSchema,
event: processTraceIdentifierSchema,
anchor: processTraceIdentifierSchema,
}),
)
.default([]),
unordered_groups: z
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
.array(
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
)
.default([]),
prefix: z.array(identifierSchema).default([]),
suffix: z.array(identifierSchema).default([]),
prefix: z.array(processTraceIdentifierSchema).default([]),
suffix: z.array(processTraceIdentifierSchema).default([]),
});
const finiteTraceTokenSchema = z.union([
identifierSchema,
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
processTraceIdentifierSchema,
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
]);
const finiteTraceLanguageSchema = z.strictObject({
@@ -86,7 +97,7 @@ const finiteTraceLanguageSchema = z.strictObject({
variants: z
.array(
z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
trace: z.array(finiteTraceTokenSchema),
}),
)
+3 -2
View File
@@ -23,6 +23,7 @@ import {
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import {
@@ -759,7 +760,7 @@ export class FlutterBuildProvider {
toolchain_capped: value.libflutter.toolchainCapped,
},
}))
.sort((left, right) => left.abi.localeCompare(right.abi));
.sort((left, right) => compareUnicodeCodePoints(left.abi, right.abi));
const flutterDetected = abis.some((entry) => entry.libapp.present);
const partial =
abis.some(
@@ -871,7 +872,7 @@ export class FlutterBuildProvider {
(left, right) =>
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
left.abi.localeCompare(right.abi),
compareUnicodeCodePoints(left.abi, right.abi),
)[0]!
: candidates.find((candidate) => candidate.abi === abi);
if (selected === undefined)
+4 -2
View File
@@ -85,8 +85,10 @@ export class IdaWorkspace {
slice === undefined
? position + bytes.length
: Math.min(position + bytes.length, slice.offset + slice.size);
const admitted = bytes.subarray(start - position, end - position);
if (admitted.length > 0) {
// A chunk after the slice has end < position, and a negative subarray
// bound would count from the chunk's end instead of being empty.
if (end > start) {
const admitted = bytes.subarray(start - position, end - position);
inputHash.update(admitted);
await input.write(admitted);
}
+92 -1
View File
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
import { parseExecutableHeader } from "../domain/binaryTarget.js";
import { fat } from "../domain/binaryTarget.fixture.js";
import { fat, thinMach } from "../domain/binaryTarget.fixture.js";
import {
createIdaTarget,
RecordingIdaMcp,
@@ -35,6 +35,45 @@ const universalTarget = async (hostArchitecture: "arm64" | "x64") => {
return { bytes, target: resolved.value };
};
/** One slice of a synthetic universal file: CPU type, offset and size. */
interface Layout {
readonly cpu: number;
readonly offset: number;
readonly size: number;
}
/**
* Write a universal file whose slices span more than one 64 KiB read, each
* filled with its own byte so bytes outside the selected slice are visible.
*/
const largeUniversalTarget = async (
layout: readonly Layout[],
hostArchitecture: "arm64" | "x64",
) => {
const directory = await createTestTempDirectory("rea-ida-thin-large-");
roots.push(directory);
const path = join(directory, "universal");
const total = Math.max(...layout.map(({ offset, size }) => offset + size));
const bytes = Buffer.alloc(total);
bytes.writeUInt32BE(0xcafebabe, 0);
bytes.writeUInt32BE(layout.length, 4);
layout.forEach(({ cpu, offset, size }, index) => {
const entry = 8 + index * 20;
bytes.writeUInt32BE(cpu, entry);
bytes.writeUInt32BE(offset, entry + 8);
bytes.writeUInt32BE(size, entry + 12);
bytes.writeUInt32BE(14, entry + 16);
bytes.fill(0x11 * (index + 1), offset, offset + size);
thinMach(0xfeedfacf, cpu).copy(bytes, offset);
});
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path, { hostArchitecture });
if (!resolved.ok) throw resolved.error;
if (resolved.value.format !== "mach-o-universal")
throw new Error("the universal fixture did not resolve as a FAT container");
return { bytes, target: resolved.value };
};
describe("IDA workspace input thinning", () => {
it.skipIf(process.platform === "win32")(
"thins the selected arm64 slice into the private headless input",
@@ -78,6 +117,58 @@ describe("IDA workspace input thinning", () => {
},
);
it.skipIf(process.platform === "win32")(
"copies exactly the selected slice when later slices follow it across read boundaries",
async () => {
const { bytes, target } = await largeUniversalTarget(
[
{ cpu: 0x01000007, offset: 4096, size: 8480 },
{ cpu: 0x0100000c, offset: 16384, size: 33464 },
{ cpu: 0x00000007, offset: 65536, size: 33464 },
],
"arm64",
);
const workspace = await IdaWorkspace.allocate(target);
roots.push(workspace.directory);
await workspace.copyInput();
const input = await readFile(workspace.inputPath);
const { offset, size } = target.universalSlice;
expect(size, "the arm64 slice is selected").toBe(33464);
expect(input.length, "no byte after the slice is copied").toBe(size);
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
expect(workspace.inputSha256).toBe(
createHash("sha256")
.update(bytes.subarray(offset, offset + size))
.digest("hex"),
);
await workspace.remove();
},
);
it.skipIf(process.platform === "win32")(
"copies exactly the first slice when it is selected and others follow",
async () => {
const { bytes, target } = await largeUniversalTarget(
[
{ cpu: 0x01000007, offset: 16384, size: 37456 },
{ cpu: 0x0100000c, offset: 65536, size: 33464 },
],
"x64",
);
const workspace = await IdaWorkspace.allocate(target);
roots.push(workspace.directory);
await workspace.copyInput();
const input = await readFile(workspace.inputPath);
const { offset, size } = target.universalSlice;
expect(size, "the x86_64 slice is selected").toBe(37456);
expect(input.length, "no byte after the slice is copied").toBe(size);
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
await workspace.remove();
},
);
it("keeps a whole-file copy for thin targets", async () => {
const { root, target } = await createIdaTarget("arm64");
roots.push(root);
+31
View File
@@ -35,6 +35,37 @@ const validPng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
it.each([
{ offset: 8, value: 12 },
{ offset: 16, value: 0x8000_0000 },
{ offset: 20, value: 0x8000_0000 },
])(
"rejects invalid IHDR metadata with a matching digest",
async ({ offset, value }) => {
const bytes = Buffer.from(validPng);
bytes.writeUInt32BE(value, offset);
const screenshot = {
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: bytes.readUInt32BE(16),
height: bytes.readUInt32BE(20),
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
expect(result.ok).toBe(false);
},
);
describe("native UI screenshot validation", () => {
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
const screenshot = {
+18
View File
@@ -83,6 +83,24 @@ it("counts IPv6 endpoints once per packet and preserves every examined fact", as
expect(result.partial).toBe(false);
});
it("orders equal-count endpoints and protocols by code point, not host locale", async () => {
// Locale collation puts "fe80::1" first and, under da-DK, "aarp" after "zz".
const result = await parseTsharkJsonOutput(
capture([
{ "ipv6.src": ["fe80::1"], "frame.protocols": ["eth:llc:zz"] },
{ "ipv6.src": ["fe80:1::1"], "frame.protocols": ["eth:llc:aarp"] },
]),
);
expect(result.endpoints.map(({ address }) => address)).toEqual([
"fe80:1::1",
"fe80::1",
]);
expect(result.protocolDistribution.map(({ protocol }) => protocol)).toEqual([
"eth:llc:aarp",
"eth:llc:zz",
]);
});
it("preserves all DNS addresses and their exact examined count", async () => {
const result = await parseTsharkJsonOutput(
capture(
+3 -2
View File
@@ -4,6 +4,7 @@ import {
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
const OPERATION = "inspect_pcap_capture";
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
@@ -284,7 +285,7 @@ export const parseTsharkJsonOutput = async (
signal?.throwIfAborted();
return {
endpoints: [...endpoints]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([address, packet_count]) => ({
address,
port: null,
@@ -300,7 +301,7 @@ export const parseTsharkJsonOutput = async (
tlsSniValues: [...sni],
tlsSniCount: sni.size,
protocolDistribution: [...protocols]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
protocolCount: protocols.size,
httpRequestUris: [...uris],
+47 -31
View File
@@ -12,6 +12,8 @@ import { err, ok } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
interface EvidenceToolRegistration {
readonly server: EvidenceMcpServer;
@@ -92,40 +94,54 @@ const registerImportEvidenceTool = ({
resources,
importContract,
}: EvidenceToolRegistration): void => {
const admission = withAdmittedAnalysis({ kind: "session", session });
server.registerTool(
importContract.name,
toolRegistrationOptions(importContract),
async (input, context) => {
const path = input.path;
const signal = context.mcpReq.signal;
const loaded = await readImmutableEvidenceBundle(path, signal, resources);
if (!loaded.ok)
return server.delivery.toCallToolResult(loaded, importContract);
const retainedUnknownRevisions = new Set(
bundleForSerialization(session).unknowns.map((unknown) =>
unknownRevisionKey(unknown),
),
);
if (signal.aborted)
return server.delivery.toCallToolResult(
err(new AnalysisCancelledError("import_evidence_bundle")),
importContract,
);
const imported = session.importEvidenceBundle(loaded.value);
return imported.ok
? server.delivery.toCallToolResult(
ok({
imported: imported.value,
unknowns_added: loaded.value.unknowns.filter(
(unknown) =>
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
).length,
total: bundleForSerialization(session).records.length,
}),
importContract,
)
: server.delivery.toCallToolResult(imported, importContract);
},
async (input, context) =>
runAdmittedToolOperation(
server,
admission,
importContract.name,
context.mcpReq.signal,
async () => {
const path = input.path;
const signal = context.mcpReq.signal;
const loaded = await readImmutableEvidenceBundle(
path,
signal,
resources,
);
if (!loaded.ok)
return server.delivery.toCallToolResult(loaded, importContract);
const retainedUnknownRevisions = new Set(
bundleForSerialization(session).unknowns.map((unknown) =>
unknownRevisionKey(unknown),
),
);
if (signal.aborted)
return server.delivery.toCallToolResult(
err(new AnalysisCancelledError("import_evidence_bundle")),
importContract,
);
const imported = session.importEvidenceBundle(loaded.value);
return imported.ok
? server.delivery.toCallToolResult(
ok({
imported: imported.value,
unknowns_added: loaded.value.unknowns.filter(
(unknown) =>
!retainedUnknownRevisions.has(
unknownRevisionKey(unknown),
),
).length,
total: bundleForSerialization(session).records.length,
}),
importContract,
)
: server.delivery.toCallToolResult(imported, importContract);
},
),
);
};