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:
@@ -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) };
|
||||
};
|
||||
@@ -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",
|
||||
});
|
||||
};
|
||||
@@ -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)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -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))),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { AndroidRequest } from "../domain/androidAnalysis.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** Static Android inspection boundary; implementation details belong to the provider. */
|
||||
export interface AndroidAnalysisPort {
|
||||
execute(
|
||||
target: BinaryTarget,
|
||||
request: AndroidRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { AndroidAnalysisPort } from "./AndroidAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import {
|
||||
androidRequestSchema,
|
||||
type AndroidOperation,
|
||||
} from "../domain/androidAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP admission, execution and Evidence composition for Android. */
|
||||
export class AndroidAnalysisService {
|
||||
constructor(readonly provider: AndroidAnalysisPort) {}
|
||||
|
||||
/** Inspect a caller-selected APK and retain producing-provider provenance inline. */
|
||||
async execute(
|
||||
operation: AndroidOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const request = androidRequestSchema.safeParse({ operation, input });
|
||||
if (!request.success)
|
||||
return err(new AnalysisInputError(operation, { cause: request.error }));
|
||||
const target = await parseBinaryTarget(request.data.input.path);
|
||||
if (!target.ok) return target;
|
||||
const executed = await this.provider.execute(
|
||||
target.value,
|
||||
request.data,
|
||||
options,
|
||||
);
|
||||
if (!executed.ok) return executed;
|
||||
const execution = executed.value;
|
||||
return ok(
|
||||
createEvidence(execution.subject ?? target.value, execution.provider, {
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(request.data.input),
|
||||
result: execution.result,
|
||||
rawResult: execution.rawResult,
|
||||
limitations: execution.limitations,
|
||||
locations: execution.locations,
|
||||
confidence:
|
||||
operation === "inspect_android_method" ? "derived" : "observed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,27 @@ const entry = (
|
||||
};
|
||||
|
||||
describe("capability inventory: provider status", () => {
|
||||
it("keeps Android APK operations target-free and reports their explicit engine prerequisite", () => {
|
||||
expect(
|
||||
entry("inspect_android_package", status(), {
|
||||
processCaptureEnabled: true,
|
||||
androidAnalysisEnabled: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
available: true,
|
||||
surface: "android-provider",
|
||||
reason: "available",
|
||||
});
|
||||
expect(
|
||||
entry("inspect_android_package", status(), {
|
||||
processCaptureEnabled: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
remediation: expect.stringContaining("REA_JADX_MCP_JAR"),
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
{
|
||||
label: "requires a target",
|
||||
|
||||
@@ -28,6 +28,7 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly androidAnalysisEnabled?: boolean;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly browserScenarioEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
@@ -205,6 +206,14 @@ const workflowAvailabilityFor = ({
|
||||
kind,
|
||||
policy,
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
if (kind === "android-provider")
|
||||
return policy.androidAnalysisEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide Java on Linux or macOS. Only Linux has real-provider verification.",
|
||||
};
|
||||
const browser = browserProviderAvailability(name, kind, policy);
|
||||
if (browser !== null) return browser;
|
||||
if (name === "capture_process_scenario" && !policy.processCaptureEnabled)
|
||||
|
||||
@@ -7,6 +7,7 @@ import { registerCoreAnalysisCommands } from "./cli/coreAnalysisCommands.js";
|
||||
import { registerUtilityCommands } from "./cli/utilityCommands.js";
|
||||
import { registerArtifactCommands } from "./cli/artifactCommands.js";
|
||||
import { registerManagedCommands } from "./cli/managedCommands.js";
|
||||
import { registerAndroidCommands } from "./cli/androidCommands.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cli/processCommands.js";
|
||||
import { registerBrowserCommands } from "./cli/browserCommands.js";
|
||||
@@ -47,6 +48,7 @@ export const createCli = (
|
||||
registerUtilityCommands(cli, logger, environment);
|
||||
registerArtifactCommands(cli, logger);
|
||||
registerManagedCommands(cli, logger);
|
||||
registerAndroidCommands(cli, logger, environment);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerProcessCommands(cli, logger, environment);
|
||||
registerBrowserCommands(cli, logger);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { z } from "incur";
|
||||
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
|
||||
import { JadxProvider } from "../android/JadxProvider.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { AndroidOperation } from "../domain/androidAnalysis.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Expose the same explicit APK requests through one-shot CLI commands. */
|
||||
export const registerAndroidCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): void => {
|
||||
const service = new AndroidAnalysisService(new JadxProvider(environment));
|
||||
const execute = (name: string, operation: AndroidOperation, input: unknown) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, name, async () => {
|
||||
const result = await service.execute(operation, input, { signal });
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
);
|
||||
const path = z.string().describe("Local standalone APK path");
|
||||
const className = z.string().describe("Exact fully qualified class name");
|
||||
cli.command(CLI_COMMANDS.inspectAndroidPackage, {
|
||||
description:
|
||||
"Inspect APK declarations and decoded manifest without executing it",
|
||||
args: z.object({ path }),
|
||||
run: ({ args }) =>
|
||||
execute(
|
||||
CLI_COMMANDS.inspectAndroidPackage,
|
||||
"inspect_android_package",
|
||||
args,
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.searchAndroidClasses, {
|
||||
description: "Search APK class names; empty query inventories all classes",
|
||||
args: z.object({
|
||||
path,
|
||||
query: z
|
||||
.string()
|
||||
.describe(
|
||||
"Case-sensitive class-name substring; empty lists all classes",
|
||||
),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
execute(
|
||||
CLI_COMMANDS.searchAndroidClasses,
|
||||
"search_android_classes",
|
||||
args,
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectAndroidClass, {
|
||||
description: "Inspect one exact APK class's member inventory",
|
||||
args: z.object({ path, className }),
|
||||
run: ({ args }) =>
|
||||
execute(CLI_COMMANDS.inspectAndroidClass, "inspect_android_class", {
|
||||
path: args.path,
|
||||
class_name: args.className,
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectAndroidMethod, {
|
||||
description: "Decompile one APK method with explicit overload selection",
|
||||
args: z.object({
|
||||
path,
|
||||
className,
|
||||
methodName: z.string().describe("Exact declared method name"),
|
||||
}),
|
||||
options: z.object({
|
||||
overloadIndex: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit zero-based index among same-name methods; required when ambiguous",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
execute(CLI_COMMANDS.inspectAndroidMethod, "inspect_android_method", {
|
||||
path: args.path,
|
||||
class_name: args.className,
|
||||
method_name: args.methodName,
|
||||
...(options.overloadIndex === undefined
|
||||
? {}
|
||||
: { overload_index: options.overloadIndex }),
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.traceAndroidReferences, {
|
||||
description: "Trace incoming APK class or unique-method references",
|
||||
args: z.object({ path, className }),
|
||||
options: z.object({
|
||||
methodName: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Unique declared method name; omit for class references"),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
execute(CLI_COMMANDS.traceAndroidReferences, "trace_android_references", {
|
||||
path: args.path,
|
||||
class_name: args.className,
|
||||
...(options.methodName === undefined
|
||||
? {}
|
||||
: { method_name: options.methodName }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
/** Process signal boundary injectable without emitting signals into a test runner. */
|
||||
export interface CommandCancellationHost {
|
||||
on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
||||
off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
||||
exitCode?: number | string | null | undefined;
|
||||
}
|
||||
|
||||
/** Translate one-shot CLI interrupts into awaited cleanup and conventional exit codes. */
|
||||
export const withCommandCancellation = async <Value>(
|
||||
operation: (signal: AbortSignal) => Promise<Value>,
|
||||
host: CommandCancellationHost = process,
|
||||
): Promise<Value> => {
|
||||
const controller = new AbortController();
|
||||
let exitCode: number | undefined;
|
||||
const interrupt = () => {
|
||||
exitCode ??= 130;
|
||||
controller.abort();
|
||||
};
|
||||
const terminate = () => {
|
||||
exitCode ??= 143;
|
||||
controller.abort();
|
||||
};
|
||||
host.on("SIGINT", interrupt);
|
||||
host.on("SIGTERM", terminate);
|
||||
try {
|
||||
return await operation(controller.signal);
|
||||
} finally {
|
||||
host.off("SIGINT", interrupt);
|
||||
host.off("SIGTERM", terminate);
|
||||
if (exitCode !== undefined) host.exitCode = exitCode;
|
||||
}
|
||||
};
|
||||
@@ -32,6 +32,11 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
resolveNativeCallTargets: "resolve-native-call-targets",
|
||||
inspectAssetCatalog: "inspect-asset-catalog",
|
||||
inspectManagedArtifact: "inspect-managed-artifact",
|
||||
inspectAndroidPackage: "inspect-android-package",
|
||||
searchAndroidClasses: "search-android-classes",
|
||||
inspectAndroidClass: "inspect-android-class",
|
||||
inspectAndroidMethod: "inspect-android-method",
|
||||
traceAndroidReferences: "trace-android-references",
|
||||
inspectManagedMembers: "inspect-managed-members",
|
||||
inspectManagedNativeBoundaries: "inspect-managed-native-boundaries",
|
||||
compareManagedMembers: "compare-managed-members",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
androidInputSchemas,
|
||||
androidResultSchemas,
|
||||
} from "../domain/androidAnalysis.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
|
||||
/** Static APK operations backed by a separately supplied headless engine. */
|
||||
export const ANDROID_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_android_package",
|
||||
...toolContractMetadata("inspect_android_package"),
|
||||
description:
|
||||
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and Java; uses one worker in an isolated temporary workspace.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.inspect_android_package,
|
||||
outputSchema: evidenceResultOf(
|
||||
androidResultSchemas.inspect_android_package,
|
||||
),
|
||||
examples: [
|
||||
{ title: "Inspect an APK", input: { path: "/tmp/Example.apk" } },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "search_android_classes",
|
||||
...toolContractMetadata("search_android_classes"),
|
||||
description:
|
||||
"Search complete decompiler class names in an explicit local APK by case-sensitive substring. Empty query inventories all classes. Retains artifact and engine identity; no APK execution.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.search_android_classes,
|
||||
outputSchema: evidenceResultOf(androidResultSchemas.search_android_classes),
|
||||
examples: [
|
||||
{
|
||||
title: "Find activity classes",
|
||||
input: { path: "/tmp/Example.apk", query: "Activity" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_android_class",
|
||||
...toolContractMetadata("inspect_android_class"),
|
||||
description:
|
||||
"Inspect one exact Android class's methods, fields and inner classes. Returns display signatures and explicit unknown DEX descriptors without materializing the whole application source.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.inspect_android_class,
|
||||
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_class),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a class",
|
||||
input: { path: "/tmp/Example.apk", class_name: "example.MainActivity" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_android_method",
|
||||
...toolContractMetadata("inspect_android_method"),
|
||||
description:
|
||||
"Decompile one Android method with smali fallback. Requires explicit overload_index when multiple methods share a name. Reports representation, fallback markers and source truncation; never treats display signatures as exact DEX identities.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.inspect_android_method,
|
||||
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_method),
|
||||
examples: [
|
||||
{
|
||||
title: "Decompile a method",
|
||||
input: {
|
||||
path: "/tmp/Example.apk",
|
||||
class_name: "example.MainActivity",
|
||||
method_name: "onCreate",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "trace_android_references",
|
||||
...toolContractMetadata("trace_android_references"),
|
||||
description:
|
||||
"Trace incoming static references to an exact Android class or unique method. Overloaded method reference queries are explicitly unsupported by the current engine. Source lines and DEX offsets remain unknown; no runtime calls are inferred.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.trace_android_references,
|
||||
outputSchema: evidenceResultOf(
|
||||
androidResultSchemas.trace_android_references,
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Find references to a class",
|
||||
input: { path: "/tmp/Example.apk", class_name: "example.MainActivity" },
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -8,6 +8,7 @@ import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
@@ -73,6 +74,7 @@ describe("tool contract surface", () => {
|
||||
...ENHANCED_TOOL_CONTRACTS,
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
...BROWSER_TOOL_CONTRACTS,
|
||||
|
||||
@@ -24,6 +24,7 @@ export const TOOL_KINDS = [
|
||||
"native-provider",
|
||||
"artifact-provider",
|
||||
"managed-provider",
|
||||
"android-provider",
|
||||
"browser-provider",
|
||||
"electron-provider",
|
||||
"runtime-provider",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
@@ -19,6 +20,7 @@ const GROUPS = {
|
||||
native: NATIVE_TOOL_CONTRACTS,
|
||||
artifact: ARTIFACT_TOOL_CONTRACTS,
|
||||
managed: MANAGED_TOOL_CONTRACTS,
|
||||
android: ANDROID_TOOL_CONTRACTS,
|
||||
managed_workflow: MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
browser_provider: BROWSER_PROVIDER_TOOL_CONTRACTS,
|
||||
electron: ELECTRON_TOOL_CONTRACTS,
|
||||
@@ -91,6 +93,11 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
|
||||
"inspect_electron_page",
|
||||
"inspect_macho",
|
||||
"inspect_managed_artifact",
|
||||
"inspect_android_package",
|
||||
"search_android_classes",
|
||||
"inspect_android_class",
|
||||
"inspect_android_method",
|
||||
"trace_android_references",
|
||||
"inspect_managed_members",
|
||||
"inspect_managed_native_boundaries",
|
||||
"inspect_native_api",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
|
||||
@@ -19,6 +20,7 @@ export const TOOL_CONTRACTS = [
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
...BROWSER_PROVIDER_TOOL_CONTRACTS,
|
||||
...ELECTRON_TOOL_CONTRACTS,
|
||||
|
||||
@@ -41,6 +41,31 @@ const sessionEvidence = effects({ mutatesSession: true });
|
||||
|
||||
/** Explicit effect audit for every public tool. */
|
||||
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_android_package: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
search_android_classes: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_android_class: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_android_method: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
trace_android_references: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
annotate_native_function: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const target = {
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Local APK path; the target is never executed"),
|
||||
};
|
||||
const classTarget = {
|
||||
...target,
|
||||
class_name: z.string().min(1).describe("Exact fully qualified class name"),
|
||||
};
|
||||
|
||||
/** Caller intent for static Android inspection, independent of its engine. */
|
||||
export const androidInputSchemas = {
|
||||
inspect_android_package: z.strictObject(target),
|
||||
search_android_classes: z.strictObject({
|
||||
...target,
|
||||
query: z
|
||||
.string()
|
||||
.describe("Case-sensitive class-name substring; empty lists all classes"),
|
||||
}),
|
||||
inspect_android_class: z.strictObject(classTarget),
|
||||
inspect_android_method: z.strictObject({
|
||||
...classTarget,
|
||||
method_name: z.string().min(1),
|
||||
overload_index: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit index among same-name methods; required when ambiguous",
|
||||
),
|
||||
}),
|
||||
trace_android_references: z.strictObject({
|
||||
...classTarget,
|
||||
method_name: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Omit for class references; ambiguous overloaded methods are unsupported",
|
||||
),
|
||||
}),
|
||||
} as const;
|
||||
|
||||
/** Supported static Android operations. */
|
||||
export type AndroidOperation = keyof typeof androidInputSchemas;
|
||||
/** Validated Android requests carry their selected operation. */
|
||||
export type AndroidRequest = {
|
||||
[Name in AndroidOperation]: {
|
||||
operation: Name;
|
||||
input: z.infer<(typeof androidInputSchemas)[Name]>;
|
||||
};
|
||||
}[AndroidOperation];
|
||||
|
||||
/** Validate operation and input together so their types remain correlated. */
|
||||
export const androidRequestSchema = z.discriminatedUnion("operation", [
|
||||
z.strictObject({
|
||||
operation: z.literal("inspect_android_package"),
|
||||
input: androidInputSchemas.inspect_android_package,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("search_android_classes"),
|
||||
input: androidInputSchemas.search_android_classes,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("inspect_android_class"),
|
||||
input: androidInputSchemas.inspect_android_class,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("inspect_android_method"),
|
||||
input: androidInputSchemas.inspect_android_method,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("trace_android_references"),
|
||||
input: androidInputSchemas.trace_android_references,
|
||||
}),
|
||||
]);
|
||||
|
||||
const textCoverage = z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
text: z.string(),
|
||||
reported_total_bytes: z.number().int().nonnegative().nullable(),
|
||||
});
|
||||
const method = z.strictObject({
|
||||
name: z.string(),
|
||||
reported_signature: z.string(),
|
||||
overload_index: z.number().int().nonnegative(),
|
||||
is_constructor: z.boolean(),
|
||||
dex_descriptor: z.null(),
|
||||
});
|
||||
const engine = z.strictObject({
|
||||
name: z.string().min(1),
|
||||
version: z.string().nullable(),
|
||||
artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
source_revision: z.string().nullable(),
|
||||
worker_count: z.number().int().positive(),
|
||||
heap_limit_mib: z.number().int().positive().nullable(),
|
||||
});
|
||||
const common = { engine };
|
||||
|
||||
/** Portable observations with explicit decompiler and identity limitations. */
|
||||
export const androidResultSchemas = {
|
||||
inspect_android_package: z.strictObject({
|
||||
...common,
|
||||
package_name: z.string().nullable(),
|
||||
version_name: z.string().nullable(),
|
||||
version_code: z.string().nullable(),
|
||||
min_sdk: z.string().nullable(),
|
||||
target_sdk: z.string().nullable(),
|
||||
permissions: z.array(z.string()),
|
||||
manifest: textCoverage,
|
||||
class_count: z.number().int().nonnegative(),
|
||||
resource_count: z.number().int().nonnegative(),
|
||||
signature_verification: z.literal("not_performed"),
|
||||
}),
|
||||
search_android_classes: z.strictObject({
|
||||
...common,
|
||||
query: z.string(),
|
||||
total_classes: z.number().int().nonnegative(),
|
||||
matches: z.array(z.string()),
|
||||
coverage: z.literal("complete"),
|
||||
}),
|
||||
inspect_android_class: z.strictObject({
|
||||
...common,
|
||||
class_name: z.string(),
|
||||
methods: z.array(method),
|
||||
fields: z.array(
|
||||
z.strictObject({ name: z.string(), reported_type: z.string() }),
|
||||
),
|
||||
inner_classes: z.array(z.string()),
|
||||
}),
|
||||
inspect_android_method: z.strictObject({
|
||||
...common,
|
||||
class_name: z.string(),
|
||||
method: method,
|
||||
overload_count: z.number().int().positive(),
|
||||
representation: z.enum(["java", "smali"]),
|
||||
body_status: z.enum(["available", "not_available"]),
|
||||
fell_back: z.boolean(),
|
||||
markers: z.array(z.string()),
|
||||
source: textCoverage,
|
||||
}),
|
||||
trace_android_references: z.strictObject({
|
||||
...common,
|
||||
class_name: z.string(),
|
||||
method_name: z.string().nullable(),
|
||||
total: z.number().int().nonnegative(),
|
||||
references: z.array(
|
||||
z.strictObject({
|
||||
kind: z.string(),
|
||||
name: z.string(),
|
||||
reported_full_name: z.string(),
|
||||
containing_class: z.string(),
|
||||
top_class: z.string(),
|
||||
source_line: z.null(),
|
||||
dex_offset: z.null(),
|
||||
}),
|
||||
),
|
||||
coverage: z.literal("complete"),
|
||||
}),
|
||||
} as const;
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import type { EventEmitter } from "node:events";
|
||||
import type { Readable } from "node:stream";
|
||||
import type { Readable, Writable } from "node:stream";
|
||||
|
||||
import { WindowsOwnedProcess } from "../windows/WindowsOwnedProcess.js";
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface OwnedProviderProcessSpawnOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
/** Host environment used as the base for the child environment. */
|
||||
readonly hostEnvironment?: NodeJS.ProcessEnv;
|
||||
/** Opt into a writable protocol stream; other providers retain ignored stdin. */
|
||||
readonly stdin?: "pipe";
|
||||
}
|
||||
|
||||
/** Spawned process paired with the identity proof required for group cleanup. */
|
||||
@@ -43,6 +45,7 @@ export interface ProviderProcessHandle extends Pick<
|
||||
> {
|
||||
readonly pid?: number | undefined;
|
||||
readonly stdout: Readable | null;
|
||||
readonly stdin?: Writable | null;
|
||||
readonly stderr: Readable | null;
|
||||
readonly exitCode: number | null;
|
||||
readonly signalCode: NodeJS.Signals | null;
|
||||
@@ -135,6 +138,10 @@ export const spawnOwnedProviderProcess = async (
|
||||
REA_PROCESS_RUN_ID: options.runId,
|
||||
};
|
||||
if (platform === "win32" && process.platform === "win32") {
|
||||
if (options.stdin === "pipe")
|
||||
throw new Error(
|
||||
"Owned Windows provider processes do not support protocol stdin",
|
||||
);
|
||||
const child = new WindowsOwnedProcess(
|
||||
options.command,
|
||||
options.arguments,
|
||||
@@ -156,7 +163,7 @@ export const spawnOwnedProviderProcess = async (
|
||||
const child = spawn(options.command, [...options.arguments], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
|
||||
detached: platform !== "win32",
|
||||
windowsVerbatimArguments: options.windowsVerbatimArguments ?? false,
|
||||
env: environment,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
@@ -17,6 +18,10 @@ import { registerElectronTools } from "./registerElectronTools.js";
|
||||
import { registerEnhancedTools } from "./registerEnhancedTools.js";
|
||||
import { registerJavaScriptRuntimeObservationTools } from "./registerJavaScriptRuntimeObservationTools.js";
|
||||
import { registerManagedTools } from "./registerManagedTools.js";
|
||||
import { registerAndroidTools } from "./registerAndroidTools.js";
|
||||
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
|
||||
import type { AndroidAnalysisPort } from "../application/AndroidAnalysisPort.js";
|
||||
import { JadxProvider } from "../android/JadxProvider.js";
|
||||
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
|
||||
import { registerNativeTools } from "./registerNativeTools.js";
|
||||
import { registerOfficialTools } from "./registerOfficialTools.js";
|
||||
@@ -33,6 +38,7 @@ const ACTIVE_TARGET_INSTRUCTIONS =
|
||||
|
||||
export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
readonly androidAnalysis?: AndroidAnalysisPort;
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
|
||||
readonly electronObservation?: ElectronObservationPort;
|
||||
@@ -49,6 +55,10 @@ const installSessionToolAvailability = (
|
||||
if (session === undefined) return undefined;
|
||||
const policy = sessionAvailabilityPolicy(options.availabilityPolicy, {
|
||||
optionalFeatures: {
|
||||
androidAnalysisEnabled:
|
||||
options.androidAnalysis !== undefined ||
|
||||
((process.platform === "linux" || process.platform === "darwin") &&
|
||||
isAbsolute(process.env.REA_JADX_MCP_JAR ?? "")),
|
||||
browserObservationEnabled: options.browserObservation !== undefined,
|
||||
browserScenarioEnabled: options.browserScenarioCapture !== undefined,
|
||||
electronObservationEnabled: options.electronObservation !== undefined,
|
||||
@@ -111,6 +121,12 @@ export const createServer = (
|
||||
recordEvidenceWithUnknown,
|
||||
};
|
||||
registerBinaryAnalysisTools(toolContext);
|
||||
registerAndroidTools(
|
||||
server,
|
||||
new AndroidAnalysisService(options.androidAnalysis ?? new JadxProvider()),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerObservationTools(toolContext);
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { AndroidOperation } from "../domain/androidAnalysis.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
/** Bind Android handlers to their exact named contracts through shared workflows. */
|
||||
export const registerAndroidTools = (
|
||||
server: McpServer,
|
||||
service: AndroidAnalysisService,
|
||||
logger: Logger,
|
||||
recordEvidence?: BinarySessionPort["recordEvidence"],
|
||||
): void => {
|
||||
const handler = (contract: ToolContract<AndroidOperation>) => {
|
||||
const name = contract.name;
|
||||
return async (input: unknown, context: ServerContext) => {
|
||||
const result = await logToolExecution(logger, name, () =>
|
||||
service.execute(name, input, { signal: context.mcpReq.signal }),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordEvidence?.(result.value);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, contract)
|
||||
: toCallToolResult(result, contract);
|
||||
};
|
||||
};
|
||||
const packageContract = toolContract("inspect_android_package");
|
||||
server.registerTool(
|
||||
packageContract.name,
|
||||
toolRegistrationOptions(packageContract),
|
||||
handler(packageContract),
|
||||
);
|
||||
const searchContract = toolContract("search_android_classes");
|
||||
server.registerTool(
|
||||
searchContract.name,
|
||||
toolRegistrationOptions(searchContract),
|
||||
handler(searchContract),
|
||||
);
|
||||
const classContract = toolContract("inspect_android_class");
|
||||
server.registerTool(
|
||||
classContract.name,
|
||||
toolRegistrationOptions(classContract),
|
||||
handler(classContract),
|
||||
);
|
||||
const methodContract = toolContract("inspect_android_method");
|
||||
server.registerTool(
|
||||
methodContract.name,
|
||||
toolRegistrationOptions(methodContract),
|
||||
handler(methodContract),
|
||||
);
|
||||
const referencesContract = toolContract("trace_android_references");
|
||||
server.registerTool(
|
||||
referencesContract.name,
|
||||
toolRegistrationOptions(referencesContract),
|
||||
handler(referencesContract),
|
||||
);
|
||||
};
|
||||
@@ -11,6 +11,7 @@ export interface SessionAvailabilityDefaults {
|
||||
| "electronObservationEnabled"
|
||||
| "electronAutomationEnabled"
|
||||
| "v8InspectorObservationEnabled"
|
||||
| "androidAnalysisEnabled"
|
||||
>;
|
||||
}
|
||||
|
||||
@@ -22,6 +23,8 @@ export const sessionAvailabilityPolicy = (
|
||||
configured ??
|
||||
(() => ({
|
||||
processCaptureEnabled: platform !== "win32",
|
||||
androidAnalysisEnabled:
|
||||
defaults.optionalFeatures?.androidAnalysisEnabled ?? false,
|
||||
browserObservationEnabled:
|
||||
defaults.optionalFeatures?.browserObservationEnabled ?? false,
|
||||
browserScenarioEnabled:
|
||||
|
||||
Reference in New Issue
Block a user