From 11c1e45cce80555133a352617a94a11dd22cf409 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:04:45 +0800 Subject: [PATCH] fix(cli): record the caller's --join-path spelling in Apple IPS Evidence (#10606) * fix(cli): record the caller's --join-path spelling in Apple IPS Evidence * refactor(cli): project CLI-only options for release exposure and IL2CPP from contracts (#10635) * refactor(cli): project CLI-only options for release exposure and IL2CPP from contracts The contract command description gains CLI-only options whose effect the handler owns, plus their dependentRequired entries. audit-release-exposure keeps --fail_on (exit status 3) and inspect-il2cpp-metadata keeps --ghidra-seeds/--seed-base; their hand-written options and input spreads are deleted. * refactor(cli): project GPU, signal and capture inspectors from their contracts (#10643) The contract command description gains JSON options decoded when the command runs, admitted with the delivery by the contract input, and bare flags that spell a nullable limit's null. inspect-gpu-code-objects, inspect-signal-decoders, decode-signal-recording, inspect-packet-fields and inspect-packet-capture are derived from their contracts; their hand-written options, superRefine blocks and CLI-only option schemas are deleted. --- src/cli/captureCommands.ts | 222 ++++------- src/cli/contractCliDescription.ts | 352 +++++++++++++----- src/cli/contractCommand.ts | 99 +++-- src/cli/gpuCommands.ts | 183 +++------ src/cli/il2cppCommands.ts | 207 +++++----- src/cli/releaseExposureCommands.ts | 120 +++--- src/cli/signalCommands.ts | 219 ++++------- src/domain/captures/packetCapture.ts | 3 - src/domain/signals/signalRecording.ts | 6 - tests/acceptance/appleIpsArmJoinCli.test.ts | 33 ++ .../cli/cliContractCommandParity.test.ts | 274 ++++++++++---- 11 files changed, 944 insertions(+), 774 deletions(-) diff --git a/src/cli/captureCommands.ts b/src/cli/captureCommands.ts index 8ac552c04d..59143dd015 100644 --- a/src/cli/captureCommands.ts +++ b/src/cli/captureCommands.ts @@ -1,24 +1,18 @@ -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { inspectPacketFieldsInputSchema } from "../domain/captures/packetFields.js"; -import { z } from "incur"; -import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js"; -import { createPacketCaptureService } from "../composition/captures.js"; -import { - packetCaptureOptionsSchema, - packetCaptureSelectorBudgetIssue, - withinPacketCaptureSelectorBudget, -} from "../domain/captures/packetCapture.js"; -import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; + +import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js"; +import { CLI_COMMANDS } from "../cliCommandNames.js"; +import { createPacketCaptureService } from "../composition/captures.js"; +import { CAPTURE_TOOL_CONTRACTS } from "../contracts/captures/captureToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { + analyzeWithService, + inspectWithService, + registerContractCommand, +} from "./contractCommand.js"; +import { PRODUCER_LIMITS_HELP } from "./producerLimitsOption.js"; import type { CliInstance } from "./types.js"; -import { withCommandCancellation } from "./commandCancellation.js"; -import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; -import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; -import { cliDecimalField, cliDecimalShape } from "./options.js"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { producerLimitsOption } from "./producerLimitsOption.js"; + export const registerCaptureCommands = ( cli: CliInstance, logger: Logger, @@ -28,133 +22,75 @@ export const registerCaptureCommands = ( "inspect" | "inspectFields" | "close" > = createPacketCaptureService(environment), ): void => { - const { producer_limits: discoveryLimits, ...discoveryShape } = - inspectPacketFieldsInputSchema.shape; - const { producer_limits: selectedLimits, ...selectedShape } = - packetCaptureOptionsSchema.shape; - cli.command(CLI_COMMANDS.inspectPacketFields, { - description: "Search installed TShark protocol and field definitions", - options: z - .object({ - ...cliDecimalShape(discoveryShape), - producerLimits: producerLimitsOption(discoveryLimits.unwrap()), - limit: cliDecimalField( - z - .number() - .int() - .positive() - .max(Number.MAX_SAFE_INTEGER) - .optional() - .describe("Maximum matching records to return; defaults to 50"), - ), - all: z - .boolean() - .default(false) - .describe("Return all remaining matches within resource limits"), - }) - .superRefine((options, context) => { - if (options.all && options.limit !== undefined) - context.addIssue({ - code: "custom", - path: ["all"], - message: "all and limit are mutually exclusive", - }); - }) - .meta({ - not: { - required: ["all", "limit"], - properties: { all: { const: true } }, + const close = () => service.close(); + registerContractCommand( + cli, + logger, + contractNamed(CAPTURE_TOOL_CONTRACTS, "inspect_packet_fields"), + { + command: CLI_COMMANDS.inspectPacketFields, + description: "Search installed TShark protocol and field definitions", + jsonText: ["producer_limits"], + nullFlags: { + limit: { + key: "all", + description: "Return all remaining matches within resource limits", }, + }, + fields: { + producer_limits: { description: PRODUCER_LIMITS_HELP }, + limit: { + description: "Maximum matching records to return; defaults to 50", + }, + }, + }, + analyzeWithService( + () => ({ + inspect: (input, options) => service.inspectFields(input, options), + close, }), - run: ({ options: { all, producerLimits, ...options } }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectPacketFields, async () => - finishAnalysisCommand( - () => - service.inspectFields( - { - ...options, - ...(producerLimits === undefined - ? {} - : { producer_limits: producerLimits }), - ...(all ? { limit: null } : {}), - }, - { signal }, - ), - service, - "tshark-capture", - "inspect_packet_fields", - signal, - ).then(projectCliAnalysisResult), - ), - ), - }); - cli.command(CLI_COMMANDS.inspectPacketCapture, { - description: - "Inspect an existing packet capture with caller-supplied TShark", - args: z.object({ - path: localPathStringSchema.describe("Local packet capture"), - }), - options: z - .object({ - ...cliDecimalShape(selectedShape), - producerLimits: producerLimitsOption(selectedLimits.unwrap()), - match_limit: cliDecimalField( - z - .number() - .int() - .positive() - .optional() - .describe("Returned matching frames per page; default 50"), - ), - all_matches: z - .boolean() - .default(false) - .describe( + "tshark-capture", + ), + ); + registerContractCommand( + cli, + logger, + contractNamed(CAPTURE_TOOL_CONTRACTS, "inspect_packet_capture"), + { + command: CLI_COMMANDS.inspectPacketCapture, + description: + "Inspect an existing packet capture with caller-supplied TShark", + positionals: ["path"], + callerPaths: ["path"], + jsonText: ["producer_limits"], + nullFlags: { + match_limit: { + key: "all_matches", + description: "Return all remaining matching frames instead of a bounded page", - ), - }) - .superRefine((options, context) => { - if (options.all_matches && options.match_limit !== undefined) - context.addIssue({ - code: "custom", - path: ["all_matches"], - message: "all_matches and match_limit are mutually exclusive", - }); - }) - .refine( - withinPacketCaptureSelectorBudget, - packetCaptureSelectorBudgetIssue, - ) - .meta({ - not: { - required: ["all_matches", "match_limit"], - properties: { all_matches: { const: true } }, }, + }, + crossFieldRules: "argv", + fields: { + path: { description: "Local packet capture" }, + producer_limits: { description: PRODUCER_LIMITS_HELP }, + display_filter: { name: "display_filter" }, + decode_as: { name: "decode_as" }, + packet_limit: { name: "packet_limit" }, + two_pass: { name: "two_pass" }, + match_offset: { name: "match_offset" }, + match_limit: { + name: "match_limit", + description: "Returned matching frames per page; default 50", + }, + }, + }, + inspectWithService( + () => ({ + inspect: (input, options) => service.inspect(input, options), + close, }), - run: ({ args, options: { all_matches, producerLimits, ...options } }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectPacketCapture, async () => { - return finishCliEvidenceCommand( - args.path, - () => - service.inspect( - { - ...options, - ...(producerLimits === undefined - ? {} - : { producer_limits: producerLimits }), - ...(all_matches ? { match_limit: null } : {}), - path: absoluteCallerPath(args.path), - }, - { signal }, - ), - service, - "tshark-capture", - "inspect_packet_capture", - signal, - ).then(projectCliAnalysisResult); - }), - ), - }); + "tshark-capture", + ), + ); }; diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index f5fb948678..14c965afeb 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -54,7 +54,10 @@ export interface CliFieldProjection { * from the contract input schema: each field keeps its own schema, so the * CLI admits what the contract admits. */ -export interface CliContractProjection { +export interface CliContractProjection< + Field extends string, + CliOptions extends CliOptionShape = CliOptionShape, +> { readonly command: string; readonly description: string; /** Fields taken as positional arguments, in argv order. */ @@ -70,6 +73,18 @@ export interface CliContractProjection { * at argv parsing and then admitted by the contract field's own schema. */ readonly jsonText?: readonly Field[]; + /** + * Structured fields taken as JSON text that is decoded when the command + * runs, each with its refusal when the text is not JSON. The decoded input + * is then admitted by the contract input before any target is opened. + */ + readonly runtimeJson?: { readonly [Key in Field]?: string }; + /** + * Nullable limits whose null ("all remaining") is spelled by a bare flag, + * keyed by contract field. The limit option takes only a value; the flag + * and the limit are mutually exclusive. + */ + readonly nullFlags?: { readonly [Key in Field]?: CliNullFlag }; readonly fields?: { readonly [Key in Field]?: CliFieldProjection }; /** * Optional fields this one-shot command does not expose, each with the @@ -95,6 +110,34 @@ export interface CliContractProjection { * target is opened. */ readonly viewDelivery?: CliViewDelivery; + /** + * Options no contract field owns, keyed by their CLI key. Each is admitted + * by its own schema and takes effect in the command handler, never in the + * contract input; for example, an exit status chosen from the result. + */ + readonly cliOptions?: CliOptions; + /** + * `dependentRequired` entries over CLI keys that the CLI-only options add + * to the contract's own. Help and `--schema` advertise them; the handler + * enforces them. + */ + readonly cliOptionDependencies?: Readonly< + Partial> + >; +} + +/** Schemas of the CLI-only options of one command, keyed by CLI key. */ +export type CliOptionShape = Readonly>; + +/** Parsed values of the CLI-only options of one command. */ +export type CliOptionValues = { + readonly [Key in keyof CliOptions]: z.output; +}; + +/** A bare flag that sets a nullable contract field to null. */ +export interface CliNullFlag { + readonly key: string; + readonly description: string; } /** How a contract command takes its `view` selection. */ @@ -156,6 +199,20 @@ export interface ContractCliParameter { * with the delivery by the contract input. */ readonly viewSelection: boolean; + /** + * The refusal for text that is not JSON, when the value is JSON text + * decoded when the command runs; undefined otherwise. + */ + readonly runtimeJson: string | undefined; + /** The bare flag that sets this nullable field to null, if any. */ + readonly nullFlag: string | undefined; +} + +/** The contract input and delivery one invocation selected. */ +export interface ContractCliAdmission { + readonly input: Record; + /** The admitted delivery, for a projection with `evidenceDelivery`. */ + readonly delivery: CliEvidenceDeliveryChoice | undefined; } /** One cross-field refusal, naming CLI keys. */ @@ -191,7 +248,10 @@ export interface ContractCliDescription { options: Readonly>, ) => readonly ContractCliIssue[]) | undefined; - /** Map parsed values, keyed by parameter key, to the contract input. */ + /** + * Map parsed values, keyed by parameter key, to the contract input. Values + * of run-time JSON parameters must already be decoded. + */ readonly toContractInput: ( values: Readonly>, ) => Record; @@ -199,15 +259,20 @@ export interface ContractCliDescription { readonly callerInputs: ( values: Readonly>, ) => Readonly>; + /** The parsed values of the projection's CLI-only options. */ + readonly cliOptionValues: ( + values: Readonly>, + ) => Readonly>; + /** The command adds `--detail` and `--evidence_output`. */ + readonly evidenceDelivery: boolean; /** - * The selected delivery, for a projection with `evidenceDelivery`, refused - * before any target is opened when it is not admitted. + * Decode run-time JSON, then map parsed values to the contract input and + * the selected delivery. An input or delivery that is not admitted is + * refused before any target is opened. */ - readonly delivery: - | (( - values: Readonly>, - ) => Result) - | undefined; + readonly admit: ( + values: Readonly>, + ) => Result; } /** One contract from a contract group, keeping its exact schema types. */ @@ -368,9 +433,10 @@ const projectObjectConstraints = ( contract: ProjectedContract, rename: (field: string) => string, deliveryFields: ReadonlySet, + cliOptionDependencies: Readonly>, + nullFlagLimits: readonly (readonly [flag: string, limit: string])[], ): Record | undefined => { - const metadata = contract.inputSchema.meta(); - if (metadata === undefined) return undefined; + const metadata = contract.inputSchema.meta() ?? {}; for (const keyword of Object.keys(metadata)) if ( !ROOT_ANNOTATIONS.has(keyword) && @@ -396,6 +462,18 @@ const projectObjectConstraints = ( ) : renameConstraint(contract.name, value, rename); } + if (Object.keys(cliOptionDependencies).length > 0) + projected.dependentRequired = { + ...(projected.dependentRequired as object | undefined), + ...cliOptionDependencies, + }; + if (nullFlagLimits.length > 1) + throw new Error(`${contract.name} has more than one null flag`); + for (const [flag, limit] of nullFlagLimits) + projected.not = { + required: [flag, limit], + properties: { [flag]: { const: true } }, + }; return Object.keys(projected).length === 0 ? undefined : projected; }; @@ -434,9 +512,12 @@ const inputFields = ( }; /** Derive the CLI parameters of one contract from its input schema and projection. */ -export const describeContractCommand = ( +export const describeContractCommand = < + Contract extends ProjectedContract, + CliOptions extends CliOptionShape = CliOptionShape, +>( contract: Contract, - projection: CliContractProjection>, + projection: CliContractProjection, CliOptions>, ): ContractCliDescription => { const evidenceDelivery = projection.evidenceDelivery === true; const { viewDelivery } = projection; @@ -462,6 +543,10 @@ export const describeContractCommand = ( const jsonTextFields: ReadonlySet = new Set( projection.jsonText ?? [], ); + const runtimeJsonFields: Readonly> = + projection.runtimeJson ?? {}; + const nullFlags: Readonly> = + projection.nullFlags ?? {}; const omitted: Readonly> = Object.fromEntries( Object.entries(projection.omit ?? {}).filter( (entry): entry is [string, string] => typeof entry[1] === "string", @@ -471,6 +556,8 @@ export const describeContractCommand = ( ...positionals, ...callerPaths, ...jsonTextFields, + ...Object.keys(runtimeJsonFields), + ...Object.keys(nullFlags), ...Object.keys(fieldProjections), ...Object.keys(omitted), ]) @@ -487,10 +574,27 @@ export const describeContractCommand = ( const delivery = deliveryFields.has(field); const viewSelection = delivery && field === "view"; const jsonText = jsonTextFields.has(field); + const runtimeJson = viewSelection + ? viewDelivery?.invalidJson + : runtimeJsonFields[field]; + const nullFlag = nullFlags[field]?.key; const key = projected?.name ?? camelCase(field); let schema: z.ZodType; - if (viewSelection) schema = z.string().optional(); - else if (delivery) + if (runtimeJson !== undefined) { + if (!admitsOmission(declared)) + throw new Error(`${contract.name}.${field} is required on the CLI`); + schema = z.string().optional(); + if (declared.description !== undefined && !viewSelection) + schema = schema.describe(declared.description); + } else if (nullFlag !== undefined) { + // The flag spells null, so the option itself takes only a value. + if (!declared.safeParse(null).success) + throw new Error(`${contract.name}.${field} does not admit null`); + assertArgvField(contract.name, field, declared); + schema = cliDecimalShape({ field: core(declared).optional() }).field; + if (declared.description !== undefined) + schema = schema.describe(declared.description); + } else if (delivery) schema = viewDelivery?.viewSelectsSummary === true ? analysisEvidenceDeliveryOptions.detail.unwrap().optional() @@ -524,6 +628,8 @@ export const describeContractCommand = ( delivery, jsonText, viewSelection, + runtimeJson, + nullFlag, }; }; const parameters = [ @@ -532,13 +638,27 @@ export const describeContractCommand = ( (field) => !positionals.includes(field) && !Object.hasOwn(omitted, field), ), ].map(parameter); - const cliOnlyOptions: readonly CliOnlyOption[] = Object.entries( - evidenceDelivery - ? Object.hasOwn(shape, "detail") - ? { evidence_output: analysisEvidenceDeliveryOptions.evidence_output } - : analysisEvidenceDeliveryOptions - : {}, - ).map(([key, schema]: [string, z.ZodType]) => ({ + const cliOptions: CliOptionShape = projection.cliOptions ?? {}; + const cliOnlyOptions: readonly CliOnlyOption[] = [ + ...Object.values(nullFlags).flatMap((flag) => + flag === undefined + ? [] + : [ + [ + flag.key, + z.boolean().default(false).describe(flag.description), + ] satisfies [string, z.ZodType], + ], + ), + ...Object.entries( + evidenceDelivery + ? Object.hasOwn(shape, "detail") + ? { evidence_output: analysisEvidenceDeliveryOptions.evidence_output } + : analysisEvidenceDeliveryOptions + : {}, + ), + ...Object.entries(cliOptions), + ].map(([key, schema]: [string, z.ZodType]) => ({ key, description: schema.description, schema, @@ -549,6 +669,15 @@ export const describeContractCommand = ( ]); if (keys.size !== parameters.length + cliOnlyOptions.length) throw new Error(`${contract.name} projects two fields to one CLI key`); + const cliOptionDependencies = Object.fromEntries( + Object.entries(projection.cliOptionDependencies ?? {}).filter( + (entry): entry is [string, readonly string[]] => entry[1] !== undefined, + ), + ); + for (const [key, required] of Object.entries(cliOptionDependencies)) + for (const dependency of [key, ...required]) + if (!keys.has(dependency)) + throw new Error(`${contract.name} has no CLI option ${dependency}`); const keyOf = new Map(parameters.map(({ field, key }) => [field, key])); const rename = (field: string): string => keyOf.get(field) ?? field; @@ -564,8 +693,14 @@ export const describeContractCommand = ( ? absoluteCallerPath(value) : value; } + for (const { field, nullFlag } of parameters) + if (nullFlag !== undefined && values[nullFlag] === true) + input[field] = null; return input; }; + const nullFlagLimits = parameters.flatMap(({ key, nullFlag }) => + nullFlag === undefined ? [] : [[nullFlag, key] as const], + ); // Cross-field rules belong to the contract: run its own object checks on // the options mapped to contract names, then name CLI keys. Positional @@ -575,28 +710,50 @@ export const describeContractCommand = ( projection.crossFieldRules === "argv" ? (contract.inputSchema._zod.def.checks ?? []) : []; + if ( + checks.length > 0 && + parameters.some(({ runtimeJson }) => runtimeJson !== undefined) + ) + throw new Error( + `${contract.name} decodes JSON when it runs, after argv cross-field rules`, + ); const contractChecks = z .object({}) .loose() .check(...(checks as z.core.$ZodCheck>[])); const checkOptions = - checks.length === 0 + checks.length === 0 && nullFlagLimits.length === 0 ? undefined : (options: Readonly>) => { + const conflicts = nullFlagLimits.flatMap(([flag, limit]) => { + if (options[flag] !== true || options[limit] === undefined) + return []; + const message = `${flag} and ${limit} are mutually exclusive`; + const issue: z.core.$ZodIssueCustom = { + code: "custom", + path: [flag], + message, + input: undefined, + }; + return [{ path: [flag], message, issue }]; + }); const result = contractChecks.safeParse(toContractInput(options)); return result.success - ? [] - : result.error.issues.map((issue) => { - const [field, ...rest] = issue.path; - return { - path: - typeof field === "string" - ? [rename(field), ...rest] - : issue.path, - message: issue.message, - issue, - }; - }); + ? conflicts + : [ + ...conflicts, + ...result.error.issues.map((issue) => { + const [field, ...rest] = issue.path; + return { + path: + typeof field === "string" + ? [rename(field), ...rest] + : issue.path, + message: issue.message, + issue, + }; + }), + ]; }; return { @@ -611,6 +768,8 @@ export const describeContractCommand = ( contract, rename, deliveryFields, + cliOptionDependencies, + nullFlagLimits, ), checkOptions, toContractInput, @@ -623,70 +782,97 @@ export const describeContractCommand = ( : []; }), ), - delivery: evidenceDelivery - ? (values) => { - const selected = selectDelivery( - contract, - viewDelivery, - values, - toContractInput, - rename, - ); - if (!selected.ok) return selected; - const refused = cliEvidenceDeliveryInputError({ - ...selected.value, - operation: contract.name, - }); - return refused === undefined ? selected : err(refused); - } - : undefined, + cliOptionValues: (values) => + Object.fromEntries( + Object.keys(cliOptions).flatMap((key) => + values[key] === undefined ? [] : [[key, values[key]]], + ), + ), + evidenceDelivery, + admit: (values) => + admitInvocation( + contract, + { evidenceDelivery, viewDelivery, parameters, shape }, + values, + toContractInput, + rename, + ), }; }; /** - * The delivery the parsed values select. A view is decoded from its JSON - * text and admitted with the delivery and the other inputs by the contract - * input schema, so the contract's own delivery rules and messages apply. + * Decode run-time JSON, then map the values to the contract input and the + * selected delivery. When the projection decodes JSON at run time, the + * decoded input, delivery and view are admitted together by the contract + * input schema, so the contract's own rules and messages apply. */ -const selectDelivery = ( +const admitInvocation = ( contract: ProjectedContract, - viewDelivery: CliViewDelivery | undefined, + command: { + readonly evidenceDelivery: boolean; + readonly viewDelivery: CliViewDelivery | undefined; + readonly parameters: readonly ContractCliParameter[]; + readonly shape: Readonly>; + }, values: Readonly>, toContractInput: ContractCliDescription["toContractInput"], rename: (field: string) => string, -): Result => { - const detail = values[rename("detail")] as "complete" | "summary" | undefined; - const evidenceOutput = values.evidence_output as string | undefined; - if (viewDelivery === undefined) - return ok({ detail: detail ?? "complete", evidenceOutput }); - const viewKey = rename("view"); - const decoded = parseCliJsonOption( - contract.name, - viewKey, - values[viewKey] as string | undefined, - viewDelivery.invalidJson, - ); - if (!decoded.ok) return decoded; - const input = { - ...toContractInput(values), - ...(detail === undefined ? {} : { detail }), - ...(decoded.value === undefined ? {} : { view: decoded.value }), - }; - const admitted = contract.inputSchema.safeParse(input); - if (!admitted.success) - return err( - analysisInputErrorFromIssues(contract.name, admitted.error.issues, input), +): Result => { + const { evidenceDelivery, viewDelivery, parameters, shape } = command; + const decoded: Record = { ...values }; + for (const { key, runtimeJson } of parameters) { + if (runtimeJson === undefined) continue; + const parsed = parseCliJsonOption( + contract.name, + key, + values[key] as string | undefined, + runtimeJson, ); - const { view } = admitted.data as { readonly view?: object }; - return ok({ + if (!parsed.ok) return parsed; + decoded[key] = parsed.value; + } + const input = toContractInput(decoded); + const detail = evidenceDelivery + ? (decoded[rename("detail")] as "complete" | "summary" | undefined) + : undefined; + let view: object | undefined; + if (parameters.some(({ runtimeJson }) => runtimeJson !== undefined)) { + const selected = + viewDelivery === undefined ? undefined : decoded[rename("view")]; + const candidate = { + ...input, + ...(detail === undefined || !Object.hasOwn(shape, "detail") + ? {} + : { detail }), + ...(selected === undefined ? {} : { view: selected }), + }; + const admitted = contract.inputSchema.safeParse(candidate); + if (!admitted.success) + return err( + analysisInputErrorFromIssues( + contract.name, + admitted.error.issues, + candidate, + ), + ); + if (viewDelivery !== undefined) + ({ view } = admitted.data as { readonly view?: object }); + } + if (!evidenceDelivery) return ok({ input, delivery: undefined }); + const delivery: CliEvidenceDeliveryChoice = { detail: detail ?? (view === undefined ? "complete" : "summary"), - evidenceOutput, + evidenceOutput: decoded.evidence_output as string | undefined, ...(view === undefined ? {} : { - view: (viewDelivery.kind === undefined + view: (viewDelivery?.kind === undefined ? view : { kind: viewDelivery.kind, ...view }) as AnalysisViewRequest, }), + }; + const refused = cliEvidenceDeliveryInputError({ + ...delivery, + operation: contract.name, }); + return refused === undefined ? ok({ input, delivery }) : err(refused); }; diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index b4065ee556..3311e0b024 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -4,15 +4,18 @@ import type { Logger } from "pino"; import { logCliCommand } from "../cliLogging.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; -import type { Evidence } from "../domain/evidence.js"; +import type { CallerInputPaths, Evidence } from "../domain/evidence.js"; import type { Result } from "../domain/result.js"; import { deliverCliAnalysisEvidence } from "./analysisEvidenceDelivery.js"; import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; +import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { describeContractCommand, type CliContractProjection, type CliEvidenceDeliveryChoice, + type CliOptionShape, + type CliOptionValues, type ContractCliDescription, type ContractField, type ProjectedContract, @@ -27,7 +30,11 @@ import type { CliInstance } from "./types.js"; */ /** What a contract command's handler receives besides the contract input. */ -export interface ContractCommandContext { +export interface ContractCommandContext< + CliOptions extends Readonly> = Readonly< + Record + >, +> { readonly signal: AbortSignal; /** The contract name, which is the canonical operation. */ readonly operation: string; @@ -35,6 +42,8 @@ export interface ContractCommandContext { readonly callerInputs: Readonly>; /** The admitted delivery, for a projection with `evidenceDelivery`. */ readonly delivery: CliEvidenceDeliveryChoice | undefined; + /** The projection's CLI-only options, whose effect the handler owns. */ + readonly cliOptions: CliOptions; } /** A closeable one-shot service that inspects one contract input. */ @@ -46,27 +55,57 @@ export interface EvidenceInspectionService { close(): Promise; } -const primaryCallerPath = ({ +/** + * The caller's spelling of `path`, and of each other caller-path field keyed + * by its contract field name. + */ +const callerSpellings = ({ operation, callerInputs, -}: ContractCommandContext): string => { - const callerPath = callerInputs.path; - if (callerPath === undefined) +}: ContractCommandContext): { + readonly path: string; + readonly others: CallerInputPaths | undefined; +} => { + const { path, ...others } = callerInputs; + if (path === undefined) throw new Error(`${operation} has no caller path field named path`); - return callerPath; + return { + path, + others: Object.keys(others).length === 0 ? undefined : others, + }; }; /** * Inspect through a closeable service, finish its cleanup, and record the - * caller's spelling of `path` in the Evidence. + * caller's spelling of each selected path in the Evidence. */ export const inspectWithService = (service: () => EvidenceInspectionService, providerId: string) => (input: unknown, context: ContractCommandContext) => { - const callerPath = primaryCallerPath(context); + const spellings = callerSpellings(context); const owned = service(); return finishCliEvidenceCommand( - callerPath, + spellings.path, + () => owned.inspect(input, { signal: context.signal }), + owned, + providerId, + context.operation, + context.signal, + spellings.others, + ).then(projectCliAnalysisResult); + }; + +/** + * Run an analysis that selects no target path through a closeable service + * and finish its cleanup. + */ +export const analyzeWithService = + (service: () => EvidenceInspectionService, providerId: string) => + (input: unknown, context: ContractCommandContext) => { + if (Object.keys(context.callerInputs).length > 0) + throw new Error(`${context.operation} selects a caller path`); + const owned = service(); + return finishAnalysisCommand( () => owned.inspect(input, { signal: context.signal }), owned, providerId, @@ -77,18 +116,22 @@ export const inspectWithService = /** * Inspect through a closeable service, then deliver complete Evidence or a - * summary with its bundle, recording the caller's spelling of `path`. + * summary with its bundle, recording the caller's spelling of each selected + * path. */ export const deliverWithService = (service: () => EvidenceInspectionService, providerId: string) => (input: unknown, context: ContractCommandContext) => { - const callerInputPath = primaryCallerPath(context); + const spellings = callerSpellings(context); const { delivery } = context; if (delivery === undefined) throw new Error(`${context.operation} does not declare evidenceDelivery`); const owned = service(); return deliverCliAnalysisEvidence({ - callerInputPath, + callerInputPath: spellings.path, + ...(spellings.others === undefined + ? {} + : { callerInputPaths: spellings.others }), run: () => owned.inspect(input, { signal: context.signal }), service: owned, providerId, @@ -138,14 +181,15 @@ const incurOptions = (description: ContractCliDescription): z.ZodType => { export const registerContractCommand = < Contract extends ProjectedContract, Value, + CliOptions extends CliOptionShape = Record, >( cli: CliInstance, logger: Logger, contract: Contract, - projection: CliContractProjection>, + projection: CliContractProjection, CliOptions>, run: ( input: z.input, - context: ContractCommandContext, + context: ContractCommandContext>, ) => Promise, ): void => { const description = describeContractCommand(contract, projection); @@ -180,20 +224,17 @@ export const registerContractCommand = < const values = { ...options, ...args }; return withCommandCancellation((signal) => logCliCommand(logger, description.command, async () => { - const delivery = description.delivery?.(values); - if (delivery?.ok === false) - return projectAnalysisError(delivery.error); - return run( - description.toContractInput(values) as z.input< - Contract["inputSchema"] - >, - { - signal, - operation: contract.name, - callerInputs: description.callerInputs(values), - delivery: delivery?.value, - }, - ); + const admitted = description.admit(values); + if (!admitted.ok) return projectAnalysisError(admitted.error); + return run(admitted.value.input as z.input, { + signal, + operation: contract.name, + callerInputs: description.callerInputs(values), + delivery: admitted.value.delivery, + cliOptions: description.cliOptionValues( + values, + ) as CliOptionValues, + }); }), ); }, diff --git a/src/cli/gpuCommands.ts b/src/cli/gpuCommands.ts index 9d6b847c87..8e5713dfdf 100644 --- a/src/cli/gpuCommands.ts +++ b/src/cli/gpuCommands.ts @@ -1,129 +1,68 @@ -import { inspectGpuCodeObjectsInputSchema } from "../domain/gpu/gpuCodeObjects.js"; -import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; -import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; -import { parseCliJsonOption } from "./cliJsonOption.js"; -import { z } from "incur"; import type { Logger } from "pino"; -import type { CliInstance } from "./types.js"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { createGpuCodeObjectsService } from "../composition/gpu.js"; + import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; -import { withCommandCancellation } from "./commandCancellation.js"; +import { createGpuCodeObjectsService } from "../composition/gpu.js"; +import { GPU_TOOL_CONTRACTS } from "../contracts/gpu/gpuToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; import { - analysisEvidenceDeliveryOptions, - deliverCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; + deliverWithService, + registerContractCommand, +} from "./contractCommand.js"; +import type { CliInstance } from "./types.js"; /** One-shot summaries export the same complete observations used by MCP retained pages. */ export const registerGpuCommands = (cli: CliInstance, logger: Logger): void => { - cli.command(CLI_COMMANDS.inspectGpuCodeObjects, { - description: - "Inspect embedded CUDA/HIP targets and selected static kernel metadata", - args: z.object({ - path: localPathStringSchema.describe( - "Local ELF/PE, CUDA fatbin, CUBIN, PTX or HIP bundle", - ), - }), - options: z.object({ - ...analysisEvidenceDeliveryOptions, - view: z - .string() - .optional() - .describe( - "JSON GPU object/kernel/PTX page selection; requires --detail summary and --evidence_output", - ), - analysis: z - .enum(["inventory", "kernels"]) - .default("inventory") - .describe("Inventory GPU targets or decode selected kernel metadata"), - expected_sha256: - inspectGpuCodeObjectsInputSchema.shape.expected_sha256.describe( - "Inventory SHA-256 as 64 lowercase hex digits; required with --object_ids", - ), - object_ids: z - .string() - .optional() - .describe("JSON array of exact object IDs to decode"), - targets: z - .string() - .optional() - .describe("JSON array of exact target declarations to decode"), - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectGpuCodeObjects, async () => { - const selectors: Partial< - Record<"object_ids" | "targets" | "view", unknown> - > = {}; - for (const name of ["object_ids", "targets", "view"] as const) { - const value = options[name]; - if (value === undefined) continue; - const decoded = parseCliJsonOption( - "inspect_gpu_code_objects", - name, - value, - `${name} must be valid JSON`, - ); - if (!decoded.ok) return projectAnalysisError(decoded.error); - selectors[name] = decoded.value; - } - const rawInput = { - path: absoluteCallerPath(args.path), - analysis: options.analysis, - ...(options.expected_sha256 === undefined - ? {} - : { expected_sha256: options.expected_sha256 }), - ...selectors, - detail: options.detail, - }; - const selected = inspectGpuCodeObjectsInputSchema.safeParse(rawInput); - if (!selected.success) - return projectAnalysisError( - analysisInputErrorFromIssues( - "inspect_gpu_code_objects", - selected.error.issues, - rawInput, - ), - ); - const service = createGpuCodeObjectsService(); - return deliverCliAnalysisEvidence({ - callerInputPath: args.path, - run: () => - service.inspect( - { - path: selected.data.path, - analysis: selected.data.analysis, - ...(selected.data.expected_sha256 === undefined - ? {} - : { expected_sha256: selected.data.expected_sha256 }), - ...(selected.data.object_ids === undefined - ? {} - : { object_ids: selected.data.object_ids }), - ...(selected.data.targets === undefined - ? {} - : { targets: selected.data.targets }), - detail: "complete", - }, - { signal }, - ), - service, - providerId: "gpu-code-objects", - operation: "inspect_gpu_code_objects", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - ...(selected.data.view === undefined - ? {} - : { - view: { - kind: "gpu-code-objects" as const, - ...selected.data.view, - }, - }), - }); - }), - ), - }); + const deliver = deliverWithService( + createGpuCodeObjectsService, + "gpu-code-objects", + ); + registerContractCommand( + cli, + logger, + contractNamed(GPU_TOOL_CONTRACTS, "inspect_gpu_code_objects"), + { + command: CLI_COMMANDS.inspectGpuCodeObjects, + description: + "Inspect embedded CUDA/HIP targets and selected static kernel metadata", + positionals: ["path"], + callerPaths: ["path"], + evidenceDelivery: true, + viewDelivery: { + invalidJson: "view must be valid JSON", + kind: "gpu-code-objects", + }, + runtimeJson: { + object_ids: "object_ids must be valid JSON", + targets: "targets must be valid JSON", + }, + fields: { + path: { + description: "Local ELF/PE, CUDA fatbin, CUBIN, PTX or HIP bundle", + }, + analysis: { + description: + "Inventory GPU targets or decode selected kernel metadata", + }, + expected_sha256: { + name: "expected_sha256", + description: + "Inventory SHA-256 as 64 lowercase hex digits; required with --object_ids", + }, + object_ids: { + name: "object_ids", + description: "JSON array of exact object IDs to decode", + }, + targets: { + description: "JSON array of exact target declarations to decode", + }, + view: { + description: + "JSON GPU object/kernel/PTX page selection; requires --detail summary and --evidence_output", + }, + }, + }, + // The CLI delivers the summary itself, so the service returns complete + // Evidence; the contract's own default would retain a summary instead. + (input, context) => deliver({ ...input, detail: "complete" }, context), + ); }; diff --git a/src/cli/il2cppCommands.ts b/src/cli/il2cppCommands.ts index 0a1a36ed51..9f4aec4244 100644 --- a/src/cli/il2cppCommands.ts +++ b/src/cli/il2cppCommands.ts @@ -1,50 +1,94 @@ -import { localPathStringSchema } from "../domain/localPath.js"; -import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { z } from "incur"; -import { AnalysisInputError } from "../domain/analysisErrorCore.js"; -import { err } from "../domain/result.js"; -import { createIl2cppMetadataService } from "../composition/il2cpp.js"; -import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; -import type { CliInstance } from "./types.js"; -import { withCommandCancellation } from "./commandCancellation.js"; + +import { CLI_COMMANDS } from "../cliCommandNames.js"; +import { createIl2cppMetadataService } from "../composition/il2cpp.js"; +import { IL2CPP_TOOL_CONTRACTS } from "../contracts/il2cpp/il2cppToolContracts.js"; +import { AnalysisInputError } from "../domain/analysisErrorCore.js"; +import { localPathStringSchema } from "../domain/localPath.js"; +import { err } from "../domain/result.js"; +import { absoluteCallerPath } from "../filesystem/callerPath.js"; +import { contractNamed } from "./contractCliDescription.js"; import { - analysisEvidenceDeliveryOptions, - deliverCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; + deliverWithService, + registerContractCommand, +} from "./contractCommand.js"; +import type { CliInstance } from "./types.js"; + +/** + * Inspection with the CLI-only Ghidra seed output: `--ghidra-seeds` writes + * seeds for the linked methods, and `--seed-base` rebases them. + */ +const il2cppService = ( + ghidraSeeds: string | undefined, + seedBase: string | undefined, +) => { + const service = createIl2cppMetadataService(); + return { + inspect: (input: unknown, options: { readonly signal: AbortSignal }) => { + if (ghidraSeeds !== undefined) + return service.inspectWithGhidraSeeds( + input, + { + path: absoluteCallerPath(ghidraSeeds), + ...(seedBase === undefined ? {} : { base: seedBase }), + }, + options, + ); + if (seedBase !== undefined) + return Promise.resolve( + err( + new AnalysisInputError("inspect_il2cpp_metadata", undefined, [ + { + path: ["seed_base"], + reason: "invalid_value", + message: "--seed-base requires --ghidra-seeds.", + }, + ]), + ), + ); + return service.inspect(input, options); + }, + close: () => service.close(), + }; +}; /** CLI and MCP share inspection; one-shot summaries preserve a complete Evidence file. */ export const registerIl2cppCommands = ( cli: CliInstance, logger: Logger, ): void => { - cli.command(CLI_COMMANDS.inspectIl2cppMetadata, { - description: - "Inventory IL2CPP global-metadata.dat names, owners and string literals, optionally linking method addresses from the native binary", - args: z.object({ - path: localPathStringSchema.describe( - "Local global-metadata.dat (version 24, 27, 29, 31 or 39)", - ), - }), - options: z - .object({ - ...analysisEvidenceDeliveryOptions, - binary: localPathStringSchema - .optional() - .describe( + registerContractCommand( + cli, + logger, + contractNamed(IL2CPP_TOOL_CONTRACTS, "inspect_il2cpp_metadata"), + { + command: CLI_COMMANDS.inspectIl2cppMetadata, + description: + "Inventory IL2CPP global-metadata.dat names, owners and string literals, optionally linking method addresses from the native binary", + positionals: ["path"], + callerPaths: ["path", "binary_path"], + evidenceDelivery: true, + fields: { + path: { + description: + "Local global-metadata.dat (version 24, 27, 29, 31 or 39)", + }, + binary_path: { + name: "binary", + description: "Matching native binary (Mach-O GameAssembly.dylib, PE GameAssembly.dll or ELF libil2cpp.so) to link method addresses; read only", - ), - architecture: z - .enum(["arm64", "amd64"]) - .optional() - .describe("Slice of a universal Mach-O binary"), - genericInstances: z - .boolean() - .optional() - .describe( + }, + binary_architecture: { + name: "architecture", + description: "Slice of a universal Mach-O binary", + }, + generic_instances: { + description: "Also link generic method instances (Type$$Method) and include them in --ghidra-seeds; needs --binary", - ), + }, + }, + cliOptions: { ghidraSeeds: localPathStringSchema .optional() .describe( @@ -57,79 +101,20 @@ export const registerIl2cppCommands = ( .describe( "Address Ghidra loads the binary at; seeds are seed-base + RVA (default: Ghidra's loader default, 0x100000 for an ELF linked at 0, else the link base)", ), - }) - .meta({ - dependentRequired: { - architecture: ["binary"], - ghidraSeeds: ["binary"], - seedBase: ["ghidraSeeds"], - }, - if: { - properties: { genericInstances: { const: true } }, - required: ["genericInstances"], - }, - then: { required: ["binary"] }, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectIl2cppMetadata, async () => { - const service = createIl2cppMetadataService(); - return deliverCliAnalysisEvidence({ - callerInputPath: args.path, - ...(options.binary === undefined - ? {} - : { callerInputPaths: { binary_path: options.binary } }), - run: () => { - const input = { - path: absoluteCallerPath(args.path), - detail: "complete" as const, - ...(options.binary === undefined - ? {} - : { binary_path: absoluteCallerPath(options.binary) }), - ...(options.architecture === undefined - ? {} - : { binary_architecture: options.architecture }), - ...(options.genericInstances === true - ? { generic_instances: true } - : {}), - }; - if (options.ghidraSeeds !== undefined) - return service.inspectWithGhidraSeeds( - input, - { - path: absoluteCallerPath(options.ghidraSeeds), - ...(options.seedBase === undefined - ? {} - : { base: options.seedBase }), - }, - { signal }, - ); - if (options.seedBase !== undefined) - return Promise.resolve( - err( - new AnalysisInputError( - "inspect_il2cpp_metadata", - undefined, - [ - { - path: ["seed_base"], - reason: "invalid_value", - message: "--seed-base requires --ghidra-seeds.", - }, - ], - ), - ), - ); - return service.inspect(input, { signal }); - }, - service, - providerId: "il2cpp-metadata", - operation: "inspect_il2cpp_metadata", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }); - }), - ), - }); + }, + cliOptionDependencies: { + ghidraSeeds: ["binary"], + seedBase: ["ghidraSeeds"], + }, + }, + (input, context) => { + const { ghidraSeeds, seedBase } = context.cliOptions; + // The CLI delivers the summary itself, so the service returns complete + // Evidence; the contract's own default would retain a summary instead. + return deliverWithService( + () => il2cppService(ghidraSeeds, seedBase), + "il2cpp-metadata", + )({ ...input, detail: "complete" }, context); + }, + ); }; diff --git a/src/cli/releaseExposureCommands.ts b/src/cli/releaseExposureCommands.ts index 22382612b6..d9f08d1b69 100644 --- a/src/cli/releaseExposureCommands.ts +++ b/src/cli/releaseExposureCommands.ts @@ -2,19 +2,17 @@ import { z } from "incur"; import type { Logger } from "pino"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; import { createReleaseExposureService } from "../composition/releaseExposure.js"; -import { localPathStringSchema } from "../domain/localPath.js"; +import { RELEASE_EXPOSURE_TOOL_CONTRACTS } from "../contracts/releaseExposureToolContracts.js"; import { - auditReleaseExposureInputSchema, exposureMeetsFailOn, releaseExposureReportSchema, } from "../domain/releaseExposure.js"; -import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { withCommandCancellation } from "./commandCancellation.js"; -import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; -import { cliDecimalField } from "./options.js"; -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { + inspectWithService, + registerContractCommand, +} from "./contractCommand.js"; import type { CliInstance } from "./types.js"; /** Report what static analysis recovers from one shipped artifact. */ @@ -23,65 +21,51 @@ export const registerReleaseExposureCommands = ( logger: Logger, environment: Readonly>, ): void => { - cli.command(CLI_COMMANDS.auditReleaseExposure, { - description: - "Report what static analysis of a shipped artifact recovers. Reads the selected path. When the selection is a file, the parent directory is listed for sibling .pdb, .dSYM, .debug, and .map debug companions.", - args: z.object({ - path: localPathStringSchema.describe( - "Shipped .app bundle, install directory, ASAR, or executable", - ), - }), - options: z.object({ - fail_on: z - .enum(["high", "medium", "low"]) - .optional() - .describe( - "Completed audit exits 3 when an exposed check meets this severity. Unknown and unassessed checks do not.", - ), - maxFileBytes: cliDecimalField( - auditReleaseExposureInputSchema.shape.max_file_bytes, - ), - }), - run: ({ args, options }) => - withCommandCancellation(async (signal) => { - const service = createReleaseExposureService(environment); - return await logCliCommand( - logger, - CLI_COMMANDS.auditReleaseExposure, - async () => { - const projected = await finishCliEvidenceCommand( - args.path, - () => - service.inspect( - { - path: absoluteCallerPath(args.path), - max_file_bytes: options.maxFileBytes, - }, - { signal }, - ), - service, - "rea-release-exposure", - "audit_release_exposure", - signal, - ).then(projectCliAnalysisResult); - if ( - options.fail_on !== undefined && - projected !== null && - typeof projected === "object" && - "normalized_result" in projected - ) { - const report = releaseExposureReportSchema.safeParse( - projected.normalized_result, - ); - if ( - report.success && - exposureMeetsFailOn(report.data, options.fail_on) - ) - process.exitCode = 3; - } - return projected; - }, + const inspect = inspectWithService( + () => createReleaseExposureService(environment), + "rea-release-exposure", + ); + registerContractCommand( + cli, + logger, + contractNamed(RELEASE_EXPOSURE_TOOL_CONTRACTS, "audit_release_exposure"), + { + command: CLI_COMMANDS.auditReleaseExposure, + description: + "Report what static analysis of a shipped artifact recovers. Reads the selected path. When the selection is a file, the parent directory is listed for sibling .pdb, .dSYM, .debug, and .map debug companions.", + positionals: ["path"], + callerPaths: ["path"], + fields: { + path: { + description: + "Shipped .app bundle, install directory, ASAR, or executable", + }, + }, + cliOptions: { + fail_on: z + .enum(["high", "medium", "low"]) + .optional() + .describe( + "Completed audit exits 3 when an exposed check meets this severity. Unknown and unassessed checks do not.", + ), + }, + }, + async (input, context) => { + const projected = await inspect(input, context); + const failOn = context.cliOptions.fail_on; + if ( + failOn !== undefined && + projected !== null && + typeof projected === "object" && + "normalized_result" in projected + ) { + const report = releaseExposureReportSchema.safeParse( + projected.normalized_result, ); - }), - }); + if (report.success && exposureMeetsFailOn(report.data, failOn)) + process.exitCode = 3; + } + return projected; + }, + ); }; diff --git a/src/cli/signalCommands.ts b/src/cli/signalCommands.ts index 114783dc81..7172b95d0c 100644 --- a/src/cli/signalCommands.ts +++ b/src/cli/signalCommands.ts @@ -1,24 +1,18 @@ -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { inspectSignalDecodersInputSchema } from "../domain/signals/signalDecoders.js"; -import { z } from "incur"; -import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js"; -import { createSignalRecordingService } from "../composition/signals.js"; -import { - signalRecordingOptionsSchema, - signalRecordingSelectorBudgetIssue, - withinSignalRecordingSelectorBudget, -} from "../domain/signals/signalRecording.js"; -import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; + +import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js"; +import { CLI_COMMANDS } from "../cliCommandNames.js"; +import { createSignalRecordingService } from "../composition/signals.js"; +import { SIGNAL_TOOL_CONTRACTS } from "../contracts/signals/signalToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { + analyzeWithService, + inspectWithService, + registerContractCommand, +} from "./contractCommand.js"; +import { PRODUCER_LIMITS_HELP } from "./producerLimitsOption.js"; import type { CliInstance } from "./types.js"; -import { withCommandCancellation } from "./commandCancellation.js"; -import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; -import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; -import { cliDecimalField, cliDecimalShape } from "./options.js"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { producerLimitsOption } from "./producerLimitsOption.js"; + export const registerSignalCommands = ( cli: CliInstance, logger: Logger, @@ -28,135 +22,70 @@ export const registerSignalCommands = ( "decode" | "inspectDecoders" | "close" > = createSignalRecordingService(environment), ): void => { - const { producer_limits: discoveryLimits, ...discoveryShape } = - inspectSignalDecodersInputSchema.shape; - const { producer_limits: selectedLimits, ...selectedShape } = - signalRecordingOptionsSchema.shape; - cli.command(CLI_COMMANDS.inspectSignalDecoders, { - description: "Search installed sigrok decoders or selected decoder help", - options: z - .object({ - ...cliDecimalShape(discoveryShape), - producerLimits: producerLimitsOption(discoveryLimits.unwrap()), - limit: cliDecimalField( - z - .number() - .int() - .positive() - .max(Number.MAX_SAFE_INTEGER) - .optional() - .describe( - "Maximum matching decoders or help lines to return; defaults to 50", - ), - ), - all: z - .boolean() - .default(false) - .describe("Return all remaining matches"), - }) - .superRefine((options, context) => { - if (options.all && options.limit !== undefined) - context.addIssue({ - code: "custom", - path: ["all"], - message: "all and limit are mutually exclusive", - }); - }) - .meta({ - not: { - required: ["all", "limit"], - properties: { all: { const: true } }, + const close = () => service.close(); + registerContractCommand( + cli, + logger, + contractNamed(SIGNAL_TOOL_CONTRACTS, "inspect_signal_decoders"), + { + command: CLI_COMMANDS.inspectSignalDecoders, + description: "Search installed sigrok decoders or selected decoder help", + jsonText: ["producer_limits"], + nullFlags: { + limit: { key: "all", description: "Return all remaining matches" }, + }, + fields: { + producer_limits: { description: PRODUCER_LIMITS_HELP }, + limit: { + description: + "Maximum matching decoders or help lines to return; defaults to 50", }, + }, + }, + analyzeWithService( + () => ({ + inspect: (input, options) => service.inspectDecoders(input, options), + close, }), - run: ({ options: { all, producerLimits, ...options } }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectSignalDecoders, async () => - finishAnalysisCommand( - () => - service.inspectDecoders( - { - ...options, - ...(producerLimits === undefined - ? {} - : { producer_limits: producerLimits }), - ...(all ? { limit: null } : {}), - }, - { signal }, - ), - service, - "sigrok-recording", - "inspect_signal_decoders", - signal, - ).then(projectCliAnalysisResult), - ), - ), - }); - cli.command(CLI_COMMANDS.decodeSignalRecording, { - description: - "Decode an existing signal recording with caller-supplied sigrok", - args: z.object({ - path: localPathStringSchema.describe("Local signal recording"), - }), - options: z - .object({ - ...cliDecimalShape(selectedShape), - producerLimits: producerLimitsOption(selectedLimits.unwrap()), - line_limit: cliDecimalField( - z - .number() - .int() - .positive() - .optional() - .describe("Returned output lines per page; default 50"), - ), - all_lines: z - .boolean() - .default(false) - .describe( + "sigrok-recording", + ), + ); + registerContractCommand( + cli, + logger, + contractNamed(SIGNAL_TOOL_CONTRACTS, "decode_signal_recording"), + { + command: CLI_COMMANDS.decodeSignalRecording, + description: + "Decode an existing signal recording with caller-supplied sigrok", + positionals: ["path"], + callerPaths: ["path"], + jsonText: ["producer_limits"], + nullFlags: { + line_limit: { + key: "all_lines", + description: "Return all remaining output lines instead of a bounded page", - ), - }) - .superRefine((options, context) => { - if (options.all_lines && options.line_limit !== undefined) - context.addIssue({ - code: "custom", - path: ["all_lines"], - message: "all_lines and line_limit are mutually exclusive", - }); - }) - .refine( - withinSignalRecordingSelectorBudget, - signalRecordingSelectorBudgetIssue, - ) - .meta({ - not: { - required: ["all_lines", "line_limit"], - properties: { all_lines: { const: true } }, }, + }, + crossFieldRules: "argv", + fields: { + path: { description: "Local signal recording" }, + producer_limits: { description: PRODUCER_LIMITS_HELP }, + input_format: { name: "input_format" }, + line_offset: { name: "line_offset" }, + line_limit: { + name: "line_limit", + description: "Returned output lines per page; default 50", + }, + }, + }, + inspectWithService( + () => ({ + inspect: (input, options) => service.decode(input, options), + close, }), - run: ({ args, options: { all_lines, producerLimits, ...options } }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.decodeSignalRecording, async () => { - return finishCliEvidenceCommand( - args.path, - () => - service.decode( - { - ...options, - ...(producerLimits === undefined - ? {} - : { producer_limits: producerLimits }), - ...(all_lines ? { line_limit: null } : {}), - path: absoluteCallerPath(args.path), - }, - { signal }, - ), - service, - "sigrok-recording", - "decode_signal_recording", - signal, - ).then(projectCliAnalysisResult); - }), - ), - }); + "sigrok-recording", + ), + ); }; diff --git a/src/domain/captures/packetCapture.ts b/src/domain/captures/packetCapture.ts index 235e8513f6..ec849573de 100644 --- a/src/domain/captures/packetCapture.ts +++ b/src/domain/captures/packetCapture.ts @@ -98,9 +98,6 @@ export const inspectPacketCaptureInputSchema = packetCaptureSelectionSchema.safeExtend({ path: absoluteLocalPathStringSchema.describe("Absolute local capture path"), }); -export const packetCaptureOptionsSchema = captureInputShape - .omit({ path: true }) - .refine(withinPacketCaptureSelectorBudget, packetCaptureSelectorBudgetIssue); export type InspectPacketCaptureInput = z.infer< typeof inspectPacketCaptureInputSchema >; diff --git a/src/domain/signals/signalRecording.ts b/src/domain/signals/signalRecording.ts index 08e7b3cfbc..0a7d0f1d42 100644 --- a/src/domain/signals/signalRecording.ts +++ b/src/domain/signals/signalRecording.ts @@ -76,12 +76,6 @@ export const decodeSignalRecordingInputSchema = "Absolute local recording path", ), }); -export const signalRecordingOptionsSchema = signalInputShape - .omit({ path: true }) - .refine( - withinSignalRecordingSelectorBudget, - signalRecordingSelectorBudgetIssue, - ); export type DecodeSignalRecordingInput = z.infer< typeof decodeSignalRecordingInputSchema >; diff --git a/tests/acceptance/appleIpsArmJoinCli.test.ts b/tests/acceptance/appleIpsArmJoinCli.test.ts index eb10e37a3f..648f79af3a 100644 --- a/tests/acceptance/appleIpsArmJoinCli.test.ts +++ b/tests/acceptance/appleIpsArmJoinCli.test.ts @@ -6,6 +6,7 @@ import { machoImage, } from "../../src/artifacts/apple/MachoImage.fixture.js"; import { toolContract } from "../../src/contracts/toolContracts.js"; +import { parseEvidence } from "../../src/domain/evidence.js"; import { appleIpsBytes } from "../fixtures/binaryDiagnostics/appleIps.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; @@ -114,3 +115,35 @@ cliTest.for([11, 99])( expect(report.join.limitations.join(" ")).toContain("UUID is unknown"); }, ); + +cliTest( + "records the caller's spelling of the report and the joined image", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-ips-join-spelling-"); + await writeFile( + join(root, "report.ips"), + appleIpsBytes({ arch: "armv7", base: 0x8000 }), + ); + await writeFile(join(root, "image.bin"), armImage(9)); + const joined = await cli.run({ + cwd: root, + arguments: [ + "inspect-apple-ips", + "./report.ips", + "--join-path", + "./image.bin", + "--json", + ], + }); + expect(joined.exitCode, joined.stderr).toBe(0); + const evidence = parseEvidence(joined.json); + expect(evidence.caller_input_path).toBe("./report.ips"); + expect(evidence.caller_input_paths).toEqual({ join_path: "./image.bin" }); + const alone = await cli.run({ + cwd: root, + arguments: ["inspect-apple-ips", "./report.ips", "--json"], + }); + expect(alone.exitCode, alone.stderr).toBe(0); + expect(parseEvidence(alone.json).caller_input_paths).toBeUndefined(); + }, +); diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index c03b72fe1f..fb3327461e 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -82,9 +82,13 @@ const probes = (field: z.ZodType): readonly unknown[] => { return values; }; +/** The field admits a number, possibly alongside null. */ const isNumeric = (field: z.ZodType): boolean => { const json = inputJsonSchema(field); - return json.type === "integer" || json.type === "number"; + const branches = Array.isArray(json.anyOf) + ? (json.anyOf as Record[]) + : [json]; + return branches.some(({ type }) => type === "integer" || type === "number"); }; /** Argv omission is an absent key, never an explicit undefined. */ @@ -111,6 +115,9 @@ const expectedAdmission = ( } return admits(contractField, decoded) && decoded !== undefined; } + if (parameter.nullFlag !== undefined && value === null) + // Null is spelled by the bare flag, never by the limit option. + return false; if (parameter.callerPath) { // A caller path is validated as typed: an empty value never becomes the // working directory. A nonempty value is resolved, then the contract rules. @@ -136,8 +143,8 @@ const registeredField = ( const contractShape = (description: ContractCliDescription) => description.fields; -/** A caller-relative target, or the first probe the positional admits. */ -const positionalValue = ( +/** A caller-relative target, or the first probe the argument admits. */ +const requiredValue = ( description: ContractCliDescription, parameter: ContractCliParameter, ): unknown => @@ -149,23 +156,38 @@ const positionalValue = ( admits(registeredField(description, parameter), value), ); -/** Parsed option values plus admitted positionals. */ +/** Parsed option values plus admitted positionals and required options. */ const argvValues = ( description: ContractCliDescription, options: Readonly>, -): Record => ({ - ...(registered.get(description.command)!.options as z.ZodObject).parse( - options, - ), - ...Object.fromEntries( - description.parameters - .filter(({ positional }) => positional) - .map((parameter) => [ - parameter.key, - positionalValue(description, parameter), - ]), - ), -}); +): Record => { + const required = description.parameters.filter( + (parameter) => + !admits(registeredField(description, parameter), undefined) && + (parameter.positional || !Object.hasOwn(options, parameter.key)), + ); + const filled = Object.fromEntries( + required.map((parameter) => [ + parameter.key, + requiredValue(description, parameter), + ]), + ); + return { + ...(registered.get(description.command)!.options as z.ZodObject).parse({ + ...options, + ...Object.fromEntries( + required + .filter(({ positional }) => !positional) + .map(({ key }) => [key, filled[key]]), + ), + }), + ...Object.fromEntries( + required + .filter(({ positional }) => positional) + .map(({ key }) => [key, filled[key]]), + ), + }; +}; const each = descriptions.map( (description) => [description.command, description] as const, @@ -188,6 +210,13 @@ describe("CLI commands projected from tool contracts", () => { "inspect-apk-signature", "inspect-desktop-application", "inspect-evm-interface", + "audit-release-exposure", + "inspect-il2cpp-metadata", + "inspect-gpu-code-objects", + "inspect-signal-decoders", + "decode-signal-recording", + "inspect-packet-fields", + "inspect-packet-capture", ]), ); }); @@ -240,8 +269,8 @@ describe("CLI commands projected from tool contracts", () => { expect(admits(contractField, "rel/x"), parameter.field).toBe(false); expect(admits(contractField, absoluteCallerPath("rel/x"))).toBe(true); } - if (parameter.viewSelection) { - // The view is JSON text decoded when the command runs; see below. + if (parameter.runtimeJson !== undefined) { + // JSON text decoded when the command runs; see below. for (const value of [undefined, "", "{", "{}"]) expect(admits(cliField, value), parameter.key).toBe(true); continue; @@ -324,15 +353,174 @@ describe("CLI commands projected from tool contracts", () => { }); }); +describe("CLI-only options of contract commands", () => { + it.each(each)( + "%s keeps its CLI-only options out of the contract input", + (_command, description) => { + const cliKeys = description.cliOnlyOptions.map(({ key }) => key); + const values = Object.fromEntries(cliKeys.map((key) => [key, "set"])); + const input = description.toContractInput(values); + for (const key of cliKeys) { + expect(Object.values(input), key).not.toContain("set"); + expect(Object.keys(description.fields), key).not.toContain(key); + } + }, + ); + + it("refuses CLI-only options that collide with or depend on unknown keys", () => { + const contract = { + name: "probe", + inputSchema: z.object({ value: z.string().optional() }), + }; + expect(() => + describeContractCommand(contract, { + command: "probe", + description: "Probe", + cliOptions: { value: z.string().optional() }, + }), + ).toThrow("probe projects two fields to one CLI key"); + expect(() => + describeContractCommand(contract, { + command: "probe", + description: "Probe", + cliOptions: { extra: z.string().optional() }, + cliOptionDependencies: { extra: ["missing"] }, + }), + ).toThrow("probe has no CLI option missing"); + const described = describeContractCommand(contract, { + command: "probe", + description: "Probe", + cliOptions: { extra: z.string().optional() }, + cliOptionDependencies: { extra: ["value"] }, + }); + expect(described.optionConstraints).toEqual({ + dependentRequired: { extra: ["value"] }, + }); + expect(described.cliOptionValues({ value: "a", extra: "b" })).toEqual({ + extra: "b", + }); + expect(described.toContractInput({ value: "a", extra: "b" })).toEqual({ + value: "a", + }); + }); +}); + +const decodingAtRunTime = each.filter(([, description]) => + description.parameters.some(({ runtimeJson }) => runtimeJson !== undefined), +); + +describe("JSON decoded when contract commands run", () => { + it.each(decodingAtRunTime)( + "%s refuses text that is not JSON before analysis", + (_command, description) => { + for (const parameter of description.parameters) { + if (parameter.runtimeJson === undefined) continue; + const malformed = description.admit( + argvValues(description, { + detail: "summary", + evidence_output: "out.json", + [parameter.key]: "{", + }), + ); + expect(malformed.ok, parameter.key).toBe(false); + if (!malformed.ok) + expect(malformed.error.issues).toEqual([ + expect.objectContaining({ + path: [parameter.key], + reason: "invalid_format", + message: parameter.runtimeJson, + }), + ]); + } + }, + ); + + it.each(decodingAtRunTime)( + "%s admits what its contract admits once decoded", + (_command, description) => { + const mismatches: string[] = []; + const details = description.evidenceDelivery + ? (["complete", "summary"] as const) + : [undefined]; + for (const parameter of description.parameters) { + if (parameter.runtimeJson === undefined) continue; + for (const detail of details) + for (const text of ["{}", "[]", "null", '{"unknown":1}', '["x"]']) { + const values = argvValues(description, { + ...(detail === undefined + ? {} + : { detail, evidence_output: "out.json" }), + [parameter.key]: text, + }); + const expected = description.contract.inputSchema.safeParse({ + ...description.toContractInput({ + ...values, + [parameter.key]: undefined, + }), + ...(detail === undefined ? {} : { detail }), + [parameter.field]: JSON.parse(text) as unknown, + }).success; + if (description.admit(values).ok !== expected) + mismatches.push( + `${parameter.key} ${String(detail)} ${text} expected ${String(expected)}`, + ); + } + } + expect(mismatches).toEqual([]); + }, + ); +}); + +const nullFlagged = each.filter(([, description]) => + description.parameters.some(({ nullFlag }) => nullFlag !== undefined), +); + +describe("Null-limit flags of contract commands", () => { + it.each(nullFlagged)( + "%s spells null with its flag and refuses the flag with a limit", + (_command, description) => { + const parameter = description.parameters.find( + ({ nullFlag }) => nullFlag !== undefined, + )!; + const flag = parameter.nullFlag!; + expect(description.cliOnlyOptions.map(({ key }) => key)).toContain(flag); + expect(admits(contractShape(description)[parameter.field]!, null)).toBe( + true, + ); + const all = argvValues(description, { [flag]: true }); + expect(description.toContractInput(all)[parameter.field]).toBeNull(); + expect( + description.contract.inputSchema.safeParse( + description.toContractInput(all), + ).error, + ).toBe(undefined); + expect(description.checkOptions?.(all)).toEqual([]); + const both = { ...all, [parameter.key]: 1 }; + expect(description.checkOptions?.(both)).toEqual([ + expect.objectContaining({ + path: [flag], + message: `${flag} and ${parameter.key} are mutually exclusive`, + }), + ]); + expect(description.optionConstraints?.not).toEqual({ + required: [flag, parameter.key], + properties: { [flag]: { const: true } }, + }); + const bounded = argvValues(description, { [parameter.key]: 1 }); + expect(description.toContractInput(bounded)[parameter.field]).toBe(1); + }, + ); +}); + const delivering = each.filter( - ([, description]) => description.delivery !== undefined, + ([, description]) => description.evidenceDelivery, ); describe("Evidence delivery of contract commands", () => { it.each(delivering)( "%s refuses summary delivery without --evidence_output before analysis", (_command, description) => { - const refused = description.delivery!( + const refused = description.admit( argvValues(description, { detail: "summary" }), ); expect(refused.ok).toBe(false); @@ -341,7 +529,7 @@ describe("Evidence delivery of contract commands", () => { ["evidence_output"], ]); expect( - description.delivery!( + description.admit( argvValues(description, { detail: "summary", evidence_output: "out.json", @@ -351,48 +539,6 @@ describe("Evidence delivery of contract commands", () => { }, ); - it.each( - delivering.filter(([, description]) => - description.parameters.some(({ viewSelection }) => viewSelection), - ), - )( - "%s decodes --view when it runs and admits what its contract admits", - (_command, description) => { - const view = description.parameters.find( - ({ viewSelection }) => viewSelection, - )!; - const malformed = description.delivery!( - argvValues(description, { - detail: "summary", - evidence_output: "out.json", - [view.key]: "{", - }), - ); - expect(malformed.ok).toBe(false); - if (!malformed.ok) - expect(malformed.error.issues).toEqual([ - expect.objectContaining({ path: ["view"], reason: "invalid_format" }), - ]); - const mismatches: string[] = []; - for (const detail of ["complete", "summary"] as const) - for (const text of ["{}", "[]", "null", '{"unknown":1}']) { - const values = argvValues(description, { - detail, - evidence_output: "out.json", - [view.key]: text, - }); - const expected = description.contract.inputSchema.safeParse({ - ...description.toContractInput(values), - detail, - view: JSON.parse(text) as unknown, - }).success; - if (description.delivery!(values).ok !== expected) - mismatches.push(`${detail} ${text} expected ${String(expected)}`); - } - expect(mismatches).toEqual([]); - }, - ); - it("refuses a union input whose branches differ outside the delivery", () => { const inputSchema = z.discriminatedUnion("detail", [ z.object({