fix(artifacts): preserve integrity evidence across workflows and integrate main
This commit is contained in:
+48
-15
@@ -1,7 +1,8 @@
|
||||
import { z } from "incur";
|
||||
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
|
||||
|
||||
import { runProviderAnalysis } from "../composition/directAnalysis.js";
|
||||
import { createArtifactExtractionDestination } from "../application/ArtifactExtractionDestination.js";
|
||||
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -15,6 +16,7 @@ export const registerArtifactCommands = (
|
||||
registerExtractionCommand(cli, logger);
|
||||
registerInterfaceBuilderCommand(cli, logger);
|
||||
registerAssetCatalogCommand(cli, logger);
|
||||
registerDylibResolutionCommand(cli, logger);
|
||||
cli.command(CLI_COMMANDS.inspectKeyedArchive, {
|
||||
description:
|
||||
"Inspect a Foundation keyed archive as an object-reference graph",
|
||||
@@ -58,6 +60,45 @@ export const registerArtifactCommands = (
|
||||
});
|
||||
};
|
||||
|
||||
const registerDylibResolutionCommand = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.traceDylibResolution, {
|
||||
description:
|
||||
"Trace dyld load-path resolution for a Mach-O or every executable in an app bundle",
|
||||
args: z.object({
|
||||
path: z.string().describe("Mach-O file or Apple .app bundle path"),
|
||||
}),
|
||||
options: z.object({
|
||||
root: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe(
|
||||
"Process root relative to the bundle or the Mach-O's directory (repeatable)",
|
||||
),
|
||||
architecture: z
|
||||
.enum(["arm64", "arm64e", "x86_64"])
|
||||
.optional()
|
||||
.describe("Trace only this slice of each root"),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.traceDylibResolution, () =>
|
||||
runProviderAnalysis(
|
||||
args.path,
|
||||
"trace_dylib_resolution",
|
||||
{
|
||||
...(options.root === undefined ? {} : { roots: options.root }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
},
|
||||
logger,
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerAssetCatalogCommand = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
@@ -154,14 +195,10 @@ const registerExtractionCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
path: z.string().describe("Application or package path"),
|
||||
}),
|
||||
options: z.object({
|
||||
integrityPolicy: z
|
||||
.enum(["fail", "record-and-continue"])
|
||||
.default("fail")
|
||||
.describe("Behavior when declared artifact integrity does not match"),
|
||||
integrityPolicy: artifactIntegrityPolicySchema.describe(
|
||||
"Behavior when declared artifact integrity does not match",
|
||||
),
|
||||
}),
|
||||
alias: {
|
||||
integrityPolicy: "integrity-policy",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "extract-artifact", () =>
|
||||
runProviderAnalysis(
|
||||
@@ -185,14 +222,10 @@ const registerInspectionCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
path: z.string().describe("Application or package path"),
|
||||
}),
|
||||
options: z.object({
|
||||
integrityPolicy: z
|
||||
.enum(["fail", "record-and-continue"])
|
||||
.default("fail")
|
||||
.describe("Behavior when declared artifact integrity does not match"),
|
||||
integrityPolicy: artifactIntegrityPolicySchema.describe(
|
||||
"Behavior when declared artifact integrity does not match",
|
||||
),
|
||||
}),
|
||||
alias: {
|
||||
integrityPolicy: "integrity-policy",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-artifact", () =>
|
||||
runProviderAnalysis(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
createRecordedCrashService,
|
||||
createBinaryLayoutService,
|
||||
} from "../composition/binaryDiagnostics.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Inspect operator-selected files through the same shared workflow as MCP. */
|
||||
export const registerBinaryDiagnosticsCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createBinaryLayoutService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectBinaryLayout, {
|
||||
description:
|
||||
"Inspect binary file/linked layout without executing the selected object",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local ELF binary or relocatable object"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectBinaryLayout, async () => {
|
||||
const result = await service.inspect(
|
||||
{ path: resolve(args.path) },
|
||||
{ signal },
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
const recorded = createRecordedCrashService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectRecordedCrash, {
|
||||
description:
|
||||
"Inspect supplied core registers/signals and optional debugger mapping evidence",
|
||||
args: z.object({ path: z.string().describe("Local Linux amd64 ELF core") }),
|
||||
options: z.object({
|
||||
debuggerContext: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Add BYO core-only GDB/pwndbg mapping candidates"),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectRecordedCrash, async () => {
|
||||
const result = await recorded.inspect(
|
||||
{
|
||||
path: resolve(args.path),
|
||||
include_debugger_context: options.debuggerContext,
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
} from "../application/BrowserObservationService.js";
|
||||
import { CdpBrowserProvider } from "../browser/CdpBrowserProvider.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
type AnalysisInputIssue,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../domain/browserCaptureComparison.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "../domain/webMcpDiscovery.js";
|
||||
import {
|
||||
@@ -89,19 +92,32 @@ const registerCaptureDiff = (
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "compare-web-captures", async () => {
|
||||
const before = parseJson(args.beforeJson);
|
||||
const after = parseJson(args.afterJson);
|
||||
const before = safeParseJson(args.beforeJson);
|
||||
const after = safeParseJson(args.afterJson);
|
||||
const normalization = safeParseJson(options.normalizationJson);
|
||||
if (!before.ok)
|
||||
return inputError("compare_web_captures", [
|
||||
invalidJsonIssue("before"),
|
||||
]);
|
||||
if (!after.ok)
|
||||
return inputError("compare_web_captures", [
|
||||
invalidJsonIssue("after"),
|
||||
]);
|
||||
if (!normalization.ok)
|
||||
return inputError("compare_web_captures", [
|
||||
invalidJsonIssue("normalization"),
|
||||
]);
|
||||
const scenarioComparison =
|
||||
browserCaptureComparisonInputSchema.safeParse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: parseJson(options.normalizationJson),
|
||||
before_scenario: before.value,
|
||||
after_scenario: after.value,
|
||||
normalization: normalization.value,
|
||||
});
|
||||
const parsed = scenarioComparison.success
|
||||
? scenarioComparison
|
||||
: browserCaptureComparisonInputSchema.safeParse({
|
||||
before,
|
||||
after,
|
||||
before: before.value,
|
||||
after: after.value,
|
||||
});
|
||||
if (!parsed.success) return inputError("compare_web_captures");
|
||||
const result = await compareWebCaptureEvidence(
|
||||
@@ -186,5 +202,14 @@ const parseJson = (value: string): unknown => {
|
||||
return parsed.ok ? parsed.value : undefined;
|
||||
};
|
||||
|
||||
const inputError = (operation: string): JsonValue =>
|
||||
browserCliError(new AnalysisInputError(operation));
|
||||
const invalidJsonIssue = (field: string): AnalysisInputIssue => ({
|
||||
path: [field],
|
||||
reason: "invalid_format",
|
||||
expected: "JSON",
|
||||
});
|
||||
|
||||
const inputError = (
|
||||
operation: string,
|
||||
issues: readonly AnalysisInputIssue[] = [],
|
||||
): JsonValue =>
|
||||
browserCliError(new AnalysisInputError(operation, undefined, issues));
|
||||
|
||||
@@ -2,12 +2,14 @@ import type { Logger } from "../logger.js";
|
||||
import { registerCoreBinaryCommands } from "./coreBinaryCommands.js";
|
||||
import { registerCoreNativeCommands } from "./coreNativeCommands.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import type { CliResultOutput } from "./streamedJsonOutput.js";
|
||||
|
||||
/** Register core binary and native deep-analysis CLI commands. */
|
||||
export const registerCoreAnalysisCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
resultOutput?: CliResultOutput,
|
||||
): void => {
|
||||
registerCoreBinaryCommands(cli, logger);
|
||||
registerCoreBinaryCommands(cli, logger, resultOutput);
|
||||
registerCoreNativeCommands(cli, logger);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "incur";
|
||||
import { artifactIntegrityPolicySchema } from "../domain/artifactGraph.js";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -13,13 +14,18 @@ import {
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
|
||||
import type {
|
||||
CliCommandOutput,
|
||||
CliResultOutput,
|
||||
} from "./streamedJsonOutput.js";
|
||||
|
||||
/** Register provider-neutral binary overview and procedure CLI commands. */
|
||||
export const registerCoreBinaryCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
resultOutput?: CliResultOutput,
|
||||
): void => {
|
||||
registerOverviewCommands(cli, logger);
|
||||
registerOverviewCommands(cli, logger, resultOutput);
|
||||
registerFunctionCommand(cli, logger);
|
||||
registerInstructionsCommand(cli, logger);
|
||||
registerSearchCommand(cli, logger);
|
||||
@@ -27,7 +33,11 @@ export const registerCoreBinaryCommands = (
|
||||
registerTraceCommand(cli, logger);
|
||||
};
|
||||
|
||||
const registerOverviewCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
const registerOverviewCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
resultOutput?: CliResultOutput,
|
||||
): void => {
|
||||
const overviewOptions = z.object({
|
||||
snapshot: z
|
||||
.string()
|
||||
@@ -43,19 +53,20 @@ const registerOverviewCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
path: z.string().describe("App, program, or analysis database path"),
|
||||
}),
|
||||
options: overviewOptions.extend({
|
||||
integrityPolicy: z
|
||||
.enum(["fail", "record-and-continue"])
|
||||
.default("fail")
|
||||
.describe(
|
||||
"Behavior when a routed JavaScript application declares integrity that does not match",
|
||||
),
|
||||
integrityPolicy: artifactIntegrityPolicySchema.describe(
|
||||
"Behavior when declared JavaScript artifact integrity does not match",
|
||||
),
|
||||
}),
|
||||
alias: {
|
||||
integrityPolicy: "integrity-policy",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
run: ({ args, options, format }) =>
|
||||
logCliCommand(logger, "analyze", () =>
|
||||
runRoutedOverview(args.path, options, logger),
|
||||
runRoutedOverview(
|
||||
args.path,
|
||||
options,
|
||||
logger,
|
||||
resultOutput === undefined
|
||||
? undefined
|
||||
: { output: resultOutput, command: CLI_COMMANDS.analyze, format },
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspect, {
|
||||
@@ -120,6 +131,7 @@ const runRoutedOverview = async (
|
||||
readonly integrityPolicy?: "fail" | "record-and-continue" | undefined;
|
||||
},
|
||||
logger: Logger,
|
||||
output?: CliCommandOutput,
|
||||
) => {
|
||||
if (
|
||||
options.provider === undefined &&
|
||||
@@ -127,10 +139,13 @@ const runRoutedOverview = async (
|
||||
options["target-format"] === undefined &&
|
||||
(await isJavaScriptApplicationPath(path))
|
||||
)
|
||||
return runCliJavaScriptApplicationAnalysis({
|
||||
input_path: resolve(path),
|
||||
integrity_policy: options.integrityPolicy ?? "fail",
|
||||
});
|
||||
return runCliJavaScriptApplicationAnalysis(
|
||||
{
|
||||
input_path: resolve(path),
|
||||
integrity_policy: options.integrityPolicy ?? "fail",
|
||||
},
|
||||
output,
|
||||
);
|
||||
return runDirectAnalysis(
|
||||
path,
|
||||
"binary_overview",
|
||||
|
||||
+44
-12
@@ -14,24 +14,27 @@ import {
|
||||
import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "../cliJsonInput.js";
|
||||
import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js";
|
||||
import {
|
||||
electronPageInspectionOptions,
|
||||
javascriptApplicationOptions,
|
||||
} from "../cliObservationOptions.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
|
||||
import type { CliResultOutput } from "./streamedJsonOutput.js";
|
||||
|
||||
/** Register CLI equivalents of the Electron MCP tools. */
|
||||
export const registerElectronCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
resultOutput?: CliResultOutput,
|
||||
): void => {
|
||||
registerElectronObservationCommands(cli, logger);
|
||||
registerElectronActiveCommand(cli, logger);
|
||||
registerJavaScriptApplicationCommand(cli, logger);
|
||||
registerJavaScriptApplicationCommand(cli, logger, resultOutput);
|
||||
registerJavaScriptRuntimeReconciliationCommand(cli, logger);
|
||||
};
|
||||
|
||||
@@ -56,9 +59,18 @@ const registerElectronActiveCommand = (
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const parsed = electronActiveObservationInputSchema.safeParse(
|
||||
input.value,
|
||||
resolveCliJsonPaths(input.value, [
|
||||
["executable_path"],
|
||||
["application_path"],
|
||||
["application_root"],
|
||||
]),
|
||||
);
|
||||
if (!parsed.success) return inputError("capture_electron_scenario");
|
||||
if (!parsed.success)
|
||||
return inputError(
|
||||
"capture_electron_scenario",
|
||||
parsed.error.issues,
|
||||
input.value,
|
||||
);
|
||||
const { createElectronScenarioProvider } =
|
||||
await import("../composition/electronScenario.js");
|
||||
const result = await captureElectronScenario(
|
||||
@@ -162,6 +174,7 @@ const registerElectronPageInspection = (
|
||||
const registerJavaScriptApplicationCommand = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
resultOutput?: CliResultOutput,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.analyzeJavaScriptApplication, {
|
||||
description:
|
||||
@@ -170,13 +183,22 @@ const registerJavaScriptApplicationCommand = (
|
||||
path: z.string().describe("ASAR or extracted application path"),
|
||||
}),
|
||||
options: javascriptApplicationOptions,
|
||||
run: ({ args, options }) =>
|
||||
run: ({ args, options, format }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () =>
|
||||
runCliJavaScriptApplicationAnalysis({
|
||||
input_path: args.path,
|
||||
format: options.artifactFormat,
|
||||
integrity_policy: options.integrityPolicy,
|
||||
}),
|
||||
runCliJavaScriptApplicationAnalysis(
|
||||
{
|
||||
input_path: args.path,
|
||||
format: options.artifactFormat,
|
||||
integrity_policy: options.integrityPolicy,
|
||||
},
|
||||
resultOutput === undefined
|
||||
? undefined
|
||||
: {
|
||||
output: resultOutput,
|
||||
command: CLI_COMMANDS.analyzeJavaScriptApplication,
|
||||
format,
|
||||
},
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -187,8 +209,18 @@ const electronObservationContext = async () => {
|
||||
return { provider: createElectronObservationProvider() };
|
||||
};
|
||||
|
||||
const inputError = (operation: string): JsonValue =>
|
||||
cliError(new AnalysisInputError(operation));
|
||||
const inputError = (
|
||||
operation: string,
|
||||
issues?: Parameters<typeof projectInputIssues>[0],
|
||||
input?: unknown,
|
||||
): JsonValue =>
|
||||
cliError(
|
||||
new AnalysisInputError(
|
||||
operation,
|
||||
undefined,
|
||||
issues === undefined ? [] : projectInputIssues(issues, input),
|
||||
),
|
||||
);
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { createEvmInterfaceService } from "../composition/evm.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Resolve operator paths and preserve explicit encoding through the shared workflow. */
|
||||
export const registerEvmCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createEvmInterfaceService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectEvmInterface, {
|
||||
description: "Infer interface candidates from explicit local EVM bytecode",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local bytecode carrier"),
|
||||
encoding: z
|
||||
.enum(["raw", "hex"])
|
||||
.describe("Selected carrier representation"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectEvmInterface, async () => {
|
||||
const result = await service.inspect(
|
||||
{ path: resolve(args.path), encoding: args.encoding },
|
||||
{ signal },
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysisService.js";
|
||||
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
@@ -38,7 +39,8 @@ export const registerFirmwareCommands = (
|
||||
execute(
|
||||
CLI_COMMANDS.inspectFirmwareRegions,
|
||||
"inspect_firmware_regions",
|
||||
args,
|
||||
// CLI paths are operator-relative; resolve before shared validation.
|
||||
{ path: resolve(args.path) },
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.extractFirmware, {
|
||||
@@ -81,8 +83,8 @@ export const registerFirmwareCommands = (
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
execute(CLI_COMMANDS.extractFirmware, "extract_firmware", {
|
||||
path: args.path,
|
||||
output_directory: args.outputDirectory,
|
||||
path: resolve(args.path),
|
||||
output_directory: resolve(args.outputDirectory),
|
||||
...(options.offset === undefined && options.length === undefined
|
||||
? {}
|
||||
: { range: { offset: options.offset, length: options.length } }),
|
||||
|
||||
@@ -1,13 +1,33 @@
|
||||
import { analyzeJavaScriptApplication } from "../application/javascript/JavaScriptApplicationService.js";
|
||||
import { createProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { CliCommandOutput } from "./streamedJsonOutput.js";
|
||||
|
||||
/** Execute the shared one-shot CLI boundary for static JavaScript analysis. */
|
||||
export const runCliJavaScriptApplicationAnalysis = async (
|
||||
input: unknown,
|
||||
): Promise<JsonValue> => {
|
||||
const result = await analyzeJavaScriptApplication(input);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
output?: CliCommandOutput,
|
||||
): Promise<JsonValue | undefined> => {
|
||||
const started = performance.now();
|
||||
const progress = createProgressReporter(
|
||||
async (update) => {
|
||||
process.stderr.write(`${JSON.stringify({ rea_progress: update })}\n`);
|
||||
},
|
||||
{ minimumIntervalMs: 0 },
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(input, { progress });
|
||||
const value = result.ok ? result.value : cliError(result.error);
|
||||
if (
|
||||
output !== undefined &&
|
||||
(await output.output.write(value, {
|
||||
command: output.command,
|
||||
format: output.format,
|
||||
duration: `${Math.round(performance.now() - started)}ms`,
|
||||
}))
|
||||
)
|
||||
return undefined;
|
||||
return value;
|
||||
};
|
||||
|
||||
const cliError = (
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { Writable } from "node:stream";
|
||||
|
||||
type JsonOutputFormat = "json" | "jsonl";
|
||||
|
||||
/** Write ordinary JSON without constructing a document-sized string. */
|
||||
export const writeJsonOutput = async (
|
||||
value: unknown,
|
||||
destination: Writable,
|
||||
format: JsonOutputFormat = "json",
|
||||
): Promise<void> => {
|
||||
for (const part of bufferedParts(documentParts(value, format)))
|
||||
await writePart(destination, part);
|
||||
};
|
||||
|
||||
const writePart = (destination: Writable, part: string): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const onError = (cause: unknown): void => reject(cause);
|
||||
destination.once("error", onError);
|
||||
try {
|
||||
destination.write(part, (cause) => {
|
||||
if (cause) {
|
||||
// A Writable can emit its error after invoking the write callback.
|
||||
setImmediate(() => destination.off("error", onError));
|
||||
reject(cause);
|
||||
} else {
|
||||
destination.off("error", onError);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
destination.off("error", onError);
|
||||
reject(cause);
|
||||
}
|
||||
});
|
||||
|
||||
function* documentParts(
|
||||
value: unknown,
|
||||
format: JsonOutputFormat,
|
||||
): Generator<string> {
|
||||
if (format === "jsonl" && Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
yield* encodeValue(item, false, 0, new Set());
|
||||
yield "\n";
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* encodeValue(value, format === "json", 0, new Set());
|
||||
yield "\n";
|
||||
}
|
||||
|
||||
function* bufferedParts(parts: Iterable<string>): Generator<string> {
|
||||
let buffer = "";
|
||||
for (const part of parts) {
|
||||
if (buffer.length + part.length > 64 * 1024 && buffer !== "") {
|
||||
yield buffer;
|
||||
buffer = "";
|
||||
}
|
||||
buffer += part;
|
||||
}
|
||||
if (buffer !== "") yield buffer;
|
||||
}
|
||||
|
||||
function* encodeString(value: string): Generator<string> {
|
||||
if (value.length <= 8192) {
|
||||
yield JSON.stringify(value);
|
||||
return;
|
||||
}
|
||||
yield '"';
|
||||
for (let start = 0; start < value.length;) {
|
||||
let end = Math.min(start + 8192, value.length);
|
||||
const last = value.charCodeAt(end - 1);
|
||||
const next = value.charCodeAt(end);
|
||||
// Keep a surrogate pair in the same JSON.stringify and UTF-8 write.
|
||||
if (
|
||||
end < value.length &&
|
||||
last >= 0xd800 &&
|
||||
last <= 0xdbff &&
|
||||
next >= 0xdc00 &&
|
||||
next <= 0xdfff
|
||||
)
|
||||
end -= 1;
|
||||
yield JSON.stringify(value.slice(start, end)).slice(1, -1);
|
||||
start = end;
|
||||
}
|
||||
yield '"';
|
||||
}
|
||||
|
||||
function* encodeValue(
|
||||
value: unknown,
|
||||
pretty: boolean,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
): Generator<string> {
|
||||
if (typeof value === "string") {
|
||||
yield* encodeString(value);
|
||||
return;
|
||||
}
|
||||
if (value === null || typeof value === "boolean") {
|
||||
yield value === null ? "null" : String(value);
|
||||
return;
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
yield String(value);
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new TypeError("CLI JSON output requires ordinary JSON values");
|
||||
if (ancestors.has(value))
|
||||
throw new TypeError("CLI JSON output contains a circular reference");
|
||||
if (
|
||||
!Array.isArray(value) &&
|
||||
Object.prototype.toString.call(value) !== "[object Object]"
|
||||
)
|
||||
throw new TypeError("CLI JSON output requires ordinary JSON objects");
|
||||
ancestors.add(value);
|
||||
try {
|
||||
const array = Array.isArray(value);
|
||||
const keys = array
|
||||
? undefined
|
||||
: Object.keys(value).filter((key) => {
|
||||
const item: unknown = Reflect.get(value, key);
|
||||
// Incur's filter can select inherited methods. Match native JSON's
|
||||
// omission of fields that have no JSON representation.
|
||||
return (
|
||||
item !== undefined &&
|
||||
typeof item !== "function" &&
|
||||
typeof item !== "symbol"
|
||||
);
|
||||
});
|
||||
const count = array ? value.length : (keys?.length ?? 0);
|
||||
yield array ? "[" : "{";
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
if (index > 0) yield ",";
|
||||
if (pretty) yield `\n${" ".repeat(depth + 1)}`;
|
||||
let item: unknown;
|
||||
if (array) {
|
||||
item = value[index];
|
||||
} else {
|
||||
const key = keys?.[index];
|
||||
if (key === undefined)
|
||||
throw new TypeError("CLI JSON object changed during serialization");
|
||||
yield* encodeString(key);
|
||||
yield pretty ? ": " : ":";
|
||||
item = Reflect.get(value, key);
|
||||
}
|
||||
yield* encodeValue(item, pretty, depth + 1, ancestors);
|
||||
}
|
||||
if (pretty && count > 0) yield `\n${" ".repeat(depth)}`;
|
||||
yield array ? "]" : "}";
|
||||
} finally {
|
||||
ancestors.delete(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "incur";
|
||||
|
||||
import { runProviderAnalysis } from "../composition/directAnalysis.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "../cliJsonInput.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { nativeCallObservationInputSchema } from "../domain/native/nativeCallObservation.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
const OPERATION = "observe_native_calls";
|
||||
|
||||
/** `observe-native-calls <path> <input-json>`: the MCP input object as JSON. */
|
||||
export const registerNativeCallCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.observeNativeCalls, {
|
||||
description:
|
||||
"Launch a Mach-O under LLDB and record entries into selected functions or Objective-C methods",
|
||||
args: z.object({
|
||||
path: z.string().describe("Mach-O or app path"),
|
||||
inputJson: z
|
||||
.string()
|
||||
.describe(
|
||||
"Inline JSON or a JSON file path: breakpoints, arguments, environment, duration_ms, max_events, argument_registers, backtrace_frames",
|
||||
),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.observeNativeCalls, async () => {
|
||||
const input = await parseCliJsonInput(args.inputJson, OPERATION);
|
||||
if (!input.ok) return input.error;
|
||||
const parsed = nativeCallObservationInputSchema.safeParse(input.value);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
error: "Analysis failed",
|
||||
...projectAnalysisError(
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
undefined,
|
||||
projectInputIssues(parsed.error.issues, input.value),
|
||||
),
|
||||
),
|
||||
};
|
||||
return runProviderAnalysis(
|
||||
args.path,
|
||||
OPERATION,
|
||||
z.record(z.string(), jsonValueSchema).parse(parsed.data),
|
||||
logger,
|
||||
);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
isProcessCliFailure,
|
||||
} from "../application/ProcessCli.js";
|
||||
} from "../application/process/ProcessCli.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { type Writable } from "node:stream";
|
||||
|
||||
import { Filter } from "incur";
|
||||
|
||||
import { parseCliOutputArguments } from "../cliOutput.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { writeJsonOutput } from "./jsonOutput.js";
|
||||
|
||||
/** Result metadata supplied by the command that actually ran. */
|
||||
export interface CliResultOutputMetadata {
|
||||
readonly command: string;
|
||||
readonly duration: string;
|
||||
readonly format: string;
|
||||
}
|
||||
|
||||
/** Optional executable-owned result surface for one CLI invocation. */
|
||||
export interface CliResultOutput {
|
||||
readonly handled: boolean;
|
||||
readonly failed: boolean;
|
||||
write(value: JsonValue, metadata: CliResultOutputMetadata): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Selected command output context, independent of application workflows. */
|
||||
export interface CliCommandOutput {
|
||||
readonly output: CliResultOutput;
|
||||
readonly command: string;
|
||||
readonly format: string;
|
||||
}
|
||||
|
||||
/** Preserve Incur's JSON controls while streaming the complete result. */
|
||||
export const createStreamedCliJsonOutput = (
|
||||
arguments_: readonly string[],
|
||||
destination: Writable,
|
||||
): CliResultOutput | undefined => {
|
||||
const options = parseCliOutputArguments(arguments_);
|
||||
if (
|
||||
options.parseError ||
|
||||
options.tokenCount ||
|
||||
options.tokenWindow ||
|
||||
(options.format !== "json" && options.format !== "jsonl")
|
||||
)
|
||||
return undefined;
|
||||
const format = options.format;
|
||||
let handled = false;
|
||||
let failed = false;
|
||||
return {
|
||||
get handled() {
|
||||
return handled;
|
||||
},
|
||||
get failed() {
|
||||
return failed;
|
||||
},
|
||||
async write(value, metadata) {
|
||||
if (metadata.format !== format) return false;
|
||||
const filtered: unknown = options.filterOutput
|
||||
? Filter.apply(value, Filter.parse(options.filterOutput))
|
||||
: value;
|
||||
const meta = {
|
||||
command: metadata.command,
|
||||
duration: metadata.duration,
|
||||
};
|
||||
const document = options.fullOutput
|
||||
? filtered === undefined
|
||||
? { ok: true, meta }
|
||||
: { ok: true, data: filtered, meta }
|
||||
: filtered === undefined ||
|
||||
filtered === null ||
|
||||
typeof filtered === "function" ||
|
||||
typeof filtered === "symbol"
|
||||
? {}
|
||||
: filtered;
|
||||
// Once writing starts, a failed destination must not receive a second
|
||||
// document from Incur's error formatter.
|
||||
handled = true;
|
||||
try {
|
||||
await writeJsonOutput(document, destination, format);
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
throw cause;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
+54
-23
@@ -1,5 +1,4 @@
|
||||
import { z } from "incur";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
|
||||
import {
|
||||
runCapabilityStatus,
|
||||
@@ -10,6 +9,10 @@ import { importReferenceSource } from "../application/ReferenceSourceImport.js";
|
||||
import { projectReferenceSourceImportError } from "../application/ReferenceSourceImportTypes.js";
|
||||
import { parseConfig } from "../config.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
import { nativeUiScenarioInputSchema } from "../domain/native/nativeUiObservation.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
@@ -17,6 +20,7 @@ import { swiftSymbolsSchema } from "../contracts/native/nativeToolContracts.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { isReferenceSourceImportCliFailure } from "./referenceSourceImportStatus.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { registerNativeCallCommands } from "./nativeCallCommands.js";
|
||||
|
||||
export const registerUtilityCommands = (
|
||||
cli: CliInstance,
|
||||
@@ -25,6 +29,7 @@ export const registerUtilityCommands = (
|
||||
): void => {
|
||||
registerCapabilityCommands(cli, logger);
|
||||
registerNativeCommands(cli, logger);
|
||||
registerNativeCallCommands(cli, logger);
|
||||
for (const [command, operation] of [
|
||||
[CLI_COMMANDS.observeNativeUi, "observe_native_ui"],
|
||||
[CLI_COMMANDS.captureNativeUiScenario, "capture_native_ui_scenario"],
|
||||
@@ -67,33 +72,59 @@ export const registerUtilityCommands = (
|
||||
maxNodes: "max-nodes",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, command, () =>
|
||||
runProviderAnalysis(
|
||||
args.path,
|
||||
operation,
|
||||
{
|
||||
pid: options.pid,
|
||||
window_id: options.windowId,
|
||||
screenshot: options.screenshot,
|
||||
accessibility: options.accessibility,
|
||||
max_nodes: options.maxNodes,
|
||||
...(operation === "capture_native_ui_scenario"
|
||||
? {
|
||||
steps:
|
||||
options.steps === undefined
|
||||
? []
|
||||
: jsonValueSchema.parse(JSON.parse(options.steps)),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
logger,
|
||||
),
|
||||
),
|
||||
logCliCommand(logger, command, async () => {
|
||||
const parameters = {
|
||||
pid: options.pid,
|
||||
window_id: options.windowId,
|
||||
screenshot: options.screenshot,
|
||||
accessibility: options.accessibility,
|
||||
max_nodes: options.maxNodes,
|
||||
};
|
||||
if (operation === "capture_native_ui_scenario") {
|
||||
const decoded =
|
||||
options.steps === undefined
|
||||
? { ok: true as const, value: undefined }
|
||||
: safeParseJson(options.steps);
|
||||
if (!decoded.ok)
|
||||
return invalidNativeUiScenarioInput(operation, [
|
||||
{ path: ["steps"], reason: "invalid_format", expected: "JSON" },
|
||||
]);
|
||||
const parsed = nativeUiScenarioInputSchema.safeParse({
|
||||
...parameters,
|
||||
steps: decoded.value,
|
||||
});
|
||||
if (!parsed.success)
|
||||
return invalidNativeUiScenarioInput(
|
||||
operation,
|
||||
projectInputIssues(parsed.error.issues, {
|
||||
...parameters,
|
||||
...(options.steps === undefined
|
||||
? {}
|
||||
: { steps: decoded.value }),
|
||||
}),
|
||||
);
|
||||
return runProviderAnalysis(
|
||||
args.path,
|
||||
operation,
|
||||
parsed.data,
|
||||
logger,
|
||||
);
|
||||
}
|
||||
return runProviderAnalysis(args.path, operation, parameters, logger);
|
||||
}),
|
||||
});
|
||||
}
|
||||
registerReferenceSourceCommand(cli, logger, environment);
|
||||
};
|
||||
|
||||
const invalidNativeUiScenarioInput = (
|
||||
operation: string,
|
||||
issues: ConstructorParameters<typeof AnalysisInputError>[2],
|
||||
) => ({
|
||||
error: "Application workflow failed",
|
||||
...projectAnalysisError(new AnalysisInputError(operation, undefined, issues)),
|
||||
});
|
||||
|
||||
const registerCapabilityCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
for (const command of [
|
||||
CLI_COMMANDS.capabilities,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from "incur";
|
||||
import { createWebNetworkCaptureService } from "../composition/webNetworkCaptures.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Expose offline historical capture inspection with the same selection contract as MCP. */
|
||||
export const registerWebNetworkCaptureCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createWebNetworkCaptureService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectWebNetworkCapture, {
|
||||
description:
|
||||
"Inspect retained HAR or native mitmproxy records without fetching recorded URLs",
|
||||
args: z.object({
|
||||
capturePath: z.string().describe("Absolute local capture path"),
|
||||
format: z.enum(["har", "mitmproxy"]).describe("Producer capture format"),
|
||||
}),
|
||||
options: z.object({
|
||||
record: z
|
||||
.array(z.coerce.number().int().nonnegative())
|
||||
.optional()
|
||||
.describe("Zero-based producer ordinals; repeat to select several"),
|
||||
sensitiveValue: z
|
||||
.array(z.string().min(1))
|
||||
.default([])
|
||||
.describe(
|
||||
"Literal string values explicitly marked sensitive; repeat as needed",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectWebNetworkCapture,
|
||||
async () => {
|
||||
const result = await service.inspect(
|
||||
{
|
||||
capture_path: args.capturePath,
|
||||
format: args.format,
|
||||
sensitive_values: options.sensitiveValue,
|
||||
...(options.record === undefined
|
||||
? {}
|
||||
: { record_ordinals: options.record }),
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return result.ok
|
||||
? result.value
|
||||
: projectAnalysisError(result.error);
|
||||
},
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user