feat(android): integrate static APK analysis with headless JADX (#738)

* feat(android): integrate static APK analysis with headless JADX

* test(android): include APK tools in explicit effects audit
This commit is contained in:
N0zoM1z0
2026-10-06 12:46:48 +00:00
committed by GitHub
parent d0f3480a3c
commit 904d03e987
59 changed files with 3342 additions and 52 deletions
+46
View File
@@ -0,0 +1,46 @@
import { constants, createReadStream } from "node:fs";
import { chmod, copyFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join } from "node:path";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AndroidOperation } from "../domain/androidAnalysis.js";
/** Stream a local file digest without retaining the APK or JAR in memory. */
export const hashAndroidFile = async (path: string): Promise<string> => {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
};
/** Bind decompiler input to the admitted artifact, even if the original changes. */
export const snapshotAndroidTarget = async (
path: string,
sha256: string,
root: string,
operation: AndroidOperation,
): Promise<string> => {
const snapshot = join(root, "target.apk");
await copyFile(path, snapshot, constants.COPYFILE_EXCL);
await chmod(snapshot, 0o400);
if ((await hashAndroidFile(snapshot)) !== sha256)
throw new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_value",
message:
"APK bytes changed after admission; retry against a stable file.",
},
]);
return snapshot;
};
/** Fingerprint the actual immutable engine bytes executed for this observation. */
export const snapshotAndroidEngine = async (
source: string,
root: string,
): Promise<{ path: string; sha256: string }> => {
const path = join(root, "engine.jar");
await copyFile(source, path, constants.COPYFILE_EXCL);
await chmod(path, 0o400);
return { path, sha256: await hashAndroidFile(path) };
};
+351
View File
@@ -0,0 +1,351 @@
import type { z } from "zod";
import type { AndroidRequest } from "../domain/androidAnalysis.js";
import { androidResultSchemas } from "../domain/androidAnalysis.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
jadxAppSchema,
jadxClassPageSchema,
jadxClassSchema,
jadxLoadSchema,
jadxMethodSchema,
jadxXrefsSchema,
normalizeJadxText,
} from "./JadxProtocol.js";
/** The adapter consumes tool payloads, never provider RPC details outside this layer. */
export interface JadxToolPort {
json(
name: string,
input: Readonly<Record<string, JsonValue>>,
): Promise<JsonValue>;
text(
name: string,
input: Readonly<Record<string, JsonValue>>,
): Promise<string>;
}
type Engine = z.infer<
typeof androidResultSchemas.inspect_android_package
>["engine"];
type ClassSummary = z.infer<typeof jadxClassSchema>;
const methodsOf = (summary: ClassSummary) => {
const seen = new Map<string, number>();
return summary.methods.map((method) => {
const index = seen.get(method.name) ?? 0;
seen.set(method.name, index + 1);
return {
name: method.name,
reported_signature: method.signature,
overload_index: index,
is_constructor: method.is_constructor,
dex_descriptor: null,
};
});
};
const inputFailure = (
request: AndroidRequest,
field: string,
message: string,
): never => {
throw new AnalysisInputError(request.operation, undefined, [
{ path: [field], reason: "invalid_value", message },
]);
};
const classSummary = async (
tools: JadxToolPort,
request: Exclude<
AndroidRequest,
{ operation: "inspect_android_package" | "search_android_classes" }
>,
): Promise<ClassSummary> => {
const raw = await tools.json("get_class_summary", {
class_name: request.input.class_name,
});
if (
raw !== null &&
typeof raw === "object" &&
!Array.isArray(raw) &&
typeof raw.error === "string"
)
throw new AnalysisOutputError(
request.operation,
`JADX class summary failed: ${raw.error}`,
);
const summary = jadxClassSchema.safeParse(raw);
if (!summary.success)
throw new AnalysisOutputError(
request.operation,
"JADX class summary failed or was malformed; negative counts are not an empty class",
{ cause: summary.error },
);
const value = summary.data;
if (value.full_name !== request.input.class_name)
inputFailure(
request,
"class_name",
`Exact class ${request.input.class_name} resolved to ${value.full_name}; use the fully qualified class name from search_android_classes.`,
);
if (
value.method_count !== value.methods.length ||
value.field_count !== value.fields.length ||
value.inner_class_count !== value.inner_classes.length
)
throw new AnalysisOutputError(
request.operation,
"JADX class member counts do not match the returned inventory",
);
return value;
};
const inspectPackage = async (
tools: JadxToolPort,
loaded: z.infer<typeof jadxLoadSchema>,
engine: Engine,
): Promise<JsonValue> => {
const app = jadxAppSchema.parse(await tools.json("get_app_info", {}));
const manifest = normalizeJadxText(
await tools.text("get_android_manifest", {}),
);
return androidResultSchemas.inspect_android_package.parse({
engine,
package_name: app.package || null,
version_name: app.version_name || null,
version_code: app.version_code || null,
min_sdk: app.min_sdk || null,
target_sdk: app.target_sdk || null,
permissions: app.permissions,
manifest,
class_count: loaded.class_count,
resource_count: loaded.resource_count,
signature_verification: "not_performed",
});
};
const searchClasses = async (
tools: JadxToolPort,
request: Extract<AndroidRequest, { operation: "search_android_classes" }>,
loaded: z.infer<typeof jadxLoadSchema>,
engine: Engine,
): Promise<JsonValue> => {
const classes: string[] = [];
let total: number | undefined;
do {
const page = jadxClassPageSchema.parse(
await tools.json("list_classes", {
offset: classes.length,
limit: 200,
}),
);
if (
(total !== undefined && total !== page.total) ||
page.offset !== classes.length ||
page.limit !== 200 ||
page.items.length > 200
)
throw new AnalysisOutputError(
request.operation,
"JADX class pagination changed identity or counts",
);
total = page.total;
classes.push(...page.items);
if (
classes.length > total ||
(page.items.length === 0 && classes.length < total)
)
throw new AnalysisOutputError(
request.operation,
"JADX class pagination is incomplete",
);
} while (classes.length < total);
if (new Set(classes).size !== classes.length || total !== loaded.class_count)
throw new AnalysisOutputError(
request.operation,
"JADX class inventory is duplicated or differs from the loaded class count",
);
return androidResultSchemas.search_android_classes.parse({
engine,
query: request.input.query,
total_classes: total,
matches: classes.filter((name) => name.includes(request.input.query)),
coverage: "complete",
});
};
const matchingMethods = (
summary: ClassSummary,
request: Extract<
AndroidRequest,
{ operation: "inspect_android_method" | "trace_android_references" }
>,
) => {
const candidates = methodsOf(summary).filter(
(method) => method.name === request.input.method_name,
);
if (request.input.method_name !== undefined && candidates.length === 0)
inputFailure(
request,
"method_name",
`Method ${summary.full_name}.${request.input.method_name} was not found; inspect_android_class lists available methods.`,
);
return candidates;
};
const inspectMethod = async (
tools: JadxToolPort,
request: Extract<AndroidRequest, { operation: "inspect_android_method" }>,
summary: ClassSummary,
engine: Engine,
): Promise<JsonValue> => {
const candidates = matchingMethods(summary, request);
if (candidates.length > 1 && request.input.overload_index === undefined)
inputFailure(
request,
"overload_index",
`Select one of ${candidates.length} overloads: ${candidates.map((method) => `${method.overload_index}: ${method.reported_signature}`).join("; ")}`,
);
const index = request.input.overload_index ?? 0;
const selected = candidates[index];
if (selected === undefined)
inputFailure(
request,
"overload_index",
`Index ${index} is outside the ${candidates.length} matching overloads.`,
);
const body = jadxMethodSchema.parse(
await tools.json("get_method_body", {
class_name: summary.full_name,
method_name: request.input.method_name,
overload_index: index,
smali_fallback: true,
}),
);
if (
body.class_name !== summary.full_name ||
body.method_name !== request.input.method_name ||
body.overload_index !== index ||
body.overload_count !== candidates.length
)
throw new AnalysisOutputError(
request.operation,
"JADX returned a different method or overload inventory",
);
if (body.body.startsWith("// ERROR:"))
throw new AnalysisOutputError(
request.operation,
`JADX did not produce method source: ${body.body}`,
);
if (body.mode === "smali" && candidates.length > 1)
throw new AnalysisCapabilityUnavailableError(
"jadx",
request.operation,
`JADX 0.7.1 smali fallback joins all same-name overloads for ${summary.full_name}.${request.input.method_name}; it cannot establish source for only overload ${index}.`,
);
return androidResultSchemas.inspect_android_method.parse({
engine,
class_name: summary.full_name,
method: selected,
overload_count: candidates.length,
representation: body.mode,
body_status:
body.body.length === 0 ||
body.body ===
"// method exists but has no decompiled body (native/abstract)"
? "not_available"
: "available",
fell_back: body.fell_back,
markers: body.markers,
source: normalizeJadxText(body.body),
});
};
/** Normalize only the selected analyst outcome and reject ambiguous engine selectors. */
export const analyzeJadxRequest = async (
tools: JadxToolPort,
request: AndroidRequest,
loaded: z.infer<typeof jadxLoadSchema>,
engine: Engine,
): Promise<JsonValue> => {
if (request.operation === "inspect_android_package")
return inspectPackage(tools, loaded, engine);
if (request.operation === "search_android_classes")
return searchClasses(tools, request, loaded, engine);
const summary = await classSummary(tools, request);
if (request.operation === "inspect_android_class")
return androidResultSchemas.inspect_android_class.parse({
engine,
class_name: summary.full_name,
methods: methodsOf(summary),
fields: summary.fields.map((field) => ({
name: field.name,
reported_type: field.type,
})),
inner_classes: summary.inner_classes,
});
if (request.operation === "inspect_android_method")
return inspectMethod(tools, request, summary, engine);
return traceReferences(tools, request, summary, engine);
};
const traceReferences = async (
tools: JadxToolPort,
request: Extract<AndroidRequest, { operation: "trace_android_references" }>,
summary: ClassSummary,
engine: Engine,
): Promise<JsonValue> => {
const methodName = request.input.method_name;
const candidates = matchingMethods(summary, request);
if (candidates.length > 1)
throw new AnalysisCapabilityUnavailableError(
"jadx",
request.operation,
`JADX 0.7.1 references select the first same-name method; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
);
const expectedTarget =
methodName === undefined
? summary.full_name
: `${summary.full_name}.${methodName}`;
const xrefs = jadxXrefsSchema.parse(
await tools.json(
methodName === undefined ? "get_xrefs_to_class" : "get_xrefs_to_method",
{
class_name: summary.full_name,
...(methodName === undefined ? {} : { method_name: methodName }),
limit: 2_147_483_647,
resolve_line: false,
},
),
);
if (
xrefs.target !== expectedTarget ||
xrefs.total !== xrefs.count ||
xrefs.count !== xrefs.items.length
)
throw new AnalysisOutputError(
request.operation,
"JADX references are incomplete or refer to another target",
);
return androidResultSchemas.trace_android_references.parse({
engine,
class_name: summary.full_name,
method_name: methodName ?? null,
total: xrefs.total,
references: xrefs.items.map((reference) => ({
kind: reference.kind,
name: reference.name,
reported_full_name: reference.full_name,
containing_class: reference.containing_class,
top_class: reference.top_class,
source_line: null,
dex_offset: null,
})),
coverage: "complete",
});
};
+50
View File
@@ -0,0 +1,50 @@
import { access, realpath, stat } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { AndroidOperation } from "../domain/androidAnalysis.js";
/** Caller-supplied tools, resolved only when an Android operation is selected. */
export interface JadxConfiguration {
readonly jar: string;
readonly java: string;
}
/** Admit explicit local tooling without installing or changing host configuration. */
export const resolveJadxConfiguration = async (
environment: Readonly<Record<string, string | undefined>>,
operation: AndroidOperation,
): Promise<JadxConfiguration> => {
const unavailable = (reason: string) =>
new AnalysisCapabilityUnavailableError("jadx", operation, reason);
if (process.platform !== "linux" && process.platform !== "darwin")
throw unavailable(
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. Only Linux has real-provider verification.`,
);
const jar = environment.REA_JADX_MCP_JAR;
if (environment.JAVA_HOME !== undefined && !isAbsolute(environment.JAVA_HOME))
throw unavailable(
"JAVA_HOME must select an existing JDK by absolute path; omit it to use java on PATH.",
);
if (jar === undefined || !isAbsolute(jar))
throw unavailable(
"Set REA_JADX_MCP_JAR to the absolute path of a caller-supplied jadx-headless-mcp 0.7.1 JAR. REA does not download or install it.",
);
try {
await access(jar, constants.R_OK);
if (!(await stat(jar)).isFile())
throw unavailable(`REA_JADX_MCP_JAR is not a regular file: ${jar}`);
return {
jar: await realpath(jar),
java:
environment.JAVA_HOME === undefined
? "java"
: join(environment.JAVA_HOME, "bin", "java"),
};
} catch (cause) {
if (cause instanceof AnalysisCapabilityUnavailableError) throw cause;
throw unavailable(
`Cannot read REA_JADX_MCP_JAR ${jar}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
};
+183
View File
@@ -0,0 +1,183 @@
import {
deserializeMessage,
serializeMessage,
type JSONRPCMessage,
type Transport,
} from "@modelcontextprotocol/client";
import { randomUUID } from "node:crypto";
import type {
OwnedProviderProcessSpawnOptions,
SpawnedOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
const MAX_SESSION_BYTES = 32 * 1024 * 1024;
/** Injectable process acquisition seam; the production launcher owns a POSIX group. */
export type JadxLauncher = (
options: OwnedProviderProcessSpawnOptions,
) => Promise<SpawnedOwnedProviderProcess>;
/** SDK-framed stdio with REA-owned process cleanup rather than an unowned child. */
export class JadxMcpTransport implements Transport {
onclose: Transport["onclose"];
onerror: Transport["onerror"];
onmessage: Transport["onmessage"];
readonly runId = randomUUID();
#spawned: SpawnedOwnedProviderProcess | undefined;
#supervisor: ProviderProcessSupervisor | undefined;
#buffer = Buffer.alloc(0);
#bytes = 0;
#started = false;
#closed = false;
#closePromise: Promise<void> | undefined;
#starting: Promise<void> | undefined;
#failure: string | null = null;
constructor(
readonly options: Omit<OwnedProviderProcessSpawnOptions, "runId" | "stdin">,
readonly launcher: JadxLauncher = spawnOwnedProviderProcess,
) {}
/** Acquires exactly one protocol process after the SDK installs callbacks. */
start(): Promise<void> {
if (this.#started || this.#closed)
throw new Error("JADX transport cannot be restarted");
this.#started = true;
this.#starting = this.#acquire();
return this.#starting;
}
async #acquire(): Promise<void> {
const spawned = await this.launcher({
...this.options,
runId: this.runId,
stdin: "pipe",
});
this.#spawned = spawned;
this.#supervisor = new ProviderProcessSupervisor({
...spawned,
ownsProcessLifetime: true,
cleanup:
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
});
if (
spawned.process.stdin === undefined ||
spawned.process.stdin === null ||
spawned.process.stdout === null
)
throw new Error("JADX launcher did not supply protocol stdin/stdout");
spawned.process.stdout.on("data", this.#read);
spawned.process.stderr?.on("data", this.#countStderr);
spawned.process.on("error", this.#error);
spawned.process.once("exit", this.#exit);
spawned.process.stdin.on("error", this.#error);
if (this.#closed) throw new Error("JADX transport closed during startup");
}
/** Writes SDK-serialized messages and observes stream backpressure. */
async send(message: JSONRPCMessage): Promise<void> {
const input = this.#spawned?.process.stdin;
if (this.#closed || input === undefined || input === null)
throw new Error("JADX protocol process is not writable");
await new Promise<void>((resolve, reject) => {
input.write(serializeMessage(message), (cause) =>
cause === null || cause === undefined ? resolve() : reject(cause),
);
});
}
/** Verifies owned process exit before declaring the transport closed. */
close(): Promise<void> {
this.#closePromise ??= this.#stop();
return this.#closePromise;
}
/** Captured provider stderr without persisting inherited environment values. */
diagnostics(): string {
return this.#supervisor?.snapshot().stderr.text ?? "";
}
/** Preserve the failed protocol/resource constraint after the SDK closes requests. */
failureReason(): string | null {
return this.#failure;
}
async #stop(): Promise<void> {
this.#closed = true;
// A cancellation may race acquisition. Join it before inspecting ownership.
await this.#starting?.catch(() => undefined);
const process = this.#spawned?.process;
process?.stdout?.off("data", this.#read);
process?.stderr?.off("data", this.#countStderr);
process?.off("error", this.#error);
process?.off("exit", this.#exit);
process?.stdin?.off("error", this.#error);
const stopped = await this.#supervisor?.stop();
this.onclose?.();
if (stopped?.status === "incomplete")
throw new ProviderCleanupError("jadx", [this.runId], {
reason: stopped.reason,
stderr: this.diagnostics(),
});
}
readonly #error = (error: Error): void => {
this.onerror?.(error);
};
readonly #exit = (): void => {
this.onclose?.();
};
readonly #countStderr = (chunk: Buffer | string): void => {
this.#bytes += Buffer.byteLength(chunk);
if (this.#bytes > MAX_SESSION_BYTES)
this.#fail(
new Error(
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
),
);
};
readonly #read = (chunk: Buffer | string): void => {
if (this.#closed) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
this.#bytes += bytes.length;
if (this.#bytes > MAX_SESSION_BYTES) {
this.#fail(
new Error(
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
),
);
return;
}
this.#buffer = Buffer.concat([this.#buffer, bytes]);
try {
let newline: number;
while ((newline = this.#buffer.indexOf(10)) !== -1) {
if (newline > MAX_FRAME_BYTES)
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
const line = this.#buffer.subarray(0, newline).toString("utf8");
this.#buffer = this.#buffer.subarray(newline + 1);
this.onmessage?.(deserializeMessage(line));
}
if (this.#buffer.length > MAX_FRAME_BYTES)
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
} catch (cause) {
this.#fail(cause instanceof Error ? cause : new Error(String(cause)));
}
};
#fail(error: Error): void {
this.#failure ??= error.message;
this.onerror?.(error);
// Closing immediately rejects the SDK's outstanding request. The owner
// awaits close again and retains a cleanup failure in the returned Result.
void this.close().catch((cause: unknown) =>
this.onerror?.(cause instanceof Error ? cause : new Error(String(cause))),
);
}
}
+134
View File
@@ -0,0 +1,134 @@
import { z } from "zod";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { AndroidOperation } from "../domain/androidAnalysis.js";
const count = z.number().int().nonnegative();
export const jadxLoadSchema = z.object({
state: z.literal("LOADED"),
apk_path: z.string(),
class_count: count,
resource_count: count,
threads: z.literal(1),
resources: z.literal("full"),
});
export const jadxAppSchema = z.object({
package: z.string(),
version_name: z.string(),
version_code: z.string(),
min_sdk: z.string(),
target_sdk: z.string(),
permissions: z.array(z.string()),
});
export const jadxClassPageSchema = z.object({
total: count,
offset: count,
limit: count,
items: z.array(z.string()),
});
export const jadxClassSchema = z.object({
full_name: z.string(),
name: z.string(),
method_count: count,
field_count: count,
inner_class_count: count,
methods: z.array(
z.object({
name: z.string(),
signature: z.string(),
is_constructor: z.boolean(),
def_pos: z.number().int(),
}),
),
fields: z.array(
z.object({ name: z.string(), type: z.string(), def_pos: z.number().int() }),
),
inner_classes: z.array(z.string()),
});
export const jadxMethodSchema = z.object({
class_name: z.string(),
method_name: z.string(),
full_name: z.string(),
overload_index: count,
overload_count: count,
mode: z.enum(["java", "smali"]),
fell_back: z.boolean(),
markers: z.array(z.string()),
body: z.string(),
});
export const jadxXrefsSchema = z.object({
target: z.string(),
total: count,
count,
resolve_line: z.literal(false),
items: z.array(
z.object({
kind: z.string(),
name: z.string(),
full_name: z.string(),
containing_class: z.string(),
top_class: z.string(),
def_pos: z.number().int(),
}),
),
});
const toolResponse = z.object({
content: z
.array(z.object({ type: z.literal("text"), text: z.string() }))
.length(1),
isError: z.boolean().optional(),
});
/** Parse the upstream text-only envelope, preserving errors at the producing boundary. */
export const parseJadxEnvelope = (
response: unknown,
operation: AndroidOperation,
): { text: string; failed: boolean } => {
const parsed = toolResponse.safeParse(response);
if (!parsed.success || parsed.data.content[0] === undefined)
throw new AnalysisOutputError(
operation,
"JADX returned an unsupported MCP content envelope",
);
return {
text: parsed.data.content[0].text,
failed: parsed.data.isError === true,
};
};
/** Decode an upstream JSON text payload without trusting its contents. */
export const parseJadxJson = (
text: string,
operation: AndroidOperation,
): z.infer<typeof jsonValueSchema> => {
try {
return jsonValueSchema.parse(JSON.parse(text));
} catch (cause) {
throw new AnalysisOutputError(
operation,
"JADX returned malformed JSON text",
{ cause },
);
}
};
/** Upstream byte truncation is reported rather than promoted to a complete source. */
export const normalizeJadxText = (
text: string,
): {
status: "complete" | "partial";
text: string;
reported_total_bytes: number | null;
} => {
const marker =
/\n\n\.\.\. \[truncated: exceeds (\d+) bytes, total (\d+) bytes\]$/u.exec(
text,
);
const total = marker?.[2] === undefined ? null : Number(marker[2]);
return {
status: marker === null ? "complete" : "partial",
text,
reported_total_bytes:
total !== null && Number.isSafeInteger(total) ? total : null,
};
};
+245
View File
@@ -0,0 +1,245 @@
import { z } from "zod";
import type { AndroidAnalysisPort } from "../application/AndroidAnalysisPort.js";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { AndroidRequest } from "../domain/androidAnalysis.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { err, ok } from "../domain/result.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import {
snapshotAndroidEngine,
snapshotAndroidTarget,
} from "./AndroidTargetSnapshot.js";
import { resolveJadxConfiguration } from "./JadxConfiguration.js";
import type { JadxLauncher } from "./JadxMcpTransport.js";
import { JadxSession } from "./JadxSession.js";
const OPERATION_TIMEOUT_MS = 120_000;
type Outcome = Awaited<ReturnType<AndroidAnalysisPort["execute"]>>;
const waitForTurn = (
predecessor: Promise<void>,
request: AndroidRequest,
signal?: AbortSignal,
): Promise<void> =>
new Promise((resolve, reject) => {
const abort = () => reject(new AnalysisCancelledError(request.operation));
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted === true) abort();
void predecessor.then(() => {
signal?.removeEventListener("abort", abort);
resolve();
});
});
const executionError = (context: {
cause: unknown;
request: AndroidRequest;
timeout: AbortSignal;
signal: AbortSignal | undefined;
session: JadxSession | undefined;
}): AnalysisError => {
const { cause, request, timeout, signal, session } = context;
if (signal?.aborted === true)
return new AnalysisCancelledError(request.operation);
if (timeout.aborted)
return new AnalysisTimeoutError(request.operation, OPERATION_TIMEOUT_MS);
if (cause instanceof AnalysisError) return cause;
const protocolFailure = session?.transport.failureReason();
if (protocolFailure !== undefined && protocolFailure !== null)
return new AnalysisOutputError(request.operation, protocolFailure, {
cause,
});
if (cause instanceof z.ZodError)
return new AnalysisOutputError(
request.operation,
"JADX response violated the pinned upstream protocol",
{ cause },
);
return new ProviderAdapterError("jadx", request.operation, {
cause,
diagnostics: {
reason: cause instanceof Error ? cause.message : String(cause),
stderr: session?.transport.diagnostics() ?? "",
},
});
};
const cleanup = async (
session: JadxSession | undefined,
root: PrivateRuntimeRoot | undefined,
previous: Outcome,
): Promise<Outcome> => {
const diagnostics = {
previous_error: previous.ok
? null
: { tag: previous.error._tag, message: previous.error.message },
};
try {
await session?.close();
} catch (cause) {
// Retain an uncertain workspace until the caller can resolve process ownership.
return err(
new ProviderCleanupError(
"jadx",
[
session?.transport.runId ?? "unknown",
...(root === undefined ? [] : [root.path]),
],
{
...diagnostics,
reason: cause instanceof Error ? cause.message : String(cause),
provider_cleanup:
cause instanceof ProviderCleanupError
? (cause.diagnostics ?? null)
: null,
},
{ cause },
),
);
}
try {
await root?.close();
} catch (cause) {
return err(
new ProviderCleanupError(
"jadx",
[root?.path ?? "unknown"],
{
...diagnostics,
reason: cause instanceof Error ? cause.message : String(cause),
},
{ cause },
),
);
}
return previous;
};
/** One queued engine per REA instance, with a fresh owned workspace for every request. */
export class JadxProvider implements AndroidAnalysisPort {
#tail: Promise<void> = Promise.resolve();
#cleanupFailure: AnalysisError | undefined;
constructor(
readonly environment: Readonly<
Record<string, string | undefined>
> = process.env,
readonly launcher?: JadxLauncher,
) {}
/** Serialize expensive work and bind both raw and normalized results to the APK. */
async execute(
target: BinaryTarget,
request: AndroidRequest,
options?: ExecutionOptions,
): Promise<Outcome> {
const predecessor = this.#tail;
let release: () => void = () => {};
this.#tail = new Promise<void>((resolve) => {
release = resolve;
});
try {
await waitForTurn(predecessor, request, options?.signal);
} catch {
void predecessor.then(release);
return err(new AnalysisCancelledError(request.operation));
}
try {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(request.operation));
if (this.#cleanupFailure !== undefined) return err(this.#cleanupFailure);
const outcome = await this.#execute(target, request, options);
if (!outcome.ok && outcome.error.cleanupIncomplete)
this.#cleanupFailure = outcome.error;
return outcome;
} finally {
release();
}
}
async #execute(
target: BinaryTarget,
request: AndroidRequest,
options?: ExecutionOptions,
): Promise<Outcome> {
const timeout = AbortSignal.timeout(OPERATION_TIMEOUT_MS);
const signal =
options?.signal === undefined
? timeout
: AbortSignal.any([options.signal, timeout]);
let root: PrivateRuntimeRoot | undefined;
let session: JadxSession | undefined;
let outcome: Outcome;
try {
if (target.format !== "apk")
throw new AnalysisCapabilityUnavailableError(
"jadx",
request.operation,
`Target ${target.path} is ${target.format}; provide one standalone APK.`,
);
const configuration = await resolveJadxConfiguration(
this.environment,
request.operation,
);
signal.throwIfAborted();
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
const engine = await snapshotAndroidEngine(configuration.jar, root.path);
const snapshot = await snapshotAndroidTarget(
target.path,
target.sha256,
root.path,
request.operation,
);
signal.throwIfAborted();
session = new JadxSession(
{
command: configuration.java,
arguments: [
"-Xmx512m",
"-XX:ActiveProcessorCount=1",
"-jar",
engine.path,
"--threads",
"1",
"--max-source-bytes",
"1048576",
"--decompile-timeout-ms",
"90000",
],
cwd: root.path,
hostEnvironment: this.environment,
env: { _JAVA_OPTIONS: "-Xmx512m -XX:ActiveProcessorCount=1" },
},
this.launcher,
);
outcome = ok(
await session.execute({
request,
target,
snapshot,
jarHash: engine.sha256,
signal,
}),
);
} catch (cause) {
outcome = err(
executionError({
cause,
request,
timeout,
signal: options?.signal,
session,
}),
);
}
return cleanup(session, root, outcome);
}
}
+21
View File
@@ -0,0 +1,21 @@
/** Audited upstream release; source remains unmodified in the Git submodule. */
export const JADX_RELEASE = Object.freeze({
version: "0.7.1",
revision: "5844800a486d2248fa949b74c9896285f5b54de2",
sha256: "6e5eacf500b64292bfb73c49797c1958f6ee44646e43e868039ae7feb573ff75",
url: "https://github.com/1013503897/jadx-headless-mcp/releases/download/v0.7.1/jadx-headless-mcp-0.7.1-all.jar",
});
/** Producing engine identity used by Evidence and the generated product catalog. */
export const JADX_PROVIDER_IDENTITY = Object.freeze({
id: "jadx",
name: "JADX headless",
version: JADX_RELEASE.version,
});
/** Audited engine coverage, kept outside portable Android semantics. */
export const JADX_LIMITATIONS = [
"Static decompiler observations do not establish runtime behavior; the APK is never executed.",
"Method signatures use provider display types; exact DEX descriptors and instruction offsets are unavailable. Overload indices are local to this engine and artifact.",
"Manifest summary fields are extracted by the upstream engine; decoded XML is retained for verification. APK signatures, split APKs, native libraries and Android runtime capture are not verified by this provider.",
] as const;
+150
View File
@@ -0,0 +1,150 @@
import { Client } from "@modelcontextprotocol/client";
import {
createAnalysisExecution,
type AnalysisExecution,
} from "../application/AnalysisProvider.js";
import type { AndroidRequest } from "../domain/androidAnalysis.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import type { OwnedProviderProcessSpawnOptions } from "../process/ProviderProcess.js";
import { analyzeJadxRequest, type JadxToolPort } from "./JadxAnalysis.js";
import { JadxMcpTransport, type JadxLauncher } from "./JadxMcpTransport.js";
import {
jadxLoadSchema,
parseJadxEnvelope,
parseJadxJson,
} from "./JadxProtocol.js";
import {
JADX_RELEASE,
JADX_PROVIDER_IDENTITY,
JADX_LIMITATIONS,
} from "./JadxRelease.js";
/** One owned engine connection; its wire protocol stays inside the Android adapter. */
export class JadxSession {
readonly transport: JadxMcpTransport;
readonly #client = new Client({ name: "rea-android-adapter", version: "1" });
readonly #raw: JsonValue[] = [];
constructor(
options: Omit<OwnedProviderProcessSpawnOptions, "runId" | "stdin">,
launcher?: JadxLauncher,
) {
this.transport = new JadxMcpTransport(options, launcher);
}
/** Analyze one admitted immutable APK, checking producer identity and selectors. */
async execute(context: {
readonly request: AndroidRequest;
readonly target: BinaryTarget;
readonly snapshot: string;
readonly jarHash: string;
readonly signal: AbortSignal;
}): Promise<AnalysisExecution> {
const { request, target, snapshot, jarHash, signal } = context;
const abort = () => {
void this.transport.close().catch(() => undefined);
};
signal.addEventListener("abort", abort, { once: true });
try {
signal.throwIfAborted();
await this.#client.connect(this.transport, { timeout: 30_000 });
const server = this.#client.getServerVersion();
if (
server?.name !== "jadx-headless-mcp" ||
server.version !== JADX_RELEASE.version
)
throw new AnalysisCapabilityUnavailableError(
"jadx",
request.operation,
`Expected jadx-headless-mcp ${JADX_RELEASE.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
);
const tools = this.#tools(request, target, signal);
const loaded = jadxLoadSchema.parse(
await tools.json("load_apk", {
path: snapshot,
threads: 1,
resources: "full",
}),
);
if (loaded.apk_path !== snapshot)
throw new AnalysisOutputError(
request.operation,
"JADX loaded a different APK path than the admitted snapshot",
);
const engine = {
name: "jadx-headless-mcp",
version: "0.7.1",
artifact_sha256: jarHash,
source_revision:
jarHash === JADX_RELEASE.sha256 ? JADX_RELEASE.revision : null,
worker_count: 1,
heap_limit_mib: 512,
} as const;
const result = await analyzeJadxRequest(tools, request, loaded, engine);
return createAnalysisExecution(result, JADX_PROVIDER_IDENTITY, {
rawResult: { server, jar_sha256: jarHash, calls: this.#raw },
subject: target,
limitations: JADX_LIMITATIONS,
locations:
request.operation === "inspect_android_package"
? [{ kind: "artifact-path", path: "AndroidManifest.xml" }]
: [],
});
} finally {
signal.removeEventListener("abort", abort);
}
}
/** Join owned cleanup even if SDK connection teardown itself fails. */
async close(): Promise<void> {
try {
await this.#client.close();
} finally {
await this.transport.close();
}
}
#tools(
request: AndroidRequest,
target: BinaryTarget,
signal: AbortSignal,
): JadxToolPort {
const call = async (
name: string,
input: Readonly<Record<string, JsonValue>>,
): Promise<string> => {
signal.throwIfAborted();
const response = await this.#client.callTool(
{ name, arguments: input },
{ timeout: 120_000, signal },
);
const envelope = parseJadxEnvelope(response, request.operation);
this.#raw.push({
operation: name,
input,
response: jsonValueSchema.parse(response),
});
if (envelope.failed)
throw new ProviderAdapterError("jadx", request.operation, {
diagnostics: {
upstream_operation: name,
reason: envelope.text,
target_path: target.path,
target_sha256: target.sha256,
},
});
return envelope.text;
};
return {
text: call,
json: async (name, input) =>
parseJadxJson(await call(name, input), request.operation),
};
}
}