Simplify REA onboarding and app targeting
This commit is contained in:
@@ -6,6 +6,7 @@ import { join } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { probeHomebrew } from "./homebrew.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -25,7 +26,7 @@ export interface DoctorHost {
|
||||
readonly nodeVersion: string;
|
||||
readonly configuredHopperPath?: string;
|
||||
macosVersion(): Promise<string | undefined>;
|
||||
readable(path: string): Promise<boolean>;
|
||||
validTarget(path: string): Promise<boolean>;
|
||||
executable(path: string): Promise<boolean>;
|
||||
brewHopperPath(): Promise<string | undefined>;
|
||||
manualHopperPaths(): Promise<readonly string[]>;
|
||||
@@ -89,9 +90,9 @@ export const runDoctor = async (
|
||||
checks.push(
|
||||
check(
|
||||
"target",
|
||||
await host.readable(target),
|
||||
await host.validTarget(target),
|
||||
target,
|
||||
"Supply a readable local binary path.",
|
||||
"Supply a readable local app or program path.",
|
||||
),
|
||||
);
|
||||
return {
|
||||
@@ -117,13 +118,8 @@ export const systemDoctorHost = (): DoctorHost => ({
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
async readable(path) {
|
||||
try {
|
||||
await access(path, constants.R_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
async validTarget(path) {
|
||||
return (await parseBinaryTarget(path)).ok;
|
||||
},
|
||||
async executable(path) {
|
||||
try {
|
||||
|
||||
@@ -276,8 +276,14 @@ const installCanonicalSkill = async (
|
||||
PRODUCT_IDENTITY.skillName,
|
||||
"SKILL.md",
|
||||
);
|
||||
const content = `---\nname: ${PRODUCT_IDENTITY.skillName}\ndescription: Analyze binaries with REA and Hopper.\n---\n\nOpen a target with open_binary, begin with binary_overview, and close it when finished.\n`;
|
||||
try {
|
||||
const content = await readFile(
|
||||
new URL(
|
||||
`../../skills/${PRODUCT_IDENTITY.skillName}/SKILL.md`,
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
if (
|
||||
(await readFile(destination, "utf8").catch(() => undefined)) === content
|
||||
)
|
||||
|
||||
+12
-12
@@ -21,25 +21,25 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
);
|
||||
const cli = Cli.create(PRODUCT_IDENTITY.cliBinary, {
|
||||
version: "0.1.0",
|
||||
description: "Install, diagnose, and automate Hopper binary analysis.",
|
||||
description: "Reverse engineer apps from your terminal or coding agent.",
|
||||
mcp: {
|
||||
command: PRODUCT_IDENTITY.mcpCommand,
|
||||
instructions:
|
||||
"Open a local target with open_binary, analyze it, and close the session when finished.",
|
||||
"Ask which app and feature the user wants to understand, then open the app and investigate it.",
|
||||
},
|
||||
sync: {
|
||||
cwd: fileURLToPath(new URL("..", import.meta.url)),
|
||||
include: ["skills/*"],
|
||||
suggestions: [
|
||||
"open a binary and summarize it",
|
||||
"decompile a procedure",
|
||||
"diagnose my Hopper setup",
|
||||
"understand how an app feature works",
|
||||
"decompile part of an app",
|
||||
"check my REA setup",
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
cli.command("setup", {
|
||||
description: "Install prerequisites and configure binary analysis",
|
||||
description: "Install requirements and configure coding agents",
|
||||
options: z.object({
|
||||
yes: z
|
||||
.boolean()
|
||||
@@ -51,17 +51,17 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
logCliCommand(logger, "setup", () => runSetup(options.yes)),
|
||||
});
|
||||
cli.command("doctor", {
|
||||
description: "Diagnose the local Hopper integration",
|
||||
description: "Check whether REA is ready",
|
||||
options: z.object({
|
||||
target: z.string().optional().describe("Optional binary path to check"),
|
||||
target: z.string().optional().describe("Optional app path to check"),
|
||||
}),
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, "doctor", () => runDoctor(options.target)),
|
||||
});
|
||||
cli.command("analyze", {
|
||||
description: "Analyze a binary through the shared Hopper core",
|
||||
description: "Get an overview of an app",
|
||||
args: z.object({
|
||||
path: z.string().describe("Binary or Hopper database path"),
|
||||
path: z.string().describe("App, program, or Hopper database path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "analyze", () =>
|
||||
@@ -69,9 +69,9 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
),
|
||||
});
|
||||
cli.command("decompile", {
|
||||
description: "Decompile an address through the shared Hopper core",
|
||||
description: "Read one part of an app as code",
|
||||
args: z.object({
|
||||
path: z.string().describe("Binary path"),
|
||||
path: z.string().describe("App or program path"),
|
||||
address: z.string().describe("Procedure address"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
|
||||
@@ -2,15 +2,20 @@ import { constants } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { BinaryTargetError } from "./errors.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** CPU families understood by the supported executable loaders. */
|
||||
type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
|
||||
/**
|
||||
@@ -41,7 +46,10 @@ export const parseBinaryTarget = async (
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
await access(candidate, constants.R_OK);
|
||||
const path = await realpath(candidate);
|
||||
const canonical = await realpath(candidate);
|
||||
const resolved = await resolveAppBundle(canonical);
|
||||
if (!resolved.ok) return err(resolved.error);
|
||||
const path = resolved.value;
|
||||
if (!(await stat(path)).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
if (
|
||||
@@ -65,6 +73,93 @@ export const parseBinaryTarget = async (
|
||||
}
|
||||
};
|
||||
|
||||
const resolveAppBundle = async (
|
||||
path: string,
|
||||
): Promise<Result<string, BinaryTargetError>> => {
|
||||
const metadata = await stat(path);
|
||||
if (!metadata.isDirectory()) return ok(path);
|
||||
if (extname(path).toLowerCase() !== ".app")
|
||||
return err(new BinaryTargetError(path, "target is not an app or file"));
|
||||
const plistPath = join(path, "Contents", "Info.plist");
|
||||
let name: string;
|
||||
try {
|
||||
const plist = await readFile(plistPath);
|
||||
name =
|
||||
plist.subarray(0, 6).toString("ascii") === "bplist"
|
||||
? await readBinaryPlistExecutable(plistPath)
|
||||
: parseXmlPlistExecutable(plist.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!isSafeExecutableName(name))
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has an unsafe CFBundleExecutable"),
|
||||
);
|
||||
const programs = join(path, "Contents", "MacOS");
|
||||
const executable = join(programs, name);
|
||||
try {
|
||||
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
|
||||
realpath(programs),
|
||||
realpath(executable),
|
||||
]);
|
||||
const location = relative(canonicalPrograms, canonicalExecutable);
|
||||
if (
|
||||
location === ".." ||
|
||||
location.startsWith(`..${sep}`) ||
|
||||
isAbsolute(location)
|
||||
)
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file leaves Contents/MacOS"),
|
||||
);
|
||||
return ok(canonicalExecutable);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file is missing", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const parseXmlPlistExecutable = (plist: string): string => {
|
||||
const match =
|
||||
/<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]+)<\/string>/u.exec(
|
||||
plist,
|
||||
);
|
||||
if (match?.[1] === undefined)
|
||||
throw new Error("CFBundleExecutable is missing");
|
||||
return decodeXml(match[1].trim());
|
||||
};
|
||||
|
||||
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
|
||||
(
|
||||
await execFileAsync("/usr/bin/plutil", [
|
||||
"-extract",
|
||||
"CFBundleExecutable",
|
||||
"raw",
|
||||
"-o",
|
||||
"-",
|
||||
plistPath,
|
||||
])
|
||||
).stdout.trim();
|
||||
|
||||
const isSafeExecutableName = (name: string): boolean =>
|
||||
name.length > 0 &&
|
||||
name !== "." &&
|
||||
name !== ".." &&
|
||||
!name.includes("\0") &&
|
||||
!/[/\\]/u.test(name);
|
||||
|
||||
const decodeXml = (value: string): string =>
|
||||
value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll(""", '"')
|
||||
.replaceAll("'", "'");
|
||||
|
||||
type ExecutableMetadata = Pick<
|
||||
BinaryTarget,
|
||||
"format" | "architecture" | "availableArchitectures" | "loaderArgs"
|
||||
|
||||
@@ -61,17 +61,17 @@ export class ConfigurationError extends HopperError {
|
||||
readonly _tag = "ConfigurationError";
|
||||
}
|
||||
|
||||
/** No binary session exists for an analysis request. */
|
||||
/** No app or binary session exists for an analysis request. */
|
||||
export class NoBinaryOpenError extends HopperError {
|
||||
readonly _tag = "NoBinaryOpenError";
|
||||
constructor() {
|
||||
super(
|
||||
"No binary is open. Call open_binary with a readable local path first.",
|
||||
"No app is open. Ask the user which app to investigate, then call open_binary with its local path.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** A supplied target path could not be safely opened as a supported binary. */
|
||||
/** A supplied target path could not be safely opened as a supported app or binary. */
|
||||
export class BinaryTargetError extends HopperError {
|
||||
readonly _tag = "BinaryTargetError";
|
||||
constructor(
|
||||
@@ -79,6 +79,6 @@ export class BinaryTargetError extends HopperError {
|
||||
reason: string,
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Cannot open binary: ${reason}: ${path}`, options);
|
||||
super(`Cannot open app: ${reason}: ${path}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user