Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
import { createHash } from "node:crypto";
import { lstat } from "node:fs/promises";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import {
ArtifactReaderFailure,
sameArtifactSourceIdentity,
} from "../ArtifactReader.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
appleResourceKeyFields,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../../domain/apple/appleAssetCatalog.js";
import {
ExecFileOutputCancelledError,
execFileOutput,
} from "../../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
/** The command owner wraps the exact caller reason; do not replace it with the wrapper. */
const cancellationCause = (cause: unknown, signal?: AbortSignal): unknown =>
cause instanceof ExecFileOutputCancelledError ? cause.cause : signal?.reason;
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly targetSha256: string | null;
readonly resourceRoot?: import("../../domain/apple/bundleResourceRoot.js").BundleResourceRoot;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly page?: unknown;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
readonly analyzeInterfaceBuilder?: typeof analyzeInterfaceBuilderBundle;
}) => {
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Apple asset catalog inspection requires macOS assetutil",
);
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
// The Interface Builder graph only supplies resource keys for the join. Its
// bundle walk is independent of the catalog walk, so both run together; a
// catalog failure cancels it and is reported as the sequential order would.
const interfaceBuilderCancel = new AbortController();
const interfaceBuilderAnalysis = (
input.analyzeInterfaceBuilder ?? analyzeInterfaceBuilderBundle
)({
bundlePath: input.bundlePath,
targetSha256: input.targetSha256,
...(input.resourceRoot === undefined
? {}
: { resourceRoot: input.resourceRoot }),
signal:
input.signal === undefined
? interfaceBuilderCancel.signal
: AbortSignal.any([input.signal, interfaceBuilderCancel.signal]),
}).then(
(value) => ({ ok: true, value }) as const,
(error: unknown) => ({ ok: false, error }) as const,
);
let catalogs: Awaited<ReturnType<typeof collectAssetCatalogs>>["catalogs"];
let uninspected: readonly string[];
try {
({ catalogs, uninspected } = await collectAssetCatalogs(input));
} catch (cause: unknown) {
interfaceBuilderCancel.abort();
await interfaceBuilderAnalysis;
throw cause;
}
const analyzed = await interfaceBuilderAnalysis;
if (!analyzed.ok) throw analyzed.error;
const interfaceBuilder = analyzed.value;
const resourceReferences = collectInterfaceBuilderResourceKeys(
interfaceBuilder.graph.nodes,
);
const result = projectAppleAssetCatalogPage({
targetSha256: input.targetSha256,
...(input.resourceRoot === undefined
? {}
: { resourceRoot: input.resourceRoot }),
catalogs,
offset: page.offset,
limit: page.limit,
resourceReferences,
});
return {
...result,
limitations: [
...result.limitations,
// An app without a compiled catalog is an observed empty inventory, not
// a missing host tool.
...(catalogs.length === 0
? [
"No compiled Assets.car catalog was found among the app bundle's regular files (symlinks are not followed); any resource keys are reported as unmatched.",
]
: []),
...(uninspected.length === 0
? []
: [
`Asset catalog entries that are not regular files were not inspected, so resource keys reported as unmatched may resolve there: ${uninspected.join(", ")}`,
]),
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
...(interfaceBuilder.graph.truncated
? [
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
]
: []),
],
};
};
/** Inspect every regular Assets.car in the bundle; non-file entries are listed. */
const collectAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
}) => {
const reader = new DirectoryArtifactReader(input.bundlePath);
const catalogs: {
path: string;
sha256: string;
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
}[] = [];
const uninspected: string[] = [];
let totalMetadataBytes = 0;
try {
for await (const entry of reader.entries(input.signal)) {
// Reader paths are `/`-separated; only an entry named exactly
// Assets.car is a compiled catalog, not e.g. NotAssets.car.
if (entry.path.split("/").at(-1) !== "Assets.car") continue;
if (entry.kind !== "file") {
uninspected.push(`${entry.path} (${entry.kind})`);
continue;
}
const inspected = await inspectAssetCatalogEntry({
reader,
entry,
runAssetUtil:
input.runAssetUtil ??
((path, signal) => runAssetUtil(path, input.environment, signal)),
...(input.signal === undefined ? {} : { signal: input.signal }),
});
totalMetadataBytes += inspected.metadataBytes;
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
);
catalogs.push(inspected.catalog);
}
} finally {
await reader.close();
}
// Without any readable catalog, unmatched resource keys would overstate an
// absence that a skipped catalog entry may contradict.
if (catalogs.length === 0 && uninspected.length > 0)
throw new ArtifactReaderFailure(
"path",
`Asset catalog entries are not regular files and were not inspected: ${uninspected.join(", ")}`,
);
return { catalogs, uninspected };
};
const inspectAssetCatalogEntry = async (input: {
readonly reader: DirectoryArtifactReader;
readonly entry: import("../ArtifactReader.js").ArtifactEntry;
readonly runAssetUtil: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
readonly signal?: AbortSignal;
}) => {
const { entry, reader, signal } = input;
const sha256 = await digestBounded(reader, entry, signal);
const before = await lstat(entry.adapterKey, { bigint: true });
if (
!before.isFile() ||
!sameArtifactSourceIdentity(entry.sourceIdentity, before)
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed before inspection: ${entry.path}`,
);
const output = await input.runAssetUtil(entry.adapterKey, signal);
const after = await lstat(entry.adapterKey, { bigint: true });
if (
!after.isFile() ||
!sameArtifactSourceIdentity(entry.sourceIdentity, after) ||
(await digestBounded(reader, entry, signal)) !== sha256
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed during inspection: ${entry.path}`,
);
let parsed: unknown;
try {
parsed = JSON.parse(output);
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned invalid JSON for ${entry.path}`,
{ cause },
);
}
try {
return {
catalog: {
path: entry.path,
sha256,
records: parseAppleAssetCatalogRecords(parsed),
},
metadataBytes: Buffer.byteLength(output, "utf8"),
};
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned an unsupported record for ${entry.path}`,
{ cause },
);
}
};
/** Return only explicit image or asset fields from decoded resource objects. */
export const collectInterfaceBuilderResourceKeys = (
nodes: readonly {
readonly id: string;
readonly kind: string;
readonly name?: string;
readonly attributes: Readonly<Record<string, unknown>>;
readonly evidence: readonly {
readonly artifact_path: string | null;
readonly artifact_sha256: string | null;
}[];
}[],
) =>
nodes.flatMap((node) => {
if (node.kind !== "resource") return [];
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return appleResourceKeyFields(node.attributes).flatMap(([field, value]) => [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]);
});
const runAssetUtil = async (
path: string,
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
): Promise<string> => {
try {
return (
await execFileOutput(ASSETUTIL, ["--info", path], {
env: environment,
timeout: 60_000,
maxBuffer: MAX_CATALOG_BYTES,
stopSignal: "SIGTERM",
...(signal === undefined ? {} : { signal }),
})
).stdout;
} catch (cause: unknown) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
{ cause: cancellationCause(cause, signal) },
);
const code =
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
throw new ArtifactReaderFailure(
code === "ENOENT"
? "unavailable"
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
? "limit"
: "io",
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
{ cause },
);
}
};
const digestBounded = async (
reader: DirectoryArtifactReader,
entry: import("../ArtifactReader.js").ArtifactEntry,
signal?: AbortSignal,
): Promise<string> => {
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
);
const stream = await reader.open(entry, signal);
const hash = createHash("sha256");
let length = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
{ cause: signal.reason },
);
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
length += bytes.length;
if (length > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds byte limit: ${entry.path}`,
);
hash.update(bytes);
}
return hash.digest("hex");
};