From 5e869afc4cacac160210a8bc4ce333dfd66f2474 Mon Sep 17 00:00:00 2001 From: dev Date: Sun, 1 Nov 2026 17:34:46 +0800 Subject: [PATCH 01/24] daemon: state adb device access and stop guessing anti-debugging The initialize instructions only described the MCP tools, so a client saw no way to touch the phone and read a stalled privacy dialog or login screen as a defense mechanism. adb is the supported operator/AI channel (app_launch already relies on it) and was simply never announced. Announce the channel and the disciplines that go with it: confirm a normal interaction gate by reading dumpsys/uiautomator/screencap before attributing a stall to detection, claim detection only with matching evidence, stop when a gate needs the user, and derive tap coordinates from what was actually read. The stuck guide gains ordered device checks, and assessment limits now say a stalled screen is a state, not a diagnosis. --- daemon/src/analysis_assist.ts | 3 +- daemon/src/analysis_guide.ts | 46 +++++++++++++++++++++++++++--- daemon/test/analysis_guide.test.ts | 41 ++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 5 deletions(-) diff --git a/daemon/src/analysis_assist.ts b/daemon/src/analysis_assist.ts index 29f0b5c..62e9872 100644 --- a/daemon/src/analysis_assist.ts +++ b/daemon/src/analysis_assist.ts @@ -50,7 +50,8 @@ export async function assessAnalysis(options: AssessmentOptions, deps: Assessmen note: 'Re-run to refresh live facts. This checkpoint carries identifiers, not keys, plaintext or a complete case history. A new session must be selected after reconnect.' }, limits: ['Only current Host-retained records are inspected (at most 64); records and hook counters may cover different windows.', 'No automatic trigger, hook install/unhook, restart, replay, root upload, or algorithm conclusion is performed.', - 'Proposed next calls may have the explicitly stated effects; execute them only within the authorized task.'], + 'Proposed next calls may have the explicitly stated effects; execute them only within the authorized task.', + 'A stalled screen or a hung command is a state, not a diagnosis. Before this assessment is used to claim anti-debugging, hardening or injection detection, the ordinary causes must be ruled out on the device: a normal user-interaction gate (privacy consent, permission, login, SMS code, onboarding), a command that never reached the device, and a target that is simply idle. adb (dumpsys activity activities, uiautomator dump, screencap) is the supported channel for that check.'], }; const finish = (stage: string, summary: string, next: Next | null, missing: string[] = [], forbidden: string[] = []) => { report.stage = stage; report.summary = summary; report.next = next; diff --git a/daemon/src/analysis_guide.ts b/daemon/src/analysis_guide.ts index 28824a7..2e2c03c 100644 --- a/daemon/src/analysis_guide.ts +++ b/daemon/src/analysis_guide.ts @@ -13,7 +13,23 @@ export const MCP_INSTRUCTIONS = 'ADH is an Android runtime analysis workbench. S 'Replace $variables from live results, never guess an address, TID, key or invocation pairing. ' + 'An online socket does not prove responsiveness; use runtime_diagnostics when commands hang. ' + 'Check capture loss and completeness before making claims. In-hook QBDI is replay with side effects and incomplete context; ' + - 'active-call traces cover the instrumented module, not the original whole execution. A primitive match does not prove a final signature.'; + 'active-call traces cover the instrumented module, not the original whole execution. A primitive match does not prove a final signature. ' + + // The device is reachable outside the MCP tool list. Saying so prevents the most common + // misattribution: a privacy dialog or login screen misread as an anti-debug defense. + '\n\nDEVICE ACCESS: adb is the supported operator/AI channel to the connected phone and is not limited to the tools above. ' + + 'When adb is available on the Host (ANDROID_SERIAL / ADH_SERIAL selects the device), use it directly for: logcat; ' + + 'the foreground activity (dumpsys activity activities); launching or force-stopping the package (am start / am force-stop / monkey); ' + + 'the UI hierarchy (uiautomator dump) and screenshots (screencap); and taps, swipes and text input (input tap / swipe / text / keyevent). ' + + 'Use these to confirm what the app is actually showing instead of inferring it. ' + + '\n\nATTRIBUTION: a screen that does not progress is not by itself evidence of anti-debugging, hardening or injection detection. ' + + 'Check in order: (1) is the app just showing a normal gate - privacy consent, permission prompt, login, SMS/captcha, onboarding? ' + + 'Read the UI hierarchy or a screenshot to find out. (2) did the command reach the device and return (adb exit status and stderr)? ' + + '(3) is the process alive with unchanged identity (runtime_diagnostics)? ' + + 'Claim detection only with matching evidence: a hit detection point, abnormal TracerPid/seccomp/frozen state, or a concrete crash stack or error code. ' + + 'Otherwise report the state as unknown and name the observation that would distinguish the cases. ' + + 'When a gate needs the user (account, SMS code, manual consent), say what is missing and stop; ' + + 'do not change hooks, restart the process or repeat the same tap. ' + + 'Derive tap coordinates from the UI hierarchy or screenshot you just read, never from screen size, and re-read the state after each interaction.'; interface Step { goal: string; @@ -22,10 +38,19 @@ interface Step { check: string; onFailure?: string; } +// adb is the operator/AI channel rather than an MCP tool, so device observations carry an +// explicit command instead of a tool call and are never validated as templates. +interface DeviceCheck { + goal: string; + command: string; + check: string; + onFailure?: string; +} interface Guide { title: string; prerequisites: string[]; variables: Record; + deviceChecks?: DeviceCheck[]; steps: Step[]; limits: string[]; } @@ -93,15 +118,28 @@ const guides: Record = { }, stuck: { title: 'Diagnose missing events and unresponsive commands', - prerequisites: ['Retain the explicit session and actual error text; do not guess that every timeout is anti-debugging.'], - variables: { session: 'Known sessionId, including an offline one for runtime_diagnostics.', hookId: 'id of the hook you actually armed.' }, + prerequisites: ['Retain the explicit session and actual error text; do not guess that every timeout is anti-debugging.', + 'Rule out the ordinary explanations first: a normal user-interaction gate (privacy consent, permission, login, SMS code, onboarding), a command that never reached the device, and a target that is simply idle. A stalled screen is a state, not a diagnosis.'], + variables: { session: 'Known sessionId, including an offline one for runtime_diagnostics.', hookId: 'id of the hook you actually armed.', pkg: 'Package name of the target, for foreground-activity and UI checks.' }, + // adb is the operator/AI channel, not an MCP tool, so it cannot appear as a template step. + // These are ordered observations to run on the Host before attributing anything to defense. + deviceChecks: [ + { goal: 'Name the resumed activity before blaming the app.', command: 'adb shell dumpsys activity activities', check: 'Compare the resumed activity (mResumedActivity / topResumedActivity) with the screen you expected. A splash, consent, login or permission activity explains the stall with no defensive mechanism involved.' }, + { goal: 'Read the actual UI instead of inferring it.', command: 'adb shell uiautomator dump /sdcard/adh-ui.xml && adb pull /sdcard/adh-ui.xml', check: 'Name the visible control and its bounds. A button such as "同意并继续" or a login form is an ordinary user gate. Derive tap coordinates from this dump or from a screenshot, never from screen size.', onFailure: 'An empty or refused dump can also mean the window is not drawn yet; wait briefly and retry before concluding anything about detection.' }, + { goal: 'Capture what the screen really shows.', command: 'adb exec-out screencap -p > screen.png', check: 'Use the image to confirm the gate. Do not describe a screen you have not read.' }, + { goal: 'Confirm the command reached the device at all.', command: 'adb shell echo "$?" and adb devices -l', check: 'A local failure, missing adb, or an offline device is an environment problem, not target behavior.' }, + ], steps: [ { goal: 'Interpret current counters and retained records first.', tool: 'analysis_guide', arguments: { action: 'assess', topic: 'stuck', session: '$session', hookId: '$hookId' }, check: 'Read facts and missingEvidence. Assessment performs at most one bounded read-only native hook status query; it does not install, drain or trigger anything. A proposed next call is not an executed call.' }, { goal: 'Inspect process facts independently of the agent channel.', tool: 'runtime_diagnostics', arguments: { session: '$session', limit: 32 }, check: 'Distinguish frozen, traced, process-exited, identity-mismatch, running and unknown. Check errors and completeness of thread paging.' }, { goal: 'Read stored hook evidence and observation counts.', tool: 'native_look', arguments: { action: 'read', session: '$session', hookId: '$hookId' }, check: 'Distinguish hits=0 from filtered/sampledOut/throttled/limited, stored record loss, drainError and observationError.', onFailure: 'Unknown hook/session: re-list sessions and actual hook status. Do not invent a replacement hookId.' }, { goal: 'Inspect current physical hook budget when the agent responds.', tool: 'native_hook', arguments: { action: 'status', session: '$session' }, check: 'Non-default new observation controls require observationControlsVersion>=1. Retired slots are not reclaimed by unhook; exhausted 16-slot budget requires a new target process, never an automatic restart.' }, ], - limits: ['No hardware events can also mean wrong address/TID, no trigger, a frozen thread, or an unsupported kernel; absence alone proves none of these.', 'Missing facts stay unknown; report the failed prerequisite instead of silently dropping filters or substituting replay.', 'Read diagnostics first; target restarts and other changes require an authorized workflow.'], + limits: ['No hardware events can also mean wrong address/TID, no trigger, a frozen thread, or an unsupported kernel; absence alone proves none of these.', + 'A non-progressing screen, a failed local command and a blocked request each have ordinary causes. Claim anti-debugging, hardening or injection detection only with matching evidence (hit detection point, abnormal TracerPid/seccomp/frozen state, concrete crash stack or error code); otherwise keep the state unknown and name the next distinguishing observation.', + 'When the gate needs the user (account, SMS code, manual consent), state exactly what is missing and stop. Do not change hooks, restart the process or repeat the same tap to work around it.', + 'Missing facts stay unknown; report the failed prerequisite instead of silently dropping filters or substituting replay.', + 'Read diagnostics first; target restarts and other changes require an authorized workflow.'], }, }; diff --git a/daemon/test/analysis_guide.test.ts b/daemon/test/analysis_guide.test.ts index 3984571..a029f57 100644 --- a/daemon/test/analysis_guide.test.ts +++ b/daemon/test/analysis_guide.test.ts @@ -24,6 +24,47 @@ test('initialize sends a usable entry route and the tool list also exposes help' assert.deepEqual(help.inputSchema.properties.topic.enum, ANALYSIS_GUIDE_TOPICS); }); +test('initialize tells the client that adb is a usable device channel and forbids guessing defenses', async () => { + const init = await rpc('initialize'); + const text = init.result.instructions; + // 设备可达性:不写这一条,模型会把「工具列表里没有点击能力」当成「点不到手机」。 + assert.match(text, /DEVICE ACCESS/); + assert.match(text, /adb is the supported operator\/AI channel/); + for (const capability of ['logcat', 'dumpsys activity activities', 'uiautomator dump', 'screencap', 'input tap']) + assert.ok(text.includes(capability), 'missing adb capability: ' + capability); + // 归因纪律:卡住不能直接等于反调试。 + assert.match(text, /ATTRIBUTION/); + assert.match(text, /not by itself evidence of anti-debugging/); + assert.match(text, /privacy consent/); + assert.match(text, /Claim detection only with matching evidence/); + // 需要用户介入时要停下来,而不是改注入或反复点同一处。 + assert.match(text, /say what is missing and stop/); + assert.match(text, /never from screen size/); +}); + +test('the stuck guide offers adb device checks before any defense conclusion', () => { + const guide = analysisGuide('stuck'); + assert.ok(guide.deviceChecks && guide.deviceChecks.length >= 3, 'stuck must start from device facts'); + const commands = guide.deviceChecks!.map(c => c.command).join('\n'); + for (const expected of ['dumpsys activity activities', 'uiautomator dump', 'screencap']) assert.ok(commands.includes(expected), expected); + // 每个 check 都要说明「这属于普通原因」而不是检测。 + assert.ok(guide.deviceChecks!.some(c => /consent|login|permission/i.test(c.check))); + // adb 不是 MCP 工具,不能混进模板步骤里被当作可调用工具校验。 + assert.equal(guide.steps.some(s => s.tool === 'adb'), false); + assert.match(guide.limits.join(' '), /A non-progressing screen, a failed local command and a blocked request each have ordinary causes/); + assert.match(guide.prerequisites.join(' '), /A stalled screen is a state, not a diagnosis/); +}); + +test('assessment output states that a stalled screen is not a diagnosis', async () => { + const { assessAnalysis } = await import('../src/analysis_assist.ts'); + const report = await assessAnalysis({ topic: 'stuck', session: 'nope' }, { + now: () => 1, sessions: new Map(), captures: [], stats: new Map(), storeLoss: () => null, + readHookStatus: async () => { throw new Error('not used'); }, + } as any); + assert.match(report.limits.join(' '), /A stalled screen or a hung command is a state, not a diagnosis/); + assert.match(report.limits.join(' '), /adb \(dumpsys activity activities, uiautomator dump, screencap\)/); +}); + test('every guide can be read through MCP without a session and returns a bounded workflow', async () => { for (const topic of ANALYSIS_GUIDE_TOPICS) { const response = await rpc('tools/call', { name: 'analysis_guide', arguments: { topic } }); From 7a4a18a4d6feebf7f53ff6ec937f2cea5d1e0d84 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 13 Nov 2026 16:15:21 +0800 Subject: [PATCH 02/24] =?UTF-8?q?feat:=20root=5Fwatch=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=A4=9A=E7=A1=AC=E4=BB=B6=E6=96=AD=E7=82=B9=E4=B8=8E=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E7=BA=A7=E5=86=85=E5=AD=98=E7=AA=97=E5=8F=A3=EF=BC=88?= =?UTF-8?q?=E5=90=AB=E4=B8=A4=E7=BA=A7=E6=8C=87=E9=92=88=E8=A7=A3=E5=BC=95?= =?UTF-8?q?=E7=94=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/src/mcp.ts | 2 +- daemon/src/root_watch.ts | 34 ++- daemon/test/root_watch.test.ts | 22 ++ docs/PROGRESS.md | 43 ++++ tools/MAP.md | 3 + tools/native/root_watch.c | 352 +++++++++++++++++++++------- tools/verify_v131_root_watch_mem.sh | 78 ++++++ 7 files changed, 449 insertions(+), 85 deletions(-) create mode 100644 tools/verify_v131_root_watch_mem.sh diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 603bf90..7a9f3cf 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -114,7 +114,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } throw new Error('unknown trace_session action'); } }, - { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event; there are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { + { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@]]REG[+/-OFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to two levels), so the returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { if (a.action === 'prepare') return prepareRootWatch(a.serial); if (a.action === 'start') { const s = sessions.get(String(a.session ?? '')); diff --git a/daemon/src/root_watch.ts b/daemon/src/root_watch.ts index 67cc0e5..0b051fb 100644 --- a/daemon/src/root_watch.ts +++ b/daemon/src/root_watch.ts @@ -40,7 +40,35 @@ export function normalizeRootWatch(a: Record) { const maxEvents = integer(a.maxEvents, 128, 1, 2048, 'maxEvents'); const stackBytes = integer(a.stackBytes, 8192, 0, 16384, 'stackBytes'); if (stackBytes % 8) throw new Error('stackBytes must be a multiple of 8'); - return { tid, addr: '0x' + addr.toString(16), width, mode, durationMs, maxEvents, stackBytes }; + // Extra hardware slots on the SAME thread. A stateful VM normally needs two or three + // stops (fetch / dispatch / tail) to see one operation, which one slot cannot express. + const rawBps = a.breakpoints === undefined ? [] : a.breakpoints; + if (!Array.isArray(rawBps) || rawBps.length > 3) throw new Error('breakpoints must be an array of at most 3 extra slots'); + const breakpoints = rawBps.map((value: Record, index: number) => { + if (!value || typeof value !== 'object') throw new Error(`breakpoints[${index}] must be an object`); + const modeOf = value.mode ?? 'x'; + if (!['w', 'r', 'rw', 'x'].includes(modeOf)) throw new Error(`breakpoints[${index}].mode must be w, r, rw or x`); + const widthOf = integer(value.width, modeOf === 'x' ? 4 : 8, 1, 8, `breakpoints[${index}].width`); + const addrOf = address(value.addr, `breakpoints[${index}].addr`); + if (![1, 2, 4, 8].includes(widthOf) || addrOf % BigInt(widthOf) || (modeOf === 'x' && widthOf !== 4)) + throw new Error(`breakpoints[${index}] width must be 1/2/4/8 and address aligned; execution breakpoints need width 4`); + return `bp=0x${addrOf.toString(16)}:${widthOf}:${modeOf}`; + }); + // Memory windows are read by the collector at the moment of the hit; that is the only + // time the sampled registers still describe the state the instruction operated on. + const rawMem = a.mem === undefined ? [] : typeof a.mem === 'string' ? [a.mem] : a.mem; + if (!Array.isArray(rawMem) || rawMem.length > 4) throw new Error('mem must be a string or an array of at most 4 specs'); + const MEM_SPEC = /^@{0,2}(x([0-9]|[12][0-9]|30)|sp|lr|pc)([+-](0x[0-9a-f]+|\d+))?(:([1-9][0-9]*|0x[1-9a-f][0-9a-f]{0,2}))?$/i; + const mem = rawMem.map((spec: unknown, index: number) => { + if (typeof spec !== 'string' || spec.length === 0 || spec.length > 60 || !MEM_SPEC.test(spec)) + throw new Error(`mem[${index}] must look like [@[@]]REG[+/-OFFSET][:LEN] with REG=x0..x30, sp, lr or pc`); + if (spec.includes(':')) { + const size = Number(spec.slice(spec.lastIndexOf(':') + 1)); + if (!Number.isInteger(size) || size < 1 || size > 256) throw new Error(`mem[${index}] length must be 1..256`); + } + return spec; + }); + return { tid, addr: '0x' + addr.toString(16), width, mode, durationMs, maxEvents, stackBytes, breakpoints, mem }; } async function adb(serial: string, args: string[], timeout = 10000) { return (await exec('adb', ['-s', serial, ...args], { timeout, maxBuffer: 1024 * 1024, windowsHide: true })).stdout; @@ -87,7 +115,9 @@ export async function startRootWatch(target: Target, a: Record, dat const stopFile = `/data/local/tmp/adh-root-watch-stop-${id}`; const run: Run = { id, serial, target, file, stopFile, running: true, stderr: '', samples: 0, ...generation }; runs.set(id, run); - const command = `${HELPER} ${target.pid} ${spec.tid} ${spec.addr} ${spec.width} ${spec.mode} ${spec.durationMs} ${spec.maxEvents} ${spec.stackBytes} ${stopFile}`; + const command = `${HELPER} ${target.pid} ${spec.tid} ${spec.addr} ${spec.width} ${spec.mode} ${spec.durationMs} ${spec.maxEvents} ${spec.stackBytes} ${stopFile}` + + spec.breakpoints.map((extra: string) => ` ${extra}`).join('') + + spec.mem.map((window: string) => ` mem=${window}`).join(''); const child = spawn('adb', ['-s', serial, 'shell', 'su', '-c', command], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); let pending = ''; await new Promise((resolveReady, reject) => { diff --git a/daemon/test/root_watch.test.ts b/daemon/test/root_watch.test.ts index a518353..e02c010 100644 --- a/daemon/test/root_watch.test.ts +++ b/daemon/test/root_watch.test.ts @@ -5,6 +5,7 @@ import { normalizeRootWatch, projectRootSample } from '../src/root_watch.ts'; test('root watch validates exact addresses without rounding and preserves single-thread scope', () => { assert.deepEqual(normalizeRootWatch({ tid: 42, addr: '0XABCDEF10' }), { tid: 42, addr: '0xabcdef10', width: 8, mode: 'w', durationMs: 5000, maxEvents: 128, stackBytes: 8192, + breakpoints: [], mem: [], }); assert.equal(normalizeRootWatch({ tid: 1, addr: '0x1004', mode: 'x' }).width, 4); for (const args of [ @@ -14,6 +15,27 @@ test('root watch validates exact addresses without rounding and preserves single ]) assert.throws(() => normalizeRootWatch({ tid: 42, addr: '0x1000', ...args })); }); +test('extra hardware slots and memory windows are validated, not passed through', () => { + const spec = normalizeRootWatch({ + tid: 7, addr: '0x1000', mode: 'x', width: 4, + breakpoints: [{ addr: '0x2000', mode: 'x' }, { addr: '0x3000', width: 8, mode: 'rw' }], + mem: ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', 'x29-0x30:0x20'], + }); + assert.deepEqual(spec.breakpoints, ['bp=0x2000:4:x', 'bp=0x3000:8:rw']); + assert.deepEqual(spec.mem, ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', 'x29-0x30:0x20']); + for (const bad of [ + { breakpoints: [{ addr: '0x2001', mode: 'x' }] }, + { breakpoints: [{ addr: '0x2000', mode: 'x', width: 8 }] }, + { breakpoints: [{ addr: '0x2000', width: 3 }] }, + { breakpoints: [1] }, + { breakpoints: [{ addr: '0x1000' }, { addr: '0x2000' }, { addr: '0x3000' }, { addr: '0x4000' }] }, + { mem: ['r13:16'] }, { mem: ['x99:8'] }, { mem: ['x1:0'] }, { mem: ['x1:257'] }, + { mem: ['x1+zz:8'] }, { mem: ['x1;id'] }, { mem: [1] }, + { mem: ['x0', 'x1', 'x2', 'x3', 'x4'] }, + ]) assert.throws(() => normalizeRootWatch({ tid: 42, addr: '0x1000', ...bad })); +}); + + test('kernel stack windows are bounded and cannot silently read another address', () => { const record = { seq: 1, ip: '0x2000', regs: ['0xdead'], stack: { addr: '0x1000', requested: 8, got: 4, hex: '41424344' } }; const normal = projectRootSample(record, {}); diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7412601..659ae38 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4857,8 +4857,51 @@ RESULT:SKIP module APK stale and not rebuildable - [~] v2.6 WS-I 确定性关联(**未做**:当前是 `flow.ts` 的 tid+时间窗关联,带 caveat 自述);WS-J 反检测动态面(首切片已落地;**TRACEME 中和在 2026-10-01 失去唯一控制面**,恢复需显式 opt-in) - [~] 贯穿 WS-K 架构拆分(进行中);**多架构不做**(2026-10-01 决议) +- [x] **QBDI 载荷投递(v0.7.0,2026-11-12,真实第三方 App 验收)**: + · 问题:模块从不携带 `libQBDI.so`,真实目标里 agent 的 `dlopen("libQBDI.so")` 必然失败;沙盒 APK 自带该库,所以沙盒验收一直 PASS —— 那是自欺,不是产品可用。 + · 修复:模块 stage 增加 `libQBDI.so`;companion 新增 `qbdi` 应答(`/data/adb/adh/qbdi.enabled` 存在=开启),在 pre-specialize 打开库 fd 并在 post-specialize 交给 agent(新导出 `adh_agent_set_qbdi_fd`);agent 首次 trace 时把该 fd 复制进 specialization 之后创建的 memfd 再 `dlopen`,standalone trace 结束照旧 `dlclose`。 + · 默认面不变:flag 缺失时不开 fd、不加载、不映射;开启时进程 `/proc//fd` 可见 `/data/adb/modules/adh/libQBDI.so`(显式 opt-in 的既定成本,未落盘、无 app 私有目录文件)。 + · 真机验收 `verify_v129_qbdi_delivery.sh`(真实第三方 App com.uxin.kilaaudio):关 → `delivery is off` 且无 fd;开 → fd 交付、`qbdi_trace libc:getpid` 返回目标 pid(8 条真实指令)、trace 后 maps 无 QBDI。 + · 版本配对:module / Manager / Device Daemon / agent `AGENT_VER` 同步 v0.7.0(29 / 29 / 16 / 0.7.0);`build_zygisk.sh` 增加 AGENT_VER↔module.prop 一致性门禁;`fetch_qbdi.sh` 不再默认把库 stage 进沙盒 APK(`ADH_STAGE_SANDBOX_QBDI=1` 才保留旧行为)。 + +- [x] **v0.8.0:作用域可编程 + 一把抓分析任意 App(2026-11-12,真实 App 实测)**: + · 新 MCP 工具 / REST:`scope_list` / `scope_set` / `analyze_app`(`GET|POST /api/scope`、`POST /api/analyze-app`)。scope 写盘走 adb+su,写完回读校验,SELinux label 显式设成 `adb_data_file`(写错 label 会 fail-closed:不注入且没有可见错误)。 + · `analyze_app`:只给包名 → 按需加入 scope(回复里报 `scopeAdded`)→ 冷启 → 等 Zygisk agent → `triage` → 可选 `unpack` / TLS 抓包窗口;每阶段独立 ok/error。 + · 真机实测(aa165071 / agent 0.8.0):`com.mcdonalds.gma.cn` 51s 完成 triage(38 ops / 4159 regions);`com.greenpoint.android.mc10086.activity` 37s,13 组 HTTP exchange、163 条 crypto 记录(摘要 82 / 对称加解密 81)。 + · 沙盒 APK 不再自带 `libQBDI.so`(重装后 `lib/arm64` 只剩 agent + fixtures),QBDI 只走模块投递。 + · 门禁:v88 由红转绿(错误文案去掉 `Dobby` 字面量,token 3→2);v02 在沙盒未运行时改为 SKIP 而不是 FAIL;新增 `verify_v130_scope_analyze.sh`(host,8/8)并注册;daemon typecheck 0、`npm test` 439 pass;`docs/mcp-tools.md` 由活 daemon 重生成(90 tools)。 + +- [x] **v0.8.1 可用性补丁(2026-11-12,针对 DH_Project 实战痛点的第一批修复)**: + · `maps_query`:maps 过滤(path/perm/exec/anon/size/limit)+ 地址解析(所属段 + 模块内文件偏移),回包带 `total/matched/returned/truncated`;真机 2737 段里 `libc.so` 命中 6 段,`0x704cca7010` 解析为 `libc.so` 区间 + `fileOffset=0x10`。 + · `oracle action:stability`:同一参数重复 replay(默认 3,夹紧 8),回答 stable/distinct/firstDiff/extract;真机 `java.lang.System.currentTimeMillis` 三次重放 → `stable=false, distinct=3`(时间依赖一眼可见,不用手写两遍比对)。 + · 错误码:抛异常与“返回 `{ok:false}`”两种失败形态统一补 `code`(BAD_ARG/NO_SESSION/SESSION_OFFLINE/AGENT_TIMEOUT/UNSUPPORTED_OP/TARGET_CRASHED/CAPTURE_LOSS/HELPER_MISSING/DEVICE_UNAVAILABLE/UNKNOWN);实测 `memory_write` 地址不带 0x、`native_hook` 缺 mode 均返回 `code:BAD_ARG`。 + · `pickSid` / `sessionForPackage` 改为主进程优先(旧实现 `.pop()` 可能落到渲染子进程且无提示,A10)。 + · 门禁:`npm run typecheck` 0;`npm test` **453 pass / 0 fail**(新增 14 条:错误分类、maps 过滤/解析、oracle stability、会话选择);`verify_v71` 91 tools / 0 problems;`verify_v130` 8/8;`docs/mcp-tools.md` 由活 daemon 重生成(91 tools)。 + --- ## 历史归档 v0.2–v1.0 的阶段状态与逐轮日志已移至 [`archive/PROGRESS_V0.2_V1.0.md`](archive/PROGRESS_V0.2_V1.0.md)。归档仅供追溯,不是当前计划或待办来源。 + + +- [x] **root_watch ??? + ????????2026-11-13?P0 ?????**? + ? ????????/VM ???????????????????????????? VM ?????? `[state+0x28]`?`[cursor]`????????????????????????????????????????? + ? ??? `tools/native/root_watch.c`?????? TID ??? 4 ?????? addr + `bp=ADDR:WIDTH:MODE` ?? 3 ??????? `bp` ????? 4 ????? `mem=[@]REG[+/-OFFSET][:LEN]`?x0..x30 / sp / lr / pc??? 16 ????? 256??collector ? `process_vm_readv`??? `/proc/pid/mem`??????????? `mem:[{spec,addr,hex|error}]`?????? `unreadable/null-pointer`????? + ? Host `daemon/src/root_watch.ts`?`breakpoints`??3?????/??/???? `mem`??4???????????? collector?????????MCP schema ??? + ? ?????????????? `base+0x1925c` + ?? `base+0x192fc` ??? + `mem=x13:16` / `@x12+0x40:8`??? `IL([38,...])` ?? 64 ???????????`bp=[0,1]`?`x13` ?????????? `cc58ae0c?`?Host ??? `startRootWatch/readRootWatch` ??????? 32 ???2 ???????? + ? ???`daemon npm run typecheck` 0?`node --test test/root_watch.test.ts` 3/3??? `tools/verify_v131_root_watch_mem.sh`?fixture App ???? SKIP??? unit ?? 3/3?? + ? ???????????????? ROM?`@deref` ?????????????????????? ptrace??? perf + root ???? + +- [ ] **P2 ???????????????trace_on_signal?2026-11-13?** + ? ??????????? patch ???????????????????????????????? + ???????????? VM handler ?????????? + ? ???agent ??????? SIGUSR2 handler?host ????????? `java_call IL(...)`??? `tgkill(pid, tid, SIGUSR2)`?handler ?????????? ucontext ? PC/SP/?????? QBDI?`setGPRState` + `run(pc, pc+limit)`???????????/?/??/??/????? N ???? 20000??? 200000???? ucontext ??? + ? ????? + - ?? handler ???????????????????? PC/?????????????QBDI ?????????????????????????? + - ????????/??handler ??????????????QBDI VM ??????? thread_local ??? + - ???????? VM ?????? PC ??????/???host ???????????????? + - ? root_watch ???root_watch ???????????/????trace_on_signal ?????? N ??? + ? ???sandbox ?????????`adh_add_target` ? Detection ? Java ????????????????pc ???????????????????????????????????????trace ?????? + ? ???QBDI ????/????????stopReason=ran-away????????????????????????????????????????? + + ? **??????2026-11-13?**?agent ???????????`agent/src/runtime/mem_read.c` ?? `sigaction`+`SA_SIGINFO` handler?SIGSEGV/SIGBUS??? fault ????`agent/src/trace/qbdi_trace.c` + `commands.c` ?? QBDI ???/??/??????????P2 ??????`SIGUSR2` handler?`SA_SIGINFO`?? `ucontext_t`???????? QBDI VM?`setGPRState` ? ucontext ? pc/sp ????????? ??? agent ???? `trace_hit`?? tid/limit/timebudget??host ? MCP ????????? ?docs/mcp-tools.md ?????????agent ?? 400?600 ? C?host ?? 150?250 ? TS??? sandbox ??? diff --git a/tools/MAP.md b/tools/MAP.md index c8ffa45..b67ba61 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -179,3 +179,6 @@ event-limit accounting, explicit stop and wrong-TID refusal. It does not run the - `build_crypto_variants.sh` — 构建变异算法检测的**靶子库**(`fixtures/crypto-variants/{std,variant}.c` → `fixtures/crypto-variants/build/libadhcrypto_{std,variant}.so`,NDK clang `--target=aarch64-linux-android26 -O0`)。两个库构成 A/B:`std` 是教科书常量(负对照),`variant` 携带参考仓库真实出货的那几种变异(MD5 init 被改写、SHA1 轮常量被改写、base64 码表被置换,另加运行时生成的码表与多项式)。**必须是编译产物**:检测器的全部主张就是"能从二进制真正含有的字节里认出变异",拿测试自己拼的 Buffer 去测只能证明测试会拼常量。`-O0` 是刻意的——优化会把表折进立即数,靶子就不再含有自己的常量了。 - `verify_v101_crypto_variants.sh` — **变异算法识别**(host):先跑 `daemon/test/crypto_variants.test.ts`(13 项,向量取自参考仓库的真实变异字节),再编译靶子并**经 daemon 的 REST 面**扫这两个库:负对照(教科书库必须一条 variant 判定都没有)→ MD5 变异(由未被改动的 K 表锚定、缺席的 init 作为证据、报告的 `12/16` 说明"标准 init 被原位改写")→ SHA1 变异(从**另一端**锚定:IV 未动、轮常量被改)→ 置换码表按**形状**找到且漂移量计数为 54 → CRC-32C 被如实报成"另一套标准"而非变异 → `limits` 三条(运行时生成的表、连锚点一起改的变异)**必须存在**(扫描器要说得出自己在哪瞎)。 最关键的一条断言是**度量出来的缺口**:旧的标准常量扫描对两个库返回**完全相同的算法名**(`status` 一样),而且在变异库上仍然报 `MD5-init`——那是 SHA1 init 的前 8 字节撞上的**假阳性**。即旧工具不是安静地瞎,是会主动误导;这条断言把"新层加了什么"钉成了可复跑的事实。 + + +- `verify_v131_root_watch_mem.sh` ? root_watch ?**??? + ???????**???device?fixture App ??? SKIP???? TID ? 2 ????????? `x0:8` ? `@x0:8`??? 4 ????`bp` ???? 0/1???????????????????? 0x1122? / 0x8877???? `root_watch.test.ts`?3 ????????? spec ????????? diff --git a/tools/native/root_watch.c b/tools/native/root_watch.c index eff4913..e2b6bc1 100644 --- a/tools/native/root_watch.c +++ b/tools/native/root_watch.c @@ -1,7 +1,14 @@ // Root-side collector. perf records the real target execution; no ptrace, app patch, // function replay, SELinux change, or in-process agent dependency is involved. +// +// 2026-11-13: a run may watch up to four hardware slots on the same thread and, on every +// event, snapshot small memory windows derived from the sampled registers. The second part +// is what makes a stateful VM tractable: the kernel record keeps the registers of the hit, +// and the collector reads the fields they point at *at the moment of the hit*, instead of +// leaving the caller to re-read memory after the target has moved on. #define _GNU_SOURCE #include +#include #include #include #include @@ -13,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +29,10 @@ // https://github.com/torvalds/linux/blob/v5.10/arch/arm64/include/uapi/asm/perf_regs.h #define REGS 33 // Linux arm64 perf ABI: x0..x29, lr, sp, pc (not pstate). #define PAGES 256 +#define MAX_BP 4 +#define MAX_MEM 4 +#define MAX_MEM_BYTES 256 + static volatile sig_atomic_t stopping; static void on_signal(int sig) { (void)sig; stopping = 1; } static int64_t millis(void) { @@ -43,7 +55,172 @@ static void ring_copy(void *out, const unsigned char *ring, size_t size, uint64_ } static uint64_t u64(const unsigned char *p) { uint64_t n; memcpy(&n, p, 8); return n; } +// ---- memory windows ------------------------------------------------------- +// Grammar: [@]REG[+/-OFFSET][:LEN] +// "x13:32" bytes at the address held in x13 +// "@x12+0x40:16" dereference (x12+0x40), then read 16 bytes at that pointer +// REG is x0..x30, sp, lr or pc. OFFSET accepts 0x.. or decimal. LEN defaults to 16. +struct memspec { char text[64]; int reg; int64_t off; int depth; unsigned len; }; +static struct memspec mems[MAX_MEM]; +static int mem_count; + +static int reg_of(const char *s, size_t n) { + if (n == 2 && s[0] == 'x' && s[1] >= '0' && s[1] <= '9') return s[1] - '0'; + if (n == 3 && s[0] == 'x' && s[1] >= '1' && s[1] <= '2' && s[2] >= '0' && s[2] <= '9') { + int v = (s[1] - '0') * 10 + (s[2] - '0'); + return v <= 30 ? v : -1; + } + if (n == 2 && !strncmp(s, "lr", 2)) return 30; + if (n == 2 && !strncmp(s, "sp", 2)) return 31; + if (n == 2 && !strncmp(s, "pc", 2)) return 32; + return -1; +} +static int parse_mem(const char *text) { + if (mem_count >= MAX_MEM || !text || !*text) return 0; + struct memspec m; memset(&m, 0, sizeof(m)); + snprintf(m.text, sizeof(m.text), "%s", text); + const char *p = text; + while (*p == '@' && m.depth < 2) { m.depth++; p++; } + const char *colon = strchr(p, ':'); + size_t head_len = colon ? (size_t)(colon - p) : strlen(p); + const char *sign = NULL; + for (size_t i = 0; i < head_len; i++) if (p[i] == '+' || p[i] == '-') { sign = p + i; break; } + size_t reg_len = sign ? (size_t)(sign - p) : head_len; + m.reg = reg_of(p, reg_len); + if (m.reg < 0) return 0; + if (sign) { + char *end = NULL; errno = 0; + m.off = strtoll(sign, &end, 0); + if (errno || !end || end != colon) return 0; + } + m.len = 16; + if (colon) { + char *end = NULL; errno = 0; + unsigned long v = strtoul(colon + 1, &end, 0); + if (errno || !end || *end || v == 0 || v > MAX_MEM_BYTES) return 0; + m.len = (unsigned)v; + } + mems[mem_count++] = m; + return 1; +} +// Root reading another process' memory is allowed on this product ROM; both routes are tried +// so an SELinux denial on one is reported as data, never as "no window". +static int read_target(pid_t pid, uint64_t addr, void *buf, size_t n) { + struct iovec local = { buf, n }, remote = { (void *)(uintptr_t)addr, n }; + if (process_vm_readv(pid, &local, 1, &remote, 1, 0) == (ssize_t)n) return 0; + char path[40]; snprintf(path, sizeof(path), "/proc/%d/mem", pid); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + ssize_t got = pread(fd, buf, n, (off_t)addr); + close(fd); + return got == (ssize_t)n ? 0 : -1; +} +static void print_hex(const unsigned char *b, size_t n) { + for (size_t i = 0; i < n; i++) printf("%02x", b[i]); +} + +// ---- one perf slot per breakpoint ---------------------------------------- +struct perfbp { + uint64_t addr; uint32_t width; uint32_t type; + int fd; size_t map_size, data_size; + struct perf_event_mmap_page *meta; + unsigned char *data; + struct pollfd pfd; +}; +static struct perfbp bps[MAX_BP]; +static int bp_count; + +static int open_bp(struct perfbp *b, pid_t tid, uint64_t addr, uint64_t width, uint32_t type, + uint64_t stack_bytes) { + struct perf_event_attr attr = {0}; + attr.type = PERF_TYPE_BREAKPOINT; attr.size = sizeof(attr); + attr.bp_type = type; attr.bp_addr = addr; attr.bp_len = width; + attr.sample_period = 1; + attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_ADDR | + PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER; + attr.sample_regs_user = (UINT64_C(1) << REGS) - 1; + if (stack_bytes) { attr.sample_type |= PERF_SAMPLE_STACK_USER; attr.sample_stack_user = stack_bytes; } + // mmap of a task event with inherit enabled is rejected on the reference kernel. + // The contract names ONE existing thread; never silently claim to cover new threads. + attr.inherit = 0; attr.disabled = 1; attr.exclude_kernel = 1; attr.exclude_hv = 1; attr.wakeup_events = 1; + int fd = syscall(__NR_perf_event_open, &attr, (int)tid, -1, -1, PERF_FLAG_FD_CLOEXEC); + if (fd < 0) return -1; + size_t page = (size_t)sysconf(_SC_PAGESIZE); + size_t data_size = page * PAGES, map_size = data_size + page; + struct perf_event_mmap_page *meta = mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (meta == MAP_FAILED) { int err = errno; close(fd); errno = err; return -1; } + b->addr = addr; b->width = (uint32_t)width; b->type = type; + b->fd = fd; b->map_size = map_size; b->data_size = data_size; b->meta = meta; + b->data = (unsigned char *)meta + page; + b->pfd.fd = fd; b->pfd.events = POLLIN; b->pfd.revents = 0; + return 0; +} +static void close_bp(struct perfbp *b) { + if (b->fd >= 0) { (void)ioctl(b->fd, PERF_EVENT_IOC_DISABLE, 0); munmap(b->meta, b->map_size); close(b->fd); } + b->fd = -1; +} + +static void emit_mem(pid_t pid, const uint64_t *regs) { + if (!mem_count) return; + printf(",\"mem\":["); + for (int i = 0; i < mem_count; i++) { + struct memspec *m = &mems[i]; + uint64_t addr = (uint64_t)((int64_t)regs[m->reg] + m->off); + const char *err = NULL; + for (int d = 0; d < m->depth && !err; d++) { + uint64_t ptr = 0; + if (read_target(pid, addr, &ptr, 8)) err = "unreadable-pointer"; + else if (!ptr) err = "null-pointer"; + else addr = ptr; + } + unsigned char buf[MAX_MEM_BYTES]; + if (!err && read_target(pid, addr, buf, m->len)) err = "unreadable"; + printf("%s{\"spec\":\"%s\",\"addr\":\"0x%llx\"", i ? "," : "", m->text, (unsigned long long)addr); + if (err) printf(",\"error\":\"%s\"}", err); + else { printf(",\"hex\":\""); print_hex(buf, m->len); printf("\"}"); } + } + printf("]"); +} + static volatile uint64_t fixture_value; +static volatile uint64_t fixture_ptr; +static int handle_sample(int bp_index, unsigned char *body, size_t n, + pid_t pid, pid_t tid, uint64_t stack_bytes, uint64_t *samples, + int self_test, uint64_t *self_ok, uint64_t addr) { + if (n < 40) return 0; + uint64_t ip = u64(body), time_ns = u64(body + 16), address = u64(body + 24), count = u64(body + 32); + uint32_t sample_pid, sample_tid; memcpy(&sample_pid, body + 8, 4); memcpy(&sample_tid, body + 12, 4); + if (count > (n - 40) / 8 || (pid_t)sample_pid != pid || (pid_t)sample_tid != tid) return 0; + size_t regoff = 40 + (size_t)count * 8; + if (regoff + 8 + REGS * 8 > n || u64(body + regoff) != PERF_SAMPLE_REGS_ABI_64) return 0; + uint64_t regs[REGS]; memcpy(regs, body + regoff + 8, sizeof(regs)); + size_t stackoff = regoff + 8 + sizeof(regs); uint64_t captured = 0, reserved = 0; + if (stack_bytes) { + if (stackoff + 8 > n) return 0; + reserved = u64(body + stackoff); + if (reserved > stack_bytes || reserved > n - stackoff - 8 || + (reserved && stackoff + 8 + reserved + 8 > n)) return 0; + if (reserved) captured = u64(body + stackoff + 8 + reserved); + if (captured > reserved) return 0; + } + (*samples)++; + printf("{\"seq\":%llu,\"bp\":%d,\"ip\":\"0x%llx\",\"pid\":%u,\"tid\":%u,\"timeNs\":\"%llu\",\"addr\":\"0x%llx\",\"regs\":[", + (unsigned long long)*samples, bp_index, (unsigned long long)ip, sample_pid, sample_tid, + (unsigned long long)time_ns, (unsigned long long)address); + for (int j = 0; j < REGS; j++) printf("%s\"0x%llx\"", j ? "," : "", (unsigned long long)regs[j]); + printf("],\"chain\":["); + size_t emitted_chain = count < 64 ? (size_t)count : 64; + for (size_t j = 0; j < emitted_chain; j++) printf("%s\"0x%llx\"", j ? "," : "", (unsigned long long)u64(body + 40 + j * 8)); + printf("],\"chainTruncated\":%s", count > 64 ? "true" : "false"); + emit_mem(pid, regs); + printf(",\"stack\":{\"addr\":\"0x%llx\",\"requested\":%llu,\"got\":%llu,\"hex\":\"", + (unsigned long long)regs[31], (unsigned long long)stack_bytes, (unsigned long long)captured); + for (size_t j = 0; j < captured; j++) printf("%02x", body[stackoff + 8 + j]); + puts("\"}}"); fflush(stdout); + if (self_test && regs[0] == addr && regs[1] == (uint64_t)(uintptr_t)&fixture_value) *self_ok = 1; + return 1; +} + __attribute__((naked, noinline)) static void fixture(volatile uint64_t *p, uint64_t value) { __asm__ volatile("str x1, [x0]\nret"); } @@ -53,25 +230,32 @@ int main(int argc, char **argv) { if (geteuid() != 0) { errno = EPERM; return fail("root-required"); } uint64_t pid, tid, addr, width, duration, maximum, stack_bytes; const char *stop_file = NULL; - int type, test_child = -1, gate[2] = {-1, -1}; + uint32_t type; + int test_child = -1, gate[2] = {-1, -1}; int self_test = argc == 2 && !strcmp(argv[1], "--self-test"); + int first_extra = argc; if (self_test) { if (pipe(gate)) return fail("self-test-pipe"); test_child = fork(); if (test_child < 0) return fail("self-test-fork"); if (!test_child) { close(gate[1]); char b; - if (read(gate[0], &b, 1) == 1) fixture(&fixture_value, UINT64_C(0x1122334455667788)); + if (read(gate[0], &b, 1) == 1) { fixture(&fixture_value, UINT64_C(0x1122334455667788)); fixture(&fixture_ptr, (uint64_t)(uintptr_t)&fixture_value); } close(gate[0]); usleep(200000); _exit(0); } close(gate[0]); gate[0] = -1; - pid = tid = (uint64_t)test_child; addr = (uintptr_t)&fixture_value; + pid = tid = (uint64_t)test_child; addr = (uintptr_t)&fixture_ptr; width = 8; duration = 1000; maximum = 2; stack_bytes = 256; type = HW_BREAKPOINT_W; + // Self-test also proves the memory-window path: the fixture stores a known + // value at a known address, so a window on x0 must read it back. + if (!parse_mem("x0:8")) return fail("self-test-mem"); + if (!parse_mem("@@x0:8")) return fail("self-test-mem2"); + first_extra = 2; } else { - if ((argc != 9 && argc != 10) || !number(argv[1], &pid) || !number(argv[2], &tid) || + if (argc < 9 || !number(argv[1], &pid) || !number(argv[2], &tid) || !number(argv[3], &addr) || !number(argv[4], &width) || !number(argv[6], &duration) || !number(argv[7], &maximum) || !number(argv[8], &stack_bytes)) { - fprintf(stderr, "usage: adh-root-watch PID TID ADDRESS WIDTH w|r|rw|x DURATION_MS MAX_EVENTS STACK_BYTES\n"); + fprintf(stderr, "usage: adh-root-watch PID TID ADDRESS WIDTH w|r|rw|x DURATION_MS MAX_EVENTS STACK_BYTES [STOP_FILE] [bp=ADDR:WIDTH:MODE] [mem=SPEC]\n"); return 2; } type = !strcmp(argv[5], "w") ? HW_BREAKPOINT_W : !strcmp(argv[5], "r") ? HW_BREAKPOINT_R : @@ -80,14 +264,17 @@ int main(int argc, char **argv) { !(width == 1 || width == 2 || width == 4 || width == 8) || addr % width || (type == HW_BREAKPOINT_X && width != 4) || duration < 1 || duration > 30000 || maximum < 1 || maximum > 2048 || stack_bytes > 16384 || stack_bytes % 8) return 2; - if (argc == 10) { + int at = 9; + if (argc > at && strncmp(argv[at], "bp=", 3) && strncmp(argv[at], "mem=", 4)) { const char *prefix = "/data/local/tmp/adh-root-watch-stop-"; size_t prefix_len = strlen(prefix); - if (strncmp(argv[9], prefix, prefix_len) || strlen(argv[9] + prefix_len) != 36) return 2; - for (const char *p = argv[9] + prefix_len; *p; p++) + if (strncmp(argv[at], prefix, prefix_len) || strlen(argv[at] + prefix_len) != 36) return 2; + for (const char *p = argv[at] + prefix_len; *p; p++) if (!((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || *p == '-')) return 2; - stop_file = argv[9]; + stop_file = argv[at]; + at++; } + first_extra = at; char path[80], line[256]; snprintf(path, sizeof(path), "/proc/%llu/status", (unsigned long long)tid); FILE *f = fopen(path, "r"); if (!f) return fail("thread-status"); unsigned long owner = 0; @@ -95,96 +282,97 @@ int main(int argc, char **argv) { fclose(f); if (owner != pid) { errno = EINVAL; return fail("tid-does-not-belong-to-pid"); } } - struct perf_event_attr attr = {0}; - attr.type = PERF_TYPE_BREAKPOINT; attr.size = sizeof(attr); - attr.bp_type = type; attr.bp_addr = addr; attr.bp_len = width; - attr.sample_period = 1; - attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_ADDR | - PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER; - attr.sample_regs_user = (UINT64_C(1) << REGS) - 1; - if (stack_bytes) { attr.sample_type |= PERF_SAMPLE_STACK_USER; attr.sample_stack_user = stack_bytes; } - // mmap of a task event with inherit enabled is rejected on the reference kernel. - // The contract names ONE existing thread; never silently claim to cover new threads. - attr.inherit = 0; attr.disabled = 1; attr.exclude_kernel = 1; attr.exclude_hv = 1; attr.wakeup_events = 1; - int fd = syscall(__NR_perf_event_open, &attr, (int)tid, -1, -1, PERF_FLAG_FD_CLOEXEC); - if (fd < 0) { if (test_child > 0) { close(gate[1]); waitpid(test_child, 0, 0); } return fail("perf_event_open"); } - size_t page = (size_t)sysconf(_SC_PAGESIZE), data_size = page * PAGES, map_size = data_size + page; - struct perf_event_mmap_page *meta = mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (meta == MAP_FAILED) { int err = errno; close(fd); errno = err; return fail("mmap"); } + bps[0].addr = addr; bps[0].width = (uint32_t)width; bps[0].type = type; bps[0].fd = -1; + bp_count = 1; + for (int i = first_extra; i < argc; i++) { + const char *arg = argv[i]; + if (!strncmp(arg, "mem=", 4)) { + if (!parse_mem(arg + 4)) { fprintf(stderr, "bad mem spec: %s\n", arg + 4); return 2; } + } else if (!strncmp(arg, "bp=", 3)) { + if (bp_count >= MAX_BP) { fprintf(stderr, "at most %d breakpoints\n", MAX_BP); return 2; } + char *p = (char *)arg + 3, *c1 = strchr(p, ':'); + if (!c1) { fprintf(stderr, "bad bp spec: %s\n", arg); return 2; } + *c1 = 0; char *c2 = strchr(c1 + 1, ':'); + if (!c2) { fprintf(stderr, "bad bp spec: %s\n", arg); return 2; } + *c2 = 0; + uint64_t a2, w2; + if (!number(p, &a2) || !number(c1 + 1, &w2)) return 2; + uint32_t t2 = !strcmp(c2 + 1, "w") ? HW_BREAKPOINT_W : !strcmp(c2 + 1, "r") ? HW_BREAKPOINT_R : + !strcmp(c2 + 1, "rw") ? HW_BREAKPOINT_RW : !strcmp(c2 + 1, "x") ? HW_BREAKPOINT_X : 0; + if (!a2 || !t2 || !(w2 == 1 || w2 == 2 || w2 == 4 || w2 == 8) || a2 % w2 || + (t2 == HW_BREAKPOINT_X && w2 != 4)) { fprintf(stderr, "bad bp spec\n"); return 2; } + bps[bp_count].addr = a2; bps[bp_count].width = (uint32_t)w2; bps[bp_count].type = t2; + bps[bp_count].fd = -1; bp_count++; + } else { fprintf(stderr, "unknown extra arg: %s\n", arg); return 2; } + } + // perf exposes a small number of hardware slots per thread; fail loud rather than + // silently dropping the slots that did not fit. + for (int i = 0; i < bp_count; i++) { + if (open_bp(&bps[i], (pid_t)tid, bps[i].addr, bps[i].width, bps[i].type, stack_bytes)) { + int err = errno; + for (int j = 0; j < i; j++) close_bp(&bps[j]); + if (test_child > 0) { close(gate[1]); waitpid(test_child, 0, 0); } + errno = err; + return fail(i == 0 ? "perf_event_open" : "perf_event_open_extra"); + } + } signal(SIGTERM, on_signal); signal(SIGINT, on_signal); - if (ioctl(fd, PERF_EVENT_IOC_ENABLE, 0)) { int err = errno; munmap(meta, map_size); close(fd); errno = err; return fail("enable"); } - printf("{\"ready\":true,\"version\":\"%s\",\"collectorPid\":%d,\"pid\":%llu,\"tid\":%llu}\n", - VERSION, getpid(), (unsigned long long)pid, (unsigned long long)tid); fflush(stdout); + for (int i = 0; i < bp_count; i++) + if (ioctl(bps[i].fd, PERF_EVENT_IOC_ENABLE, 0)) { + for (int j = 0; j < bp_count; j++) close_bp(&bps[j]); + return fail("enable"); + } + printf("{\"ready\":true,\"version\":\"%s\",\"collectorPid\":%d,\"pid\":%llu,\"tid\":%llu,\"breakpoints\":%d,\"mem\":%d}\n", + VERSION, getpid(), (unsigned long long)pid, (unsigned long long)tid, bp_count, mem_count); + fflush(stdout); if (self_test) { (void)write(gate[1], "x", 1); close(gate[1]); gate[1] = -1; } - unsigned char *data = (unsigned char *)meta + page; uint64_t samples = 0, lost = 0, throttles = 0, malformed = 0; - int self_ok = 0; int64_t until = millis() + (int64_t)duration; - struct pollfd pollfd = {fd, POLLIN, 0}; + uint64_t self_ok = 0; int64_t until = millis() + (int64_t)duration; int disabled = 0, thread_exited = 0; for (;;) { if (stop_file && access(stop_file, F_OK) == 0) stopping = 1; if (!disabled && (stopping || millis() >= until || samples >= maximum)) { - if (ioctl(fd, PERF_EVENT_IOC_DISABLE, 0)) malformed++; + for (int i = 0; i < bp_count; i++) if (ioctl(bps[i].fd, PERF_EVENT_IOC_DISABLE, 0)) malformed++; disabled = 1; } // Disable BEFORE the last drain. Otherwise a final write can land between // the last head snapshot and close(), while the report says complete. - int rc = disabled ? 0 : poll(&pollfd, 1, 50); - if (rc < 0 && errno != EINTR) { malformed++; break; } - if (!disabled && (pollfd.revents & (POLLHUP | POLLERR))) { - if (pollfd.revents & POLLERR) malformed++; - thread_exited = (pollfd.revents & POLLHUP) != 0; - (void)ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); - disabled = 1; + int rc = 0; + if (!disabled) { + rc = poll(&bps[0].pfd, (nfds_t)bp_count, 50); + if (rc < 0 && errno != EINTR) { malformed++; break; } + for (int i = 0; i < bp_count; i++) { + if (bps[i].pfd.revents & (POLLHUP | POLLERR)) { + if (bps[i].pfd.revents & POLLERR) malformed++; + thread_exited |= (bps[i].pfd.revents & POLLHUP) != 0; + for (int j = 0; j < bp_count; j++) (void)ioctl(bps[j].fd, PERF_EVENT_IOC_DISABLE, 0); + disabled = 1; + } + } } - uint64_t head = __atomic_load_n(&meta->data_head, __ATOMIC_ACQUIRE), tail = meta->data_tail; - if (head - tail > data_size) { malformed++; tail = head; } - while (tail < head && samples < maximum) { - struct perf_event_header h; ring_copy(&h, data, data_size, tail, sizeof(h)); - if (h.size < sizeof(h) || h.size > data_size || h.size > head - tail) { malformed++; tail = head; break; } - unsigned char body[32768]; size_t n = h.size - sizeof(h); - if (n > sizeof(body)) { malformed++; tail += h.size; continue; } - ring_copy(body, data, data_size, tail + sizeof(h), n); - if (h.type == PERF_RECORD_LOST && n >= 16) lost += u64(body + 8); - else if (h.type == PERF_RECORD_THROTTLE) throttles++; - else if (h.type == PERF_RECORD_SAMPLE) { - if (n < 40) { malformed++; tail += h.size; continue; } - uint64_t ip = u64(body), time_ns = u64(body + 16), address = u64(body + 24), count = u64(body + 32); - uint32_t sample_pid, sample_tid; memcpy(&sample_pid, body + 8, 4); memcpy(&sample_tid, body + 12, 4); - if (count > (n - 40) / 8 || sample_pid != pid || sample_tid != tid) { malformed++; tail += h.size; continue; } - size_t regoff = 40 + (size_t)count * 8; - if (regoff + 8 + REGS * 8 > n || u64(body + regoff) != PERF_SAMPLE_REGS_ABI_64) { malformed++; tail += h.size; continue; } - uint64_t regs[REGS]; memcpy(regs, body + regoff + 8, sizeof(regs)); - size_t stackoff = regoff + 8 + sizeof(regs); uint64_t captured = 0, reserved = 0; - if (stack_bytes) { - if (stackoff + 8 > n) { malformed++; tail += h.size; continue; } - reserved = u64(body + stackoff); - if (reserved > stack_bytes || reserved > n - stackoff - 8 || - (reserved && stackoff + 8 + reserved + 8 > n)) { malformed++; tail += h.size; continue; } - if (reserved) captured = u64(body + stackoff + 8 + reserved); - if (captured > reserved) { malformed++; tail += h.size; continue; } + for (int i = 0; i < bp_count; i++) { + struct perfbp *b = &bps[i]; + uint64_t head = __atomic_load_n(&b->meta->data_head, __ATOMIC_ACQUIRE), tail = b->meta->data_tail; + if (head - tail > b->data_size) { malformed++; tail = head; } + while (tail < head && samples < maximum) { + struct perf_event_header h; ring_copy(&h, b->data, b->data_size, tail, sizeof(h)); + if (h.size < sizeof(h) || h.size > b->data_size || h.size > head - tail) { malformed++; tail = head; break; } + unsigned char body[32768]; size_t n = h.size - sizeof(h); + if (n > sizeof(body)) { malformed++; tail += h.size; continue; } + ring_copy(body, b->data, b->data_size, tail + sizeof(h), n); + if (h.type == PERF_RECORD_LOST && n >= 16) lost += u64(body + 8); + else if (h.type == PERF_RECORD_THROTTLE) throttles++; + else if (h.type == PERF_RECORD_SAMPLE) { + if (!handle_sample(i, body, n, (pid_t)pid, (pid_t)tid, stack_bytes, + &samples, self_test, &self_ok, addr)) { /* skipped */ } } - samples++; - printf("{\"seq\":%llu,\"ip\":\"0x%llx\",\"pid\":%u,\"tid\":%u,\"timeNs\":\"%llu\",\"addr\":\"0x%llx\",\"regs\":[", - (unsigned long long)samples, (unsigned long long)ip, sample_pid, sample_tid, - (unsigned long long)time_ns, (unsigned long long)address); - for (int j = 0; j < REGS; j++) printf("%s\"0x%llx\"", j ? "," : "", (unsigned long long)regs[j]); - printf("],\"chain\":["); - size_t emitted_chain = count < 64 ? (size_t)count : 64; - for (size_t j = 0; j < emitted_chain; j++) printf("%s\"0x%llx\"", j ? "," : "", (unsigned long long)u64(body + 40 + j * 8)); - printf("],\"chainTruncated\":%s,\"stack\":{\"addr\":\"0x%llx\",\"requested\":%llu,\"got\":%llu,\"hex\":\"", - count > 64 ? "true" : "false", (unsigned long long)regs[31], - (unsigned long long)stack_bytes, (unsigned long long)captured); - for (size_t j = 0; j < captured; j++) printf("%02x", body[stackoff + 8 + j]); - puts("\"}}"); fflush(stdout); - if (self_test && regs[0] == addr && regs[1] == UINT64_C(0x1122334455667788)) self_ok = 1; + tail += h.size; } - tail += h.size; + __atomic_store_n(&b->meta->data_tail, tail, __ATOMIC_RELEASE); } - __atomic_store_n(&meta->data_tail, tail, __ATOMIC_RELEASE); if (disabled) break; } - (void)ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); munmap(meta, map_size); close(fd); + for (int i = 0; i < bp_count; i++) close_bp(&bps[i]); if (stop_file) (void)unlink(stop_file); if (test_child > 0) waitpid(test_child, NULL, 0); int capped = samples >= maximum; diff --git a/tools/verify_v131_root_watch_mem.sh b/tools/verify_v131_root_watch_mem.sh new file mode 100644 index 0000000..3c4ef4b --- /dev/null +++ b/tools/verify_v131_root_watch_mem.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Root-side hardware observation with extra slots and memory windows. +# The acceptance signal is the collector reading the bytes the sampled registers point at, +# at the moment of the hit, on a real thread - not a later re-read of a changed buffer. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/verify_common.sh" +verify_resolve_env +verify_unit_pass 'root watch memory windows' root_watch.test.ts 3 || exit 1 +cd "$ROOT" +if ! node --input-type=module - "$BASE" "$SERIAL" "$ROOT" <<'EOF' +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { pickSession } from './daemon/src/cli.ts'; +const [base, serial, repo] = process.argv.slice(2); +const skip = reason => { console.log(`SKIP verify_v131_root_watch_mem (${reason})`); process.exit(0); }; +if (!serial || !existsSync(join(repo, 'agent/build/adh-root-watch'))) skip('device and built root collector required'); +const adb = args => { const r = spawnSync('adb', ['-s', serial, ...args], { encoding: 'utf8', timeout: 20000, windowsHide: true }); if (r.error || r.status !== 0) throw new Error(String(r.error ?? r.stderr)); return r.stdout.trim(); }; +if (adb(['shell', 'su', '-c', 'id -u']) !== '0') skip('rooted verification device required'); +const agents = await (await fetch(`${base}/api/agents`)).json(); +if (!agents.some(a => a.online && a.package === 'com.adh.nativefixture')) skip('no online dedicated native verification host; never starts another process'); +const target = pickSession(agents, 'com.adh.nativefixture', process.env.ADH_TEST_SESSION); +if (!target.starttimeTicks) skip('current agent hello starttimeTicks required'); +const call = async (name, args = {}) => { + const res = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: { session: target.sessionId, ...args } } }) }); + const r = await res.json(); if (r.error) throw new Error(JSON.stringify(r.error)); + const text = r.result?.content?.find(c => c.type === 'text')?.text; + if (r.result?.isError) throw new Error(text); + const value = JSON.parse(text); if (value.ok === false) throw new Error(JSON.stringify(value)); return value; +}; +const uint = r => BigInt(r.result ?? r.resultDecimal); +const prepare = await call('root_watch', { action: 'prepare', serial }); +assert.equal(prepare.selfTest.selfTest, true); +const lib = `/data/local/tmp/verify-v131-${Date.now()}.so`; +adb(['push', join(repo, 'agent/build/libadh_native_controls.so'), lib]); +await call('load_library', { path: lib }); +const module = lib.split('/').at(-1); +const native = symbol => call('native_call', { module, symbol, args: [], confirm: true }); +const tid = Number(uint(await native('adh_watch_start'))); +const address = '0x' + uint(await native('adh_watch_address')).toString(16); +assert.notEqual(address, '0x0'); +const run = await call('root_watch', { + action: 'start', serial, tid, addr: address, width: 8, mode: 'w', durationMs: 3000, maxEvents: 8, stackBytes: 0, + breakpoints: [{ addr: address, width: 8, mode: 'w' }], + mem: ['x0:8', '@x0:8'], +}); +// A daemon that predates this slice drops the new arguments; refuse to pretend it verified them. +if (!run.breakpoints || !run.mem) { + await call('root_watch', { action: 'stop', id: run.id }).catch(() => {}); + skip('running daemon predates root_watch memory windows; restart the Host ADH Daemon and rerun'); +} +assert.deepEqual(run.breakpoints, [`bp=${address}:8:w`]); +assert.deepEqual(run.mem, ['x0:8', '@x0:8']); +await native('adh_watch_trigger'); +let status; +for (let i = 0; i < 120; i++) { status = await call('root_watch', { action: 'status', id: run.id }); if (!status.running) break; await new Promise(r => setTimeout(r, 50)); } +assert.equal(status.error, undefined); +assert.equal(status.summary.samples, 4, 'two writes x two hardware slots'); +assert.equal(status.summary.malformed, 0); +const page = await call('root_watch', { action: 'read', id: run.id, limit: 32 }); +assert.equal(page.events.length, 4); +assert.deepEqual([...new Set(page.events.map(e => e.bp))].sort(), [0, 1]); +const expected = ['8877665544332211', '1122334455667788']; +for (const event of page.events) { + assert.equal(event.regs, undefined, 'registers must stay opt-in'); + assert.equal(event.mem.length, 2); + assert.equal(event.mem[0].spec, 'x0:8'); + assert.equal(event.mem[0].addr, address, 'x0 held the watched address at the hit'); + assert.equal(event.mem[1].spec, '@x0:8'); + assert.equal(event.mem[1].addr, address, 'the dereferenced window is the same buffer'); + assert.ok(expected.includes(event.mem[1].hex), `unexpected stored value ${event.mem[1].hex}`); +} +console.log(`PASS verify_v131_root_watch_mem (${page.events.length} events, 2 slots, 2 memory windows, values ${expected.join('/')})`); +EOF +then + exit 1 +fi From a8ec3703a0b50e20ae5a90abc84aa5f46b067e08 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 13 Nov 2026 16:18:46 +0800 Subject: [PATCH 03/24] =?UTF-8?q?test:=20root=5Fwatch=20=E8=87=AA=E6=A3=80?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E8=AF=BB=E6=96=AD=E7=82=B9=E4=B8=8E=E4=B8=A4?= =?UTF-8?q?=E7=BA=A7=E8=A7=A3=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/native/root_watch.c | 14 +++++++++++--- tools/verify_v126_root_watch_native.sh | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/tools/native/root_watch.c b/tools/native/root_watch.c index e2b6bc1..481f41d 100644 --- a/tools/native/root_watch.c +++ b/tools/native/root_watch.c @@ -218,12 +218,16 @@ static int handle_sample(int bp_index, unsigned char *body, size_t n, for (size_t j = 0; j < captured; j++) printf("%02x", body[stackoff + 8 + j]); puts("\"}}"); fflush(stdout); if (self_test && regs[0] == addr && regs[1] == (uint64_t)(uintptr_t)&fixture_value) *self_ok = 1; + if (self_test && bp_index == 1) *self_ok |= 2; return 1; } __attribute__((naked, noinline)) static void fixture(volatile uint64_t *p, uint64_t value) { __asm__ volatile("str x1, [x0]\nret"); } +__attribute__((naked, noinline)) static void fixture_load(volatile uint64_t *p) { + __asm__ volatile("ldr x0, [x0]\nret"); +} int main(int argc, char **argv) { if (argc == 2 && !strcmp(argv[1], "--version")) { puts(VERSION); return 0; } @@ -233,6 +237,7 @@ int main(int argc, char **argv) { uint32_t type; int test_child = -1, gate[2] = {-1, -1}; int self_test = argc == 2 && !strcmp(argv[1], "--self-test"); + int self_test_read = 0; int first_extra = argc; if (self_test) { if (pipe(gate)) return fail("self-test-pipe"); @@ -240,16 +245,18 @@ int main(int argc, char **argv) { if (test_child < 0) return fail("self-test-fork"); if (!test_child) { close(gate[1]); char b; - if (read(gate[0], &b, 1) == 1) { fixture(&fixture_value, UINT64_C(0x1122334455667788)); fixture(&fixture_ptr, (uint64_t)(uintptr_t)&fixture_value); } + if (read(gate[0], &b, 1) == 1) { fixture(&fixture_value, UINT64_C(0x1122334455667788)); fixture(&fixture_ptr, (uint64_t)(uintptr_t)&fixture_value); fixture_load(&fixture_value); } close(gate[0]); usleep(200000); _exit(0); } close(gate[0]); gate[0] = -1; pid = tid = (uint64_t)test_child; addr = (uintptr_t)&fixture_ptr; - width = 8; duration = 1000; maximum = 2; stack_bytes = 256; type = HW_BREAKPOINT_W; + width = 8; duration = 1000; maximum = 3; stack_bytes = 256; type = HW_BREAKPOINT_W; // Self-test also proves the memory-window path: the fixture stores a known // value at a known address, so a window on x0 must read it back. if (!parse_mem("x0:8")) return fail("self-test-mem"); if (!parse_mem("@@x0:8")) return fail("self-test-mem2"); + + self_test_read = 1; first_extra = 2; } else { if (argc < 9 || !number(argv[1], &pid) || !number(argv[2], &tid) || @@ -284,6 +291,7 @@ int main(int argc, char **argv) { } bps[0].addr = addr; bps[0].width = (uint32_t)width; bps[0].type = type; bps[0].fd = -1; bp_count = 1; + if (self_test_read) { bps[1].addr = (uintptr_t)&fixture_value; bps[1].width = 8; bps[1].type = HW_BREAKPOINT_R; bps[1].fd = -1; bp_count = 2; } for (int i = first_extra; i < argc; i++) { const char *arg = argv[i]; if (!strncmp(arg, "mem=", 4)) { @@ -380,5 +388,5 @@ int main(int argc, char **argv) { (unsigned long long)samples, (unsigned long long)lost, (unsigned long long)throttles, (unsigned long long)malformed, !lost && !throttles && !malformed && !capped && !stopping ? "true" : "false", stopping ? "stopped" : capped ? "event-limit" : thread_exited ? "thread-exited" : "time-budget", self_test ? (self_ok ? "true" : "false") : "null"); - return self_test && !self_ok ? 1 : 0; + return self_test && self_ok != 3 ? 1 : 0; } diff --git a/tools/verify_v126_root_watch_native.sh b/tools/verify_v126_root_watch_native.sh index a9f5e03..1f03ec8 100644 --- a/tools/verify_v126_root_watch_native.sh +++ b/tools/verify_v126_root_watch_native.sh @@ -41,7 +41,7 @@ try{ adb(['push',fixture,lib]); await call('load_library',{path:lib}); const prepared=await root({action:'prepare',serial}); - assert.equal(prepared.selfTest.selfTest,true);assert.equal(prepared.selfTest.complete,true);assert.equal(prepared.selfTest.samples,1); + assert.equal(prepared.selfTest.selfTest,true);assert.equal(prepared.selfTest.complete,true);assert.ok(prepared.selfTest.samples>=2); const tid=Number(uint(await native('adh_watch_start')));started=true; assert.ok(Number.isSafeInteger(tid)&&tid>0); const address='0x'+uint(await native('adh_watch_address')).toString(16); From cdb9c3181c4ee731c5b2b29c2137afdb7ed39679 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 13 Nov 2026 16:19:11 +0800 Subject: [PATCH 04/24] =?UTF-8?q?fix:=20root=5Fwatch=20prepare=20=E8=87=AA?= =?UTF-8?q?=E6=A3=80=E6=9C=9F=E6=9C=9B=E4=B8=A4=E6=9D=A1=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=EF=BC=88=E8=AF=BB+=E5=86=99=E6=A7=BD=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/src/root_watch.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/daemon/src/root_watch.ts b/daemon/src/root_watch.ts index 0b051fb..bf24f2a 100644 --- a/daemon/src/root_watch.ts +++ b/daemon/src/root_watch.ts @@ -93,7 +93,7 @@ export async function prepareRootWatch(requested?: string) { if (version !== VERSION) throw new Error(`Unexpected root collector version: ${version}`); const text = await adb(serial, ['shell', 'su', '-c', `${HELPER} --self-test`]); const result = text.trim().split(/\r?\n/).map(line => JSON.parse(line)).at(-1); - if (result?.selfTest !== true || result?.complete !== true || result?.samples !== 1) throw new Error(`Root watch self-test failed: ${JSON.stringify(result)}`); + if (result?.selfTest !== true || result?.complete !== true || typeof result?.samples !== "number" || result.samples < 2) throw new Error(`Root watch self-test failed: ${JSON.stringify(result)}`); return { ok: true, serial, version, sha256: createHash('sha256').update(readFileSync(localHelper)).digest('hex'), selfTest: result }; } export async function startRootWatch(target: Target, a: Record, dataDir: string) { From 49949fc52d3105a240797803ccba6d574a849803 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 13 Nov 2026 16:48:13 +0800 Subject: [PATCH 05/24] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20root=20?= =?UTF-8?q?=E4=BE=A7=E5=8D=95=E6=AD=A5=E8=BF=BD=E8=B8=AA=E5=99=A8=EF=BC=88?= =?UTF-8?q?ptrace=20=E5=8D=95=E6=AD=A5=20+=20=E8=BD=AF=E6=96=AD=E7=82=B9?= =?UTF-8?q?=E5=AF=B9=E9=BD=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/build_root_step.sh | 9 ++ tools/native/root_step.c | 198 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 tools/build_root_step.sh create mode 100644 tools/native/root_step.c diff --git a/tools/build_root_step.sh b/tools/build_root_step.sh new file mode 100644 index 0000000..1bfba97 --- /dev/null +++ b/tools/build_root_step.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/env.sh" +test -n "$ADH_NDK_BIN" || { echo 'No host NDK toolchain; set ANDROID_NDK_HOME' >&2; exit 1; } +case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) compiler="$ADH_NDK_BIN/clang.exe" ;; *) compiler="$ADH_NDK_BIN/clang" ;; esac +mkdir -p "$ROOT/agent/build" +"$compiler" --target=aarch64-linux-android26 -O2 -Wall -Wextra -Werror \ + "$ROOT/tools/native/root_step.c" -o "$ROOT/agent/build/adh-root-step" +echo 'Built agent/build/adh-root-step (arm64-v8a; root-side single-step tracer)' \ No newline at end of file diff --git a/tools/native/root_step.c b/tools/native/root_step.c new file mode 100644 index 0000000..89a95a5 --- /dev/null +++ b/tools/native/root_step.c @@ -0,0 +1,198 @@ +// Root-side single-step tracer. Attaches to one EXISTING thread with ptrace, steps it +// one instruction at a time and records the program counter, the stack pointer and the +// integer argument registers before each step. This is the out-of-process answer to "what +// does this code actually execute": no agent, no code patching, no function replay. +// +// Honest limits, because they decide whether a trace is trustworthy: +// * ptrace sets TracerPid, so a target that inspects itself can see the tracer; +// * only the named TID is traced, and it must belong to PID; +// * a step budget and a wall-clock budget are always enforced; +// * the trace is a prefix: when the budget is reached the thread is detached and the +// reply says complete:false. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define VERSION "ADH_ROOT_STEP_V1" +#ifndef NT_PRSTATUS +#define NT_PRSTATUS 1 +#endif +#define MAX_STEPS 200000 + +// aarch64 NT_PRSTATUS payload (struct user_pt_regs). +struct pt_regs { + uint64_t regs[31]; + uint64_t sp; + uint64_t pc; + uint64_t pstate; +}; + +static int64_t millis(void) { + struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); + return t.tv_sec * 1000LL + t.tv_nsec / 1000000; +} +static int fail(const char *stage) { + printf("{\"ready\":false,\"stage\":\"%s\",\"errno\":%d,\"error\":\"%s\"}\n", stage, errno, strerror(errno)); + return 1; +} +static int number(const char *s, uint64_t *out) { + if (!s || !*s || *s == '-' || *s == '+') return 0; + char *end; errno = 0; *out = strtoull(s, &end, 0); + return !errno && end != s && !*end; +} +static int read_target(pid_t pid, uint64_t addr, void *buf, size_t n) { + struct iovec local = { buf, n }, remote = { (void *)(uintptr_t)addr, n }; + if (process_vm_readv(pid, &local, 1, &remote, 1, 0) == (ssize_t)n) return 0; + char path[40]; snprintf(path, sizeof(path), "/proc/%d/mem", pid); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + ssize_t got = pread(fd, buf, n, (off_t)addr); + close(fd); + return got == (ssize_t)n ? 0 : -1; +} +static int get_regs(pid_t tid, struct pt_regs *regs) { + struct iovec io = { regs, sizeof(*regs) }; + return ptrace(PTRACE_GETREGSET, tid, (void *)NT_PRSTATUS, &io); +} + +static volatile int sink; +__attribute__((noinline)) static void tick(void) { + __asm__ volatile("add %w0, %w0, #1" : "+r"(sink)); + __asm__ volatile("nop; nop; nop"); +} +static void spin_forever(void) { + // Re-enters tick() forever, so a breakpoint written on its entry is executed again. + for (;;) tick(); +} + +int main(int argc, char **argv) { + if (argc == 2 && !strcmp(argv[1], "--version")) { puts(VERSION); return 0; } + if (geteuid() != 0) { errno = EPERM; return fail("root-required"); } + uint64_t pid = 0, tid = 0, steps = 0, budget_ms = 0, break_addr = 0; + int self_test_bp = argc == 2 && !strcmp(argv[1], "--self-test-bp"); + int self_test = self_test_bp || (argc == 2 && !strcmp(argv[1], "--self-test")); + pid_t child = -1; + if (self_test) { + child = fork(); + if (child < 0) return fail("self-test-fork"); + if (!child) { spin_forever(); _exit(0); } + pid = tid = (uint64_t)child; steps = 8; budget_ms = 2000; + if (self_test_bp) break_addr = (uint64_t)(uintptr_t)&spin_forever; + } else { + if ((argc != 5 && argc != 6) || !number(argv[1], &pid) || !number(argv[2], &tid) || + !number(argv[3], &steps) || !number(argv[4], &budget_ms)) { + fprintf(stderr, "usage: adh-root-step PID TID STEPS TIMEOUT_MS [BREAK_ADDR]\n"); + return 2; + } + if (!pid || pid > INT32_MAX || !tid || tid > INT32_MAX || !steps || steps > MAX_STEPS || + !budget_ms || budget_ms > 120000) return 2; + // The collector must not silently trace a different thread than the one asked for. + char path[64], line[256]; snprintf(path, sizeof(path), "/proc/%llu/status", (unsigned long long)tid); + FILE *f = fopen(path, "r"); if (!f) return fail("thread-status"); + unsigned long owner = 0; + while (fgets(line, sizeof(line), f)) if (sscanf(line, "Tgid: %lu", &owner) == 1) break; + fclose(f); + if (owner != pid) { errno = EINVAL; return fail("tid-does-not-belong-to-pid"); } + } + if (ptrace(PTRACE_ATTACH, (pid_t)tid, NULL, NULL)) return fail("ptrace-attach"); + int status = 0; + if (waitpid((pid_t)tid, &status, __WALL) < 0) return fail("wait-attach"); + if (!WIFSTOPPED(status)) { errno = ESRCH; return fail("attach-not-stopped"); } + if (argc == 6 || self_test_bp) { + if (argc == 6 && (!number(argv[5], &break_addr) || !break_addr)) { errno = EINVAL; return fail("break-address"); } + errno = 0; + unsigned long orig = ptrace(PTRACE_PEEKDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, NULL); + if (errno) return fail("peek-break"); + unsigned long brk = (orig & ~0xffffffffUL) | 0xd4200000UL; /* brk #0 */ + if (ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)brk)) return fail("poke-break"); + int armed = 0; + int64_t break_until = millis() + (int64_t)budget_ms; + while (!armed) { + if (ptrace(PTRACE_CONT, (pid_t)tid, NULL, NULL)) { + (void)ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig); + return fail("cont"); + } + if (waitpid((pid_t)tid, &status, __WALL) < 0) { + (void)ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig); + return fail("wait-break"); + } + if (millis() > break_until) { + (void)ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig); + errno = ETIMEDOUT; return fail("break-timeout"); + } + if (WIFEXITED(status) || WIFSIGNALED(status)) { + (void)ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig); + errno = ESRCH; return fail("break-thread-exited"); + } + if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) { armed = 1; break; } + if (WIFSTOPPED(status)) { + /* Not our trap: deliver the signal and keep waiting for the breakpoint. */ + if (ptrace(PTRACE_CONT, (pid_t)tid, NULL, (void *)(long)WSTOPSIG(status))) { + (void)ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig); + return fail("signal-forward"); + } + } + } + if (ptrace(PTRACE_POKEDATA, (pid_t)tid, (void *)(uintptr_t)break_addr, (void *)orig)) return fail("restore-break"); + struct pt_regs br; + if (get_regs((pid_t)tid, &br)) return fail("break-getregs"); + br.pc = break_addr; + struct iovec io = { &br, sizeof(br) }; + if (ptrace(PTRACE_SETREGSET, (pid_t)tid, (void *)NT_PRSTATUS, &io)) return fail("break-setregs"); + printf("{\"break\":\"0x%llx\",\"hit\":true}\n", (unsigned long long)break_addr); + fflush(stdout); + } + printf("{\"ready\":true,\"version\":\"%s\",\"collectorPid\":%d,\"pid\":%llu,\"tid\":%llu,\"budget\":%llu,\"budgetMs\":%llu}\n", + VERSION, getpid(), (unsigned long long)pid, (unsigned long long)tid, + (unsigned long long)steps, (unsigned long long)budget_ms); + fflush(stdout); + int64_t until = millis() + (int64_t)budget_ms; + uint64_t done = 0, unreadable = 0; + const char *stop = "budget"; + for (;;) { + if (done >= steps) { stop = "step-budget"; break; } + if (millis() >= until) { stop = "time-budget"; break; } + struct pt_regs r; + if (get_regs((pid_t)tid, &r)) { stop = "getregs"; break; } + unsigned char insn[4]; int have = read_target((pid_t)tid, r.pc, insn, 4) == 0; + if (!have) unreadable++; + printf("{\"n\":%llu,\"pc\":\"0x%llx\",\"sp\":\"0x%llx\",\"lr\":\"0x%llx\"" + ",\"x0\":\"0x%llx\",\"x1\":\"0x%llx\",\"x2\":\"0x%llx\",\"x3\":\"0x%llx\"" + ",\"x4\":\"0x%llx\",\"x5\":\"0x%llx\",\"x6\":\"0x%llx\",\"x7\":\"0x%llx\"" + ",\"x8\":\"0x%llx\",\"x9\":\"0x%llx\",\"x10\":\"0x%llx\",\"x11\":\"0x%llx\",\"x12\":\"0x%llx\"", + (unsigned long long)done, (unsigned long long)r.pc, (unsigned long long)r.sp, + (unsigned long long)r.regs[30], (unsigned long long)r.regs[0], (unsigned long long)r.regs[1], + (unsigned long long)r.regs[2], (unsigned long long)r.regs[3], (unsigned long long)r.regs[4], + (unsigned long long)r.regs[5], (unsigned long long)r.regs[6], (unsigned long long)r.regs[7], + (unsigned long long)r.regs[8], (unsigned long long)r.regs[9], (unsigned long long)r.regs[10], + (unsigned long long)r.regs[11], (unsigned long long)r.regs[12]); + if (have) { + unsigned word; memcpy(&word, insn, 4); + printf(",\"insn\":\"0x%08x\"", word); + } + puts("}"); + fflush(stdout); + done++; + if (ptrace(PTRACE_SINGLESTEP, (pid_t)tid, NULL, NULL)) { stop = "singlestep"; break; } + if (waitpid((pid_t)tid, &status, __WALL) < 0) { stop = "wait-step"; break; } + if (WIFEXITED(status) || WIFSIGNALED(status)) { stop = "thread-exited"; break; } + if (!WIFSTOPPED(status)) { stop = "not-stopped"; break; } + } + (void)ptrace(PTRACE_DETACH, (pid_t)tid, NULL, NULL); + if (child > 0) { kill(child, SIGKILL); waitpid(child, NULL, 0); } + printf("{\"done\":true,\"steps\":%llu,\"unreadable\":%llu,\"stopReason\":\"%s\",\"complete\":%s,\"selfTest\":%s}\n", + (unsigned long long)done, (unsigned long long)unreadable, stop, + (done && strcmp(stop, "budget") != 0) ? "true" : "false", + self_test ? (done >= 5 ? "true" : "false") : "null"); + return self_test && done < 5 ? 1 : 0; +} From 55408edbdf1b7c691ec5980947c09a23477cc1b3 Mon Sep 17 00:00:00 2001 From: codex Date: Fri, 13 Nov 2026 20:04:02 +0800 Subject: [PATCH 06/24] =?UTF-8?q?feat(adh):=20root=5Fwatch=20=E5=86=85?= =?UTF-8?q?=E5=AD=98=E7=AA=97=E5=8F=A3=E6=94=AF=E6=8C=81=E6=AF=8F=E8=B7=B3?= =?UTF-8?q?=E5=81=8F=E7=A7=BB=EF=BC=88=E6=9C=80=E5=A4=9A=E4=B8=89=E7=BA=A7?= =?UTF-8?q?=E8=A7=A3=E5=BC=95=E7=94=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原语法 @@REG+OFF:LEN 只能给第一级加偏移,无法表达 [[obj]+8] 这类 「二级解引用且第二级带偏移」的访问——而 VM 的 64 位寄存器组正好在 状态对象 +0x08 指向的数组里,导致连续多轮都读不到算法状态。 改动: - memspec 由单 off 改为 off[4],解析器按 @ 分段,每段是该跳的偏移 - 语法扩展为 [@[@[@]]]REG[+/-OFF][@HOPOFF][@HOPOFF][:LEN] - 解引用循环改为 addr = *(addr + off[d+1]) - 自检新增 @@x0@8:8,设备实测读到 [[x0]+8] 正确值 - daemon 正则与 MCP 工具描述同步,单测覆盖新语法 --- daemon/src/mcp.ts | 36 ++++++++++++++++++------- daemon/src/root_watch.ts | 2 +- daemon/test/root_watch.test.ts | 4 +-- tools/native/root_watch.c | 48 +++++++++++++++++++++++++--------- 4 files changed, 65 insertions(+), 25 deletions(-) diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 7a9f3cf..a8d1bbb 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -25,7 +25,9 @@ import { javaTraceStart, javaTraceDigest, javaTraceStop } from './java_trace.ts' import { nativeHookAll, nativeUnhookAll } from './native_hook_all.ts'; import { normalizeThrottleMs, parseMemWindows, nativeTracePayload, ensureNativeObservationSupport } from './native_hook_args.ts'; import { nativeLookArm, nativeLookRead, nativeLookStop } from './native_look.ts'; -import { dropOracle, listOracles, oracleDiff, oracleRecord, oracleReplay } from './oracle.ts'; +import { dropOracle, listOracles, oracleDiff, oracleRecord, oracleReplay, oracleStability } from './oracle.ts'; +import { errorPayload, classifyError } from './error_codes.ts'; +import { queryMaps } from './maps_query.ts'; import { prepareRootWatch, startRootWatch, rootWatchStatus, readRootWatch, stopRootWatch } from './root_watch.ts'; import { diagnoseRuntime } from './runtime_diagnostics.ts'; import { recordTrace, queryTrace, traceStats, sliceTrace, listTraces, dropTrace } from './trace_store.ts'; @@ -41,6 +43,8 @@ import { jniFieldDigest } from './jni_field_digest.ts'; // names without importing them, so their handlers threw ReferenceError at call time. import { flowCorrelate, asciiOf, b64Of } from './flow.ts'; import { listRecipes, runRecipe } from './recipes.ts'; +import { analyzePackage } from './app_analyze.ts'; +import { mergeScope, readScopeFile, writeScopePackages } from './scope_list.ts'; import { syscallTraceStart, syscallTraceDigest, syscallTraceStop } from './syscall_trace.ts'; import { backendMatrix, classifySession } from './backends.ts'; import { armDetectJava, detectJavaPlan, detectionReport, planDetectModules } from './detect.ts'; @@ -114,7 +118,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } throw new Error('unknown trace_session action'); } }, - { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@]]REG[+/-OFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to two levels), so the returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { + { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. The returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { if (a.action === 'prepare') return prepareRootWatch(a.serial); if (a.action === 'start') { const s = sessions.get(String(a.session ?? '')); @@ -267,7 +271,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h saveSettings(); return { ok: true, applied, settings, autoAntiDebug: autoAntiDebugEnabled() }; } }, -{ name: 'native_look', description: 'The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with ONE object: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from the same hit. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name.', inputSchema: { type: 'object', properties: { session: S, action: { type: 'string', enum: ['arm', 'read', 'stop'] }, hookId: N, mode: { type: 'string', enum: ['got', 'inline', 'sites', 'vtable'] }, module: S, symbol: S, addr: S, confirm: { type: 'boolean' }, mem: S, backtrace: { type: 'boolean' }, hard: { type: 'boolean' }, maxEvents:N, sampleEvery:N, tid:N, returnAddress:S, traceInsns: N, traceFrom: S, traceWatch:S }, required: ['action'] }, handler: async (a) => { +{ name: 'native_look', description: 'The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with the NEWEST hit by default: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from that same hit, and retained.total says how many numbered hits are still stored. Pass seq for one earlier hit, or beforeSeq plus limit (1..50) to page older hits; nextBeforeSeq is the cursor. Do not re-run the operation to recover an earlier call. argIndex rewrites an argument and is not a filter. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name.', inputSchema: { type: 'object', properties: { session: S, action: { type: 'string', enum: ['arm', 'read', 'stop'] }, hookId: N, seq: N, beforeSeq: N, limit: N, mode: { type: 'string', enum: ['got', 'inline', 'sites', 'vtable'] }, module: S, symbol: S, addr: S, confirm: { type: 'boolean' }, mem: S, backtrace: { type: 'boolean' }, hard: { type: 'boolean' }, maxEvents:N, sampleEvery:N, tid:N, returnAddress:S, traceInsns: N, traceFrom: S, traceWatch:S }, required: ['action'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); if (a.action === 'arm') { @@ -280,7 +284,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } return nativeLookArm(sid, { mode: a.mode ? String(a.mode) : undefined, module: a.module ? String(a.module) : '', symbol: a.symbol ? String(a.symbol) : '', addr, maxEvents:a.maxEvents, sampleEvery:a.sampleEvery, tid:a.tid, returnAddress:a.returnAddress, traceWatch:a.traceWatch, mem: a.mem === undefined ? undefined : String(a.mem), backtrace: a.backtrace !== false, traceInsns: (a as any).traceInsns === undefined ? undefined : Number((a as any).traceInsns), traceFrom: (a as any).traceFrom === undefined ? undefined : String((a as any).traceFrom) }); } - if (a.action === 'read') return nativeLookRead(sid, Number(a.hookId)); + if (a.action === 'read') return nativeLookRead(sid, Number(a.hookId), undefined, { seq: a.seq === undefined ? undefined : Number(a.seq), beforeSeq: a.beforeSeq === undefined ? undefined : Number(a.beforeSeq), limit: a.limit === undefined ? undefined : Number(a.limit) }); if (a.action === 'stop') return nativeLookStop(sid, Number(a.hookId), a.hard === true); throw new Error('action must be arm, read, or stop'); } }, @@ -305,6 +309,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h { name: 'syscall_watch', description: 'Scan one loaded module for direct svc #0 sites (libc.so is the interesting one: its stubs are what ordinary app code reaches the kernel through), attribute each site to a syscall number by decoding the MOV that precedes the svc, inline-hook up to limit of the matching sites, and report hooks whose NATIVE_HOOK events carry x8 as the runtime syscall number. syscalls filters by name or number and accepts a CSV or an array ("uname,openat,117"); a filter that matches nothing fails loud. throttleMs (0 = off) caps how often each site reports an event - hot syscalls such as read/write/futex otherwise overflow the ring and make the digest look quiet; the response echoes the effective window. Host-side orchestration: dump + static scan + native_hook; agent remains execution-only.', inputSchema: { type: 'object', properties: { session: S, module: S, limit: N, throttleMs: N, syscalls: { anyOf: [ { type: 'array', items: { anyOf: [ { type: 'string' }, { type: 'number' } ] } }, { type: 'string' } ] } }, required: ['module'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return watchSyscalls(sid, { module: a.module, limit: a.limit, syscalls: a.syscalls, throttleMs: a.throttleMs }); } }, { name: 'got_enum', description: 'Enumerate relocation/GOT entries for one loaded module: slot address, symbol name, current resolved value and relocation type. Optional filter matches one symbol exactly.', inputSchema: { type: 'object', properties: { session: S, module: S, filter: S }, required: ['module'] }, handler: (a) => agentCmd(a.session, 'got_enum', { module: a.module, filter: a.filter ?? '' }, 20_000) }, { name: 'memory_maps', description: 'On-demand full /proc/self/maps of the target', inputSchema: { type: 'object', properties: { session: S } }, handler: (a) => agentCmd(a.session, 'maps') }, + { name: 'maps_query', description: 'Filtered view of the target maps plus address resolution: the answer to "which segment is this address in", "where is the decrypted copy", "which anonymous regions are executable". A full maps reply is 2000-5000 lines and floods context; this returns only matching regions with size/perms/file-offset/path and reports matched/truncated so a short list is never mistaken for a complete one. addr resolves the containing region and its module-relative file offset (the "belongs to whom" fact that otherwise has to be inferred by hand).', inputSchema: { type: 'object', properties: { session: S, path: S, perm: S, exec: { type: 'boolean' }, anon: { type: 'boolean' }, minSize: N, maxSize: N, limit: N, addr: S } }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); const maps = await agentCmd(sid, 'maps'); const regions = Array.isArray(maps?.regions) ? maps.regions : (Array.isArray(maps) ? maps : []); return queryMaps(regions, { path: a.path ? String(a.path) : undefined, perm: a.perm ? String(a.perm) : undefined, exec: typeof a.exec === 'boolean' ? a.exec : undefined, anon: typeof a.anon === 'boolean' ? a.anon : undefined, minSize: Number(a.minSize) > 0 ? Number(a.minSize) : undefined, maxSize: Number(a.maxSize) > 0 ? Number(a.maxSize) : undefined, limit: Number(a.limit) > 0 ? Number(a.limit) : undefined, addr: a.addr ? String(a.addr) : undefined }); } }, { name: 'mem_backend', description: 'Force which route the agent reads target memory by, for the whole session: auto (default) lets it use /proc/self/mem when the target allows that fd and fall back to an in-process direct read otherwise; direct forces the fallback everywhere. The reply states requested vs effective backend, whether it is forced, and the errno of the last /proc/self/mem open attempt. This exists because a target that refuses that fd cannot be produced on demand, so without forcing it the fallback is only ever exercised on the single read command that has a per-call override - search, magic-scan, dump and art_dexfiles would never run on it. Set it back to auto when done: it is a diagnostic, not a mode to leave on.', inputSchema: { type: 'object', properties: { session: S, backend: { type: 'string', enum: ['auto', 'direct', 'proc'] } }, required: ['backend'] }, handler: (a) => agentCmd(a.session, 'mem_backend', { backend: a.backend }) }, { name: 'memory_read', description: 'Read target memory at hex addr for size bytes (base64 out). The reply carries requested/short, so a truncated read is visible without recomputing it from the base64 length, and via names the route that answered. via:"direct" forces the direct in-process reader for this one read instead of /proc/self/mem - use it to cross-check a target that answers /proc/self/mem with plausible garbage, or to read when the target refuses that fd (a protector that calls prctl(PR_SET_DUMPABLE,0) makes open("/proc/self/mem") fail with EACCES even for the process itself, and the read then falls back to the direct route on its own)', inputSchema: { type: 'object', properties: { session: S, addr: S, size: N, via: { type: 'string', enum: ['auto', 'direct'] } }, required: ['addr', 'size'] }, handler: (a) => agentCmd(a.session, 'read', { addr: a.addr, size: a.size, ...(a.via === 'direct' ? { via: 'direct' } : {}) }) }, { name: 'memory_disasm', description: 'Disassemble live target memory with host-side Capstone 5 (WASM). addr is an absolute hex address, or pass module plus offset to resolve the module base from live maps. size is bounded to 64 KiB and aligned to AArch64 instructions.', inputSchema: { type: 'object', properties: { session: S, addr: S, size: N, module: S, offset: S } }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return liveDisasm(sid, { addr: a.addr, size: a.size, module: a.module, offset: a.offset }); } }, @@ -362,7 +367,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h { name: 'fs_list', description: 'List a directory on the DEVICE through the target process, so it sees the sandbox the way the app does (its private /data/data/... dir, /data/local/tmp, /proc/self/...). Returns name/type/size/mode/mtime per entry plus count and truncated. Start here to find shared_prefs, databases, keystores or dropped scripts, then pull one with fs_read.', inputSchema: { type: 'object', properties: { session: S, path: S }, required: ['session', 'path'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return listDeviceDir(sid, String(a.path ?? '')); } }, { name: 'fs_read', description: 'Read one device file through the target process. The agent caps a read at 1MB and reports truncated honestly. Returns size, byte count, a binary flag (NUL byte present), a printable preview and the line count, plus the whole text when the file is text and is at most 256KB. Binary or oversized files come back with textOmitted saying why; pass includeBase64:true for the raw bytes.', inputSchema: { type: 'object', properties: { session: S, path: S, includeBase64: { type: 'boolean' }, includeText: { type: 'boolean' }, previewBytes: N }, required: ['session', 'path'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return readDeviceFile(sid, String(a.path ?? ''), { includeBase64: a.includeBase64 === true, includeText: a.includeText !== false, previewBytes: a.previewBytes }); } }, { name: 'load_library', description: '把任意 .so 加载进目标进程(agent 内 dlopen)。可选 symbol 探测。不是 Frida 注入入口。', inputSchema: { type: 'object', properties: { session: S, path: S, symbol: S }, required: ['path'] }, handler: (a) => agentCmd(a.session, 'load_so', { path: a.path, symbol: a.symbol ?? '' }, 30_000) }, - { name: 'oracle', description: 'Controlled invocation of the TARGET\'S OWN entry point, and the differential harness on top of it - the primitive that turns "unknown parameter" into a small search space without knowing anything about the target. action:record calls the entry ONCE (detached java_call, so a blocking method parks one thread instead of the session) and keeps its arguments as a reusable template; extract is the path in the reply of the value to watch (default result), and a string that looks like JSON is parsed while walking, so result[0].b5 works for a facade that returns a JSON string. action:replay re-runs the template with patches applied to its RECORDED arguments (byte payloads stay {\"$bytesHex\":...}, so [1][0].$bytesHex is a normal patch path), and answers value + changed. action:diff runs one replay per variant and returns the dependency matrix: sensitive lists the input fields whose change moved the observed value, insensitive those that never did - that is the answer to "which input is this digest over". action:list and action:drop manage the templates. Paths are dotted/bracketed JSON paths (`args[1][0].$bytesHex`, `[0].b5`). Nothing here is target-specific: the caller names a facade it already knows how to call.', inputSchema: { type: 'object', properties: { session: S, action: { type: 'string', enum: ['record', 'replay', 'diff', 'list', 'drop'] }, id: N, className: S, method: S, params: S, field: S, args: { type: 'array' }, extract: S, patches: { type: 'array' }, variants: { type: 'array' }, timeoutMs: N }, required: ['action'] }, handler: async (a) => { + { name: 'oracle', description: 'Controlled invocation of the TARGET\'S OWN entry point, and the differential harness on top of it - the primitive that turns "unknown parameter" into a small search space without knowing anything about the target. action:record calls the entry ONCE (detached java_call, so a blocking method parks one thread instead of the session) and keeps its arguments as a reusable template; extract is the path in the reply of the value to watch (default result), and a string that looks like JSON is parsed while walking, so result[0].b5 works for a facade that returns a JSON string. action:replay re-runs the template with patches applied to its RECORDED arguments (byte payloads stay {\"$bytesHex\":...}, so [1][0].$bytesHex is a normal patch path), and answers value + changed. action:diff runs one replay per variant and returns the dependency matrix: sensitive lists the input fields whose change moved the observed value, insensitive those that never did - that is the answer to "which input is this digest over". action:list and action:drop manage the templates. Paths are dotted/bracketed JSON paths (`args[1][0].$bytesHex`, `[0].b5`). Nothing here is target-specific: the caller names a facade it already knows how to call. action:stability replays the template repeat times with the SAME arguments and reports stable/distinct/firstDiff: a pure function answers the same value every time, a hidden state or a time input does not - know this before trusting any black-box search.', inputSchema: { type: 'object', properties: { session: S, action: { type: 'string', enum: ['record', 'replay', 'diff', 'stability', 'list', 'drop'] }, id: N, className: S, method: S, params: S, field: S, args: { type: 'array' }, extract: S, patches: { type: 'array' }, variants: { type: 'array' }, repeat: N, timeoutMs: N }, required: ['action'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); if (a.action === 'list') return { ok: true, oracles: listOracles() }; @@ -381,8 +386,14 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h if (a.action === 'diff') { return oracleDiff(sid, { id: Number(a.id), variants: Array.isArray(a.variants) ? a.variants : [], timeoutMs: Number(a.timeoutMs) > 0 ? Number(a.timeoutMs) : undefined }); } - throw new Error('action must be record | replay | diff | list | drop'); + if (a.action === 'stability') { + return oracleStability(sid, { id: Number(a.id), repeat: Number(a.repeat) > 0 ? Number(a.repeat) : 3, patches: Array.isArray(a.patches) ? a.patches : [], timeoutMs: Number(a.timeoutMs) > 0 ? Number(a.timeoutMs) : undefined }); + } + throw new Error('action must be record | replay | diff | stability | list | drop'); } }, +{ name: 'analyze_app', description: 'One call from a package name to a bounded report: adds the package to the phone injection allowlist when needed (reported as scopeAdded), cold starts it, waits for the Zygisk-injected agent, then runs triage (caps / maps size / dex files / capture window / module loads / detection surface) plus optional unpack (dump every DEX) and httpCaptureMs (a TLS traffic window). Use it when the caller knows only the app name, not a session id. Every phase reports ok/error and one failed phase does not discard the others. The target must be an installed third-party app: system packages and the ADH manager are refused.', inputSchema: { type: 'object', properties: { package: S, autoScope: { type: 'boolean' }, forceRestart: { type: 'boolean' }, captureMs: N, unpack: { type: 'boolean' }, httpCaptureMs: N, timeoutMs: N, settleMs: N }, required: ['package'] }, handler: async (a) => analyzePackage(String(a.package ?? ''), { autoScope: a.autoScope !== false, forceRestart: a.forceRestart === true, captureMs: Number(a.captureMs) > 0 ? Number(a.captureMs) : undefined, unpack: a.unpack === true, httpCaptureMs: Number(a.httpCaptureMs) > 0 ? Number(a.httpCaptureMs) : 0, timeoutMs: Number(a.timeoutMs) > 0 ? Number(a.timeoutMs) : undefined, settleMs: Number(a.settleMs) > 0 ? Number(a.settleMs) : undefined }) }, +{ name: 'scope_list', description: 'The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called.', inputSchema: { type: 'object', properties: {} }, handler: async () => { const s = await readScopeFile(); return { ok: s.error === null, packages: s.packages, version: s.version, mode: s.mode, error: s.error }; } }, +{ name: 'scope_set', description: 'Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you.', inputSchema: { type: 'object', properties: { add: { type: 'array', items: S }, remove: { type: 'array', items: S }, set: { type: 'array', items: S } } }, handler: async (a) => { const cur = await readScopeFile(); if (cur.error) return { ok: false, error: cur.error }; const before = cur.packages; const next = Array.isArray(a.set) ? mergeScope([], { add: a.set }) : mergeScope(before, { add: a.add, remove: a.remove }); const w = await writeScopePackages(next, { version: cur.version, mode: cur.mode }); if (!w.ok) return { ok: false, error: w.error, packages: before }; return { ok: true, packages: w.packages, added: w.packages.filter((p) => !before.includes(p)), removed: before.filter((p) => !w.packages.includes(p)), note: 'cold start the target to apply' }; } }, ]; export const MCP_MAP = new Map(MCP_TOOLS.map(t => [t.name, t])); @@ -414,9 +425,16 @@ export async function handleMcp(reqBody: string, res: ServerResponse, opts?: { p } try { const out = await t.handler(args); - if (t.raw) return reply(out); - return reply({ content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] }); - } catch (e) { return reply({ content: [{ type: 'text', text: 'error: ' + (e as Error).message }], isError: true }); } + // A tool may answer with its own { ok:false, error } object instead of throwing (memory_write + // validates its argument this way). Without this branch those failures have no machine-readable + // class, which is exactly the inconsistency the field reports complained about: the same kind of + // mistake arrives as a thrown error on one tool and as a result object on another. + const coded = (out && typeof out === 'object' && (out as any).ok === false && typeof (out as any).code !== 'string') + ? { ...(out as object), code: classifyError((out as any).error ?? (out as any).message ?? '') } + : out; + if (t.raw) return reply(coded); + return reply({ content: [{ type: 'text', text: JSON.stringify(coded, null, 2) }] }); + } catch (e) { return reply({ content: [{ type: 'text', text: JSON.stringify(errorPayload(e)) }], isError: true }); } } return reply(undefined, { code: -32601, message: `method not found: ${msg.method}` }); } diff --git a/daemon/src/root_watch.ts b/daemon/src/root_watch.ts index bf24f2a..5c2e0cb 100644 --- a/daemon/src/root_watch.ts +++ b/daemon/src/root_watch.ts @@ -58,7 +58,7 @@ export function normalizeRootWatch(a: Record) { // time the sampled registers still describe the state the instruction operated on. const rawMem = a.mem === undefined ? [] : typeof a.mem === 'string' ? [a.mem] : a.mem; if (!Array.isArray(rawMem) || rawMem.length > 4) throw new Error('mem must be a string or an array of at most 4 specs'); - const MEM_SPEC = /^@{0,2}(x([0-9]|[12][0-9]|30)|sp|lr|pc)([+-](0x[0-9a-f]+|\d+))?(:([1-9][0-9]*|0x[1-9a-f][0-9a-f]{0,2}))?$/i; + const MEM_SPEC = /^@{0,3}(x([0-9]|[12][0-9]|30)|sp|lr|pc)([+-](0x[0-9a-f]+|\d+))?(@(0x[0-9a-f]+|\d+))*(:([1-9][0-9]*|0x[1-9a-f][0-9a-f]{0,2}))?$/i; const mem = rawMem.map((spec: unknown, index: number) => { if (typeof spec !== 'string' || spec.length === 0 || spec.length > 60 || !MEM_SPEC.test(spec)) throw new Error(`mem[${index}] must look like [@[@]]REG[+/-OFFSET][:LEN] with REG=x0..x30, sp, lr or pc`); diff --git a/daemon/test/root_watch.test.ts b/daemon/test/root_watch.test.ts index e02c010..274e9c3 100644 --- a/daemon/test/root_watch.test.ts +++ b/daemon/test/root_watch.test.ts @@ -19,10 +19,10 @@ test('extra hardware slots and memory windows are validated, not passed through' const spec = normalizeRootWatch({ tid: 7, addr: '0x1000', mode: 'x', width: 4, breakpoints: [{ addr: '0x2000', mode: 'x' }, { addr: '0x3000', width: 8, mode: 'rw' }], - mem: ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', 'x29-0x30:0x20'], + mem: ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', '@@x12@8:0x40'], }); assert.deepEqual(spec.breakpoints, ['bp=0x2000:4:x', 'bp=0x3000:8:rw']); - assert.deepEqual(spec.mem, ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', 'x29-0x30:0x20']); + assert.deepEqual(spec.mem, ['x13:16', '@x12+0x40:8', '@@x29-0x30:8', '@@x12@8:0x40']); for (const bad of [ { breakpoints: [{ addr: '0x2001', mode: 'x' }] }, { breakpoints: [{ addr: '0x2000', mode: 'x', width: 8 }] }, diff --git a/tools/native/root_watch.c b/tools/native/root_watch.c index 481f41d..c826e62 100644 --- a/tools/native/root_watch.c +++ b/tools/native/root_watch.c @@ -60,7 +60,7 @@ static uint64_t u64(const unsigned char *p) { uint64_t n; memcpy(&n, p, 8); retu // "x13:32" bytes at the address held in x13 // "@x12+0x40:16" dereference (x12+0x40), then read 16 bytes at that pointer // REG is x0..x30, sp, lr or pc. OFFSET accepts 0x.. or decimal. LEN defaults to 16. -struct memspec { char text[64]; int reg; int64_t off; int depth; unsigned len; }; +struct memspec { char text[64]; int reg; int depth; unsigned len; int64_t off[4]; }; static struct memspec mems[MAX_MEM]; static int mem_count; @@ -80,18 +80,37 @@ static int parse_mem(const char *text) { struct memspec m; memset(&m, 0, sizeof(m)); snprintf(m.text, sizeof(m.text), "%s", text); const char *p = text; - while (*p == '@' && m.depth < 2) { m.depth++; p++; } + while (*p == '@' && m.depth < 3) { m.depth++; p++; } const char *colon = strchr(p, ':'); size_t head_len = colon ? (size_t)(colon - p) : strlen(p); - const char *sign = NULL; - for (size_t i = 0; i < head_len; i++) if (p[i] == '+' || p[i] == '-') { sign = p + i; break; } - size_t reg_len = sign ? (size_t)(sign - p) : head_len; - m.reg = reg_of(p, reg_len); - if (m.reg < 0) return 0; - if (sign) { - char *end = NULL; errno = 0; - m.off = strtoll(sign, &end, 0); - if (errno || !end || end != colon) return 0; + // Grammar with per-hop offsets: @@x12@8:64 -> addr=x12; addr=*(addr+0); addr=*(addr+8) + // The first segment carries the register and its own offset (REG[+/-OFF]); every later + // '@'-separated segment is the offset added before that hop's dereference. + size_t seg_start = 0; + for (int hop = 0; hop <= m.depth; hop++) { + size_t seg_end = seg_start; + while (seg_end < head_len && p[seg_end] != '@') seg_end++; + size_t seg_len = seg_end - seg_start; + if (hop == 0) { + const char *sign = NULL; + for (size_t i = 0; i < seg_len; i++) if (p[i] == '+' || p[i] == '-') { sign = p + i; break; } + size_t reg_len = sign ? (size_t)(sign - seg_start) : seg_len; + m.reg = reg_of(p + seg_start, reg_len); + if (m.reg < 0) return 0; + if (sign) { + char *end = NULL; errno = 0; + m.off[0] = strtoll(sign, &end, 0); + if (errno || !end || end != p + seg_end) return 0; + } + } else { + if (seg_len == 0) { m.off[hop] = 0; } + else { + char *end = NULL; errno = 0; + m.off[hop] = strtoll(p + seg_start, &end, 0); + if (errno || !end || end != p + seg_end) return 0; + } + } + seg_start = seg_end + 1; } m.len = 16; if (colon) { @@ -165,13 +184,13 @@ static void emit_mem(pid_t pid, const uint64_t *regs) { printf(",\"mem\":["); for (int i = 0; i < mem_count; i++) { struct memspec *m = &mems[i]; - uint64_t addr = (uint64_t)((int64_t)regs[m->reg] + m->off); + uint64_t addr = (uint64_t)((int64_t)regs[m->reg] + m->off[0]); const char *err = NULL; for (int d = 0; d < m->depth && !err; d++) { uint64_t ptr = 0; if (read_target(pid, addr, &ptr, 8)) err = "unreadable-pointer"; else if (!ptr) err = "null-pointer"; - else addr = ptr; + else addr = (uint64_t)((int64_t)ptr + m->off[d + 1]); } unsigned char buf[MAX_MEM_BYTES]; if (!err && read_target(pid, addr, buf, m->len)) err = "unreadable"; @@ -255,6 +274,9 @@ int main(int argc, char **argv) { // value at a known address, so a window on x0 must read it back. if (!parse_mem("x0:8")) return fail("self-test-mem"); if (!parse_mem("@@x0:8")) return fail("self-test-mem2"); + // per-hop offsets: [[x0]+8] must resolve to fixture_value through fixture_ptr2 + if (!parse_mem("@@x0@8:8")) return fail("self-test-mem3"); + if (mems[mem_count - 1].off[1] != 8) return fail("self-test-mem3-off"); self_test_read = 1; first_extra = 2; From 8950330bdd0cb4e95fe489d4610451a18ab951c7 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:55:44 +0800 Subject: [PATCH 07/24] =?UTF-8?q?feat:=20QBDI=20=E4=BA=A4=E4=BB=98?= =?UTF-8?q?=E3=80=81app=5Fanalyze=20=E4=B8=80=E9=94=AE=E5=88=86=E6=9E=90?= =?UTF-8?q?=E4=B8=8E=20maps/=E9=94=99=E8=AF=AF=E7=A0=81=E8=A1=A5=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补齐 agent/Zygisk 的 QBDI 与 JNI/GOT 追踪能力,新增 app_analyze/maps_query/error_codes 与对应验收脚本和 Skill 文档。 --- agent/exports.map | 2 + agent/src/MAP.md | 2 +- agent/src/bootstrap/agent_internal.h | 2 +- agent/src/bootstrap/agent_main.c | 36 +++++++ agent/src/hook/got.c | 65 ++++++++---- agent/src/hook/native_hooks.cpp | 46 ++++++-- agent/src/runtime/jni.c | 38 ++++++- agent/src/runtime/jni_hooks.c | 92 +++++++++++++++- agent/src/runtime/jni_hooks.h | 5 +- agent/src/trace/qbdi_trace.c | 125 +++++++++++++++++++--- agent/src/trace/qbdi_trace.h | 18 +++- daemon/src/MAP.md | 7 +- daemon/src/analysis_guide.ts | 44 +++++++- daemon/src/app_analyze.ts | 151 +++++++++++++++++++++++++++ daemon/src/error_codes.ts | 52 +++++++++ daemon/src/http/routes_system.ts | 46 +++++++- daemon/src/maps_query.ts | 149 ++++++++++++++++++++++++++ daemon/src/mcp.ts | 2 +- daemon/src/native_look.ts | 121 ++++++++++++++++++--- daemon/src/oracle.ts | 53 ++++++++++ daemon/src/scope_list.ts | 88 ++++++++++++++++ daemon/src/service.ts | 72 +++++++++++-- daemon/src/state.ts | 21 ++++ daemon/test/analysis_guide.test.ts | 3 +- daemon/test/app_analyze.test.ts | 36 +++++++ daemon/test/cmd_progress.test.ts | 107 +++++++++++++++++++ daemon/test/error_codes.test.ts | 37 +++++++ daemon/test/maps_query.test.ts | 63 +++++++++++ daemon/test/native_look.test.ts | 60 ++++++++++- daemon/test/oracle_stability.test.ts | 58 ++++++++++ daemon/test/session_pick.test.ts | 36 +++++++ device/daemon/build.gradle.kts | 4 +- device/manager/build.gradle.kts | 4 +- docs/FEATURE_STATUS.md | 37 +++++++ docs/SKILL-callgraph-first.md | 136 ++++++++++++++++++++++++ docs/SKILL-evidence-hygiene.md | 121 +++++++++++++++++++++ docs/mcp-tools.md | 16 +-- injector/zygisk/jni/main.cpp | 57 +++++++++- injector/zygisk/module/customize.sh | 5 + injector/zygisk/module/module.prop | 4 +- injector/zygisk/update.json | 10 +- tools/MAP.md | 11 ++ tools/build_zygisk.sh | 21 ++++ tools/fetch_qbdi.sh | 12 ++- tools/native/root_watch.c | 2 +- tools/qbdi_toggle.sh | 63 +++++++++++ tools/verify_all.sh | 5 + tools/verify_v02_so.sh | 6 ++ tools/verify_v129_qbdi_delivery.sh | 111 ++++++++++++++++++++ tools/verify_v130_scope_analyze.sh | 55 ++++++++++ 50 files changed, 2216 insertions(+), 101 deletions(-) create mode 100644 daemon/src/app_analyze.ts create mode 100644 daemon/src/error_codes.ts create mode 100644 daemon/src/maps_query.ts create mode 100644 daemon/test/app_analyze.test.ts create mode 100644 daemon/test/cmd_progress.test.ts create mode 100644 daemon/test/error_codes.test.ts create mode 100644 daemon/test/maps_query.test.ts create mode 100644 daemon/test/oracle_stability.test.ts create mode 100644 daemon/test/session_pick.test.ts create mode 100644 docs/SKILL-callgraph-first.md create mode 100644 docs/SKILL-evidence-hygiene.md create mode 100644 tools/qbdi_toggle.sh create mode 100644 tools/verify_v129_qbdi_delivery.sh create mode 100644 tools/verify_v130_scope_analyze.sh diff --git a/agent/exports.map b/agent/exports.map index da6b4ae..dfc53b7 100644 --- a/agent/exports.map +++ b/agent/exports.map @@ -4,6 +4,8 @@ adh_agent_set_package; adh_agent_set_policy; adh_agent_set_endpoint; + adh_agent_set_qbdi_fd; + adh_agent_set_vm; adh_agent_start; local: *; diff --git a/agent/src/MAP.md b/agent/src/MAP.md index 55ba41a..9cc6d11 100644 --- a/agent/src/MAP.md +++ b/agent/src/MAP.md @@ -41,7 +41,7 @@ never mixes trace IDs. The hook-time path remains replay with incomplete context | `runtime/jni_onload.c` | JNI_OnLoad work: already-loaded module discovery, inline hook with prologue snapshot, manual invocation, real unhook (restores the bytes), plus the load-time watch state consumed by `runtime/dlopen_watch.c` (skip/return replacement of a load-time call) | | `runtime/dlopen_watch.c` | Lazily-installed dlopen watch on **both** entry points (`dlopen` and `android_dlopen_ext`/`__loader_` alias, each with its own trampoline). Two consumers: the JNI_OnLoad watch (patch a module's entry before the VM calls it) and the opt-in **`module_watch`** broadcast, which emits a `MODULE_LOAD` capture event (path, handle, base, size) for every library mapped afterwards — the initial map of an already-loaded module never passes here, a runtime-decrypted payload does. Hooking only the first entry that resolved made the broadcast blind to plain-`dlopen` loads (including the agent's own `load_so`), which is what the two slots fix. | | `trace/commands.c` | QBDI command response handling (`qbdi_trace`). The one-shot function tracer (`trace_run`) was deleted on 2026-10-01: `native_hook mode=got` + `java_call` + `native_backtrace`/`trace_digest` cover it without hardcoding a target trigger | -| `trace/qbdi_trace.c` | QBDI instruction trace, two entry points over ONE run engine and one set of guards. `adh_qbdi_trace` = standalone command-thread trace (`qbdi_call`, library loaded/unloaded per call). `adh_qbdi_run_from` / `_ex` = **in-hook** trace from an arbitrary pc with the hit's registers (`gpr` = x0-x8, x29, x30, x18), used by `native_hook { traceInsns, traceFrom }` on the TARGET thread: **per-thread VM** (`pthread_getspecific`, never a global lock), 300 ms wall clock, instruction budget, executable-range snapshot, `pc == lr` return detection, thread-local re-entrancy guard. The range snapshot is immutable once published and replaced by a pointer swap (in-hook runs read it concurrently); it is rebuilt only when the start address is not covered. An inline hook's entry carries our own Dobby branch, so that path starts in the trampoline and adds its page + the function's module explicitly (`qbdi_addInstrumentedRange`), otherwise the run reports `did-not-run`. `stopReason` is the caller's fact: `completed | instruction-budget | time-budget | ran-away | left-range | did-not-run | reentrant`. Costs (documented in `qbdi_trace.h`): the traced function EXECUTES under the emulator (twice per hit), stack-passed/float arguments are not seeded, and libQBDI.so must be loadable in the target (a real app usually needs it pushed + `load_library` first). Optional **write watch** for the run (`traceWatch: "x0:32"`, same window grammar as `mem`, armed as `qbdi_addMemRangeCB(QBDI_MEMORY_WRITE)` and deleted right after): the event then carries `traceWatch {lo, hi, count, truncated, hits:[{pc, insn, addr, size, value}]}`, i.e. WHICH instruction wrote WHICH address with WHICH value — the software stand-in for a hardware watchpoint, which app domains are denied (perf_event_open: errno 13) | +| `trace/qbdi_trace.c` | QBDI instruction trace, two entry points over ONE run engine and one set of guards. `adh_qbdi_trace` = standalone command-thread trace (`qbdi_call`, library loaded/unloaded per call). `adh_qbdi_run_from` / `_ex` = **in-hook** trace from an arbitrary pc with the hit's registers (`gpr` = x0-x8, x29, x30, x18), used by `native_hook { traceInsns, traceFrom }` on the TARGET thread: **per-thread VM** (`pthread_getspecific`, never a global lock), 300 ms wall clock, instruction budget, executable-range snapshot, `pc == lr` return detection, thread-local re-entrancy guard. The range snapshot is immutable once published and replaced by a pointer swap (in-hook runs read it concurrently); it is rebuilt only when the start address is not covered. An inline hook's entry carries our own Dobby branch, so that path starts in the trampoline and adds its page + the function's module explicitly (`qbdi_addInstrumentedRange`), otherwise the run reports `did-not-run`. `stopReason` is the caller's fact: `completed | instruction-budget | time-budget | ran-away | left-range | did-not-run | reentrant`. Costs (documented in `qbdi_trace.h`): the traced function EXECUTES under the emulator (twice per hit), stack-passed/float arguments are not seeded, and libQBDI.so must be loadable in the target (a real app usually needs it pushed + `load_library` first). Optional **write watch** for the run (`traceWatch: "x0:32"`, same window grammar as `mem`, armed as `qbdi_addMemRangeCB(QBDI_MEMORY_WRITE)` and deleted right after): the event then carries `traceWatch {lo, hi, count, truncated, hits:[{pc, insn, addr, size, value}]}`, i.e. WHICH instruction wrote WHICH address with WHICH value — the software stand-in for a hardware watchpoint, which app domains are denied (perf_event_open: errno 13). Delivery: a real target does not carry the tracer, so the injector hands over an fd it opened pre-specialize (`adh_agent_set_qbdi_fd` → `adh_qbdi_set_source_fd`); `api_load` copies it into a memfd created after specialization and `dlopen`s that, so nothing is loaded or mapped until a trace actually runs, and a standalone trace `dlclose`s it again | ## Naming diff --git a/agent/src/bootstrap/agent_internal.h b/agent/src/bootstrap/agent_internal.h index 24affef..3c19b58 100644 --- a/agent/src/bootstrap/agent_internal.h +++ b/agent/src/bootstrap/agent_internal.h @@ -19,7 +19,7 @@ // .so, so "which agent is flashed?" and "which module is flashed?" must not be two different // answers. Reported by compat_probe and in the hello; the string is already compiled in either // way, so surfacing it adds no new string to the release image (v88 unaffected). -#define AGENT_VER "0.6.0" +#define AGENT_VER "0.8.0" #define ADH_HOST "127.0.0.1" #define ADH_PORT 8761 // Loopback is always tried first (adb reverse). adh_agent_set_endpoint may name one extra diff --git a/agent/src/bootstrap/agent_main.c b/agent/src/bootstrap/agent_main.c index 2ea4670..7949e50 100644 --- a/agent/src/bootstrap/agent_main.c +++ b/agent/src/bootstrap/agent_main.c @@ -29,6 +29,7 @@ #include "../runtime/dlopen_watch.h" #include "../runtime/java_enum.h" #include "../trace/commands.h" +#include "../trace/qbdi_trace.h" #include "../hook/native_hooks.h" #include "../hook/hw_watch.h" #include "../hook/stealth_pool.h" @@ -964,6 +965,15 @@ static void *agent_thread(void *arg) { } static void do_start(void) { + // Optional bootstrap hook: registrations that happen before the host's first command are the + // interesting ones on a hardened target (they name the VM's native entry points). Off by + // default; `setprop adh.jni_early 1` (root) arms it for the NEXT process start. + { + char early[PROP_VALUE_MAX] = ""; + if (__system_property_get("adh.jni_early", early) > 0 && early[0] == '1') { + adh_jni_hook_install_early(); + } + } // The per-package policy is applied by whatever install comes next — it is NOT armed here. // Arming would mean the agent picking a module for its own GOT patch, and the agent carries no // module name by design (WS-B red line, tools/verify_v87_mcp_operability.sh); the only module it @@ -1011,6 +1021,16 @@ void adh_agent_set_policy(const char *flags) { LOGI("hook policy: %s", g_policy); } +// QBDI delivery: the Zygisk companion opens the tracer from the module directory before the +// uid/domain switch and hands the fd over here. The agent keeps it and copies it into a memfd the +// first time a trace actually runs (see trace/qbdi_trace.c). No fd = feature off for this target: +// nothing is loaded and nothing is mapped, so "not using it" really costs nothing. +__attribute__((visibility("default"))) +void adh_agent_set_qbdi_fd(int fd) { + adh_qbdi_set_source_fd(fd); + LOGI("qbdi delivery fd=%d", fd); +} + // More than one backend can load this .so into one process (Zygisk + self-load + Frida Gadget). // Each copy has its own pthread_once; only the first copy in link-map order may bootstrap. struct AgentCopyCtx { @@ -1166,3 +1186,19 @@ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { pthread_once(&g_once, do_start); return JNI_VERSION_1_6; } + +// Handed the JavaVM by the loader that already has one. +// +// Zygisk's ModuleBase::onLoad(api, env) receives a live JNIEnv, so the loader can give us the VM +// before adh_agent_start() runs. That removes the agent's only reason to call +// JNI_GetCreatedJavaVMs at all: resolving it out of the already-mapped libart.so and CALLING it +// crashed the target process at startup (SIGSEGV/SEGV_ACCERR at libart's +// JNI_GetCreatedJavaVMs+0) because the call happens from a freshly-loaded memfd DSO on a thread +// ART has not set up for it. Preferring the handed-over VM is therefore both cheaper and safer; +// the in-memory lookup stays as the fallback for loaders that cannot provide one. +JNIEXPORT void adh_agent_set_vm(void *vm) { + if (!vm) return; + if (!current_agent_copy_is_owner()) return; + adh_jni_set_vm((JavaVM *)vm); + LOGI("JavaVM handed over by loader (no symbol lookup needed)"); +} diff --git a/agent/src/hook/got.c b/agent/src/hook/got.c index cd9a45a..2e5bd4e 100644 --- a/agent/src/hook/got.c +++ b/agent/src/hook/got.c @@ -735,29 +735,15 @@ void adh_cmd_gothook_selftest(int fd, const char *id) { // Resolve an exported symbol in an already-loaded module by parsing its in-memory // dynamic symbol table (namespace-independent; works when dlopen is blocked). -static void *resolve_sym_ex(const char *mod_substr, const char *symbol, int prefix) { - unsigned long long base = 0; - FILE *m = fopen("/proc/self/maps", "r"); - if (!m) return NULL; - char line[512]; - while (fgets(line, sizeof(line), m)) { - char sa[32], ea[32], perms[8], off[32], dev[16], path[400] = ""; - unsigned long long inode = 0; - if (sscanf(line, "%31[0-9a-f]-%31[0-9a-f] %7s %31s %15s %llu %399[^\n]", sa, ea, perms, off, dev, &inode, path) < 6) continue; - char *pp = path; while (*pp == ' ') pp++; - const char *bn = strrchr(pp, '/'); bn = bn ? bn + 1 : pp; - if (strcmp(bn, mod_substr) != 0) continue; // exact basename match - if (strcmp(off, "0") && strcmp(off, "00000000")) continue; // want the mapping at file offset 0 (ELF header) - unsigned long long s = strtoull(sa, NULL, 16); - if (base == 0 || s < base) base = s; - } - fclose(m); - if (!base) return NULL; +// Parse one candidate image and look the symbol up. Returns the runtime address or NULL. +// `base` must be the address where the ELF header is mapped (offset 0 mapping). +static void *resolve_in_image(unsigned long long base, const char *symbol, int prefix) { unsigned char *p = (unsigned char *)base; if (memcmp(p, "\x7f""ELF", 4) != 0) return NULL; unsigned long long phoff = *(unsigned long long *)(p + 32); unsigned short phentsize = *(unsigned short *)(p + 54); unsigned short phnum = *(unsigned short *)(p + 56); + if (phentsize != 56 || phnum == 0 || phnum > 512) return NULL; unsigned long long dyn_vaddr = 0; for (int i = 0; i < phnum; i++) { unsigned char *ph = p + phoff + (unsigned long long)i * phentsize; @@ -814,6 +800,49 @@ static void *resolve_sym_ex(const char *mod_substr, const char *symbol, int pref } return NULL; } + +// Resolve `symbol` in `mod_substr` by parsing an in-memory image. +// +// Picking the base is the hard part on Android 15: the same APEX library shows up at offset 0 +// SEVERAL times in /proc/self/maps - the real r--p image, plus one or more r--s "shared" +// mappings that a previous version mistook for the image. Picking by address or by perms kept +// producing a base whose base+st_value landed in a non-executable mapping, which surfaced as +// either SEGV_ACCERR (before the executable check existed) or a permanent "no JavaVM". +// +// So do not guess: try every offset-0 candidate and keep a result only if the resolved address +// is really executable. That is a property of the answer, not of the guess. +static void *resolve_sym_ex(const char *mod_substr, const char *symbol, int prefix) { + unsigned long long cands[16]; + int ncand = 0; + FILE *m = fopen("/proc/self/maps", "r"); + if (!m) return NULL; + char line[512]; + while (fgets(line, sizeof(line), m)) { + char sa[32], ea[32], perms[8], off[32], dev[16], path[400] = ""; + unsigned long long inode = 0; + if (sscanf(line, "%31[0-9a-f]-%31[0-9a-f] %7s %31s %15s %llu %399[^\n]", + sa, ea, perms, off, dev, &inode, path) < 6) continue; + char *pp = path; while (*pp == ' ') pp++; + const char *bn = strrchr(pp, '/'); bn = bn ? bn + 1 : pp; + if (strcmp(bn, mod_substr) != 0) continue; + if (strcmp(off, "0") && strcmp(off, "00000000")) continue; + unsigned long long s = strtoull(sa, NULL, 16); + if (ncand < (int)(sizeof(cands) / sizeof(cands[0]))) cands[ncand++] = s; + } + fclose(m); + if (ncand == 0) return NULL; + + // Prefer an answer that is executable; fall back to any parse that succeeded (the caller + // applies its own guard, and some symbols legitimately live in non-executable data). + void *fallback = NULL; + for (int i = 0; i < ncand; i++) { + void *f = resolve_in_image(cands[i], symbol, prefix); + if (!f) continue; + if (adh_addr_is_executable(f)) return f; + if (!fallback) fallback = f; + } + return fallback; +} // Exact-match resolver (original behavior) plus a prefix variant used for symbols whose // mangled spelling varies across ROM/ABI versions. void *adh_resolve_sym(const char *mod, const char *sym) { return resolve_sym_ex(mod, sym, 0); } diff --git a/agent/src/hook/native_hooks.cpp b/agent/src/hook/native_hooks.cpp index ffab72e..001cacc 100644 --- a/agent/src/hook/native_hooks.cpp +++ b/agent/src/hook/native_hooks.cpp @@ -275,8 +275,9 @@ static size_t adh_json_append(char *out, size_t cap, size_t off, const char *for #define ADH_TRACE_JSON_MAX 3584 // `traceFrom` ("x0".."x9", "x29", "x30") -> the index of that register in the stub's saved bank. -// The stub saves x0-x9 at regs[0..9], x29 at regs[10], x30 at regs[11] and x18 at regs[12]; nothing -// else is saved, so a request for another register is refused instead of reading a stale slot. +// The stub saves x0-x9 at regs[0..9], x29 at regs[10], x30 at regs[11] and x18 at regs[12]; the real +// sp at regs[32] and x19-x28 at regs[33..42]. traceFrom names only the argument bank, so a request for +// another register is refused instead of reading a stale slot. // Returns -1 for "not given", -2 for a bad name. static int trace_from_stub_index(const char *spec, char *canon, size_t canon_size) { if (!spec || !spec[0]) return -1; @@ -739,6 +740,14 @@ extern "C" uint64_t adh_native_hook_record(uint64_t *regs, int hook_id, uint64_t // The stub's saved bank, indexed the way `traceFrom` names registers: 0-9 = x0-x9, 10 = x29, // 11 = x30. Kept here (not inside the window block) because the in-hook trace needs it too. uint64_t in9 = regs[9]; + // Callee-saved bank and the real stack pointer, saved by the stub at fixed offsets past the + // x0..x18 block. An in-hook instruction trace starts INSIDE the traced function, after its own + // prologue saved these, so it must see the real values - zeros make any function that keeps its + // state pointer here fault on first dereference. + const uint64_t in_sp = regs[32]; + const uint64_t in19 = regs[33], in20 = regs[34], in21 = regs[35], in22 = regs[36]; + const uint64_t in23 = regs[37], in24 = regs[38], in25 = regs[39], in26 = regs[40]; + const uint64_t in27 = regs[41], in28 = regs[42]; const uint64_t saved_regs[12] = { in0, in1, in2, in3, in4, in5, in6, in7, in8, in9, in29, in30 }; int arg_index = __atomic_load_n(&ctx.arg_index, __ATOMIC_RELAXED); uint64_t arg_value = __atomic_load_n(&ctx.arg_value, __ATOMIC_RELAXED); @@ -1049,8 +1058,21 @@ extern "C" uint64_t adh_native_hook_record(uint64_t *regs, int hook_id, uint64_t tpc = (uint64_t)(uintptr_t)ctx.original; } qbdi_summary_t sum; - // gpr layout expected by adh_qbdi_run_from: x0-x8, x29, x30, x18. - const uint64_t tgpr[12] = { in0, in1, in2, in3, in4, in5, in6, in7, in8, in29, in30, in18 }; + // gpr layout expected by adh_qbdi_run_from: [0..8]=x0-x8, [9]=x29, [10]=x30, [11]=x18, + // [12..21]=x19-x28, [22]=x9, [23]=sp. + // + // x19..x28 must carry the values the function actually has: this run starts INSIDE it, after + // its prologue saved them, so it is entitled to read them as its own. Passing zeros made any + // function that keeps a state pointer in that bank fault on first dereference - measured on a + // VM interpreter holding its context in x19/x21, where the trace died instantly. + // sp is the real stack pointer for the same reason: the function's own frame is live. + const uint64_t tgpr[ADH_QTRACE_GPR_LEN] = { + in0, in1, in2, in3, in4, in5, in6, in7, in8, + in29, in30, in18, + in19, in20, in21, in22, in23, in24, in25, in26, in27, in28, + in9, + in_sp, + }; // Write watch: resolve the range NOW (on the hit thread, from the hit's registers) and arm it for // this run only. A pointer that cannot be resolved is reported, never silently dropped - "the // watch saw nothing" and "the watch was never armed" must not look alike. @@ -1259,7 +1281,7 @@ extern "C" uint64_t adh_native_hook_after(uint64_t retval, uint64_t *regs, int h extern "C" void adh_native_stub_##N(void) __attribute__((naked)); \ extern "C" void adh_native_stub_##N(void) { \ __asm__ volatile( \ - "sub sp, sp, #256\n" \ + "sub sp, sp, #352\n" \ "stp x0, x1, [sp, #0]\n" \ "stp x2, x3, [sp, #16]\n" \ "stp x4, x5, [sp, #32]\n" \ @@ -1271,6 +1293,13 @@ extern "C" void adh_native_stub_##N(void) { \ "stp q2, q3, [sp, #160]\n" \ "stp q4, q5, [sp, #192]\n" \ "stp q6, q7, [sp, #224]\n" \ + "add x9, sp, #352\n" \ + "str x9, [sp, #256]\n" \ + "stp x19, x20, [sp, #264]\n" \ + "stp x21, x22, [sp, #280]\n" \ + "stp x23, x24, [sp, #296]\n" \ + "stp x25, x26, [sp, #312]\n" \ + "stp x27, x28, [sp, #328]\n" \ "mov x2, xzr\n" \ "mov x0, sp\n" \ "mov x1, #" #N "\n" \ @@ -1287,7 +1316,12 @@ extern "C" void adh_native_stub_##N(void) { \ "ldp q2, q3, [sp, #160]\n" \ "ldp q4, q5, [sp, #192]\n" \ "ldp q6, q7, [sp, #224]\n" \ - "add sp, sp, #256\n" \ + "ldp x19, x20, [sp, #264]\n" \ + "ldp x21, x22, [sp, #280]\n" \ + "ldp x23, x24, [sp, #296]\n" \ + "ldp x25, x26, [sp, #312]\n" \ + "ldp x27, x28, [sp, #328]\n" \ + "add sp, sp, #352\n" \ "cbnz x16, 1f\n" \ "adrp x17, g_native_hook_originals+" #OFF "\n" \ "add x17, x17, :lo12:g_native_hook_originals+" #OFF "\n" \ diff --git a/agent/src/runtime/jni.c b/agent/src/runtime/jni.c index 528825e..a602b14 100644 --- a/agent/src/runtime/jni.c +++ b/agent/src/runtime/jni.c @@ -4,8 +4,13 @@ #include "jni_env_hooks.h" #include "../hook/got.h" +#include #include #include +#include + +#define ADH_JNI_TAG "adh_jni" +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, ADH_JNI_TAG, __VA_ARGS__) static JavaVM *g_vm = NULL; @@ -51,14 +56,45 @@ int adh_jni_libart_symbol_resolves(void) { return adh_resolve_sym("libart.so", "JNI_GetCreatedJavaVMs") != NULL; } +// Only ever call a JNI_GetCreatedJavaVMs that is in an executable mapping, and give the loader a +// moment to make it one. +// +// Observed on a OnePlus/Android-15 target: the in-memory resolve returned a plausible libart +// address (correct libart base + the symbol's own st_value, and 0xa0e894 really is inside libart's +// executable PT_LOAD in the file), yet the process died with SIGSEGV/SEGV_ACCERR where pc == fault +// addr == that address. The address was right; the mapping was not executable YET — libart's text +// is demand-paged out of the APEX, and a freshly memfd-loaded agent can be asking before the +// segment has been faulted in. +// +// So: wait (bounded) for the page to become executable instead of calling into it blind. Callers +// still get NULL on timeout, which surfaces as the honest "no JavaVM" instead of a dead app. +#define ADH_JNI_EXEC_WAIT_MS 1500 + +static void *libart_jni_get_created_vms_safe(void) { + void *f = libart_jni_get_created_vms(); + if (!f) return NULL; + if (adh_addr_is_executable(f)) return f; + + // Not executable yet: poll briefly rather than dereference it. + for (int waited = 0; waited < ADH_JNI_EXEC_WAIT_MS; waited += 25) { + struct timespec ts = { 0, 25 * 1000 * 1000 }; + nanosleep(&ts, NULL); + if (adh_addr_is_executable(f)) return f; + } + LOGI("JNI_GetCreatedJavaVMs at %p never became executable; not calling it", f); + return NULL; +} JNIEnv *adh_jni_attach(int *did_attach) { *did_attach = 0; if (!g_vm) { typedef jint (*GetVMs)(JavaVM **, jsize, jsize *); - GetVMs f = (GetVMs)libart_jni_get_created_vms(); + GetVMs f = (GetVMs)libart_jni_get_created_vms_safe(); if (f) { JavaVM *vm = NULL; jsize n = 0; + // Calling into ART before it is ready is what killed the target; only do it when the + // symbol resolved to executable code. Callers see NULL and report "no JavaVM", which + // is the honest answer and keeps the process alive. if (f(&vm, 1, &n) == 0 && n > 0) g_vm = vm; } if (!g_vm) return NULL; diff --git a/agent/src/runtime/jni_hooks.c b/agent/src/runtime/jni_hooks.c index 0e705f6..5f016f4 100644 --- a/agent/src/runtime/jni_hooks.c +++ b/agent/src/runtime/jni_hooks.c @@ -13,7 +13,8 @@ #include #include -#include +#include +#include #include typedef jint (*register_natives_fn)(JNIEnv *, jclass, const JNINativeMethod *, jint); @@ -27,6 +28,31 @@ static int g_jni_hook_last_count = 0; static char g_jni_hook_error[256] = ""; static __thread int g_jni_hook_in_wrapper = 0; +// A registration is a one-shot event: it happens during library init, usually before capture is +// armed, so pushing it only as a capture record loses it exactly when the caller needs it (the +// field report: "hook installed, hits=6, but nothing to read"). Keep the last N registrations in a +// bounded ring here and expose them through jni_hook action:list. +#define ADH_JNI_REG_SLOTS 256 +typedef struct { + unsigned int seq; + char cls[192]; + char method[64]; + char signature[256]; + unsigned long long fn; +} adh_jni_registration; +static adh_jni_registration g_jni_regs[ADH_JNI_REG_SLOTS]; +static unsigned int g_jni_reg_seq = 0; + +static void remember_registration(const char *cls, const char *method, const char *signature, void *fn) { + unsigned int seq = __atomic_add_fetch(&g_jni_reg_seq, 1, __ATOMIC_RELAXED); + adh_jni_registration *slot = &g_jni_regs[(seq - 1) % ADH_JNI_REG_SLOTS]; + snprintf(slot->cls, sizeof(slot->cls), "%s", cls ? cls : ""); + snprintf(slot->method, sizeof(slot->method), "%s", method ? method : ""); + snprintf(slot->signature, sizeof(slot->signature), "%s", signature ? signature : ""); + slot->fn = (unsigned long long)(uintptr_t)fn; + __atomic_store_n(&slot->seq, seq, __ATOMIC_RELEASE); +} + static void set_jni_error(const char *message) { snprintf(g_jni_hook_error, sizeof(g_jni_hook_error), "%s", message ? message : ""); } @@ -58,7 +84,8 @@ static jint JNICALL register_natives_wrapper(JNIEnv *env, jclass clazz, "\"fnPtr\":\"0x%llx\",\"index\":%d,\"total\":%d}", class_escaped, name_escaped, signature_escaped, (unsigned long long)(uintptr_t)methods[i].fnPtr, i, (int)nMethods); - adh_capture_push_text("JNI_NATIVE", event); + adh_capture_push_text("JNI_NATIVE", event); + remember_registration(class_name, methods[i].name, methods[i].signature, methods[i].fnPtr); } } @@ -67,6 +94,35 @@ static jint JNICALL register_natives_wrapper(JNIEnv *env, jclass clazz, return result; } +void adh_jni_hook_install_early(void) { +#ifdef ADH_HAVE_INLINE_HOOK + pthread_mutex_lock(&g_jni_hook_lock); + int already = g_jni_hook_installed; + pthread_mutex_unlock(&g_jni_hook_lock); + if (already) return; + int did_attach = 0; + JNIEnv *env = adh_jni_attach(&did_attach); + if (!env) return; + void *target = (void *)(*env)->RegisterNatives; + adh_jni_detach(did_attach); + if (!target) return; + __atomic_store_n(&g_jni_hook_original_ptr, (void *)target, __ATOMIC_RELEASE); + void *original = NULL; + if (!adh_inline_hook(target, (void *)register_natives_wrapper, &original) || !original) { + __atomic_store_n(&g_jni_hook_original_ptr, NULL, __ATOMIC_RELEASE); + return; + } + __atomic_store_n(&g_jni_hook_original_ptr, original, __ATOMIC_RELEASE); + pthread_mutex_lock(&g_jni_hook_lock); + g_jni_hook_target = target; + g_jni_hook_installed = 1; + g_jni_hook_hits = 0; + g_jni_hook_last_count = 0; + set_jni_error(""); + pthread_mutex_unlock(&g_jni_hook_lock); +#endif +} + static void send_jni_hook_result(int fd, const char *id, const char *action, int ok, const char *error) { char idj[64], actionj[32], errorj[512]; @@ -162,6 +218,38 @@ void adh_cmd_jni_hook(int fd, const char *id, const char *action) { send_jni_hook_result(fd, id, action, ok ? 1 : 0, ok ? "" : "inline unhook failed"); return; } + if (strcmp(action, "list") == 0) { + unsigned int total = __atomic_load_n(&g_jni_reg_seq, __ATOMIC_ACQUIRE); + unsigned int count = total < ADH_JNI_REG_SLOTS ? total : ADH_JNI_REG_SLOTS; + size_t cap = (size_t)count * 720 + 512; + char *out = (char *)malloc(cap); + if (!out) { send_jni_hook_result(fd, id, action, 0, "out of memory"); return; } + size_t len = 0; + len += snprintf(out + len, cap - len, + "{\"t\":\"cmdResult\",\"id\":\"%s\",\"op\":\"jni_hook\",\"ok\":true," + "\"action\":\"list\",\"installed\":%s,\"total\":%u,\"count\":%u," + "\"registrations\":[", + id, g_jni_hook_installed ? "true" : "false", total, count); + int written = 0; + for (unsigned int i = 0; i < count; i++) { + /* Oldest first: seq numbers run (total-count+1)..total. */ + unsigned int seq = total - count + 1 + i; + adh_jni_registration *r = &g_jni_regs[(seq - 1) % ADH_JNI_REG_SLOTS]; + if (__atomic_load_n(&r->seq, __ATOMIC_ACQUIRE) != seq) continue; + char cls_escaped[400], method_escaped[160], signature_escaped[560]; + json_escape(r->cls, cls_escaped, sizeof(cls_escaped)); + json_escape(r->method, method_escaped, sizeof(method_escaped)); + json_escape(r->signature, signature_escaped, sizeof(signature_escaped)); + len += snprintf(out + len, cap > len ? cap - len : 0, + "%s{\"seq\":%u,\"class\":\"%s\",\"method\":\"%s\",\"signature\":\"%s\",\"fnPtr\":\"0x%llx\"}", + written ? "," : "", seq, cls_escaped, method_escaped, signature_escaped, r->fn); + written++; + } + len += snprintf(out + len, cap > len ? cap - len : 0, "]}\n"); + send_line(fd, out); + free(out); + return; + } if (strcmp(action, "status") == 0) { send_jni_hook_result(fd, id, action, 1, g_jni_hook_error); return; diff --git a/agent/src/runtime/jni_hooks.h b/agent/src/runtime/jni_hooks.h index 2c829e5..016b5f2 100644 --- a/agent/src/runtime/jni_hooks.h +++ b/agent/src/runtime/jni_hooks.h @@ -7,7 +7,10 @@ extern "C" { // Install/uninstall/status for the global JNIEnv->RegisterNatives hook. // Each registration emits a JNI_NATIVE capture event with class/method/signature/fnPtr. -void adh_cmd_jni_hook(int fd, const char *id, const char *action); +void adh_cmd_jni_hook(int fd, const char *id, const char *action); +// Install the same hook during agent bootstrap (gated by the caller on dh.jni_early=1), so +// registrations that happen before the first host command are still recorded. +void adh_jni_hook_install_early(void); #ifdef __cplusplus } diff --git a/agent/src/trace/qbdi_trace.c b/agent/src/trace/qbdi_trace.c index 05b3411..f51bede 100644 --- a/agent/src/trace/qbdi_trace.c +++ b/agent/src/trace/qbdi_trace.c @@ -15,12 +15,16 @@ #include "../hook/native_hooks.h" #include +#include +#include #include #include #include #include #include +#include #include +#include #include "QBDI/Options.h" #include "QBDI/State.h" @@ -65,12 +69,81 @@ struct QbdiApi { p_getInstMemAccess_t getInstMemoryAccess; }; +// Delivery fd handed over by the Zygisk companion through adh_agent_set_qbdi_fd(): it is opened from +// the module directory BEFORE the uid/domain switch, because /data/adb is not readable from the app +// domain. -1 means "QBDI is off for this target" - nothing is loaded, nothing is mapped. +static int g_qbdi_source_fd = -1; + +void adh_qbdi_set_source_fd(int fd) { + g_qbdi_source_fd = fd; +} + +// Copy the delivered fd into a memfd created HERE (after specialization, so the app-domain linker can +// stat it) and load from /proc/self/fd. The memfd is closed right after dlopen: the mapping is what +// matters, and the source fd stays open so a second trace does not need a new delivery. +static void *qbdi_dlopen_from_source(char *err, size_t errsz) { + if (errsz) err[0] = 0; + if (g_qbdi_source_fd < 0) return NULL; + int mfd = (int)syscall(__NR_memfd_create, "jit-cache", 1 /* MFD_CLOEXEC */); + if (mfd < 0) { + snprintf(err, errsz, "memfd_create failed: %s", strerror(errno)); + return NULL; + } + if (lseek(g_qbdi_source_fd, 0, SEEK_SET) != 0) { + snprintf(err, errsz, "lseek(qbdi fd) failed: %s", strerror(errno)); + close(mfd); + return NULL; + } + char buf[65536]; + for (;;) { + ssize_t n = read(g_qbdi_source_fd, buf, sizeof(buf)); + if (n < 0) { + if (errno == EINTR) continue; + snprintf(err, errsz, "read(qbdi fd) failed: %s", strerror(errno)); + close(mfd); + return NULL; + } + if (n == 0) break; + ssize_t off = 0; + while (off < n) { + ssize_t w = write(mfd, buf + off, (size_t)(n - off)); + if (w <= 0) { + if (w < 0 && errno == EINTR) continue; + snprintf(err, errsz, "write(qbdi memfd) failed: %s", strerror(errno)); + close(mfd); + return NULL; + } + off += w; + } + } + if (lseek(mfd, 0, SEEK_SET) != 0) { + snprintf(err, errsz, "lseek(qbdi memfd) failed: %s", strerror(errno)); + close(mfd); + return NULL; + } + char path[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", mfd); + void *handle = dlopen(path, RTLD_NOW); + if (!handle) snprintf(err, errsz, "dlopen(qbdi memfd) failed: %s", dlerror()); + close(mfd); + return handle; +} + static int api_load(struct QbdiApi *api, const char *libname, char *err, size_t errsz) { memset(api, 0, sizeof(*api)); api->handle = dlopen(libname, RTLD_NOW); if (!api->handle) { - snprintf(err, errsz, "%s not available (dlopen)", libname); - return 0; + // Second route: the injector delivered a source fd. This is how a REAL target gets QBDI - + // the app domain cannot read /data/adb, so an inherited fd is the only way in, and copying + // it here (after specialization) is what makes the memfd loadable by the app linker. + api->handle = qbdi_dlopen_from_source(err, errsz); + if (!api->handle) { + size_t used = strlen(err); + snprintf(err + used, errsz > used ? errsz - used : 0, + "%s not available (dlopen); QBDI delivery is off for this target " + "(enable it in the module, then restart the target)", libname); + return 0; + } } api->initVM = (p_initVM_t)dlsym(api->handle, "qbdi_initVM"); api->terminateVM = (p_terminateVM_t)dlsym(api->handle, "qbdi_terminateVM"); @@ -636,29 +709,53 @@ int adh_qbdi_run_from_watch(uint64_t pc, const uint64_t *gpr, int budget, int ti // one, otherwise the run would end the instant the trampoline branches back into the function. // (Getting this order wrong is invisible until the run reports "executed nothing": asking QBDI to // instrument the HINT first answers true, so the trampoline page was never added.) + // + // An anonymous executable MAPPING is added WHOLE, not just the page holding pc. A VM interpreter + // keeps its dispatch table and every handler in one such mapping and reaches them through `br x8`; + // instrumenting one page leaves the branch target uninstrumented, and the run then either stops at + // the edge of the page or takes the target down with it. The mapping is bounded, so adding all of + // it is cheap and is the only way an indirect dispatch survives instrumentation. if (!api->addInstrumentedModuleFromAddr(tv->vm, (rword)pc)) { - uint64_t page = pc & ~(uint64_t)0xfff; - api->addInstrumentedRange(tv->vm, (rword)page, (rword)(page + 0x1000)); + uint64_t lo = pc & ~(uint64_t)0xfff, hi = lo + 0x1000; + if (map && map->n > 0) { + for (int i = 0; i < map->n; i++) { + if (pc < map->r[i].lo || pc >= map->r[i].hi) continue; + lo = map->r[i].lo & ~(uint64_t)0xfff; + hi = (map->r[i].hi + 0xfff) & ~(uint64_t)0xfff; + break; + } + } + api->addInstrumentedRange(tv->vm, (rword)lo, (rword)hi); } if (instrument_hint && instrument_hint != pc) (void)api->addInstrumentedModuleFromAddr(tv->vm, (rword)instrument_hint); - // Seed the hit's registers. x29/x30/x18 are passed in because they are what the callee would - // actually see (frame pointer, return address, platform register). x9-x17 and x19-x28 are - // callee-saved/scratch and must not carry stale values from a previous run: a function is - // entitled to treat them as its own once it saved them. + // Seed the hit's registers from the real values the caller captured. + // + // x0..x8 are the argument/scratch bank, x29/x30 the frame and return address, x18 the platform + // register. x19..x28 are CALLEE-SAVED: in the real execution the traced function already saved them + // in its prologue and is entitled to read them as its own, so a run that starts inside the function + // must see the same values. Zeroing them (the old behaviour) made any function that keeps its state + // pointer in that bank fault on first dereference - measured on a VM interpreter holding its context + // in x19/x21. A caller that does not know a slot passes ADH_QTRACE_GPR_UNKNOWN, which zeroes it. GPRState *st = tv->gpr; st->x0 = (rword)gpr[0]; st->x1 = (rword)gpr[1]; st->x2 = (rword)gpr[2]; st->x3 = (rword)gpr[3]; st->x4 = (rword)gpr[4]; st->x5 = (rword)gpr[5]; st->x6 = (rword)gpr[6]; st->x7 = (rword)gpr[7]; st->x8 = (rword)gpr[8]; - st->x9 = st->x10 = st->x11 = st->x12 = st->x13 = st->x14 = st->x15 = 0; - st->x16 = st->x17 = 0; st->x18 = (rword)gpr[11]; - st->x19 = st->x20 = st->x21 = st->x22 = st->x23 = st->x24 = st->x25 = st->x26 = 0; - st->x27 = st->x28 = 0; + st->x19 = (rword)gpr[12]; st->x20 = (rword)gpr[13]; st->x21 = (rword)gpr[14]; st->x22 = (rword)gpr[15]; + st->x23 = (rword)gpr[16]; st->x24 = (rword)gpr[17]; st->x25 = (rword)gpr[18]; st->x26 = (rword)gpr[19]; + st->x27 = (rword)gpr[20]; st->x28 = (rword)gpr[21]; + st->x9 = (rword)gpr[22]; + st->x10 = st->x11 = st->x12 = st->x13 = st->x14 = st->x15 = 0; + st->x16 = st->x17 = 0; st->x29 = (rword)gpr[9]; st->lr = (rword)gpr[10]; - st->sp = (rword)(((uintptr_t)tv->stack + ADH_QTRACE_VSTACK - 64) & ~(uintptr_t)15); + // sp: an explicit value from the caller when it has one (an in-hook trace of a function whose frame + // is live), otherwise the private virtual stack this VM allocated. + st->sp = gpr[23] != ADH_QTRACE_GPR_UNKNOWN + ? (rword)gpr[23] + : (rword)(((uintptr_t)tv->stack + ADH_QTRACE_VSTACK - 64) & ~(uintptr_t)15); st->nzcv = 0; st->pc = (rword)pc; @@ -804,7 +901,7 @@ static int trace_collect(void *func, const unsigned long long *args, int argc, c if (adh_native_hook_at((uint64_t)(uintptr_t)func, &hooked_id, &hooked_active)) { snprintf(out, outsz, "\"ok\":false,\"error\":\"refusing to trace: this address carries an ADH inline hook " - "(id %d, %s). A soft unhook leaves the Dobby branch in the prologue, so the tracer " + "(id %d, %s). A soft unhook leaves the inline-hook branch in the prologue, so the tracer " "follows it into the trampoline and the run never returns (measured: SIGBUS at " "pc=0x2a, target killed). Hard-unhook it, or restart the target, then trace.\"," "\"hookedId\":%d,\"hookedActive\":%s", diff --git a/agent/src/trace/qbdi_trace.h b/agent/src/trace/qbdi_trace.h index 3d6c51d..fbca69a 100644 --- a/agent/src/trace/qbdi_trace.h +++ b/agent/src/trace/qbdi_trace.h @@ -10,6 +10,12 @@ extern "C" { #endif +// Delivery handle for the tracer library. The Zygisk companion opens libQBDI.so from the module +// directory BEFORE the uid/domain switch (the app domain cannot read /data/adb) and hands the plain +// fd over; the agent copies it into a memfd the first time a trace actually runs. No fd means the +// feature is off for this target: nothing is loaded and nothing is mapped. +void adh_qbdi_set_source_fd(int fd); + int adh_qbdi_trace(void *func, const unsigned long long *args, int argc, char *out, int out_size); // Explicit command-thread collection. One bounded recording is retained until released/replaced; // replies carry metadata only, and qbdi_read retrieves <=128 instructions per page. @@ -107,8 +113,16 @@ typedef struct { } qbdi_summary_t; // Run from an arbitrary pc with the hit's registers, on the current thread's VM. -// gpr layout: [0..8] = x0..x8, [9] = x29 (fp), [10] = x30 (lr), [11] = x18. -// Returns the number of instructions executed, or -1 when no run happened (out->error says why). +// gpr layout: [0..8] = x0..x8, [9] = x29 (fp), [10] = x30 (lr), [11] = x18, +// [12..21] = x19..x28 (callee-saved), [22] = x9, [23] = sp. +// The callee-saved bank matters for an IN-HOOK trace: the traced function is entitled to read x19..x28 +// as its own (it saved them in its prologue in the real execution, and this run starts after that +// prologue). Leaving them zeroed made any function that keeps a state pointer in x19..x28 fault the +// moment it dereferenced it - measured on a VM interpreter that keeps its context in x19/x21. +// Callers that do not know a register pass ADH_QTRACE_GPR_UNKNOWN and the value is zeroed, which is the +// old behaviour for that slot. +#define ADH_QTRACE_GPR_LEN 24 +#define ADH_QTRACE_GPR_UNKNOWN 0ULL int adh_qbdi_run_from(uint64_t pc, const uint64_t *gpr, int budget, int time_ms, qbdi_summary_t *out); // Same, but also names the module to instrument when the start pc is NOT inside one (the Dobby diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index 925502b..d50e0c9 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -23,10 +23,12 @@ forbidden conclusions, one proposed next call and an identifier checkpoint. No p | `sandbox_fs.ts` | **App sandbox listing without a live process.** `listSandboxDir` / `readSandboxFile` read `/data/data/` (and the `/data/user//` path it resolves to) through `adb` + `su`. Paths are confined to that package before anything is sent. The web file panel calls `/api/fs/list?package=` and `/api/fs/read` with `package`; a request that only has `session` still goes through the agent in `fs_browse.ts`. | node only | | `state.ts` | **Shared state + leaf helpers.** All registries (`sessions`/`dumps`/`agentSockets`/`pending`), `events`+`recordEvent`, `settings`+`mergeSettings`/`saveSettings`/`configStats`, `AgentSession.caps` (the agent's self-described ops+limits, set from the `caps` frame right after hello), `AgentSession.startupHooks` (the pre-arm that actually ran, with hookIds), `settings.startup` (antiDebug/module/extraTargets/packages/widenAfterMs/widenTargets — the host-side policy applied at hello plus the delayed widening, OFF by default), `readBody` (capped at `MAX_BODY_BYTES` = 8MB; an oversized body rejects with status 413 and the top-level error net answers it), capture store (classification puts `MODULE_LOAD` in the `system` category so the existing views show it), (`captures`/`pushCapture`/`clearCaptureStore`/`captureTimers`/`capStats`/`captureHealth`), plus the pure `filterLiveCaptures(category, session, package)` that `live_captures` shares with `http_exchanges` semantics (a record is attributed by its own package stamp first, so it stays attributable after its process exits), **on-disk artifact store** (`loadArtifactsFromDisk` adopts `captures/` into the `dumps` map at boot, `pruneArtifacts` enforces `settings.artifacts`, `artifactStats`), classification (`hexToPreview`/`categoryOf`/`classify`/`cryptoIdentify`), `captureModules` (reads settings, not a target constant), infra (`wss`/`broadcast`/`log`/`readBody`), framing (`frameJson`/`FRAME_JSON`/`FRAME_MAX`). **Imports nothing from service/mcp/index** (no cycles). | node + ws + `capture_persist.ts` | | `capture_persist.ts` | **Package-scoped capture log.** Append/load/trim/clear/export/age-prune `adhd-data/packages//captures.jsonl`. Per-package retain so one app cannot evict another. No daemon state imports. | node:fs only | -| `scope_list.ts` | Switcher = phone `scope.json` only. `autoArmAllowed(pkg, entry, scope)` is the pure rule (unit-tested): `entry === 'jni_onload'` is a self-load session and always arms; a scope that was never read fails open; otherwise the package must be listed. Keyed on HOW the agent was loaded instead of a special package name, so the daemon holds no target identity. Never merge capture-disk packages into the app list. | node only | +| `scope_list.ts` | Switcher = phone `scope.json` only. `autoArmAllowed(pkg, entry, scope)` is the pure rule (unit-tested): `entry === 'jni_onload'` is a self-load session and always arms; a scope that was never read fails open; otherwise the package must be listed. Keyed on HOW the agent was loaded instead of a special package name, so the daemon holds no target identity. Never merge capture-disk packages into the app list. **Host-side write** (2026-11-12): `readScopeFile` / `mergeScope` / `writeScopePackages` / `packageInstalled` are the AI/operator channel — the file is written through adb+su, read back to prove the write stuck, and the `adb_data_file` label is set explicitly, because a wrong label fails closed (no injection, no visible error). | node only | | `service.ts` | **Service layer.** Agent-command transport (`sendCmd`/`agentCmd`/`pickSid`), dump engine (`readMem`/`reconstructSo`/`repairDexHeader`/`dumpRegion`/`dumpBuf`/`dumpBufPath`/`modulesFromMaps`/`dumpAppSo`), capture ops (`setCapture` — the one implementation behind the `capture_start`/`capture_stop` tools: install + a derived `installed===expected` verdict, and stop-that-drains-first —/`startCaptureLoop`/`dumpAllDex` — which now classifies every dex (carrier vs real code) and indexes it in the same pass —/`autoDumpDex`/`applyCaptureEnabled`), artifact retention (`pruneArtifactsAndIndex` — wires the eviction plan to the dex-index row). `capSeq` is service-local (`++`'d in `startCaptureLoop` — can't reassign an imported binding in ESM). **Memory write + undo:** `writeMem` validates the hex/address before sending (a bad request writes nothing), calls the agent's `write`, and remembers the returned `before` bytes per session (bounded, 64 entries); `restoreMem` puts them back and `listWriteUndo` lists what is still restorable — so an operator/AI patches one branch and undoes it with one call, without tracking bytes. `moduleLoads(sid)` decodes the MODULE_LOAD capture records back into `{path,handle,base,size}` so a caller never hex-decodes a capture by hand. **Startup pre-arm:** `applyStartupHooks(sid)` runs on hello (index.ts) BEFORE the capture loop — `autoAntiDebugEnabled` (settings + `ADH_AUTO_ANTIDEBUG` override) and `shouldPreArm(pkg)` (settings.startup.packages whitelist, empty = all) decide whether to install the minimal plan, then `session.startupHooks` carries the hookIds so they are visible and undoable. The plan is `ptrace` only by default: a measured test showed hooking `access`/`faccessat` at hello makes the app's OWN path checks fail during initialization and killed the sandbox within ~0.5 s. Those two are installed LATER by `startupWidenPlan` / `widenStartupHooks` (`startup.widenAfterMs` + `widenTargets`, unref'd timer, once per session) so the app is settled first — verified on device: at hello 1 hook and `access` → ENOENT, 5 s later 3 hooks and `access` → EACCES, process alive. `daemon/test/agent_caps.test.ts` guards the agent capability manifest against the dispatch chain. **`withCaptureSuspended` was removed on 2026-10-01** together with the one-shot probe routes it existed for: it stopped/restarted the persistent hooks so a probe saw a clean GOT slot, and the last probe that needed that (`file_hook_test`) is gone — reintroduce it deliberately if a future call-site tool needs a clean slot, not by accident. | `state.ts`, `dex.ts`, `so_select.ts`, node | | `mcp.ts` | **MCP Server (JSON-RPC).** `MCP_TOOLS` registry (single array — **add a tool = add one entry**) + `handleMcp`. AI-first tools: `capabilities` answers with the agent's own hello `caps` (ops + limits) plus the daemon body cap, so a client plans from the running build instead of a document; `memory_write` / `memory_restore` are the write side of `memory_read` with host-kept undo; `module_watch` arms/disarms the MODULE_LOAD broadcast and lists the records; `recipe` runs a named multi-step workflow from `recipes.ts` (one call instead of eight in the right order); `settings` gets/patches the daemon settings (including the `startup` pre-arm policy) so an AI can configure the daemon without dropping to REST. All of them are shared with the REST routes, never a second implementation. Handlers delegate to `service.ts` primitives + `state.ts` reads + DEX/index/analysis layers. | `state.ts`, `service.ts`, `dex.ts`, `dex_index.ts`, `analysis.ts`, `memory.ts`, `syscall_watch.ts`, `recipes.ts` | | `recipes.ts` | **Named multi-step workflows.** The primitives answer "what CAN I do"; a recipe answers "do the thing": `triage` (caps, maps, dex files, a capture window with module-load watch, detection summary, capture counts), `capture_window` (arm capture, optionally run ONE caller-supplied Java method as the trigger, wait, digest), `http_capture` (arm TLS, optionally trigger, drain, pair plaintext into whole HTTP exchanges), `anti_debug` (plan without `confirm:true`; with it, neutralizes ptrace/access/faccessat return+errno and returns the hookIds, `undoHookIds` removes a previous run), `unpack` (cold start + every dex into a bundle). Every step reports `ok`/`ms`/`error` and a failed step does not abort the rest, so a partial answer stays usable; steps return small summaries, never raw agent replies. Recipes orchestrate only — no new agent capability is invented here. Unit-tested (`test/recipes.test.ts`). | `state.ts`, `service.ts`, `detect.ts`, `http_exchange.ts` | +| `error_codes.ts` | **Machine-readable failure classes.** `classifyError`/`errorPayload` map every tool failure (thrown or returned as `{ok:false}`) to BAD_ARG / NO_SESSION / SESSION_OFFLINE / AGENT_TIMEOUT / UNSUPPORTED_OP / TARGET_CRASHED / CAPTURE_LOSS / HELPER_MISSING / DEVICE_UNAVAILABLE / UNKNOWN, so a client can branch instead of parsing prose. | — | +| `app_analyze.ts` | **"Analyze this app" in one call.** Given only a package name it adds the package to the injection allowlist when needed (reported as `scopeAdded`), cold-starts it, waits for the Zygisk-injected agent, then runs `triage` plus optional `unpack` / `http_capture`. It owns the part BEFORE a session exists (recipes take a session). Every phase reports `ok`/detail/`error`; one failed phase does not discard the others. Unit-tested (`test/app_analyze.test.ts`: merge rules, main-process pick, refusal before adb). | `app_launch.ts`, `dump_inventory.ts`, `recipes.ts`, `scope_list.ts`, `service.ts` | | `http/router.ts` | **REST composition and first-match dispatch.** Creates request context, concatenates route domains in stable order, then `/` dashboard + `POST //mcp` pin, then 404. | `http/routes_*.ts`, `mcp.ts` | | `http/routes_system.ts` | Health, MCP, captures/events, settings, destructive data lifecycle, diagnostics, agent registry, `/wechat-follow.png`, `/raven.svg`/`/raven.png`/`/favicon.ico`, and `/api/mcp/config` (the three-block MCP onboarding the Web panel renders: install / connect / config, built by `mcp_onboarding.ts` from the request's own Host so a LAN browser and a loopback shell each get an address that works) | `config.ts`, `mcp_onboarding.ts`, `state.ts`, `service.ts`, `mcp.ts` | — also serves `GET /api/backends` (injection-backend matrix: sessions by entry + Zygisk pointers; read-only; this route does not shell out to adb). | | `http/routes_runtime.ts` | Live agent execution routes: maps, object/JNI/ART, hook/trace, filesystem, memory, trigger, and unpack commands. | `state.ts`, `service.ts`, `memory.ts`, `syscall_watch.ts` | @@ -38,6 +40,7 @@ forbidden conclusions, one proposed next call and an identifier checkpoint. No p | `so_select.ts` | **Pure app-SO selection.** `appOwnedSoModules` keeps loaded `.so` files whose path is under the selected package and drops system/apex libraries plus `libadh_agent.so`. Callers: `dumpAppSo` and `detect.ts`. | — | | `detect.ts` | **Detection checklist (module V).** Pure `summarizeDetection` turns ptrace/access/faccessat/property lines, detection-shaped open paths, and the named Java detection hooks into debug/root/signature/emulator/integrity counts. `selectDetectModules` picks this app's libraries that import those libc symbols. `planDetectModules` / `armDetectJava` are the live shells (maps + got_enum, and confirm-gated Java hooks). REST `GET /api/detect/summary` and MCP `detect_summary` / `detect_modules` / `detect_java` call the same functions. | `state.ts`, `service.ts`, `so_select.ts` | | `dump_inventory.ts` | **Pure dump-page decisions.** `contiguousReadable`; `packageSoDirs` (mapped parents + private `lib/`/`files/`); `preferMainProcess`. | — | +| `maps_query.ts` | **Maps filtering + address resolution.** `queryMaps` turns the agent's 2000-5000-line maps reply into a filtered, paginated view (path substring / perm / exec / anon / size / limit) with `total`/`matched`/`returned`/`truncated`, and `resolveAddress` answers "which segment is this address in and what is its module-relative file offset". Added 2026-11-12 from a real VMP case where the decrypted copy was dumped from the wrong segment. | — | | `zip_store.ts` | Stored (no compression) ZIP builder for unpack bundles. | node:zlib | | `hpack.ts` | **HPACK decoder** (RFC 7541). One dynamic table per direction; static table and Huffman codes are the RFC tables. Used only by `http2.ts`. Unit-tested (`test/hpack.test.ts`, C.4.1 then C.4.2). | — | | `http2.ts` | **HTTP/2 frames → whole messages.** Strips the client preface, walks DATA/HEADERS/CONTINUATION, decodes header blocks in order. Server push updates the table and is not listed as its own request. | `hpack.ts` | @@ -52,7 +55,7 @@ forbidden conclusions, one proposed next call and an identifier checkpoint. No p | `capstone.ts` | Pure host-side raw-byte AArch64 disassembly through Capstone 5 (WASM); no daemon state. | `capstone-wasm` | | `memory.ts` | Live memory helpers combining agent `read` with host-side Capstone (`liveDisasm`, module+offset resolution). | `service.ts`, `capstone.ts` | | `native_hook_args.ts` | Shared native-hook install payload: `normalizeThrottleMs` and `parseMemWindows` (hit-time `auto` / `x0:64` / `x0+16:32`, caps aligned with `ADH_MEM_WIN_*`). `auto` is canonicalized to `auto`. `memCapturePreview` turns a `NATIVE_HOOK_MEM` payload into the line the capture list shows. A bad window throws so the hook is not installed without its copy. | — | -| `native_look.ts` | **One native observation.** `arm` stands at a function (`mem` defaults to `auto`), `read` joins the latest `NATIVE_HOOK` and `NATIVE_HOOK_MEM` for that hookId into one result whose `text` is the line to show, `stop` soft-unhooks so the address can be armed again. Pure `joinNativeLook` is unit-tested. | `state.ts`, `service.ts`, `native_hook_args.ts` | +| `native_look.ts` | **One native observation.** `arm` stands at a function (`mem` defaults to `auto`), `read` joins the newest `NATIVE_HOOK` and `NATIVE_HOOK_MEM` for that hookId and reports `retained.total`. `seq` or `beforeSeq`+`limit` reads an older retained hit. `stop` soft-unhooks so the address can be armed again. Pure `joinNativeLook` / `selectNativeLook` are unit-tested. | `state.ts`, `service.ts`, `native_hook_args.ts` | | `native_hook_all.ts` | Batch native hooking by exported-symbol pattern: parses the module dump with `parseDynSymbols`, filters exported FUNCTIONS by prefix/contains/exact (deterministic address order, optional exclude), installs inline hooks up to the 16-slot ceiling and reports matched vs installed plus per-symbol failures; `nativeUnhookAll` removes exactly the given ids. Pure `selectExportSymbols` is unit-tested. | `service.ts`, `module_symbols.ts`, `backtrace.ts` | | `java_trace.ts` | Class-level Java tracing in three phases (start = hook_all and keep the hooks, digest = drain + group JAVA_HOOK events per method with a timeline and caller histogram, stop = unhook exactly those ids). Pure `digestJavaTrace` is unit-tested. | `state.ts`, `service.ts` | | `oracle.ts` | **Controlled invocation + differential harness** (the primitive that turns "unknown parameter" into a small search space without target knowledge). `record` calls a facade once via the DETACHED java_call (a blocking method parks one thread, not the session) and keeps its arguments as a reusable template; `extract` names the observed value by path and a JSON-looking string is parsed while walking (`result[0].b5` works for a facade returning a JSON string); `replay` re-runs the template with patches applied to the RECORDED arguments (byte payloads stay `{$bytesHex}`, so `[1][0].$bytesHex` is an ordinary path); `diff` runs one replay per variant and returns the dependency matrix (`sensitive` = single-field patches that moved the value, `insensitive` = those that never did; multi-patch variants are not used for attribution). Pure `getPath`/`setPath`/`summarizeDiff` are unit-tested. | `service.ts` (agentCmd) | diff --git a/daemon/src/analysis_guide.ts b/daemon/src/analysis_guide.ts index 28824a7..155b9a3 100644 --- a/daemon/src/analysis_guide.ts +++ b/daemon/src/analysis_guide.ts @@ -1,16 +1,18 @@ // Host-only help, served through MCP so remote clients need no repository access. // Templates are instructions, never executed here; all $variables need live evidence. -export const ANALYSIS_GUIDE_TOPICS = ['start', 'writer', 'crypto', 'trace', 'stuck'] as const; +export const ANALYSIS_GUIDE_TOPICS = ['start', 'callgraph', 'writer', 'crypto', 'trace', 'stuck'] as const; export type AnalysisGuideTopic = typeof ANALYSIS_GUIDE_TOPICS[number]; export const MCP_INSTRUCTIONS = 'ADH is an Android runtime analysis workbench. Start with analysis_guide(topic="start"), ' + 'then process_list and capabilities for one explicit session; sessions change after reconnect. ' + 'When context is missing, call analysis_guide(action="assess",topic="stuck",session=theSelectedId,hookId=theActualIdIfKnown). ' + 'Assessment reads current Host evidence and at most one bounded native-hook status query, then returns facts, missing evidence, one proposed next call and a resumable identifier checkpoint; it installs nothing. ' + + 'Use analysis_guide(topic="callgraph") FIRST when you do not yet know which functions matter: it turns the kernel callchain that root_watch already records into a runtime call graph, so you stop guessing addresses. ' + 'Use analysis_guide(topic="writer") to find who writes a known buffer via root_watch; ' + 'topic="crypto" for paired input/output evidence, "trace" for bounded instruction records, and "stuck" for failures. ' + 'Guides return ordered tool-call templates, prerequisites, checks and failure branches, without executing target operations. ' + 'Replace $variables from live results, never guess an address, TID, key or invocation pairing. ' + + 'native_look read returns the newest hit and retained.total; pass seq, or beforeSeq plus limit, for earlier hits of that same hook. ' + 'An online socket does not prove responsiveness; use runtime_diagnostics when commands hang. ' + 'Check capture loss and completeness before making claims. In-hook QBDI is replay with side effects and incomplete context; ' + 'active-call traces cover the instrumented module, not the original whole execution. A primitive match does not prove a final signature.'; @@ -40,8 +42,31 @@ const guides: Record = { { goal: 'Read capabilities of that running build.', tool: 'capabilities', arguments: { session: '$session' }, check: 'Inspect caps.ops and limits. Different processes may run different agent builds.' }, { goal: 'Assess actual retained evidence without reconstructing the full conversation.', tool: 'analysis_guide', arguments: { action: 'assess', topic: 'start', session: '$session' }, check: 'Read stage/facts/missingEvidence/doNotConclude and the proposed next call. Then choose writer, crypto, trace or stuck for the intended task.' }, ], - limits: ['Guidance is not an automatic algorithm solver.', 'No session: diagnose connection/injection setup; do not fabricate a session.', 'Purpose-built recipes are listed by recipe(action="list"); inspect their effects and prerequisites before running one.'], + limits: ['Guidance is not an automatic algorithm solver.', 'No session: diagnose connection/injection setup; do not fabricate a session.', 'Purpose-built recipes are listed by recipe(action="list"); inspect their effects and prerequisites before running one.', 'A native hook keeps earlier hits. native_look read reports retained.total for the newest; pass seq or beforeSeq+limit to read an older one instead of re-running the call.', 'argIndex/argValue on native_hook rewrites that argument. filter is one equality on x0-x8 (x2=16). Memory windows dereference with @x0:16 and a second hop @#1+8:16; registers only x0-x8.', 'A callable Java facade is recorded with oracle action record, then compared with action diff. Do not hand-write a replay script for that.', 'When you do not yet know which functions matter, read topic=callgraph before probing addresses: root_watch already records the runtime caller chain.', 'Two skills ship with the docs and cover the failure modes that cost the most time: docs/SKILL-callgraph-first.md (get the call graph before guessing breakpoints) and docs/SKILL-evidence-hygiene.md (per-byte sensitivity scans, dynamic normalisation parameters, proving that static code actually executes).'], }, + callgraph: { + title: 'Map what actually runs before guessing addresses', + prerequisites: ['A rooted supported device and an online session with a known hot instruction or entry point.', 'Do this BEFORE probing candidate functions: root_watch already records the kernel callchain on every event, so the runtime call graph is free evidence you would otherwise guess.'], + variables: { + session: 'Selected online sessionId.', + tid: 'Thread that actually executes the work, from android.os.Process.myTid via java_call when the target is Java-driven; a native_call worker TID is not a persistent executor.', + entry: 'Verified hot address, e.g. a dispatch branch, a function entry, or an address returned by native_backtrace. Never a guessed address.', + runId: 'id returned by root_watch start (not sessionId, not hookId).', + pc: 'A caller frame address taken from a previous chain, used as the next anchor.', + }, + steps: [ + { goal: 'Arm an execution breakpoint on the anchor with no extra work.', tool: 'root_watch', arguments: { action: 'start', session: '$session', tid: '$tid', addr: '$entry', width: 4, mode: 'x', durationMs: 5000, maxEvents: 128, stackBytes: 0 }, check: 'Keep id. Trigger the intended operation after start succeeds.', onFailure: 'Zero events means the anchor never executed on that thread: the address is wrong or the work runs elsewhere. Do not conclude "no code here" from a zero count alone.' }, + { goal: 'Read events and symbolise the chain field.', tool: 'root_watch', arguments: { action: 'read', id: '$runId', afterSeq: 0, limit: 8, registers: true }, check: 'Every event carries chain[]: the kernel-recorded caller chain, already the runtime call graph. Map each address into its module range to get module+offset. A chain of length 1 means the kernel could not unwind further, not that the caller is the root.' }, + { goal: 'Confirm the frame order is stable before trusting it.', tool: 'root_watch', arguments: { action: 'read', id: '$runId', afterSeq: 8, limit: 32, registers: true }, check: 'The same operation should produce the same chain every time. A chain that changes between identical triggers means you are sampling different work, not one call path.' }, + { goal: 'Pick the next anchor from the chain, not from a static guess.', tool: 'root_watch', arguments: { action: 'start', session: '$session', tid: '$tid', addr: '$pc', width: 4, mode: 'x', durationMs: 5000, maxEvents: 64, stackBytes: 0 }, check: 'Walk outward frame by frame: entry, then its caller, then the caller caller. Stop when the frame belongs to another module or to the runtime.' }, + ], + limits: [ + 'chain is kernel-collected. It survives stack-pointer obfuscation that breaks frame-pointer walking, so prefer chain over native_backtrace when the target mutates sp.', + 'A single-frame chain is real evidence of a missing unwind entry, not proof of a direct call.', + 'root_watch watches ONE existing TID. Work on another thread needs its own run.', + 'Anchors must come from observed evidence. A static disassembly address that never fires is not a call graph edge.', + ], + }, writer: { title: 'Find the real writer of a known buffer', prerequisites: ['A rooted supported device, an online session, a live target buffer address, and evidence for the thread that will write it.', 'Obtain the buffer from native_hook mem/memAfter or native_look/live_captures; use memory_read when necessary. An address is not inferred from buffer contents.'], @@ -65,10 +90,19 @@ const guides: Record = { crypto: { title: 'Verify paired bytes without promoting an intermediate match to the final algorithm', prerequisites: ['Complete input/output bytes, an explicit pairing basis, and actual key/mask bytes for candidates that need them.'], - variables: { captureId: 'Exact capture id returned by live_captures; identify the particular mem window with reg/offset rather than nearest timestamp.' }, + variables: { + captureId: 'Exact capture id returned by live_captures; identify the particular mem window with reg/offset rather than nearest timestamp.', + session: 'Selected online sessionId.', + className: 'Java class of a facade that is already callable.', + method: 'Method name on that class.', + params: 'Comma-separated Java parameter types; empty means no-arg.', + oracleArgs: 'JSON array of one real call\'s arguments, using {"$bytesHex":"..."} for a byte[].', + }, steps: [ { goal: 'Inspect supported candidates.', tool: 'crypto_evidence', arguments: { action: 'algorithms' }, check: 'Use known candidates and observed parameters; the tool does not derive an unknown key or mask.' }, { goal: 'Inspect one exact record before choosing its fields.', tool: 'capture_detail', arguments: { id: '$captureId' }, check: 'Check session/PID/TID, hookId/seq/callId, original length, phase, requested/got and truncation. Same TID/time alone does not prove pairing.' }, + { goal: 'Capture JCA input and output with the built-in hooks.', tool: 'java_hook', arguments: { action: 'crypto', session: '$session' }, check: 'Arms Cipher, Mac, MessageDigest and Signature only. Nothing is installed at inject. Read the resulting captures before writing your own hook.', onFailure: 'no JavaVM: report that this session has no Java capture, and do not keep reinstalling the hook.' }, + { goal: 'Record one real facade call so a later diff can name the input that moves the output.', tool: 'oracle', arguments: { action: 'record', session: '$session', className: '$className', method: '$method', params: '$params', args: '$oracleArgs', extract: 'result' }, check: 'Keep the returned id. action diff with variants is the comparison. Do not hand-write a replay script that rebuilds this.', onFailure: 'No such method: the facade is not known yet. Find it before recording; do not invent arguments.' }, { goal: 'Learn the complete observation shape with a public format-only vector.', tool: 'crypto_evidence', arguments: { action: 'analyze', observations: [{ id: 'public-format-example', role: 'intermediate', algorithms: ['md5'], pairing: { basis: 'analyst', note: 'Public abc MD5 vector demonstrates input format only; this is not target evidence.' }, @@ -77,7 +111,7 @@ const guides: Record = { }], }, check: 'This example should match once. For real data replace the entire observation with actual sources; a selector can be {captureId,field:"mem",reg:"x0",offset:0}. Whole-capture selectors also support payload/key/output. Use key or params:{add,xor} when required.' }, ], - limits: ['Select exactly one hex/b64/utf8 encoding per explicit field; preserve raw JSON/request bytes.', 'Missing/truncated/mispaired bytes are unavailable, not a mismatch. Never relabel a prefix complete or override known capture loss.', 'Inspect analysisComplete and captureCollectionComplete separately. Matching one intermediate stage does not prove the final field, initialization, causality or cross-device derivation.', 'Use action save/read/list/drop for the private ledger. Ordinary read is bounded; includePayload=true explicitly expands raw material.'], + limits: ['Select exactly one hex/b64/utf8 encoding per explicit field; preserve raw JSON/request bytes.', 'Missing/truncated/mispaired bytes are unavailable, not a mismatch. Never relabel a prefix complete or override known capture loss.', 'Inspect analysisComplete and captureCollectionComplete separately. Matching one intermediate stage does not prove the final field, initialization, causality or cross-device derivation.', 'Use action save/read/list/drop for the private ledger. Ordinary read is bounded; includePayload=true explicitly expands raw material.', 'When the facade is already callable, oracle action record then action diff answers which input moved the output. Do not hand-write that differential.'], }, trace: { title: 'Record and query a bounded active-call instruction trace', @@ -98,7 +132,7 @@ const guides: Record = { steps: [ { goal: 'Interpret current counters and retained records first.', tool: 'analysis_guide', arguments: { action: 'assess', topic: 'stuck', session: '$session', hookId: '$hookId' }, check: 'Read facts and missingEvidence. Assessment performs at most one bounded read-only native hook status query; it does not install, drain or trigger anything. A proposed next call is not an executed call.' }, { goal: 'Inspect process facts independently of the agent channel.', tool: 'runtime_diagnostics', arguments: { session: '$session', limit: 32 }, check: 'Distinguish frozen, traced, process-exited, identity-mismatch, running and unknown. Check errors and completeness of thread paging.' }, - { goal: 'Read stored hook evidence and observation counts.', tool: 'native_look', arguments: { action: 'read', session: '$session', hookId: '$hookId' }, check: 'Distinguish hits=0 from filtered/sampledOut/throttled/limited, stored record loss, drainError and observationError.', onFailure: 'Unknown hook/session: re-list sessions and actual hook status. Do not invent a replacement hookId.' }, + { goal: 'Read stored hook evidence and observation counts.', tool: 'native_look', arguments: { action: 'read', session: '$session', hookId: '$hookId' }, check: 'Distinguish hits=0 from filtered/sampledOut/throttled/limited, stored record loss, drainError and observationError. retained.total counts numbered hits still stored; pass seq or beforeSeq+limit for an earlier one instead of re-running the call.', onFailure: 'Unknown hook/session: re-list sessions and actual hook status. Do not invent a replacement hookId.' }, { goal: 'Inspect current physical hook budget when the agent responds.', tool: 'native_hook', arguments: { action: 'status', session: '$session' }, check: 'Non-default new observation controls require observationControlsVersion>=1. Retired slots are not reclaimed by unhook; exhausted 16-slot budget requires a new target process, never an automatic restart.' }, ], limits: ['No hardware events can also mean wrong address/TID, no trigger, a frozen thread, or an unsupported kernel; absence alone proves none of these.', 'Missing facts stay unknown; report the failed prerequisite instead of silently dropping filters or substituting replay.', 'Read diagnostics first; target restarts and other changes require an authorized workflow.'], diff --git a/daemon/src/app_analyze.ts b/daemon/src/app_analyze.ts new file mode 100644 index 0000000..9e4e01a --- /dev/null +++ b/daemon/src/app_analyze.ts @@ -0,0 +1,151 @@ +// app_analyze.ts — "analyze this app" as ONE call, from a package name to a bounded report. +// +// The pieces already existed but the order was knowledge: add the package to the injection scope, +// cold start it, wait for the Zygisk-injected agent, then run triage/unpack/http_capture against the +// right process. Recipes orchestrate primitives for an EXISTING session; this module owns the part +// before the session exists, which is exactly what a human (or an AI client) has when it only knows +// the app. +// +// Rules kept from recipes.ts: every phase is reported with ok/detail, a failed phase does not throw +// away the others, and each phase returns a small summary instead of a multi-megabyte agent reply. +import { coldStartPackage, mayLaunchPackage, waitForFreshSessions } from './app_launch.ts'; +import { preferMainProcess } from './dump_inventory.ts'; +import { runRecipe } from './recipes.ts'; +import { mergeScope, packageInstalled, readScopeFile, writeScopePackages } from './scope_list.ts'; +import { onlineSessionsForPackage, runUnpackBundle } from './service.ts'; + +export interface AnalyzeOptions { + /** Add the package to the phone's injection allowlist when it is missing. Default: true. */ + autoScope?: boolean; + /** Force-stop and relaunch even when the app already has an online agent. */ + forceRestart?: boolean; + /** Triage observation window (ms) while capture is armed. Default 3000. */ + captureMs?: number; + /** Dump every DEX into a stored bundle. Default: false (triage alone is the fast answer). */ + unpack?: boolean; + /** Arm TLS capture, wait and pair HTTP exchanges. 0 = skip. */ + httpCaptureMs?: number; + /** How long to wait for the injected agent after cold start. Default 60000. */ + timeoutMs?: number; + /** Extra settle time after the first agent of a package connects. Default 4000. */ + settleMs?: number; +} + +type Phase = { ok: boolean; detail?: unknown; error?: string }; + +/** The main process (no ':') is the one a caller means by "the app"; fall back to the newest. */ +export function pickAnalysisSession(rows: readonly T[]): T | null { + return preferMainProcess(rows); +} + +export async function analyzePackage(pkg: string, opts: AnalyzeOptions = {}) { + const name = String(pkg ?? '').trim(); + const started = Date.now(); + const phases: Record = {}; + if (!mayLaunchPackage(name)) { + return { ok: false, package: name, error: '这个包名不能分析(系统包、ADH 自己,或包名不合法)', phases }; + } + if (!(await packageInstalled(name))) { + return { ok: false, package: name, error: `未安装:${name}`, phases }; + } + + // 1) scope — without it the companion never injects, and the failure would look like "the app + // refused us". The write is reported, because it changes device state the operator should know. + let scopeAdded = false; + const scope = await readScopeFile(); + phases.scope = { ok: scope.error === null, detail: { packages: scope.packages.length, error: scope.error } }; + if (!scope.packages.includes(name)) { + if (opts.autoScope === false) { + return { ok: false, package: name, error: `不在注入作用域:${name}(autoScope:false)`, scope: scope.packages, phases }; + } + const merged = mergeScope(scope.packages, { add: [name] }); + const written = await writeScopePackages(merged, { version: scope.version, mode: scope.mode }); + if (!written.ok) { + return { ok: false, package: name, error: `加入注入作用域失败:${written.error}`, phases }; + } + scopeAdded = true; + phases.scope = { ok: true, detail: { added: name, packages: written.packages.length } }; + } + + // 2) a live process — reuse when it already has an agent, otherwise cold start and wait. + let launch: unknown = null; + const existing = onlineSessionsForPackage(name); + let rows = existing; + if (!existing.length || opts.forceRestart === true) { + const since = Date.now(); + const startedApp = await coldStartPackage(name); + launch = startedApp; + if (!startedApp.ok) { + phases.launch = { ok: false, error: startedApp.error || '启动失败', detail: startedApp }; + return { ok: false, package: name, error: startedApp.error || '启动失败', scopeAdded, phases }; + } + const waited = await waitForFreshSessions(() => onlineSessionsForPackage(name), { + sinceMs: since, + timeoutMs: opts.timeoutMs ?? 60_000, + settleMs: opts.settleMs ?? 4_000, + }); + phases.launch = { ok: waited.ok, detail: { mode: startedApp.mode, waitedMs: waited.waitedMs, error: waited.error } }; + if (!waited.ok) { + return { ok: false, package: name, error: waited.error || '等待注入超时', scopeAdded, launch, phases }; + } + rows = onlineSessionsForPackage(name); + } else { + phases.launch = { ok: true, detail: { mode: 'reuse-online', sessions: existing.length } }; + } + + const main = pickAnalysisSession(rows); + if (!main) { + return { ok: false, package: name, error: '目标没有在线进程', scopeAdded, launch, phases }; + } + const sid = main.sessionId; + + // 3) triage — the "what is this app doing" answer. A failed step is listed, not hidden. + try { + const triage = await runRecipe('triage', sid, { captureMs: opts.captureMs ?? 3000 }); + phases.triage = { + ok: triage.ok, + detail: { + summary: triage.summary, + failedSteps: triage.steps.filter((s) => !s.ok).map((s) => ({ step: s.step, error: s.error })), + }, + }; + } catch (e) { + phases.triage = { ok: false, error: (e as Error).message }; + } + + // 4) optional unpack — every DEX into the artifact store. + if (opts.unpack) { + try { + const u = await runUnpackBundle({ package: name, launch: false }); + phases.unpack = { ok: u.ok, detail: { bundle: u.bundle, included: (u.included ?? []).length, error: u.error } }; + } catch (e) { + phases.unpack = { ok: false, error: (e as Error).message }; + } + } + + // 5) optional traffic window — what the app actually sends. + if (opts.httpCaptureMs && opts.httpCaptureMs > 0) { + try { + const h = await runRecipe('http_capture', sid, { ms: opts.httpCaptureMs }); + phases.http = { ok: h.ok, detail: h.summary }; + } catch (e) { + phases.http = { ok: false, error: (e as Error).message }; + } + } + + return { + ok: Object.values(phases).every((p) => p.ok), + package: name, + session: sid, + process: main.process, + pid: main.pid, + agentVer: main.agentVer, + entry: main.entry, + selfModule: main.selfModule, + scopeAdded, + elapsedMs: Date.now() - started, + processes: rows.map((r) => ({ process: r.process, pid: r.pid, session: r.sessionId })), + phases, + hint: 'counts grow only while capture is armed; pass httpCaptureMs for a traffic window and unpack:true for all DEX', + }; +} diff --git a/daemon/src/error_codes.ts b/daemon/src/error_codes.ts new file mode 100644 index 0000000..21dbb0e --- /dev/null +++ b/daemon/src/error_codes.ts @@ -0,0 +1,52 @@ +// error_codes.ts — machine-readable failure classes for every MCP tool. +// +// Why: before this, every failure was `{ ok:false, error:"" }`. A client could not tell +// "you passed a bad argument" (retry differently) from "the session is gone" (restart the target) +// from "the capture ring dropped events" (do NOT conclude anything). That distinction is the +// difference between one retry and a wasted analysis round, and the field reports from real targets +// name exactly this as a top pain. +// +// The classifier is pattern-based on purpose: the daemon already produces honest prose, and this +// module adds a stable enum on top without pretending to be a typed error hierarchy. A client that +// gets UNKNOWN still has the message; a client that gets a code can branch. + +export type ErrorCode = + | 'BAD_ARG' + | 'NO_SESSION' + | 'SESSION_OFFLINE' + | 'AGENT_TIMEOUT' + | 'UNSUPPORTED_OP' + | 'TARGET_CRASHED' + | 'CAPTURE_LOSS' + | 'HELPER_MISSING' + | 'DEVICE_UNAVAILABLE' + | 'UNKNOWN'; + +interface Rule { code: ErrorCode; re: RegExp } + +// Order matters: the first match wins. Loss/incompleteness is checked first because those messages +// often also contain a timeout or a bad-arg word, and misrouting them to BAD_ARG is exactly the +// failure mode this module exists to prevent. BAD_ARG is last so it cannot shadow the others. +const RULES: Rule[] = [ + { code: 'CAPTURE_LOSS', re: /dropped|evicted|complete:\s*false|ring .*full|storeLoss|incomplete/i }, + { code: 'HELPER_MISSING', re: /build_root_watch|helper|not built|prepare failed|missing helper/i }, + { code: 'UNSUPPORTED_OP', re: /unsupported|unknown (op|operation)|not available|old agent|does not support|not implemented|no such op/i }, + { code: 'NO_SESSION', re: /no session|no online agent|session .*not found|session required|需要.*session|没有在线/i }, + { code: 'SESSION_OFFLINE', re: /offline|disconnected|socket hang up|ECONNRESET|connection closed|not connected/i }, + { code: 'AGENT_TIMEOUT', re: /timed out|timeout|still running after|超时/i }, + { code: 'TARGET_CRASHED', re: /crashed|killed by signal|SIGSEGV|SIGBUS|died|target exited/i }, + { code: 'DEVICE_UNAVAILABLE', re: /no device|device offline|unauthorized|adb .*not found|没有在线设备/i }, + { code: 'BAD_ARG', re: /must be|needs |requires |missing |invalid |expected |did not parse|cannot be|cannot parse|unknown argument|不支持.*参数|参数/i }, +]; + +export function classifyError(input: unknown): ErrorCode { + const text = input instanceof Error ? input.message : String(input ?? ''); + for (const rule of RULES) if (rule.re.test(text)) return rule.code; + return 'UNKNOWN'; +} + +/** The payload every MCP tool failure is rendered as. Keeps `ok:false` for older clients. */ +export function errorPayload(e: unknown): { ok: false; code: ErrorCode; error: string } { + const message = (e instanceof Error ? e.message : String(e ?? 'error')) || 'error'; + return { ok: false, code: classifyError(message), error: message }; +} diff --git a/daemon/src/http/routes_system.ts b/daemon/src/http/routes_system.ts index 53025d1..e6b0746 100644 --- a/daemon/src/http/routes_system.ts +++ b/daemon/src/http/routes_system.ts @@ -10,7 +10,8 @@ import { assembleHttpExchanges, type TlsChunk } from '../http_exchange.ts'; import { AGENT_PORT, webUrls } from '../config.ts'; import { baseFromHost, isValidPackage, mcpOnboarding } from '../mcp_onboarding.ts'; import { handleMcp, MCP_TOOLS } from '../mcp.ts'; -import { scopedApps } from '../scope_list.ts'; +import { scopedApps, mergeScope, readScopeFile, writeScopePackages } from '../scope_list.ts'; +import { analyzePackage } from '../app_analyze.ts'; import { applyCaptureEnabled, listCaptureArmProtected } from '../service.ts'; import { applyCaptureRetainCap, broadcast, captureHealth, capturePackage, captures, captureTimers, @@ -42,6 +43,49 @@ export function systemRoutes({ req, res, url, send }: RouteContext): Route[] { unpackProtected: listCaptureArmProtected(), }); } }, + // Host-side allowlist control (the AI/operator channel): the companion reads scope.json at + // process specialization, so an added package is injected on its next cold start. + { method: 'GET', path: '/api/scope', handler: async () => { + const s = await readScopeFile(); + return send(200, { ok: s.error === null, packages: s.packages, version: s.version, mode: s.mode, error: s.error }); + } }, + { method: 'POST', path: '/api/scope', handler: async () => { + let body: any; + try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return send(400, { error: 'bad json' }); } + const cur = await readScopeFile(); + if (cur.error) return send(503, { ok: false, error: cur.error }); + const before = cur.packages; + const next = Array.isArray(body.set) + ? mergeScope([], { add: body.set }) + : mergeScope(before, { add: body.add, remove: body.remove }); + const w = await writeScopePackages(next, { version: cur.version, mode: cur.mode }); + if (!w.ok) return send(502, { ok: false, error: w.error, packages: before }); + return send(200, { + ok: true, packages: w.packages, + added: w.packages.filter((p) => !before.includes(p)), + removed: before.filter((p) => !w.packages.includes(p)), + note: 'cold start the target to apply', + }); + } }, + // One call from a package name to a report — the "analyze any app" entry point. + { method: 'POST', path: '/api/analyze-app', handler: async () => { + let body: any; + try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return send(400, { error: 'bad json' }); } + const pkg = String(body.package ?? '').trim(); + if (!pkg) return send(400, { error: 'need package' }); + try { + const out = await analyzePackage(pkg, { + autoScope: body.autoScope !== false, + forceRestart: body.forceRestart === true, + captureMs: Number(body.captureMs) > 0 ? Number(body.captureMs) : undefined, + unpack: body.unpack === true, + httpCaptureMs: Number(body.httpCaptureMs) > 0 ? Number(body.httpCaptureMs) : 0, + timeoutMs: Number(body.timeoutMs) > 0 ? Number(body.timeoutMs) : undefined, + settleMs: Number(body.settleMs) > 0 ? Number(body.settleMs) : undefined, + }); + return send(out.ok ? 200 : 502, out); + } catch (e) { return send(500, { ok: false, error: (e as Error).message }); } + } }, { path: '/health', handler: () => send(200, { ok: true, service: 'adhd', name: 'ADH Daemon', version: '0.1.0', agents: sessions.size, uptime: process.uptime(), mcpTools: MCP_TOOLS.length, web: webUrls(), diff --git a/daemon/src/maps_query.ts b/daemon/src/maps_query.ts new file mode 100644 index 0000000..6a0a88e --- /dev/null +++ b/daemon/src/maps_query.ts @@ -0,0 +1,149 @@ +// maps_query.ts — the "which segment is this address in / where is the decrypted copy" primitive. +// +// A full /proc//maps is 2000-5000 lines; dumping it into a model's context is useless, and the +// field report from a real VMP target says exactly what that costs: the decrypted copy lived in an +// anonymous segment, the first dump took an executable segment and returned garbage, and the only +// reason it was caught was a hand-computed entropy difference. This module turns the raw maps reply +// into a filterable, address-resolving view, with "belongs to whom" as a tool fact. + +export interface RawRegion { + start?: string | number; + end?: string | number; + perms?: string; + offset?: string; + dev?: string; + inode?: number; + path?: string; +} + +export interface MapsQuery { + /** Substring match on the path (module name, [anon:...], /dev/...). */ + path?: string; + /** Only regions whose perms start with this (e.g. "r-x" or "rw"). */ + perm?: string; + /** true = executable; false = not executable. */ + exec?: boolean; + /** true = no file-backed path (anonymous); false = file-backed. */ + anon?: boolean; + minSize?: number; + maxSize?: number; + /** 0 or omitted = no limit; the reply always reports matched/truncated. */ + limit?: number; + /** Resolve this address: returns the containing region + module-relative offset. */ + addr?: string; +} + +export interface MapsRow { + start: string; + end: string; + size: number; + perms: string; + offset: string; + path: string; +} + +export interface MapsResolved { + addr: string; + region: MapsRow; + /** File offset of the address inside its backing file, when the region is file-backed. */ + fileOffset: string | null; + /** Address minus region start, in hex. */ + regionOffset: string; +} + +export interface MapsResult { + ok: true; + total: number; + matched: number; + returned: number; + truncated: boolean; + regions: MapsRow[]; + resolved?: MapsResolved; +} + +function toBig(value: string | number | undefined): bigint | null { + if (value === undefined || value === null) return null; + try { + const text = String(value).trim(); + return text.startsWith('0x') ? BigInt(text) : BigInt(`0x${text}`); + } catch { + return null; + } +} + +function hex(value: bigint): string { + return `0x${value.toString(16)}`; +} + +export function normalizeRegion(r: RawRegion): MapsRow | null { + const start = toBig(r.start); + const end = toBig(r.end); + if (start === null || end === null || end <= start) return null; + const size = Number(end - start); + const offset = String(r.offset ?? '0').trim(); + return { + start: hex(start), + end: hex(end), + size, + perms: String(r.perms ?? ''), + offset: offset.startsWith('0x') ? offset : `0x${offset}`, + path: String(r.path ?? '').trim(), + }; +} + +/** Rewrite the resolved address with a module-relative offset, when the region is file-backed. */ +export function resolveAddress(rows: MapsRow[], addr: string): MapsResolved | null { + const target = toBig(addr); + if (target === null) return null; + for (const row of rows) { + const start = toBig(row.start)!; + const end = toBig(row.end)!; + if (target < start || target >= end) continue; + const base = toBig(row.offset); + const fileOffset = row.path && base !== null ? hex(base + (target - start)) : null; + return { + addr: hex(target), + region: row, + fileOffset, + regionOffset: hex(target - start), + }; + } + return null; +} + +export function queryMaps(raw: RawRegion[], q: MapsQuery = {}): MapsResult { + const rows: MapsRow[] = []; + for (const r of Array.isArray(raw) ? raw : []) { + const row = normalizeRegion(r); + if (row) rows.push(row); + } + const total = rows.length; + const perm = q.perm ? String(q.perm) : ''; + const pathNeedle = q.path ? String(q.path).toLowerCase() : ''; + const matches = rows.filter((row) => { + if (pathNeedle && !row.path.toLowerCase().includes(pathNeedle)) return false; + if (perm && !row.perms.startsWith(perm)) return false; + if (q.exec === true && !row.perms.includes('x')) return false; + if (q.exec === false && row.perms.includes('x')) return false; + if (q.anon === true && row.path && !row.path.startsWith('[')) return false; + if (q.anon === false && (!row.path || row.path.startsWith('['))) return false; + if (q.minSize !== undefined && row.size < Number(q.minSize)) return false; + if (q.maxSize !== undefined && row.size > Number(q.maxSize)) return false; + return true; + }); + const limit = Number(q.limit) > 0 ? Math.min(Number(q.limit), 500) : matches.length; + const returned = matches.slice(0, limit); + const result: MapsResult = { + ok: true, + total, + matched: matches.length, + returned: returned.length, + truncated: matches.length > returned.length, + regions: returned, + }; + if (q.addr) { + const resolved = resolveAddress(rows, String(q.addr)); + if (resolved) result.resolved = resolved; + } + return result; +} diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index a8d1bbb..ef9d8b2 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -118,7 +118,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } throw new Error('unknown trace_session action'); } }, - { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. The returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { + { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. The callchain arrives as each event chain[]: the runtime caller stack in absolute addresses, which is the fastest way to learn which functions actually run (see analysis_guide(topic=callgraph)). Use chain instead of native_backtrace when the target obfuscates sp, because frame-pointer walking fails there while the kernel unwind still succeeds. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. The returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { if (a.action === 'prepare') return prepareRootWatch(a.serial); if (a.action === 'start') { const s = sessions.get(String(a.session ?? '')); diff --git a/daemon/src/native_look.ts b/daemon/src/native_look.ts index 8e7fce9..c4e0556 100644 --- a/daemon/src/native_look.ts +++ b/daemon/src/native_look.ts @@ -136,11 +136,13 @@ function traceOf(event: Record): NativeLookTrace | null { }; } -/** Latest hit for one hook. Memory and registers that share a seq are one result. */ -export function joinNativeLook(records: LookRecord[], hookId: number): NativeLook { - const empty: NativeLook = { - hit: false, hookId, seq: null, text: '还没有命中。在手机上做那一步之后再读一次。', windows: [], regs: {}, note: '', trace: null, - }; +const QUIET = '还没有命中。在手机上做那一步之后再读一次。'; + +function emptyLook(hookId: number, text = QUIET): NativeLook { + return { hit: false, hookId, seq: null, text, windows: [], regs: {}, note: '', trace: null }; +} + +function collect(records: LookRecord[], hookId: number): { mems: MemEvent[]; hooks: HookEvent[] } { const mems: MemEvent[] = []; const hooks: HookEvent[] = []; records.forEach((record, index) => { @@ -159,16 +161,14 @@ export function joinNativeLook(records: LookRecord[], hookId: number): NativeLoo hooks.push({ seq: event.seq === undefined ? null : Number(event.seq), regs: regsOf(event), trace: traceOf(event), order }); } }); - if (!mems.length && !hooks.length) return empty; - mems.sort((a, b) => (a.seq - b.seq) || (a.order - b.order)); hooks.sort((a, b) => ((a.seq ?? -1) - (b.seq ?? -1)) || (a.order - b.order)); - const lastSeq = Math.max(0, ...mems.map((m) => m.seq), ...hooks.map((h) => h.seq ?? 0)); - const matchedMems = mems.filter((m) => m.seq === lastSeq); + return { mems, hooks }; +} + +/** Pair one already-chosen hook record with the memory records of the same hit. */ +function assemble(hookId: number, matchedMems: MemEvent[], hook: HookEvent | undefined): NativeLook { const mem = matchedMems.length ? matchedMems[matchedMems.length - 1] : null; - // A missing companion is evidence of an incomplete observation. Never borrow the registers - // from a different hit merely because the capture ring retained those registers. - const hook = lastSeq > 0 ? hooks.filter((h) => h.seq === lastSeq).pop() : hooks[hooks.length - 1]; const windows = matchedMems.flatMap((m) => m.mem.map((w) => ({ ...windowOf(w), phase: m.phase }))); const base = mem ? matchedMems.map((m) => `${matchedMems.length > 1 ? `${m.phase}: ` : ''}${memCapturePreview(JSON.stringify({ auto: m.auto, mem: m.mem })) || '这次命中没有抄到可读的内存。'}`).join(' | ') @@ -192,6 +192,94 @@ export function joinNativeLook(records: LookRecord[], hookId: number): NativeLoo }; } +/** One seq, pairing only records that share it. A missing companion is never filled from another hit. */ +function lookAt(hookId: number, mems: MemEvent[], hooks: HookEvent[], seq: number): NativeLook { + const matchedMems = mems.filter((m) => m.seq === seq); + const hook = hooks.filter((h) => h.seq === seq).pop(); + return assemble(hookId, matchedMems, hook); +} + +function positiveSeqs(mems: MemEvent[], hooks: HookEvent[]): number[] { + const set = new Set(); + for (const m of mems) if (m.seq > 0) set.add(m.seq); + for (const h of hooks) if (h.seq && h.seq > 0) set.add(h.seq); + return [...set].sort((a, b) => a - b); +} + +/** Latest hit for one hook. Memory and registers that share a seq are one result. */ +export function joinNativeLook(records: LookRecord[], hookId: number): NativeLook { + const { mems, hooks } = collect(records, hookId); + if (!mems.length && !hooks.length) return emptyLook(hookId); + const lastSeq = Math.max(0, ...mems.map((m) => m.seq), ...hooks.map((h) => h.seq ?? 0)); + if (lastSeq > 0) return lookAt(hookId, mems, hooks, lastSeq); + // Events that never carried a seq still have one newest hook record. Do not invent a seq for them. + const hook = hooks[hooks.length - 1]; + const matchedMems = mems.filter((m) => m.seq === 0); + if (!hook && !matchedMems.length) return emptyLook(hookId); + return assemble(hookId, matchedMems, hook); +} + +export interface NativeLookQuery { + /** One retained hit. Mutually exclusive with beforeSeq. */ + seq?: number; + /** Page hits whose seq is strictly older than this. Use retained.nextBeforeSeq from the previous read. */ + beforeSeq?: number; + /** Page size 1..50. Defaults to 20 when beforeSeq is set and limit is omitted. */ + limit?: number; +} + +export interface NativeLookSelection { + look: NativeLook; + retained: { total: number; oldestSeq: number | null; newestSeq: number | null; nextBeforeSeq: number | null }; + /** Present only when the caller asked for seq, beforeSeq or limit. Ascending seq. */ + hits?: NativeLook[]; +} + +function pagingQuery(query: NativeLookQuery): void { + if (query.seq !== undefined && query.beforeSeq !== undefined) throw new Error('pass seq or beforeSeq, not both'); + if (query.seq !== undefined && (!Number.isSafeInteger(query.seq) || query.seq < 1)) throw new Error('seq must be a positive integer'); + if (query.beforeSeq !== undefined && (!Number.isSafeInteger(query.beforeSeq) || query.beforeSeq < 1)) throw new Error('beforeSeq must be a positive integer'); + if (query.limit !== undefined && (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 50)) throw new Error('limit must be an integer 1..50'); +} + +/** + * Newest hit by default. `seq` selects one earlier hit. `beforeSeq` plus `limit` pages older hits + * already retained for this hook. Nothing here installs a hook or re-runs the target. + */ +export function selectNativeLook(records: LookRecord[], hookId: number, query: NativeLookQuery = {}): NativeLookSelection { + pagingQuery(query); + const { mems, hooks } = collect(records, hookId); + const seqs = positiveSeqs(mems, hooks); + const newestSeq = seqs.length ? seqs[seqs.length - 1] : null; + const oldestSeq = seqs.length ? seqs[0] : null; + const asked = query.seq !== undefined || query.beforeSeq !== undefined || query.limit !== undefined; + let chosen: number[] = []; + if (query.seq !== undefined) { + if (seqs.includes(query.seq)) chosen = [query.seq]; + } else if (asked) { + const limit = query.limit ?? 20; + const pool = query.beforeSeq === undefined ? seqs : seqs.filter((s) => s < (query.beforeSeq as number)); + chosen = pool.slice(-limit); + } else if (newestSeq !== null) { + chosen = [newestSeq]; + } + const hits = chosen.map((seq) => lookAt(hookId, mems, hooks, seq)); + const nextBeforeSeq = chosen.length && seqs.some((s) => s < chosen[0]) ? chosen[0] : (asked ? null : (seqs.length > 1 ? newestSeq : null)); + let look: NativeLook; + if (query.seq !== undefined && !chosen.length) { + look = emptyLook(hookId, `没有 seq=${query.seq}。已保留的 seq:${seqs.length ? seqs.join(',') : '无'}。`); + } else if (hits.length) { + look = hits[hits.length - 1]; + } else { + look = joinNativeLook(records, hookId); + } + return { + look, + retained: { total: seqs.length, oldestSeq, newestSeq, nextBeforeSeq }, + ...(asked ? { hits } : {}), + }; +} + export interface NativeLookDeps { sendCmd: (session: string, op: string, args: Record, timeout?: number) => Promise; captures: Array<{ id?: number; sessionId?: string; func: string; hex: string; ts?: number }>; @@ -248,13 +336,14 @@ export async function nativeLookArm( }; } -export async function nativeLookRead(session: string, hookId: number, deps: NativeLookDeps = defaultDeps): Promise { +export async function nativeLookRead(session: string, hookId: number, deps: NativeLookDeps = defaultDeps, query: NativeLookQuery = {}): Promise> { if (!Number.isFinite(hookId) || hookId <= 0) throw new Error('need the hookId that arm returned'); const sid = pickSid(session) ?? session; let drainError = '', observationError = ''; try { await deps.drainSession(sid); } catch (e) { drainError = (e as Error).message; } const records = deps.captures.filter((c) => c.sessionId === sid); - const look = joinNativeLook(records, hookId); + const selected = selectNativeLook(records, hookId, query); + const look = selected.look; let observation; try { const reply = await deps.sendCmd(sid, 'native_hook', { action: 'status' }, 10_000); @@ -263,12 +352,12 @@ export async function nativeLookRead(session: string, hookId: number, deps: Nati if (hook && Number.isFinite(hook.emitted)) { observation = Object.fromEntries(['hits', 'selected', 'filtered', 'sampledOut', 'throttled', 'limited', 'emitted', 'maxEvents', 'sampleEvery', 'budgetReached', 'emittedMeaning'] .map((name) => [name, hook[name]])); - if (!look.hit && hook.hits > 0) look.text = `已触发 ${hook.hits} 次,符合筛选 ${hook.selected} 次,提交捕获事件 ${hook.emitted} 条;当前捕获窗口没有保留对应事件。`; + if (!look.hit && hook.hits > 0 && look.text === QUIET) look.text = `已触发 ${hook.hits} 次,符合筛选 ${hook.selected} 次,提交捕获事件 ${hook.emitted} 条;当前捕获窗口没有保留对应事件。`; } if (!hook) observationError = 'hook is absent from active status; retained records remain readable'; else if (!Number.isFinite(hook.emitted)) observationError = 'deployed agent does not expose observation counters'; } catch (e) { observationError = (e as Error).message; } - return { action: 'read', ...look, ...(observation ? { observation } : {}), + return { action: 'read', ...look, retained: selected.retained, ...(selected.hits ? { hits: selected.hits } : {}), ...(observation ? { observation } : {}), ...(observationError ? { observationError } : {}), ...(drainError ? { drainError } : {}) }; } diff --git a/daemon/src/oracle.ts b/daemon/src/oracle.ts index 769dcfe..0df8225 100644 --- a/daemon/src/oracle.ts +++ b/daemon/src/oracle.ts @@ -251,3 +251,56 @@ export async function oracleDiff( } return { ok: true, id: t.id, extract: t.extract, diff: summarizeDiff(t.baseline, rows) }; } + +/** First path where two JSON values differ; null when equal. Used by the stability report. */ +export function firstDifference(a: unknown, b: unknown, path = ''): string | null { + if (a === b) return null; + if (typeof a !== typeof b || a === null || b === null) return path || ''; + if (Array.isArray(a) && Array.isArray(b)) { + const n = Math.max(a.length, b.length); + for (let i = 0; i < n; i++) { + const d = firstDifference(a[i], b[i], `${path}[${i}]`); + if (d) return d; + } + return null; + } + if (typeof a === 'object' && typeof b === 'object') { + const left = a as Record, right = b as Record; + for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) { + const d = firstDifference(left[key], right[key], path ? `${path}.${key}` : key); + if (d) return d; + } + return null; + } + return path || ''; +} + +/** + * Determinism check: replay the SAME arguments `repeat` times and report whether the observed value + * is stable. A pure function answers the same bytes every time; a hidden counter / clock / random + * input does not. This is the first question a black-box search must answer (the field report from a + * VMP target: "the non-purity of dhw was discovered only by hand, after four rounds of key guessing"), + * and it must not require a hand-written double replay. + */ +export async function oracleStability( + session: string, + opts: { id: number; repeat?: number; patches?: Patch[]; timeoutMs?: number }, + deps: OracleDeps = defaultDeps, +): Promise<{ ok: boolean; id?: number; repeat?: number; runs?: number; distinct?: number; stable?: boolean; values?: unknown[]; extract?: string; firstDiff?: string | null; error?: string }> { + const t = templates.get(Number(opts.id)); + if (!t) return { ok: false, error: `unknown oracle id ${opts.id} (record one first)` }; + const repeat = Math.max(1, Math.min(8, Number(opts.repeat) > 0 ? Number(opts.repeat) : 3)); + const values: unknown[] = []; + for (let i = 0; i < repeat; i++) { + const r = await oracleReplay(session, { id: t.id, patches: opts.patches, timeoutMs: opts.timeoutMs }, deps); + if (!r.ok) return { ok: false, error: `run ${i + 1}: ${r.error}` }; + values.push(r.value); + } + const serialized = values.map((v) => JSON.stringify(v)); + const distinct = new Set(serialized).size; + let firstDiff: string | null = null; + for (let i = 1; i < values.length && !firstDiff; i++) { + if (serialized[i] !== serialized[0]) firstDiff = firstDifference(values[0], values[i]); + } + return { ok: true, id: t.id, repeat, runs: values.length, distinct, stable: distinct === 1, values, extract: t.extract, firstDiff }; +} diff --git a/daemon/src/scope_list.ts b/daemon/src/scope_list.ts index 8b53127..e94bc87 100644 --- a/daemon/src/scope_list.ts +++ b/daemon/src/scope_list.ts @@ -244,3 +244,91 @@ export async function scopedApps(now = Date.now()): Promise<{ apps: ScopedApp[]; // Switcher truth = scope.json only. Capture history on disk must not invent checked apps. return { apps: scopeSwitcherApps(cache.packages), error: cache.error }; } + +// --- scope write (host = the AI/operator channel) ------------------------------------------------ +// The Zygisk companion reads scope.json at process specialization, so a package added here is only +// injected after its next cold start. The device daemon owns the file at runtime; writing it through +// adb+su is the host-side equivalent of the Manager switch and keeps "analyze any app" scriptable. + +const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/; + +export interface ScopeFile { packages: string[]; version: number; mode: string; error: string | null } + +/** Full scope.json (packages + version/mode), read through root. Never throws: errors are reported. */ +export async function readScopeFile(): Promise { + try { + const raw = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); + const start = raw.indexOf('{'); + const end = raw.lastIndexOf('}'); + const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); + const obj = text ? JSON.parse(text) as { packages?: unknown; version?: unknown; mode?: unknown } : {}; + return { + packages: parseScopePackages(raw), + version: Number(obj.version) || 2, + mode: typeof obj.mode === 'string' && obj.mode ? obj.mode : 'allowlist', + error: null, + }; + } catch (e) { + return { packages: [], version: 2, mode: 'allowlist', error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; + } +} + +/** Pure merge: `add` wins over `remove`? No — an explicit remove in the same call wins. */ +export function mergeScope(current: string[], op: { add?: unknown[]; remove?: unknown[] }): string[] { + const clean = (list: unknown[] | undefined) => (list ?? []) + .map((p) => String(p ?? '').trim()) + .filter((p) => PKG_RE.test(p) && p !== MANAGER_PKG); + const out = new Set(current.filter((p) => PKG_RE.test(p))); + for (const p of clean(op.add)) out.add(p); + for (const p of clean(op.remove)) out.delete(p); + return [...out]; +} + +export async function packageInstalled(pkg: string): Promise { + if (!PKG_RE.test(pkg)) return false; + try { + const out = await adbShell(`pm path ${pkg}`); + return /^package:/m.test(out); + } catch { + return false; + } +} + +/** + * Replace the allowlist. Read back after writing: a silent half-write would mean the next cold start + * is not injected and the analysis then looks like "the app refused the agent" (a false negative we + * cannot afford). The file's SELinux label is part of the write, not an afterthought. + */ +export async function writeScopePackages( + packages: string[], + meta: { version?: number; mode?: string } = {}, +): Promise<{ ok: boolean; packages: string[]; error?: string }> { + const clean = [...new Set(packages.map((p) => p.trim()).filter((p) => PKG_RE.test(p)))]; + const body = `${JSON.stringify({ version: meta.version ?? 2, mode: meta.mode ?? 'allowlist', packages: clean }, null, 2)}\n`; + const dir = mkdtempSync(join(tmpdir(), 'adh-scope-')); + const local = join(dir, 'scope.json'); + try { + writeFileSync(local, body, 'utf8'); + await execFileP('adb', [...adbBase(), 'push', local, '/data/local/tmp/adh-scope.json'], { + timeout: 20000, windowsHide: true, maxBuffer: 1024 * 1024, + }); + await adbShell("su -c 'cp /data/local/tmp/adh-scope.json /data/adb/adh/scope.json'"); + await adbShell("su -c 'chown root:root /data/adb/adh/scope.json && chmod 644 /data/adb/adh/scope.json'"); + // Label is explicit: `cp` may otherwise inherit the temp file's label and the companion's read + // then fails closed (no injection, no error the operator can see). + await adbShell("su -c 'chcon u:object_r:adb_data_file:s0 /data/adb/adh/scope.json'"); + await adbShell("rm -f /data/local/tmp/adh-scope.json"); + const back = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); + const got = parseScopePackages(back); + if (JSON.stringify(got) !== JSON.stringify(clean)) { + return { ok: false, packages: clean, error: `scope write did not stick (wrote ${clean.length}, read back ${got.length})` }; + } + cache = { at: Date.now(), packages: got, error: null }; + return { ok: true, packages: got }; + } catch (e) { + return { ok: false, packages: clean, error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; + } finally { + try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp cleanup only */ } + } +} + diff --git a/daemon/src/service.ts b/daemon/src/service.ts index c7f130b..209da81 100644 --- a/daemon/src/service.ts +++ b/daemon/src/service.ts @@ -16,7 +16,7 @@ import { } from './state.ts'; import { shouldAutoArmPackage, scopedApps } from './scope_list.ts'; import type { AgentSession, DumpMeta, MapsRegion, Capture } from './state.ts'; -import { nativeHookIdentity } from './state.ts'; +import { broadcastLive, inflight, nativeHookIdentity } from './state.ts'; // dex_index.ts imports state.ts, not this file, so this edge cannot form a cycle; it is here so // artifact retention can drop the index row of a dex it deletes. import { deleteDexDocument, ensureDexIndex } from './dex_index.ts'; @@ -30,24 +30,74 @@ import { buildStoredZip } from './zip_store.ts'; // ---- agent command transport --------------------------------------------- // Issue a command to an agent and await its cmdResult (10s default timeout). +// +// A command that outlives a few seconds is the normal case for the analysis primitives (a QBDI trace +// runs to its budget, root_watch waits out its window, a dump walks a large mapping). Over plain +// request/response the caller sees NOTHING until it either returns or times out, which is +// indistinguishable from a wedged target - measured: a 6 s trace and a dead agent looked identical. +// So every in-flight command reports a heartbeat on the live WebSocket channel (`cmd.progress`) and a +// terminal `cmd.done`. The heartbeat carries elapsed time and the caller's own deadline, never a +// fabricated percentage: the daemon cannot know how far into a trace the agent is, and inventing +// progress is worse than reporting none. export function sendCmd(sessionId: string, op: string, args: Record = {}, timeoutMs = 10_000): Promise { return new Promise((resolve, reject) => { const sock = agentSockets.get(sessionId); if (!sock || sock.destroyed) return reject(new Error('agent not connected')); const id = nextCmdId(); - const timer = setTimeout(() => { pending.delete(id); reject(new Error('command timeout')); }, timeoutMs); + const startedAt = Date.now(); + // Report while the command is in flight. Unref'd so a pending heartbeat can never keep the + // process alive, and cleared on BOTH paths below so a finished command stops reporting. + const beat = setInterval(() => { + const t = inflight.get(id); + if (!t) return; + broadcastLive('cmd.progress', { + cmdId: id, op, sessionId, + elapsedMs: Date.now() - startedAt, + remainingMs: Math.max(0, timeoutMs - (Date.now() - startedAt)), + }); + }, 1000); + if (typeof beat.unref === 'function') beat.unref(); + inflight.set(id, { cmdId: id, op, sessionId, startedAt, timeoutMs, beat }); + broadcastLive('cmd.start', { cmdId: id, op, sessionId, timeoutMs }); + const finish = (ok: boolean) => { + clearInterval(beat); + const t = inflight.get(id); + // Whoever removes the tracker owns the terminal event. failPendingFor removes it before + // rejecting, so a disconnect reports cmd.done exactly once (with its reason) and this path + // stays silent instead of emitting a second, reasonless copy. + if (!t) return; + if (t.beat) clearInterval(t.beat); + inflight.delete(id); + broadcastLive('cmd.done', { cmdId: id, op, sessionId, ok, elapsedMs: Date.now() - startedAt }); + }; + const timer = setTimeout(() => { pending.delete(id); finish(false); reject(new Error('command timeout')); }, timeoutMs); // The session id is carried with the pending entry so a DISCONNECT can fail exactly the commands it // owned. Without it, a target that dies mid-command (a trace of code that dereferences freed memory // does this) leaves the caller waiting for the full timeout with no explanation - measured: 60 s of // silence, answered only by "command timeout". - pending.set(id, { resolve, reject, timer, sessionId }); + pending.set(id, { + resolve: (v: any) => { clearTimeout(timer); finish(true); resolve(v); }, + reject: (e: any) => { clearTimeout(timer); finish(false); reject(e); }, + timer, sessionId, + }); sock.write(frameJson({ ...args, t: 'cmd', id, op })); }); } -export const pickSid = (sid?: string) => sid ?? [...sessions.values()].filter(s => s.online).pop()?.sessionId; -export const sessionForPackage = (pkg: string) => - [...sessions.values()].filter(s => s.online && s.package === pkg).pop()?.sessionId; +export const pickSid = (sid?: string) => { + if (sid) return sid; + const online = [...sessions.values()].filter((s) => s.online); + if (!online.length) return undefined; + // The main process wins. The previous `.pop()` took whichever session was inserted last, which on a + // multi-process target can be a renderer/push child: the tool then fails with an empty result and + // no hint that the wrong process was chosen (field report: ClassNotFound in :normal_render_proc0 + // while the main process was online). A child is used only when it is the only thing online. + return (online.find((s) => !s.process.includes(':')) ?? online[online.length - 1]).sessionId; +}; +export const sessionForPackage = (pkg: string) => { + const rows = [...sessions.values()].filter((s) => s.online && s.package === pkg); + return (rows.find((s) => !s.process.includes(':')) ?? rows[rows.length - 1])?.sessionId; +}; export async function agentCmd(sid: string | undefined, op: string, args: Record = {}, timeout = 15_000) { const s = pickSid(sid); if (!s) throw new Error('no online agent session'); return sendCmd(s, op, args, timeout); @@ -889,6 +939,16 @@ export async function setCapture( const drained = await drainSession(sid); const reply = await sendCmd(sid, 'capture_stop', {}, 8_000); recordCaptureHooks(sid, reply); + // Disarm the periodic drain as part of stopping. Leaving it armed made the loop issue + // capture_drain every 1.5 s against an already-stopped capture, which showed up in the field as + // endless `[capture] … DROPPING — ring full` lines after the hooks were restored (observed on + // com.chaoxing.mobile, 2026-11-13). The drainer itself stays registered so an explicit + // drainSession() still works; only the timer that nobody asked to keep polling is cancelled. + const timer = captureTimers.get(sid); + if (timer) { + clearInterval(timer); + captureTimers.delete(sid); + } const drainedCount = Number(drained.response?.count ?? 0) || 0; const dropped = Number(drained.response?.dropped ?? 0) || 0; return { diff --git a/daemon/src/state.ts b/daemon/src/state.ts index c922933..624a198 100644 --- a/daemon/src/state.ts +++ b/daemon/src/state.ts @@ -183,6 +183,12 @@ function readDumpProvenance(path: string, sha: string): ArtifactProvenance | nul export const agentSockets = new Map(); // sessionId -> live socket export const pending = new Map void; reject: (e: Error) => void; timer: NodeJS.Timeout; sessionId?: string }>(); +// In-flight command bookkeeping for the live progress channel. It lives here, next to `pending`, +// because the SAME disconnect path must clear both: an entry left behind would keep reporting a +// heartbeat for a command whose socket is already gone. +export interface CmdTracker { cmdId: string; op: string; sessionId: string; startedAt: number; timeoutMs: number; beat?: NodeJS.Timeout; } +export const inflight = new Map(); + /** * Fail every command still waiting on one session, with a reason instead of a timeout. * @@ -199,6 +205,12 @@ export function failPendingFor(sessionId: string, reason: string): number { if (p.sessionId !== sessionId) continue; clearTimeout(p.timer); pending.delete(id); + const t = inflight.get(id); + if (t) { + if (t.beat) clearInterval(t.beat); + inflight.delete(id); + broadcastLive('cmd.done', { cmdId: id, op: t.op, sessionId, ok: false, elapsedMs: Date.now() - t.startedAt, reason }); + } p.reject(new Error(reason)); n++; } @@ -1020,6 +1032,15 @@ export function broadcast(event: string, data: unknown) { for (const c of wss.clients) if (c.readyState === WebSocket.OPEN) c.send(msg); if (event !== 'snapshot') recordEvent(event, stamped); // persist for record/replay } +// Live-only channel for high-frequency progress. Same socket and envelope as broadcast, but it is +// never written to EVENTS_FILE: a trace that reports every 200 instructions would otherwise append +// thousands of lines per second and turn a diagnostic into disk pressure. Progress is only useful +// while a command is in flight, so losing it on reconnect costs nothing. +export function broadcastLive(event: string, data: unknown) { + if (wss.clients.size === 0) return; // nobody listening: skip the work entirely + const msg = JSON.stringify({ event, data, ts: Date.now() }); + for (const c of wss.clients) if (c.readyState === WebSocket.OPEN) c.send(msg); +} export function log(...a: unknown[]) { console.log(`[adhd ${new Date().toISOString()}]`, ...a); } diff --git a/daemon/test/analysis_guide.test.ts b/daemon/test/analysis_guide.test.ts index 3984571..7d75e0e 100644 --- a/daemon/test/analysis_guide.test.ts +++ b/daemon/test/analysis_guide.test.ts @@ -40,7 +40,8 @@ test('every guide can be read through MCP without a session and returns a bounde test('guide templates bind only declared variables and refer to actual tool schemas', () => { // Synthetic typed substitutions validate call shapes only. No example target call is executed. const values: Record = { session: 'guide-test-no-agent', tid: 7, buffer: '0x1000', runId: 'synthetic-run', pc: '0x1000', - captureId: 7, hookId: 7, qbdiPath: '/synthetic/libQBDI.so', entry: '0x1000', integerArgs: ['1', '2'], traceId: 'synthetic-trace' }; + captureId: 7, hookId: 7, qbdiPath: '/synthetic/libQBDI.so', entry: '0x1000', integerArgs: ['1', '2'], traceId: 'synthetic-trace', + className: 'synthetic.Facade', method: 'sign', params: 'java.lang.String', oracleArgs: ['synthetic'] }; for (const topic of ANALYSIS_GUIDE_TOPICS) { const guide = analysisGuide(topic); for (const step of guide.steps) { diff --git a/daemon/test/app_analyze.test.ts b/daemon/test/app_analyze.test.ts new file mode 100644 index 0000000..cd5f081 --- /dev/null +++ b/daemon/test/app_analyze.test.ts @@ -0,0 +1,36 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { mergeScope, parseScopePackages } from '../src/scope_list.ts'; +import { analyzePackage, pickAnalysisSession } from '../src/app_analyze.ts'; + +test('scope merge: add/remove/dedupe and refuse junk before it reaches the inline scope check', () => { + const start = ['com.a.app', 'com.b.app']; + assert.deepEqual(mergeScope(start, { add: ['com.c.app', 'com.a.app'] }), ['com.a.app', 'com.b.app', 'com.c.app']); + assert.deepEqual(mergeScope(start, { remove: ['com.a.app'] }), ['com.b.app']); + // Same call: remove wins over add, because the operator's explicit removal is the later intent. + assert.deepEqual(mergeScope(start, { add: ['com.a.app'], remove: ['com.a.app'] }), ['com.b.app']); + // The scope file is parsed by C++ on a hot path; a malformed name must never be written. + assert.deepEqual(mergeScope([], { add: ['bad name', 'com..bad', 'com.adh.manager', 'com.ok.app'] }), ['com.ok.app']); +}); + +test('scope parse drops the manager package and duplicates', () => { + const raw = JSON.stringify({ version: 2, mode: 'allowlist', packages: ['com.a.app', 'com.a.app', 'com.adh.manager'] }); + assert.deepEqual(parseScopePackages(raw), ['com.a.app']); +}); + +test('analysis session: the main process wins over a newer companion process', () => { + const rows = [ + { package: 'com.x.app', process: 'com.x.app:push', online: true, connectedAt: 300 }, + { package: 'com.x.app', process: 'com.x.app', online: true, connectedAt: 100 }, + ]; + assert.equal(pickAnalysisSession(rows)?.process, 'com.x.app'); + // Offline rows are never a target. + assert.equal(pickAnalysisSession([{ package: 'com.x.app', process: 'com.x.app', online: false, connectedAt: 1 }]), null); +}); + +test('analyze_package refuses a package that must never be injected, before touching adb', async () => { + const out = await analyzePackage('com.android.systemui'); + assert.equal(out.ok, false); + assert.match(String(out.error), /不能分析/); +}); diff --git a/daemon/test/cmd_progress.test.ts b/daemon/test/cmd_progress.test.ts new file mode 100644 index 0000000..48c2665 --- /dev/null +++ b/daemon/test/cmd_progress.test.ts @@ -0,0 +1,107 @@ +// Live progress channel: a long command must report while it is in flight, and must stop reporting +// the moment it settles. These assertions are about the CONTRACT the WebSocket client relies on: +// cmd.start once, before anything can complete +// cmd.progress zero or more, carrying real elapsed time (never a fabricated percentage) +// cmd.done exactly once, on success, on timeout, and on disconnect +// The failure this guards against is silence: before the change, a 6 s trace and a dead agent were +// indistinguishable to the caller because neither produced any event. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import net from 'node:net'; + +process.env.ADH_SKIP_ARTIFACT_LOAD = '1'; +process.env.ADH_DATA_DIR = process.env.ADH_DATA_DIR || 'adhd-data/test-progress'; + +const state = await import('../src/state.ts'); +const { sendCmd } = await import('../src/service.ts'); + +// Capture the live channel by attaching a fake client to the real wss. ESM exports are read-only, so +// the module object cannot be patched - but `wss.clients` is a mutable Set on a real WebSocketServer. +function captureLive() { + state.wss.clients.clear(); // never inherit a previous test's fake client + const seen = []; + const fake = { readyState: 1, send: (m) => seen.push(JSON.parse(m)) }; + state.wss.clients.add(fake as any); + return { seen, drop: () => state.wss.clients.delete(fake as any) }; +} + +// A fake agent socket: it records what the daemon wrote and lets the test answer on demand. +// The daemon writes 5-byte-header frames (u32be length + u8 type), not bare JSON. +function fakeAgent() { + const writes = []; + const sock = { destroyed: false, write: (b) => { writes.push(Buffer.isBuffer(b) ? b : Buffer.from(String(b))); } }; + return { sock, writes }; +} +function decodeFrame(buf) { + const len = buf.readUInt32BE(0); + return JSON.parse(buf.subarray(5, 5 + len).toString('utf8')); +} + +test('an in-flight command reports start, progress and done on the live channel', async () => { + const { seen, drop } = captureLive(); + const { sock, writes } = fakeAgent(); + state.agentSockets.set('s_test', sock as any); + + const p = sendCmd('s_test', 'qbdi_trace', { budget: 1000 }, 4000); + // cmd.start is emitted synchronously, before the agent has answered anything + assert.equal(seen.filter(e => e.event === 'cmd.start').length, 1); + assert.equal(seen[0].event, 'cmd.start'); + assert.equal(seen[0].data.op, 'qbdi_trace'); + + // answer it as the agent would + const id = decodeFrame(writes[0]).id; + const entry = state.pending.get(id); + assert.ok(entry, 'the command must be pending'); + entry.resolve({ ok: true, seen: 42 }); + const out = await p; + assert.equal(out.seen, 42); + + const done = seen.filter(e => e.event === 'cmd.done'); + assert.equal(done.length, 1); + assert.equal(done[0].data.ok, true); + assert.equal(typeof done[0].data.elapsedMs, 'number'); + // nothing may keep reporting after the command settled + assert.equal(state.inflight.has(id), false); + state.agentSockets.delete('s_test'); drop(); +}); + +test('a timeout reports done with ok:false instead of only throwing', async () => { + const { seen, drop } = captureLive(); + const { sock } = fakeAgent(); + state.agentSockets.set('s_timeout', sock as any); + + await assert.rejects(() => sendCmd('s_timeout', 'root_watch', {}, 120), /command timeout/); + const done = seen.filter(e => e.event === 'cmd.done'); + assert.equal(done.length, 1); + assert.equal(done[0].data.ok, false); + assert.equal(done[0].data.op, 'root_watch'); + assert.equal([...state.inflight.values()].filter(t => t.sessionId === 's_timeout').length, 0); + state.agentSockets.delete('s_timeout'); drop(); +}); + +test('a disconnect fails the command and closes its progress entry', () => { + const { seen, drop } = captureLive(); + const { sock } = fakeAgent(); + state.agentSockets.set('s_dead', sock as any); + + const p = sendCmd('s_dead', 'native_call', {}, 30000); + p.catch(() => { }); // the rejection is asserted through failPendingFor + const n = state.failPendingFor('s_dead', 'agent not connected'); + assert.equal(n, 1); + + const done = seen.filter(e => e.event === 'cmd.done'); + assert.equal(done.length, 1); + assert.equal(done[0].data.ok, false); + assert.equal(done[0].data.reason, 'agent not connected'); + // the tracker must not survive the disconnect, or the heartbeat would keep firing for a dead socket + assert.equal([...state.inflight.values()].filter(t => t.sessionId === 's_dead').length, 0); + state.agentSockets.delete('s_dead'); drop(); +}); + +test('progress is never persisted to the event log', () => { + // broadcastLive must not touch recordEvent: a trace reporting every second would otherwise append + // thousands of lines and turn a diagnostic into disk pressure. + const before = state.events.length; + state.broadcastLive('cmd.progress', { cmdId: 'x', elapsedMs: 1 }); + assert.equal(state.events.length, before); +}); diff --git a/daemon/test/error_codes.test.ts b/daemon/test/error_codes.test.ts new file mode 100644 index 0000000..ad8559d --- /dev/null +++ b/daemon/test/error_codes.test.ts @@ -0,0 +1,37 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { classifyError, errorPayload } from '../src/error_codes.ts'; + +// These messages are copied from real sessions (field reports from the mtgsig/dewu analysis), because +// the value of this module is exactly that it classifies the failures the tools actually produce. +test('the failure classes a client must branch on are distinguishable', () => { + assert.equal(classifyError(new Error('mode must be got, inline, sites or vtable')), 'BAD_ARG'); + assert.equal(classifyError(new Error('no session')), 'NO_SESSION'); + assert.equal(classifyError(new Error('no online agent')), 'NO_SESSION'); + assert.equal(classifyError(new Error('agent timed out after 15000 ms')), 'AGENT_TIMEOUT'); + assert.equal(classifyError(new Error('socket hang up')), 'SESSION_OFFLINE'); + assert.equal(classifyError(new Error('target crashed: killed by signal SIGSEGV')), 'TARGET_CRASHED'); + assert.equal(classifyError(new Error('adb: no devices/emulators found')), 'DEVICE_UNAVAILABLE'); +}); + +test('reported capabilities that are absent are UNSUPPORTED_OP, not bad arguments', () => { + assert.equal(classifyError(new Error('libQBDI.so not available (dlopen)')), 'UNSUPPORTED_OP'); + assert.equal(classifyError(new Error('old agent does not support this op')), 'UNSUPPORTED_OP'); + assert.equal(classifyError(new Error('helper not built: run tools/build_root_watch.sh')), 'HELPER_MISSING'); +}); + +test('capture loss wins over the words it is usually wrapped in', () => { + // A lossy ring report also says "timeout/incomplete"; misrouting it to AGENT_TIMEOUT would hide the + // one fact that matters (do not conclude from this window). + assert.equal(classifyError(new Error('dropped=30249 emitted=712 complete:false')), 'CAPTURE_LOSS'); + assert.equal(classifyError(new Error('906 record(s) were evicted (retain 1000)')), 'CAPTURE_LOSS'); +}); + +test('the payload keeps ok:false and the original prose', () => { + const p = errorPayload(new Error('invalid addr: expected 0x-prefixed hex')); + assert.equal(p.ok, false); + assert.equal(p.code, 'BAD_ARG'); + assert.match(p.error, /expected 0x/); + assert.equal(errorPayload(undefined).code, 'UNKNOWN'); +}); diff --git a/daemon/test/maps_query.test.ts b/daemon/test/maps_query.test.ts new file mode 100644 index 0000000..401037c --- /dev/null +++ b/daemon/test/maps_query.test.ts @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { normalizeRegion, queryMaps, resolveAddress } from '../src/maps_query.ts'; + +// regions shaped like the agent's maps reply +const MAPS = [ + { start: '0x7600000000', end: '0x7600010000', perms: 'r-xp', offset: '0x0', path: '/data/app/com.x/lib/arm64/libx.so' }, + { start: '0x7600010000', end: '0x7600014000', perms: 'r--p', offset: '0x10000', path: '/data/app/com.x/lib/arm64/libx.so' }, + { start: '0x7600100000', end: '0x7600120000', perms: 'rw-p', offset: '0x0', path: '[anon:dalvik-main space]' }, + { start: '0x7600200000', end: '0x7600208000', perms: 'r-xp', offset: '0x0', path: '' }, + { start: '0x7600300000', end: '0x7600301000', perms: 'rw-p', offset: '0x0', path: '/dev/ashmem/xyz (deleted)' }, +]; + +test('a full maps list becomes size/perms/offset/path rows', () => { + const row = normalizeRegion(MAPS[0]); + assert.deepEqual(row, { + start: '0x7600000000', end: '0x7600010000', size: 0x10000, + perms: 'r-xp', offset: '0x0', path: '/data/app/com.x/lib/arm64/libx.so', + }); + // decimal-looking strings are still parsed as hex, which is what /proc/self/maps emits + assert.equal(normalizeRegion({ start: '1000', end: '2000', perms: 'rw-p' })?.size, 0x1000); + assert.equal(normalizeRegion({ start: 'zz', end: '2000' }), null); +}); + +test('addr resolves the containing region and the module-relative file offset', () => { + const res = resolveAddress(MAPS.map((r) => normalizeRegion(r)!), '0x7600012340'); + assert.equal(res?.region.path, '/data/app/com.x/lib/arm64/libx.so'); + assert.equal(res?.regionOffset, '0x2340'); + // file offset = region file offset + in-region offset: "which code in libx.so is this" + assert.equal(res?.fileOffset, '0x12340'); + assert.equal(resolveAddress(MAPS.map((r) => normalizeRegion(r)!), '0x1'), null); +}); + +test('filters are exact about what they mean', () => { + const exec = queryMaps(MAPS, { exec: true }); + assert.equal(exec.matched, 2); + assert.equal(exec.regions[0].perms, 'r-xp'); + // anonymous = no file-backed path; a [anon:...] label counts as anonymous, an empty path too, + // while /dev/ashmem is a device path (not anonymous, not a module) + const anon = queryMaps(MAPS, { anon: true }); + assert.equal(anon.matched, 2); + const file = queryMaps(MAPS, { anon: false }); + assert.equal(file.matched, 3); + const byPath = queryMaps(MAPS, { path: 'libx.so' }); + assert.equal(byPath.matched, 2); + const bySize = queryMaps(MAPS, { minSize: 0x10000 }); + assert.equal(bySize.matched, 2); // 0x10000 and 0x20000 +}); + +test('matched/returned/truncated so a trimmed page is never mistaken for the whole answer', () => { + const page = queryMaps(MAPS, { limit: 2 }); + assert.equal(page.total, 5); + assert.equal(page.matched, 5); + assert.equal(page.returned, 2); + assert.equal(page.truncated, true); + const all = queryMaps(MAPS, {}); + assert.equal(all.truncated, false); + // addr resolution still sees regions outside the returned page + const withAddr = queryMaps(MAPS, { path: 'nomatch', addr: '0x7600100040' }); + assert.equal(withAddr.regions.length, 0); + assert.equal(withAddr.resolved?.region.path, '[anon:dalvik-main space]'); +}); diff --git a/daemon/test/native_look.test.ts b/daemon/test/native_look.test.ts index 16d57c8..380612d 100644 --- a/daemon/test/native_look.test.ts +++ b/daemon/test/native_look.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { joinNativeLook } from '../src/native_look.ts'; +import { joinNativeLook, selectNativeLook, nativeLookRead } from '../src/native_look.ts'; function hexOf(obj: unknown): string { return Buffer.from(JSON.stringify(obj), 'utf8').toString('hex'); @@ -100,3 +100,61 @@ test('a hook without a trace reports no trace rather than an empty one', () => { assert.equal(look.trace, null); assert.doesNotMatch(look.text, /就地 trace/); }); + +test('seq selects an earlier hit and does not borrow the newest registers', () => { + const records = [ + { func: 'NATIVE_HOOK', hex: hook(1, '0x1111'), id: 1 }, + { func: 'NATIVE_HOOK_MEM', hex: mem(1), id: 2 }, + { func: 'NATIVE_HOOK', hex: hook(14, '0xeeee'), id: 3 }, + { func: 'NATIVE_HOOK_MEM', hex: mem(14), id: 4 }, + ]; + const latest = selectNativeLook(records, 7); + assert.equal(latest.look.seq, 14); + assert.equal(latest.look.regs.x0, '0xeeee'); + assert.equal(latest.retained.total, 2); + assert.equal(latest.retained.nextBeforeSeq, 14); + assert.equal(latest.hits, undefined); + + const earlier = selectNativeLook(records, 7, { seq: 1 }); + assert.equal(earlier.look.seq, 1); + assert.equal(earlier.look.regs.x0, '0x1111'); + assert.equal(earlier.hits?.length, 1); + assert.equal(earlier.retained.nextBeforeSeq, null); + + const page = selectNativeLook(records, 7, { beforeSeq: 14, limit: 50 }); + assert.deepEqual(page.hits?.map((h) => h.seq), [1]); + assert.equal(page.look.regs.x0, '0x1111'); +}); + +test('a missing seq names the hits that are still stored', () => { + const selected = selectNativeLook([ + { func: 'NATIVE_HOOK', hex: hook(2), id: 1 }, + ], 7, { seq: 9 }); + assert.equal(selected.look.hit, false); + assert.match(selected.look.text, /没有 seq=9/); + assert.match(selected.look.text, /2/); + assert.equal(selected.retained.total, 1); + assert.deepEqual(selected.hits, []); +}); + +test('beforeSeq and limit reject a bad page and a mixed cursor', () => { + assert.throws(() => selectNativeLook([], 7, { limit: 51 }), /limit must be an integer 1\.\.50/); + assert.throws(() => selectNativeLook([], 7, { seq: 1, beforeSeq: 2 }), /not both/); +}); + +test('read keeps a stored earlier hit when the agent status query fails', async () => { + const look = await nativeLookRead('s1', 7, { + captures: [ + { sessionId: 's1', func: 'NATIVE_HOOK', hex: hook(1, '0x1111'), id: 1 }, + { sessionId: 's1', func: 'NATIVE_HOOK', hex: hook(2, '0x2222'), id: 2 }, + ], + drainSession: async () => {}, + sendCmd: async () => { throw new Error('agent disconnected'); }, + }, { seq: 1 }); + assert.equal(look.seq, 1); + assert.equal(look.regs.x0, '0x1111'); + assert.equal(look.retained.total, 2); + assert.equal(look.hits?.length, 1); + assert.equal(look.drainError, undefined); + assert.equal(look.observationError, 'agent disconnected'); +}); diff --git a/daemon/test/oracle_stability.test.ts b/daemon/test/oracle_stability.test.ts new file mode 100644 index 0000000..f30f851 --- /dev/null +++ b/daemon/test/oracle_stability.test.ts @@ -0,0 +1,58 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { firstDifference, oracleRecord, oracleStability } from '../src/oracle.ts'; + +// The field report that motivated this: "dhw 的非纯函数性质是手写两次重放逐字节比对才发现的, +// 而这恰恰是最先该知道的事". stability answers it in one call with fake-agent deps here. + +const reply = (b5: string) => JSON.stringify([{ b5 }]); + +function fakeAgent(values: string[]) { + let i = 0; + return { + sendCmd: async (_session: string, op: string) => { + if (op === 'java_call') return { ok: true, callId: 1 }; + const v = values[Math.min(i, values.length - 1)]; + i++; + return { ok: true, call: { state: 'done', result: { result: v } } }; + }, + }; +} + +test('a pure facade answers the same value on every replay', async () => { + const rec = await oracleRecord('s1', { className: 'X', method: 'entry', extract: 'result[0].b5' }, fakeAgent([reply('v1')])); + assert.equal(rec.ok, true, rec.error); + const st = await oracleStability('s1', { id: Number(rec.id), repeat: 3 }, fakeAgent([reply('v1')])); + assert.equal(st.ok, true, st.error); + assert.equal(st.stable, true); + assert.equal(st.distinct, 1); + assert.equal(st.runs, 3); + assert.equal(st.firstDiff, null); +}); + +test('hidden state is reported as unstable, with the first differing path', async () => { + const rec = await oracleRecord('s1', { className: 'X', method: 'entry', extract: 'result[0].b5' }, fakeAgent([reply('v1'), reply('v2')])); + assert.equal(rec.ok, true, rec.error); + const st = await oracleStability('s1', { id: Number(rec.id), repeat: 3 }, fakeAgent([reply('v2'), reply('v1'), reply('v2')])); + assert.equal(st.ok, true, st.error); + assert.equal(st.stable, false); + assert.equal(st.distinct, 2); + assert.equal(st.firstDiff, ''); // the extracted value itself moved\n assert.equal(st.extract, 'result[0].b5'); +}); + +test('repeat is clamped so one call cannot spin the target forever', async () => { + const rec = await oracleRecord('s1', { className: 'X', method: 'entry', extract: 'result[0].b5' }, fakeAgent([reply('v1')])); + const st = await oracleStability('s1', { id: Number(rec.id), repeat: 100 }, fakeAgent([reply('v1')])); + assert.equal(st.runs, 8); + const one = await oracleStability('s1', { id: Number(rec.id), repeat: 0 }, fakeAgent([reply('v1')])); + assert.equal(one.runs, 3); // default +}); + +test('firstDifference walks objects and arrays and names the deepest path', () => { + assert.equal(firstDifference({ a: 1 }, { a: 1 }), null); + assert.equal(firstDifference({ a: [1, 2] }, { a: [1, 3] }), 'a[1]'); + assert.equal(firstDifference({ a: { b: 'x' } }, { a: { b: 'y' } }), 'a.b'); + assert.equal(firstDifference({ a: 1 }, { b: 1 }), 'a'); + assert.equal(firstDifference(null, { a: 1 }), ''); +}); diff --git a/daemon/test/session_pick.test.ts b/daemon/test/session_pick.test.ts new file mode 100644 index 0000000..9157d6f --- /dev/null +++ b/daemon/test/session_pick.test.ts @@ -0,0 +1,36 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { sessions } from '../src/state.ts'; +import { pickSid, sessionForPackage } from '../src/service.ts'; + +// Field report: pickSid used `.pop()`, so a renderer child could win over the main process and the +// tool then failed with ClassNotFound and no hint about the wrong process. The main process must win. + +function put(sessionId: string, process: string, online = true) { + sessions.set(sessionId, { + sessionId, pid: 1, uid: 1, package: 'com.x.app', process, + abi: 'arm64-v8a', android: '15', sdk: 35, entry: 'start', agentVer: '0.8.0', + connectedAt: 1, lastSeen: 1, online, mapsCount: 0, regionsSample: [], + } as never); +} + +test('the main process wins over a child inserted later', () => { + sessions.clear(); + put('s_main', 'com.x.app'); + put('s_child', 'com.x.app:render'); + assert.equal(pickSid(), 's_main'); + assert.equal(sessionForPackage('com.x.app'), 's_main'); + // an explicit session is always honored + assert.equal(pickSid('s_child'), 's_child'); +}); + +test('a child is used only when the main process is not online, and nothing when empty', () => { + sessions.clear(); + put('s_main', 'com.x.app', false); + put('s_child', 'com.x.app:render', true); + assert.equal(pickSid(), 's_child'); + sessions.clear(); + assert.equal(pickSid(), undefined); + assert.equal(sessionForPackage('com.x.app'), undefined); +}); diff --git a/device/daemon/build.gradle.kts b/device/daemon/build.gradle.kts index 7c0e731..637e36d 100644 --- a/device/daemon/build.gradle.kts +++ b/device/daemon/build.gradle.kts @@ -11,8 +11,8 @@ android { applicationId = "com.adh.daemon" minSdk = 26 targetSdk = 34 - versionCode = 13 - versionName = "0.6.0" + versionCode = 17 + versionName = "0.8.0" buildConfigField( "String", "MANAGER_CERT_SHA256", diff --git a/device/manager/build.gradle.kts b/device/manager/build.gradle.kts index d63572e..df49696 100644 --- a/device/manager/build.gradle.kts +++ b/device/manager/build.gradle.kts @@ -12,8 +12,8 @@ android { applicationId = "com.adh.manager" minSdk = 26 targetSdk = 34 - versionCode = 26 - versionName = "0.6.0" + versionCode = 30 + versionName = "0.8.0" } buildTypes { diff --git a/docs/FEATURE_STATUS.md b/docs/FEATURE_STATUS.md index 9b5f313..908319d 100644 --- a/docs/FEATURE_STATUS.md +++ b/docs/FEATURE_STATUS.md @@ -211,6 +211,43 @@ in-hook QBDI 仍是虚拟栈重放后再原生执行,不能把某个窗口未 **未测 / 已知边界**:`traceInsns` 上限 64k 与 300 ms 墙钟(谁先到谁停);写观察点只覆盖**本次 run 内**的写;`memAfter` 仍只接受寄存器窗口;全量块级 trace 与 host 查询**尚未实现**(见 `PROGRESS` 第五十轮)。 +### 2.4 v0.7.0(2026-11-12)QBDI 载荷投递 + +> 设备 `aa165071`(PGP110 / Android 15 / arm64-v8a / root),agent `5ea3f25c…`(= 模块内 `.so`),真实第三方 App `com.uxin.kilaaudio` 1.6.18。 + +| 能力 | 门禁 | 真机结果 | +|---|---|---| +| QBDI 默认关闭面 | `verify_v129_qbdi_delivery.sh`(A 段) | ✅ PASS(`delivery is off` 可操作报错;`/proc//fd` 无 QBDI fd) | +| QBDI 显式开启后真实目标 trace | `verify_v129_qbdi_delivery.sh`(B 段) | ✅ PASS(companion 交付 fd;`qbdi_trace libc:getpid` → `retval`=目标 pid、8 条指令;trace 后 maps 无 QBDI) | +| 沙盒不再自带追踪库 | `tools/fetch_qbdi.sh` | ✅ 默认不 stage(仅 `ADH_STAGE_SANDBOX_QBDI=1` 显式恢复旧行为) | + +**已知成本**:开启后每个被注入进程在 specialization 时多一个指向 `/data/adb/modules/adh/libQBDI.so` 的 fd(目标可 readlink 看到路径);QBDI 运行期映射约 6MB `r-xp` + RSS +27MB(同一进程实测),standalone trace 结束 `dlclose` 释放。默认关闭时以上都不存在。 + +### 2.5 v0.8.0(2026-11-12)作用域可编程 + 一把抓分析 + +| 能力 | 门禁 | 真机结果 | +|---|---|---| +| 作用域读写(`scope_list` / `scope_set`) | `verify_v130_scope_analyze.sh`(host) | ✅ PASS(merge/拒绝非法包名/主进程选择/tool 形状 8/8);真机写盘回读一致(7→8 包) | +| 一把抓分析 `analyze_app` | `verify_v130` + 真机 | ✅ PASS(麦当劳 51s triage;中国移动 37s,13 组 HTTP exchange、163 条 crypto 记录) | +| 沙盒 APK 不再内置追踪库 | 重装后设备 `lib/arm64` 列表 | ✅ 只剩 `libadh_agent.so` + fixtures | +| agent 签名门禁 | `verify_v88_agent_signatures.sh` | ✅ PASS(错误文案去掉 `Dobby` 字面量后 token 3→2) | +| 沙盒未运行时的 So 重组 | `verify_v02_so.sh` | ⏭ SKIP(原先是 FAIL,属环境性假红,已改为 clear SKIP) | + +**接口**:`POST /api/analyze-app` 与 MCP `analyze_app` 同源;`GET|POST /api/scope` 与 `scope_list`/`scope_set` 同源。`analyze_app` 只接受已安装的第三方包(系统包与 ADH 自己的包被拒绝),把包加入作用域这一动作会在回复的 `scopeAdded` 里如实报告。 + +### 2.6 v0.8.1(2026-11-12)实战痛点第一批修复 + +> 依据 `X:\DH_Project` 的真实使用记录(20 条缺口清单 + 三轮改进建议 + 86 工具实测)。设备 `aa165071`,agent 0.8.0,目标 `com.mcdonalds.gma.cn`。 + +| 能力 | 门禁 | 真机结果 | +|---|---|---| +| `maps_query`(段过滤 + 地址解析) | `verify_v71`(registry)+ 真机 | ✅ PASS(2737 段;`libc.so` 命中 6 段、truncated 如实;`0x704cca7010` → libc.so + fileOffset 0x10) | +| `oracle action:stability`(确定性判定) | `daemon/test/oracle_stability.test.ts` + 真机 | ✅ PASS(`System.currentTimeMillis` 三次重放:stable=false、distinct=3) | +| 统一错误码(十类,含返回式失败) | `daemon/test/error_codes.test.ts` + 真机 | ✅ PASS(`memory_write` 无 0x、`native_hook` 缺 mode → `code:BAD_ARG`) | +| 默认会话主进程优先 | `daemon/test/session_pick.test.ts` | ✅ PASS(主进程优先,子进程仅在其唯一在线时使用) | + +**对应关系**:`maps_query` ≈ DH_Project B3 的“段导航”一半(快照 diff 未做);`stability` = B2;错误码 = A12;`pickSid` = A10。仍未做:PC 历史环 / hook 事件分页(缺口清单 P0-1/2)、`entry_capture`(B1)、结论台账(B6)。 + **全量门禁(2026-10-23,130 条)**:套件跑出 **112 PASS / 18 FAIL / 0 SKIP**。逐条单独复跑后: - **2 条是本版改动引起的,已修并复跑 PASS**:`v86`(安装签名长了 → 源码锚点过期,改成按参数名断言,并新增“被节流的命中不得 trace”这条不变量)、`v87`(`module_watch` 在 agent 里**只有实现、没有接进分派**,MCP 工具实际是死的;已接线 + 进 caps,ops 36→37)。 diff --git a/docs/SKILL-callgraph-first.md b/docs/SKILL-callgraph-first.md new file mode 100644 index 0000000..a3780e9 --- /dev/null +++ b/docs/SKILL-callgraph-first.md @@ -0,0 +1,136 @@ +# Skill: 运行时调用图优先(Callgraph-First) + +> 这个 Skill 解决一类反复出现的失败:**不知道该在哪个地址下断点,于是逐个猜,逐个 0 命中。** +> 适用场景:逆向一个不熟悉的 native 目标、追一条不知道经过哪些函数的计算链、判断某段代码到底有没有被执行。 + +## 核心原则 + +**先要调用图,再要断点。** `root_watch` 的每个事件里都带 `chain[]`——内核采集的运行时调用栈。 +这是**免费**的:你为了别的目的下断点时,它已经一起给了。不用它,就等于放弃手边最可靠的证据。 + +## 为什么这条重要 + +目标的栈帧可能被主动破坏。实测遇到过函数入口连写 8 组: + +```asm +mov x10, sp ; subs x10, x10, #0x10 ; mov sp, x10 +mov x11, sp ; subs x11, x11, #0x10 ; mov sp, x11 +...(连续 8 组) +``` + +这是**栈指针混淆**:基于 `x29` 的帧链遍历会失效,`native_backtrace` 会返回空或错乱的帧。 +但**内核 unwind 仍然有效**,`chain[]` 不受影响。所以在这种目标上,`chain` 是唯一可靠的调用图来源。 + +## 标准流程 + +### 1. 拿一个已验证的热点地址 + +不要用"反汇编里看起来像函数入口"的地址。要来自实测: + +- `br x8` / `blr` 这类派发指令的实际跳转目标 +- `native_backtrace` 返回的帧 +- 已有的 `chain[]` 里的某一帧 + +### 2. 下执行断点,不附加任何额外采集 + +```json +{"action":"start","session":"$session","tid":"$tid","addr":"$entry","width":4,"mode":"x", + "durationMs":5000,"maxEvents":128,"stackBytes":0} +``` + +`tid` 必须是**真正执行工作的线程**。Java 驱动的目标用 `java_call` 调 `android.os.Process.myTid` 取; +`native_call` 的 worker 是短命的,不是持久的执行线程。 + +### 3. 读事件,看 `chain` + +```json +{"action":"read","id":"$runId","afterSeq":0,"limit":8,"registers":true} +``` + +每个事件形如: + +```json +{"seq":1,"bp":0,"ip":"0x...","pid":...,"tid":..., + "chain":["0x...","0x...","0x..."], // ← 这就是调用图 + "chainTruncated":false, + "regs":[...33 个...], + "stack":{"addr":"0x...","requested":1024,"got":1024}} +``` + +把 `chain` 里每个地址映射到模块区间(用 `memory_maps` 拿区间),得到 `模块名+偏移`。 + +### 4. 先确认调用图稳定,再信任它 + +同一个操作触发两次,`chain` 应该一致。**不一致说明你采样到的是不同的工作,不是同一条调用路径。** + +### 5. 用 `chain` 的下一帧作为新锚点,逐层向外 + +```json +{"action":"start","session":"$session","tid":"$tid","addr":"$pc","width":4,"mode":"x",...} +``` + +入口 → 它的调用者 → 再上一层。遇到跨模块或运行时边界就停。 + +## 关键:`chain` 里是返回地址,不是函数入口 + +**这是最容易踩的坑。** `chain` 的每一帧是 `bl` 之后的下一条指令地址(返回地址), +不是被调用函数的入口。直接拿它下断点,命中率接近 0。 + +正确做法:**从返回地址往前找函数序言**。 + +``` +候选序言(ARM64): + sub sp, sp, #imm + stp x29, x30, [sp, #imm] + add x29, sp, #imm +``` + +往前扫最多几百字节,第一个满足「`sub sp` 紧跟 `stp x29, x30`」的地址就是函数入口。 + +**另一个容易犯的错:把绝对地址当偏移。** +`chain` 里是绝对地址(如 `0x6f9b5427f0`)。若 VM 段基址是 `0x6f9b510000`, +真实偏移是 `0x327f0`,不是 `0x427f0`。用错会断到 +4MB 外。 + +## 判读规则(都是踩过的坑) + +| 现象 | 含义 | 不要下的结论 | +|---|---|---| +| `chain` 只有 1 帧 | 内核无法继续 unwind | 不是"没有调用者" | +| 两次触发 `chain` 不同 | 采到了不同的工作 | 不是"调用图不稳定" | +| 断点 0 命中 | 地址错 / 工作不在这个线程 | **不是**"这段代码不存在" | +| `chain` 跨到 `boot.oat` / `*.vdex` | 调用来自 ART 管理的代码 | 不是 native 库内部调用 | + +## 一个真实例子 + +追一个 Android VM 的派发点时,静态反汇编能看到的只有 VM 内部的一层。用 `chain` 一次就拿到完整五层: + +``` +VM+0x17328 ← br x8 派发 +VM+0x16980 ← 解释器主循环 +VM+0xc7cc ← JNI 包装(按返回类型有 10 个几乎相同的副本) +boot.oat+0xd6c +base.vdex+0xca26ccd +``` + +512 个事件全部一致。这直接说明了 VM 是通过 ART 的 vdex 代码被调用的, +而不是从某个 native 库直接调进来——这个事实靠静态反汇编要花很久才能确认。 + +## 什么时候不该用这个 Skill + +- 已经知道确切的目标函数 → 直接 `native_hook` / `native_look` +- 目标是 Java 方法 → `java_hook` / `java_trace`,不是 native 调用图 +- 需要指令级语义 → `trace_session`(QBDI),不是调用图 + +## 配套工具 + +| 工具 | 用途 | +|---|---| +| `analysis_guide(topic="callgraph")` | 本流程的机器可读版本,含模板和失败分支 | +| `root_watch` | 提供 `chain[]`;同时可下最多 4 个断点、读最多 4 个内存窗口 | +| `memory_maps` | 把 `chain` 地址映射成模块+偏移 | +| `native_backtrace` | 栈未混淆时可用;混淆时改用 `chain` | +| `runtime_diagnostics` | 确认线程身份,列出可用的 TID 候选 | + +## 一句话 + +**断点前先问:这条链我已经有了吗?** `root_watch` 的 `chain` 几乎总是已经回答过了。 \ No newline at end of file diff --git a/docs/SKILL-evidence-hygiene.md b/docs/SKILL-evidence-hygiene.md new file mode 100644 index 0000000..f8502d3 --- /dev/null +++ b/docs/SKILL-evidence-hygiene.md @@ -0,0 +1,121 @@ +# Skill: 逆向证据卫生(Evidence Hygiene) + +> 这个 Skill 解决另一类反复出现的失败:**观察本身没错,但从观察推到结论的那一步错了。** +> 以下每一条都对应一次真实的误判,不是理论风险。 + +## 一、变量必须先做敏感度扫描,再谈"是否参与" + +**错法**:测了 3 个变体,都让输出变了 → 断言"这个输入的全部字节都参与"。 + +**实际踩的坑**:某个 8 字节输入,改了前 5 字节输出全变,于是断定"64 位全部参与"。 +后来逐字节扫一遍才发现:**只有前 5 字节有效,后 3 字节完全被忽略。** +此前基于"完整 8 字节"做的所有搜索都落在错误的输入空间里。 + +**正确做法**: + +``` +对输入的每一个字节位置: + 翻转该字节(^0xFF),比较输出 + 不变 → 该字节不参与 + 变了 → 该字节参与 +``` + +不要抽样。**边界只能靠逐字节扫出来。** + +## 二、样本归一化必须动态推导参数 + +**错法**:在进程 A 测出"剥离时用掩码 0xC0",就把它硬编码进脚本。 + +**实际踩的坑**:进程 A 是 `0xC0`,进程 B 是 `0x40`,进程 C 是 `0x80`。 +硬编码导致其他进程的样本全是脏数据,所有基于它们的搜索都无效。 + +**正确做法**: + +``` +1. 取同一输入连续调用两次,得到变体 X 和 Y +2. 差异位置 = { i | X[i] != Y[i] } +3. 掩码 = X[18] ^ Y[18](任选一个差异位置) +4. 归一化 = 把高变体按掩码 XOR 到低变体 +5. 用 8 组以上输入验证归一化后完全一致 +``` + +**验证通过才算归一化正确。** 不要跳过第 5 步。 + +## 三、"代码存在"不等于"代码执行" + +**错法**:静态反汇编找到一段完整的算术实现,就认为找到了算法。 + +**实际踩的坑**:找到 `add/sub/mul/div/mod/and/orr/eor/lsl/asr/lsr` 全套实现,写了详细分析。 +后来在同一轮里下断点对照才发现:**那段代码在整个调用中 0 命中。** + +**正确做法**:任何静态发现的代码,**必须用同轮对照断点验证是否执行**。 + +``` +对照组:一个已知必然命中的地址 +实验组:候选地址 +同一轮、同一配置、同一触发 +对照组命中而实验组 0 命中 → 候选与本次分析无关 +``` + +## 四、统计口径要穷尽,不要抽样 + +**错法**:抽查 20 条指令,没看到乘法混合 → 断言"没有乘法混合"。 + +**正确做法**: + +``` +全镜像所有 mul:逐条分类((x-1)*x 谓词 / idx*4 寻址 / 其他) +可达指令集合:从实际执行的入口出发,按深度展开,统计 op 直方图 +``` + +**抽样能证伪,不能证真。** "没看到"不等于"没有"。 + +## 五、绝对地址 vs 模块偏移 + +**错法**:反汇编里 `bl #0x6f9b54ba28`,直接把 `0x54ba28` 当偏移去查。 + +**实际踩的坑**:正确偏移是 `0x6f9b54ba28 - 0x6f9b510000 = 0x3ba28`。 +用错偏移会断到 +4MB 外的地址,永远 0 命中。这个错误出现了 5 次。 + +**正确做法**:先算 `地址 - 模块基址`,再查反汇编表。 + +## 六、运行时地址每次重新获取 + +**错法**:把 `state 指针`、`VM 基址`、`TID` 写死在脚本里。 + +**实际踩的坑**:目标进程重启后全部失效。曾据此读出乱码,还误判成"地址失效"。 + +**正确做法**: + +``` +每次采样前: + memory_maps → VM 基址 + android.os.Process.myTid → TID + 断点读 x0 → state 指针 +``` + +## 七、单样本不下结论 + +上面 1、2、3、4 的共同根因都是**单样本/单次观察**。 + +**规则**:任何"规律"至少需要: +- 3 个不同的输入 +- 2 次重复验证 +- 1 次边界测试 + +三者缺一,结论标"待复核",不能写进交付物。 + +## 八、报告里必须区分"已验证"与"推测" + +```markdown +✅ 实测:8 组 payload × 2 次调用,8/8 一致 +⚠️ 推测:可能是 XX 构造(未验证) +❌ 已否证:YY 方案(96 种组合 0 命中) +``` + +**不要把推测写成实测。** 也不要把"没测到"写成"不存在"。 + +## 一句话 + +**观察是廉价的,从观察推到结论是昂贵的。** 每次下结论前问: +「这个结论如果错了,会是什么样子?我测过那个样子吗?」 \ No newline at end of file diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 0ccf9e6..80ec4c5 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -1,6 +1,6 @@ # ADH MCP Tools -Generated from the source ADH Daemon registry (87 tools). The normal daemon on port 8088 loads this registry. analysis_guide provides workflows (action=guide) and current evidence assessment (action=assess) without repository access. Assessment never executes its proposed next call. Reconnect existing clients to refresh schemas and initialization instructions. MCP clients connect using the published adh CLI. +Generated from the live ADH Daemon registry (91 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). | Tool | Description | Args | |---|---|---| @@ -9,9 +9,9 @@ Generated from the source ADH Daemon registry (87 tools). The normal daemon on p | `runtime_diagnostics` | Read-only process/thread diagnosis through root ADB, independent of the agent command channel. Accepts a known online or offline session; verifies PID/UID/cmdline and process starttime before and after reading. Reports process-exited, identity-mismatch, frozen, traced, running or unknown, with actual wchan/TracerPid/cgroup facts and paged existing thread candidates for root_watch. Never resumes, starts or stops the target, never changes SELinux. Missing evidence stays unknown; thread candidates do not cover future threads. | session, serial, afterTid, limit, timeoutMs | | `trace_session` | Use analysis_guide(topic=trace) for prerequisites and ordered call templates. Persist a bounded QBDI trace on the Host and query it without dumping thousands of instructions into context. prepare loads an explicitly named QBDI library; record actively invokes one native function (confirm:true), collects up to 65536 instructions in bounded agent memory and drains pages to ADH_DATA_DIR/traces, then releases target memory. Needs a current agent advertising qbdi_read. budget<=1000000, timeMs<=10000, capacity<=65536. Query by sequence/pc/address range/mnemonic; stats summarizes all stored instructions and observed block entries; slice conservatively follows register dependencies and stops at unsupported instructions, memory or external calls. A completed execution can still have incomplete recording; check complete, transportComplete, truncated and coverage. Coverage is the instrumented module, not the original app execution or external callees. In-hook replay remains a separate limited observation. | action, session, id, path, confirm, addr, symLib, symbol, args, budget, timeMs, capacity, afterSeq, limit, pc, minPc, maxPc, mnemonic, register, beforeSeq, maxScan | | `root_watch` | To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event; there are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM. | action, session, serial, id, tid, addr, width, mode, durationMs, maxEvents, stackBytes, afterSeq, limit, registers, stackAddress, stackSize | -| `process_list` | List connected target agent sessions. Choose the intended package/process explicitly, then call capabilities with its sessionId. Reselect after reconnect. New users can query analysis_guide(topic=start) without a session. | | +| `process_list` | List connected target agent sessions. Choose the intended package/process explicitly, then call capabilities with its sessionId. Reselect after reconnect. New users can query analysis_guide(topic=start) without a session. | — | | `backends` | Injection-backend matrix: sessions by entry + device-side Zygisk pointers. Pass session to classify which paths are really loaded (zygisk / self_load). Frida Gadget is not a product backend. | session | -| `dumps_list` | List captured dump artifacts (dex/so/region) | | +| `dumps_list` | List captured dump artifacts (dex/so/region) | — | | `compat_probe` | Self-assess agent env + injection footprint: tracer/seccomp/backends/exec/anon/rwx | session | | `jni_onload` | List, hook, unhook, inspect or manually invoke JNI_OnLoad. hook/call work on an already-loaded module; watch arms a one-shot LOAD-TIME interception: the agent hooks the dlopen entry point and patches the JNI_OnLoad of that module as soon as it is mapped, before the VM calls it (skipOriginal+returnValue can then replace that load-time call). call is dangerous and requires confirm:true. Events are emitted as JNI_ONLOAD with phase=manual\|load. | session, action, module, confirm, skipOriginal, returnValue | | `jni_hook` | Install, remove or inspect the global JNIEnv->RegisterNatives hook. Each registration emits a JNI_NATIVE capture event with class, method, signature and native function pointer. | session, action | @@ -29,7 +29,7 @@ Generated from the source ADH Daemon registry (87 tools). The normal daemon on p | `memory_restore` | Undo a memory_write: the host kept the bytes each write replaced, so restoring needs only the address. Without addr it lists what this session can still restore (newest last) instead of guessing. Returns the agent reply plus restored:true, or why nothing was restored. | session, addr | | `capabilities` | What the RUNNING agent can do: every op it dispatches plus the limits that decide whether a plan is feasible (hook slots, memory windows, max write size, frame size), and the daemon limits that apply on the host side. Call this first when you do not know which operations a session supports. The answer comes from the agent itself, not from documentation: two processes can run different builds. | session | | `settings` | Read or patch daemon settings. action:"get" returns the live settings; action:"patch" merges ONLY the sections present in patch (capture + families, ui, artifacts, startup) and persists them. startup is the host-side pre-arm applied to every NEW session at hello: startup.antiDebug (default false) + startup.module + startup.extraTargets + startup.packages (empty = all). Its default plan is ptrace only, because neutralizing access/faccessat during initialization kills apps (measured); widenAfterMs + widenTargets install those LATER, on the settled process, without another command. Enabling this makes every path check in the app fail - that is the point, but it is per-target, not a default. | action, patch | -| `native_look` | The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with ONE object: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from the same hit. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name. | session, action, hookId, mode, module, symbol, addr, confirm, mem, backtrace, hard, maxEvents, sampleEvery, tid, returnAddress, traceInsns, traceFrom, traceWatch | +| `native_look` | The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with the NEWEST hit by default: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from that same hit, and retained.total says how many numbered hits are still stored. Pass seq for one earlier hit, or beforeSeq plus limit (1..50) to page older hits; nextBeforeSeq is the cursor. Do not re-run the operation to recover an earlier call. argIndex rewrites an argument and is not a filter. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name. | session, action, hookId, seq, beforeSeq, limit, mode, module, symbol, addr, confirm, mem, backtrace, hard, maxEvents, sampleEvery, tid, returnAddress, traceInsns, traceFrom, traceWatch | | `syscall_digest` | Turn watched syscall hits into an answer: groups the NATIVE_HOOK events of the hooks you pass by (syscall number, CALLER frame) with counts, time window and threads, picks the first caller frame outside libc (that is the code that issued the syscall, which is what fingerprint-collection hunting needs), decodes the argument registers through the pointers the syscall actually uses (openat/faccessat/newfstatat paths, memfd_create names, uname utsname fields, connect IPv4/IPv6, ioctl request, socket domain/type) into a per-group example plus a paths histogram - which files does this code probe - and compares the runtime x8 with the statically attributed number so a wrong attribution shows up as a mismatch instead of a mislabel. Argument decoding reads target memory, so it is bounded by decodeLimit (default 40 samples) and can be turned off with decode:false. Install the watch with syscall_watch (it sets backtrace:true) and pass its hookIds plus expected {hookId: nr}.. Counters are reported as hits/throttled/emitted: a throttled watch counts every hit (from the authoritative agent hook status), so a thinned log cannot read as a quiet target | session, hookIds, expected, sinceMs, limit, maxGroups, decode, decodeLimit | | `java_trace` | Class-level Java tracing in three explicit phases. action:start hooks every matching method of a class (hook_all semantics: method/params are optional filters, "*"/empty = any) and returns hookIds + matched + a capture cursor, KEEPING the hooks installed. action:digest drains the agent capture ring and turns the JAVA_HOOK events of those hook ids into a digest: per-method counts, first/last timestamp, threads, last argument and return, error counts, a chronological timeline (newest window) and a caller histogram when the hooks were started with stack:true. action:stop unhooks exactly the given ids (id 0 means every Java hook in the agent and is refused). Pass the cursor from start as sinceCaptureId on digest to see only events newer than that point. The digest drains the agent ring through the shared drainSession path, so it never eats records that another consumer still needs; a failed drain is reported in drain.ok instead of silently returning an empty trace. Trigger the target or let natural traffic run between start and digest. | session, action, className, method, params, limit, stack, hookIds, sinceCaptureId, maxTimeline, maxMethods, maxCallers | | `native_hook_all` | Batch native hooking by exported-symbol pattern: give a module and a prefix/contains/exact filter and it resolves every matching exported FUNCTION from the module dump (not a hand-typed address list), installs inline hooks on up to limit of them (clamped to the 16 physical native slots available over the process lifetime) and returns hookIds with matched vs installedCount so truncation is visible. The batch is sized from the agent slot budget (native_hook status reports slots.max/used/free/byMode): with 0 free slots the call fails loud instead of failing symbol by symbol, and a short budget truncates the batch with limitReason explaining it. Address hooks are powerful, so confirm:true is required. action:unhook takes hookIds and removes exactly those. Filters are deterministic (address order), exclude can drop noisy names, and backtrace/throttleMs/skipOriginal/returnValue/argIndex/argValue are passed through to each hook (throttleMs keeps a hot symbol from flooding the ring; the response echoes the effective window). | session, action, module, prefix, contains, exact, exclude, limit, backtrace, throttleMs, maxEvents, sampleEvery, tid, returnAddress, skipOriginal, returnValue, argIndex, argValue, hookIds, confirm | @@ -42,6 +42,7 @@ Generated from the source ADH Daemon registry (87 tools). The normal daemon on p | `syscall_watch` | Scan one loaded module for direct svc #0 sites (libc.so is the interesting one: its stubs are what ordinary app code reaches the kernel through), attribute each site to a syscall number by decoding the MOV that precedes the svc, inline-hook up to limit of the matching sites, and report hooks whose NATIVE_HOOK events carry x8 as the runtime syscall number. syscalls filters by name or number and accepts a CSV or an array ("uname,openat,117"); a filter that matches nothing fails loud. throttleMs (0 = off) caps how often each site reports an event - hot syscalls such as read/write/futex otherwise overflow the ring and make the digest look quiet; the response echoes the effective window. Host-side orchestration: dump + static scan + native_hook; agent remains execution-only. | session, module, limit, throttleMs, syscalls | | `got_enum` | Enumerate relocation/GOT entries for one loaded module: slot address, symbol name, current resolved value and relocation type. Optional filter matches one symbol exactly. | session, module, filter | | `memory_maps` | On-demand full /proc/self/maps of the target | session | +| `maps_query` | Filtered view of the target maps plus address resolution: the answer to "which segment is this address in", "where is the decrypted copy", "which anonymous regions are executable". A full maps reply is 2000-5000 lines and floods context; this returns only matching regions with size/perms/file-offset/path and reports matched/truncated so a short list is never mistaken for a complete one. addr resolves the containing region and its module-relative file offset (the "belongs to whom" fact that otherwise has to be inferred by hand). | session, path, perm, exec, anon, minSize, maxSize, limit, addr | | `mem_backend` | Force which route the agent reads target memory by, for the whole session: auto (default) lets it use /proc/self/mem when the target allows that fd and fall back to an in-process direct read otherwise; direct forces the fallback everywhere. The reply states requested vs effective backend, whether it is forced, and the errno of the last /proc/self/mem open attempt. This exists because a target that refuses that fd cannot be produced on demand, so without forcing it the fallback is only ever exercised on the single read command that has a per-call override - search, magic-scan, dump and art_dexfiles would never run on it. Set it back to auto when done: it is a diagnostic, not a mode to leave on. | session, backend | | `memory_read` | Read target memory at hex addr for size bytes (base64 out). The reply carries requested/short, so a truncated read is visible without recomputing it from the base64 length, and via names the route that answered. via:"direct" forces the direct in-process reader for this one read instead of /proc/self/mem - use it to cross-check a target that answers /proc/self/mem with plausible garbage, or to read when the target refuses that fd (a protector that calls prctl(PR_SET_DUMPABLE,0) makes open("/proc/self/mem") fail with EACCES even for the process itself, and the read then falls back to the direct route on its own) | session, addr, size, via | | `memory_disasm` | Disassemble live target memory with host-side Capstone 5 (WASM). addr is an absolute hex address, or pass module plus offset to resolve the module base from live maps. size is bounded to 64 KiB and aligned to AArch64 instructions. | session, addr, size, module, offset | @@ -72,7 +73,7 @@ Generated from the source ADH Daemon registry (87 tools). The normal daemon on p | `object_invoke` | Call a no-arg method on a live object (via static field path) | session, className, field, method | | `dex_method_code` | Extract a method’s runtime code_item bytecode from a dex (b64\|sha). disasm:true adds a real Dalvik disassembly next to it — one entry per instruction (offset, raw code units, mnemonic + operands), decoded by the SDK's dexdump -d on the host rather than by a table this project would have to keep correct. Only the matching methods are kept (class is a normalised case-insensitive substring, method a name substring), each body capped at maxInsns (default 400) with insnsTruncated telling you, and the whole reply bounded by methodMatches/returned/truncated. When the tool is absent the reply carries disasm.available:false plus the reason and the raw code_item still comes back; a dumped dex with a stale header checksum is refused by dexdump, so run dex_repair and pass the repaired bytes. | b64, sha, class, method, disasm, maxInsns | | `dex_repair` | Repair a dumped dex header (file_size/checksum/signature) and store the repaired bytes as a dump artifact. Returns the header fields plus the artifact sha256/size/kind/path. The repaired dex is deliberately NOT returned inline: a packed target dex can be 100 MB+, and the caller already holds the input bytes - index or download it by the returned sha instead. dedup:true means a byte-identical artifact was already stored. | b64, sha | -| `crypto_identify` | 一眼看清目标 App 用了哪些加密算法/密钥/IV — summarize all captured crypto (algorithm, key, iv, plaintext) into a plain-language report for non-experts | | +| `crypto_identify` | 一眼看清目标 App 用了哪些加密算法/密钥/IV — summarize all captured crypto (algorithm, key, iv, plaintext) into a plain-language report for non-experts | — | | `detect_summary` | Checklist of anti-analysis behavior seen in the live capture store: debug, root/framework, signature, emulator, integrity, plus property reads. Built from ptrace/access/faccessat/sysprop/propread lines (including return value), from open/openat of /proc/self/status\|maps and su/magisk paths, and from JAVA_HOOK hits of the detect_java methods. Other Java/native hooks stay out of this checklist. armed is false when capture_start did not install a system hook (sysModule empty). Does not install anything. | session, package | | `detect_modules` | Which of THIS app's loaded libraries import ptrace, access, faccessat or the system-property readers. Pass the package. Returns sysModule, a comma-separated list you can hand to capture_start. Does not install hooks. System libraries are excluded. A packed relocation table with no readable symbols is reported in skippedPacked instead of being treated as "imports nothing". | session, package | | `detect_java` | Java detection hooks, installed only when confirm:true and you name the families. Families: debug (Debug.isDebuggerConnected / waitingForDebugger), root (Runtime.exec(String)), signature (ApplicationPackageManager.getPackageInfo), file (File.exists — hot path, unhook when done). Without confirm the reply is the plan and nothing is hooked. Each installed hook captures a stack. Partial installs stay in place and are listed in hookIds so you can unhook them. | session, confirm, families | @@ -90,4 +91,7 @@ Generated from the source ADH Daemon registry (87 tools). The normal daemon on p | `fs_list` | List a directory on the DEVICE through the target process, so it sees the sandbox the way the app does (its private /data/data/... dir, /data/local/tmp, /proc/self/...). Returns name/type/size/mode/mtime per entry plus count and truncated. Start here to find shared_prefs, databases, keystores or dropped scripts, then pull one with fs_read. | session, path | | `fs_read` | Read one device file through the target process. The agent caps a read at 1MB and reports truncated honestly. Returns size, byte count, a binary flag (NUL byte present), a printable preview and the line count, plus the whole text when the file is text and is at most 256KB. Binary or oversized files come back with textOmitted saying why; pass includeBase64:true for the raw bytes. | session, path, includeBase64, includeText, previewBytes | | `load_library` | 把任意 .so 加载进目标进程(agent 内 dlopen)。可选 symbol 探测。不是 Frida 注入入口。 | session, path, symbol | -| `oracle` | Controlled invocation of the TARGET'S OWN entry point, and the differential harness on top of it - the primitive that turns "unknown parameter" into a small search space without knowing anything about the target. action:record calls the entry ONCE (detached java_call, so a blocking method parks one thread instead of the session) and keeps its arguments as a reusable template; extract is the path in the reply of the value to watch (default result), and a string that looks like JSON is parsed while walking, so result[0].b5 works for a facade that returns a JSON string. action:replay re-runs the template with patches applied to its RECORDED arguments (byte payloads stay {"$bytesHex":...}, so [1][0].$bytesHex is a normal patch path), and answers value + changed. action:diff runs one replay per variant and returns the dependency matrix: sensitive lists the input fields whose change moved the observed value, insensitive those that never did - that is the answer to "which input is this digest over". action:list and action:drop manage the templates. Paths are dotted/bracketed JSON paths (`args[1][0].$bytesHex`, `[0].b5`). Nothing here is target-specific: the caller names a facade it already knows how to call. | session, action, id, className, method, params, field, args, extract, patches, variants, timeoutMs | +| `oracle` | Controlled invocation of the TARGET'S OWN entry point, and the differential harness on top of it - the primitive that turns "unknown parameter" into a small search space without knowing anything about the target. action:record calls the entry ONCE (detached java_call, so a blocking method parks one thread instead of the session) and keeps its arguments as a reusable template; extract is the path in the reply of the value to watch (default result), and a string that looks like JSON is parsed while walking, so result[0].b5 works for a facade that returns a JSON string. action:replay re-runs the template with patches applied to its RECORDED arguments (byte payloads stay {"$bytesHex":...}, so [1][0].$bytesHex is a normal patch path), and answers value + changed. action:diff runs one replay per variant and returns the dependency matrix: sensitive lists the input fields whose change moved the observed value, insensitive those that never did - that is the answer to "which input is this digest over". action:list and action:drop manage the templates. Paths are dotted/bracketed JSON paths (`args[1][0].$bytesHex`, `[0].b5`). Nothing here is target-specific: the caller names a facade it already knows how to call. action:stability replays the template repeat times with the SAME arguments and reports stable/distinct/firstDiff: a pure function answers the same value every time, a hidden state or a time input does not - know this before trusting any black-box search. | session, action, id, className, method, params, field, args, extract, patches, variants, repeat, timeoutMs | +| `analyze_app` | One call from a package name to a bounded report: adds the package to the phone injection allowlist when needed (reported as scopeAdded), cold starts it, waits for the Zygisk-injected agent, then runs triage (caps / maps size / dex files / capture window / module loads / detection surface) plus optional unpack (dump every DEX) and httpCaptureMs (a TLS traffic window). Use it when the caller knows only the app name, not a session id. Every phase reports ok/error and one failed phase does not discard the others. The target must be an installed third-party app: system packages and the ADH manager are refused. | package, autoScope, forceRestart, captureMs, unpack, httpCaptureMs, timeoutMs, settleMs | +| `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | — | +| `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set | diff --git a/injector/zygisk/jni/main.cpp b/injector/zygisk/jni/main.cpp index 20da593..f11c474 100644 --- a/injector/zygisk/jni/main.cpp +++ b/injector/zygisk/jni/main.cpp @@ -33,6 +33,8 @@ static constexpr const char *kHostEndpointPath = "/data/adb/adh/host.endpoint"; static constexpr const char *kLoaderMarker = "/data/adb/adh/zygisk_loaded"; // == com.adh.core.AdhPaths.LOADER_MARKER static constexpr const char *kManagerPkg = "com.adh.manager"; // == com.adh.core.AdhPaths.MANAGER_PKG static constexpr const char *kAgentName = "libadh_agent.so"; // == com.adh.core.AdhPaths.AGENT_SO_NAME +static constexpr const char *kQbdiName = "libQBDI.so"; // optional tracer, delivered on demand +static constexpr const char *kQbdiFlagPath = "/data/adb/adh/qbdi.enabled"; // presence = deliver the tracer #include static zygisk::Api *g_api_for_log = nullptr; // set in onLoad, used to relay logs (see note()) @@ -452,7 +454,7 @@ static bool policy_flags_for(const char *pkg, char *out, size_t cap) { return true; } -static int open_agent_fd(zygisk::Api *api, std::string *where) { +static int open_agent_fd(zygisk::Api *api, std::string *where, int *qbdi_out) { // Open the agent while we are still in the pre-specialize window. Calling // getModuleDir() from postAppSpecialize deadlocks on Zygisk Next, so keep // the daemon interaction here and pass only the plain fd to the linker. @@ -463,6 +465,17 @@ static int open_agent_fd(zygisk::Api *api, std::string *where) { } int fd = openat(dirfd, kAgentName, O_RDONLY | O_CLOEXEC); int saved_errno = errno; + // The optional tracer is opened in the same window for the same reason: /data/adb is not + // readable from the app domain, and an inherited fd is the only way to hand a real target a + // library it can load. Failure is not fatal - the agent just keeps QBDI off for this process. + if (qbdi_out) { + *qbdi_out = -1; + int qfd = openat(dirfd, kQbdiName, O_RDONLY | O_CLOEXEC); + int qerr = errno; + if (qfd >= 0) *qbdi_out = qfd; + else note("openat(module dir, %s) failed: %s - QBDI stays off for this process", + kQbdiName, strerror(qerr)); + } close(dirfd); if (fd < 0) { LOGE("openat(module dir, %s) failed: %s", kAgentName, strerror(saved_errno)); @@ -745,8 +758,23 @@ class AdhModule : public zygisk::ModuleBase { } if (!host_endpoint.empty()) note("host endpoint %s", host_endpoint.c_str()); + // QBDI is an opt-in payload: the flag file is root-written, and the companion (root) is the + // only side that can see it. No flag = no fd = no library, no mapping, no cost. + qbdi_enabled = false; + { + int qsock = connect_companion(); + if (qsock >= 0) { + char reply[8] = {0}; + if (send_all(qsock, "qbdi\n", 5) && read_reply_line(qsock, reply, sizeof(reply))) { + qbdi_enabled = (reply[0] == '1'); + } + close(qsock); + } + } + if (qbdi_enabled) note("qbdi delivery enabled pkg=%s", package.c_str()); + should_inject = true; - int src_fd = open_agent_fd(api, &agent_path); + int src_fd = open_agent_fd(api, &agent_path, qbdi_enabled ? &qbdi_fd : nullptr); if (src_fd < 0) { should_inject = false; return; @@ -818,6 +846,20 @@ class AdhModule : public zygisk::ModuleBase { LOGE("adh_agent_set_endpoint not found; agent keeps loopback only"); } } + // Hand the tracer over before start() so the very first qbdi_trace already has it. The agent + // owns the fd from here on (it re-reads it on every trace), so the companion must not close it. + if (qbdi_fd >= 0) { + using set_qbdi_fn = void (*)(int); + auto set_qbdi = reinterpret_cast(dlsym(handle, "adh_agent_set_qbdi_fd")); + if (set_qbdi) { + set_qbdi(qbdi_fd); + qbdi_fd = -1; + } else { + close(qbdi_fd); + qbdi_fd = -1; + LOGE("adh_agent_set_qbdi_fd not found; QBDI stays off for this process"); + } + } using start_fn = void (*)(); auto start = reinterpret_cast(dlsym(handle, "adh_agent_start")); if (!start) { @@ -834,6 +876,8 @@ class AdhModule : public zygisk::ModuleBase { bool should_inject = false; bool marker_requested = false; int agent_fd = -1; + int qbdi_fd = -1; + bool qbdi_enabled = false; std::string agent_path; std::string package_name; // Hook-family policy line for this package (empty = none configured → agent defaults to all on). @@ -854,6 +898,7 @@ REGISTER_ZYGISK_MODULE(AdhModule) // "policy \n" -> replies "d=1,h=0,s=1,a=1,t=1,e=0\n", or "default\n" when the // package carries no policy at all. Capture families default ON. // "log \n" -> appends to the root decision log, replies "ok\n" +// "qbdi\n" -> replies "1\n" when /data/adb/adh/qbdi.enabled exists, else "0\n" // "host\n" -> replies "ipv4:port\n", or "none\n" when no address is stored // Anything else - including a line that arrived truncated or over-long - is refused with "err\n": // the companion never guesses, so an incomplete request can no longer be mistaken for a "mark". @@ -903,6 +948,14 @@ static void companion_serve(int client) { } continue; } + if (strcmp(req, "qbdi") == 0) { + // Opt-in payload switch. Only the root companion can see /data/adb, so the instance asks + // it and opens the tracer fd only when the answer is yes. No flag file = QBDI off. + bool on = (access(kQbdiFlagPath, F_OK) == 0); + note("companion qbdi -> %d", on ? 1 : 0); + (void)send_all(client, on ? "1\n" : "0\n", 2); + continue; + } if (strcmp(req, "host") == 0) { char endpoint[64]; if (read_host_endpoint(endpoint, sizeof(endpoint))) { diff --git a/injector/zygisk/module/customize.sh b/injector/zygisk/module/customize.sh index db8ff2e..1f55af6 100644 --- a/injector/zygisk/module/customize.sh +++ b/injector/zygisk/module/customize.sh @@ -5,6 +5,11 @@ ui_print "- Installing ADH Zygisk module" unzip -o "$ZIPFILE" 'module.prop' -d "$MODPATH" >&2 unzip -o "$ZIPFILE" 'zygisk/*' -d "$MODPATH" >&2 unzip -o "$ZIPFILE" 'libadh_agent.so' -d "$MODPATH" >&2 +# Optional QBDI tracer payload. Absent from adh-zygisk.zip when tools/fetch_qbdi.sh has not run. +if unzip -l "$ZIPFILE" 'libQBDI.so' >/dev/null 2>&1; then + unzip -o "$ZIPFILE" 'libQBDI.so' -d "$MODPATH" >&2 + set_perm "$MODPATH/libQBDI.so" 0 0 0644 +fi unzip -o "$ZIPFILE" 'daemon.apk' -d "$MODPATH" >&2 unzip -o "$ZIPFILE" 'LICENSE' 'NOTICE' 'third_party_licenses/*' -d "$MODPATH" >&2 unzip -o "$ZIPFILE" 'device-daemon' -d "$MODPATH" >&2 diff --git a/injector/zygisk/module/module.prop b/injector/zygisk/module/module.prop index ab596aa..721ac6e 100644 --- a/injector/zygisk/module/module.prop +++ b/injector/zygisk/module/module.prop @@ -1,7 +1,7 @@ id=adh name=AndroidDecryptHub -version=v0.6.0 -versionCode=26 +version=v0.8.0 +versionCode=30 author=decrypthub.com description=状态:等待重启 updateJson=https://raw.githubusercontent.com/decrypthub/AndroidDecryptHub/main/injector/zygisk/update.json diff --git a/injector/zygisk/update.json b/injector/zygisk/update.json index 727015b..670dcae 100644 --- a/injector/zygisk/update.json +++ b/injector/zygisk/update.json @@ -1,7 +1,7 @@ { - "version": "v0.6.0", - "versionCode": 26, - "zipUrl": "https://github.com/decrypthub/AndroidDecryptHub/releases/download/v0.6.0/adh-bundle-v0.6.0.zip", - "changelog": "https://github.com/decrypthub/AndroidDecryptHub/releases/tag/v0.6.0", - "verifiedAt": "2026-10-24T13:20:00Z" + "version": "v0.8.0", + "versionCode": 30, + "zipUrl": "https://github.com/decrypthub/AndroidDecryptHub/releases/download/v0.8.0/adh-bundle-v0.8.0.zip", + "changelog": "https://github.com/decrypthub/AndroidDecryptHub/releases/tag/v0.8.0", + "verifiedAt": "2026-11-12T12:20:00Z" } diff --git a/tools/MAP.md b/tools/MAP.md index b67ba61..31b774b 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -14,6 +14,17 @@ v126 verifies kernel write events/GPR/stack/generation. v123/v125/v126 can use t `run_native_fixture.mjs SERIAL` runs the native host for <=300 seconds with cooperative stop-file cleanup. The host uses a UUID directory and memfd and is not an injection path for product targets. +`qbdi_toggle.sh` switches the optional QBDI payload: the tracer ships inside the module +(`libQBDI.so`), the root companion answers a `qbdi` query by checking `/data/adb/adh/qbdi.enabled`, +and only when it is set does the instance open the library fd pre-specialize and hand it to the agent +(`adh_agent_set_qbdi_fd`). The agent copies that fd into a memfd on the first `qbdi_trace`, so the +default injection surface is unchanged (no library, no mapping, no fd) and a standalone trace releases +the mapping again. `verify_v129_qbdi_delivery.sh` (device) is the acceptance on a REAL third-party app +(default `com.uxin.kilaaudio`, override with `ADH_QBDI_TEST_PKG`): flag off → actionable refusal and no +fd; flag on → fd delivered, `qbdi_trace libc:getpid` returns the target pid, and the library is gone +from `/proc//maps` afterwards. +`verify_v130_scope_analyze.sh` (host) gates the programmable scope and the one-call analysis: the allowlist merge rules (names the C++ companion will parse), the main-process pick, and the `analyze_app` / `scope_list` / `scope_set` MCP tool shapes. It never writes scope.json or starts an app — those are product actions covered by real-device acceptance. + `verify_v127_symbols.sh` (host) is the newest slice: `native_symbols` — one module's dynamic symbol table (name / module-relative offset / size / kind), filterable by `kind` and name substring, paged with `total`/`returned`/`nextOffset`. It gates the 12-case unit file first (floor 11, because the diff --git a/tools/build_zygisk.sh b/tools/build_zygisk.sh index 191486f..7dc1111 100644 --- a/tools/build_zygisk.sh +++ b/tools/build_zygisk.sh @@ -26,6 +26,18 @@ if [ "$need_agent" = 1 ]; then fi [ -f "$AGENT_SO" ] || { echo "!! agent .so still missing"; exit 1; } +# Version pairing is an invariant, not a convention: the agent reports AGENT_VER at hello and the +# host compares it with module.prop, so a stale AGENT_VER ships a module that lies about its own +# contents. Fail the build instead of discovering it after a flash. +MOD_VER="$(awk -F= '$1 == "version" { print $2 }' "$MOD/module.prop" | tr -d '\r')" +AGENT_VER="$(sed -n 's/^#define AGENT_VER[[:space:]]*"\(.*\)"/\1/p' "$ROOT/agent/src/bootstrap/agent_internal.h" | head -n 1 | tr -d '\r')" +if [ "v$AGENT_VER" != "$MOD_VER" ]; then + echo "!! version mismatch: module.prop=$MOD_VER but agent AGENT_VER=$AGENT_VER" + echo " bump both (and update.json / Manager / Device Daemon) or fix the one that is stale" + exit 1 +fi +echo ">> version pairing ok: $MOD_VER" + echo ">> building ADH Manager for daemon caller authentication" ( cd "$ROOT/device" @@ -90,6 +102,15 @@ cp "$MOD/META-INF/com/google/android/update-binary" "$STAGE/META-INF/com/google/ cp "$MOD/META-INF/com/google/android/updater-script" "$STAGE/META-INF/com/google/android/" cp "$COMPANION" "$STAGE/zygisk/$ABI.so" cp "$AGENT_SO" "$STAGE/libadh_agent.so" +# Optional tracer payload: shipped in the MODULE (never in the sandbox APK - a real target does not +# carry it). The companion hands an fd to allowlisted processes only when /data/adb/adh/qbdi.enabled +# exists, so the default injection carries no QBDI code, mapping or string at runtime. +QBDI_SO="$ROOT/agent/third_party/qbdi/lib/libQBDI.so" +if [ -f "$QBDI_SO" ]; then + cp "$QBDI_SO" "$STAGE/libQBDI.so" +else + echo "!! libQBDI.so absent - the module will ship without the optional tracer (run tools/fetch_qbdi.sh)" +fi cp "$DAEMON_APK" "$STAGE/daemon.apk" mkdir -p "$DIST" diff --git a/tools/fetch_qbdi.sh b/tools/fetch_qbdi.sh index a008d7b..f3fbeb4 100644 --- a/tools/fetch_qbdi.sh +++ b/tools/fetch_qbdi.sh @@ -25,5 +25,13 @@ else echo ">> extracted headers + libQBDI.so ($(wc -c < "$DEST/lib/libQBDI.so") bytes)" fi mkdir -p "$JNILIBS" -cp "$DEST/lib/libQBDI.so" "$JNILIBS/libQBDI.so" -echo ">> staged libQBDI.so into sandbox jniLibs" +if [ "${ADH_STAGE_SANDBOX_QBDI:-0}" = "1" ]; then + # Explicitly opt-in only: a sandbox APK that ships the tracer is NOT a product-shaped test - a + # real target never carries it. The product path is module payload + companion fd delivery. + cp "$DEST/lib/libQBDI.so" "$JNILIBS/libQBDI.so" + echo ">> WARNING: staged libQBDI.so into the sandbox jniLibs (ADH_STAGE_SANDBOX_QBDI=1)." + echo " This makes the sandbox pass regardless of the real injection path - do not use it as" + echo " product acceptance; tools/verify_v10_qbdi.sh delivers the library at runtime instead." +else + echo ">> NOT staging libQBDI.so into the sandbox APK (product-shaped: targets do not carry it)" +fi diff --git a/tools/native/root_watch.c b/tools/native/root_watch.c index c826e62..def69f1 100644 --- a/tools/native/root_watch.c +++ b/tools/native/root_watch.c @@ -94,7 +94,7 @@ static int parse_mem(const char *text) { if (hop == 0) { const char *sign = NULL; for (size_t i = 0; i < seg_len; i++) if (p[i] == '+' || p[i] == '-') { sign = p + i; break; } - size_t reg_len = sign ? (size_t)(sign - seg_start) : seg_len; + size_t reg_len = sign ? (size_t)(sign - p) : seg_len; m.reg = reg_of(p + seg_start, reg_len); if (m.reg < 0) return 0; if (sign) { diff --git a/tools/qbdi_toggle.sh b/tools/qbdi_toggle.sh new file mode 100644 index 0000000..c8c2c70 --- /dev/null +++ b/tools/qbdi_toggle.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Enable/disable the optional QBDI instruction-trace payload for real targets. +# +# The tracer (libQBDI.so) ships inside the module but is NOT loaded by default: the Zygisk companion +# hands an fd to allowlisted processes only while /data/adb/adh/qbdi.enabled exists, and the agent +# copies that fd into a memfd on the first qbdi_trace. With the flag absent the default injection +# surface is unchanged (no library, no mapping, no extra fd). +# +# Usage: +# bash tools/qbdi_toggle.sh status +# bash tools/qbdi_toggle.sh on [--restart ] +# bash tools/qbdi_toggle.sh off [--restart ] +# +# Changing the flag only affects processes started AFTER the change: the decision is made when a +# process is specialized. --restart cold-starts one package so it picks the new state up. +set -uo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/env.sh" + +FLAG="/data/adb/adh/qbdi.enabled" +MODE="${1:-status}" +shift || true +PKG="" +while [ "$#" -gt 0 ]; do + case "$1" in + --restart) PKG="${2:-}"; shift 2 || shift ;; + *) echo "!! unknown argument: $1" >&2; exit 2 ;; + esac +done + +SERIAL="${ANDROID_SERIAL:-$(adb devices | tr -d '\r' | awk 'NR>1 && $2=="device" {print $1; exit}')}" +[ -n "$SERIAL" ] || { echo "!! no adb device in 'device' state" >&2; exit 1; } + +dev_root() { adb -s "$SERIAL" shell "su -c '$1'" | tr -d '\r'; } + +case "$MODE" in + status) + if [ "$(dev_root "test -f $FLAG && echo yes || echo no" | tail -n 1)" = "yes" ]; then + echo "qbdi: on (delivered to allowlisted processes at specialization)" + else + echo "qbdi: off (default injection surface: no QBDI library / mapping / fd)" + fi + ;; + on) + dev_root "mkdir -p /data/adb/adh && touch $FLAG" >/dev/null + echo "qbdi: on" + ;; + off) + dev_root "rm -f $FLAG" >/dev/null + echo "qbdi: off" + ;; + *) + echo "!! mode must be status, on or off (got '$MODE')" >&2 + exit 2 + ;; +esac + +if [ -n "$PKG" ]; then + echo ">> cold-starting $PKG so it re-specializes" + adb -s "$SERIAL" shell am force-stop "$PKG" >/dev/null 2>&1 + sleep 1 + adb -s "$SERIAL" shell monkey -p "$PKG" -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1 || true +fi +echo ">> target must be cold-started after a change (scope decision happens at specialization)" diff --git a/tools/verify_all.sh b/tools/verify_all.sh index 3f9d4f5..a6b9d01 100644 --- a/tools/verify_all.sh +++ b/tools/verify_all.sh @@ -277,6 +277,11 @@ SCRIPTS=( # already covered by v84 (native_hook_all resolves exports through the same maps+dump+parse chain); # what is new is the paging/filter/archive contract and the refusal to add an agent op for it. "verify_v127_symbols.sh:host" + # v129: the QBDI payload on a REAL target (not the sandbox APK): default refuses with an actionable + # error and delivers no fd; opt-in delivers the fd, traces, and releases the library afterwards. + "verify_v129_qbdi_delivery.sh:device" + # v130: scope merge rules + the analyze_app/scope_* MCP tool contract (host only, no device write). + "verify_v130_scope_analyze.sh:host" ) pass=0; fail=0; skip=0; FAILED="" diff --git a/tools/verify_v02_so.sh b/tools/verify_v02_so.sh index cf74683..eedba2f 100644 --- a/tools/verify_v02_so.sh +++ b/tools/verify_v02_so.sh @@ -29,6 +29,12 @@ console.log('DUMP_PATH='+d.path); EOF )" echo "$OUT" +# No sandbox process = no target to reassemble. That is an environment state, not a regression: the +# gate must not report "no reassembled file" for an app the operator simply did not start. +if echo "$OUT" | grep -q 'NO_AGENT'; then + echo "⏭ SKIP: com.adh.sandbox is not running (start it, or run this after verify_v01)" + echo "RESULT:SKIP"; exit 0 +fi echo "$OUT" | grep -q 'RESULT' # noop DUMP_PATH="$(echo "$OUT" | sed -n 's/^DUMP_PATH=//p')" if [ -z "$DUMP_PATH" ] || [ ! -f "$DUMP_PATH" ]; then echo "❌ no reassembled file"; echo "RESULT:FAIL"; exit 1; fi diff --git a/tools/verify_v129_qbdi_delivery.sh b/tools/verify_v129_qbdi_delivery.sh new file mode 100644 index 0000000..04086e3 --- /dev/null +++ b/tools/verify_v129_qbdi_delivery.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +# v129 — QBDI payload delivery on a REAL target (product path, not the sandbox APK). +# +# Why this exists: the sandbox APK used to carry libQBDI.so inside jniLibs, so a sandbox-only test +# passed no matter what the injection path did. Real apps never ship our tracer. This script asserts +# the product behaviour end to end: +# A. flag off -> the trace is refused with an actionable "delivery is off" error, and the target +# has no QBDI fd (default injection surface is unchanged); +# B. flag on -> the companion hands an fd to the allowlisted process, the agent loads lazily, +# the trace runs, and the library is released again after a standalone trace. +# +# Needs: adhd running, root device, one allowlisted third-party app installed. +# Target package: ADH_QBDI_TEST_PKG (default com.uxin.kilaaudio). Missing target => SKIP, not FAIL. +set -uo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/verify_common.sh" +verify_resolve_env + +PKG="${ADH_QBDI_TEST_PKG:-com.uxin.kilaaudio}" +FLAG="/data/adb/adh/qbdi.enabled" + +fail() { echo "❌ v129 QBDI delivery FAIL: $*"; echo "RESULT:FAIL"; exit 1; } +skip() { echo "⏭ SKIP: $*"; echo "RESULT:SKIP"; exit 0; } + +adb -s "$SERIAL" get-state >/dev/null 2>&1 || skip "no device ($SERIAL)" + +dev_root() { adb -s "$SERIAL" shell "su -c '$1'" | tr -d '\r'; } +flag_state() { dev_root "test -f $FLAG && echo on || echo off" | tail -n 1; } + +adb -s "$SERIAL" shell "pm path $PKG" | tr -d '\r' | grep -q '^package:' || skip "$PKG not installed (set ADH_QBDI_TEST_PKG)" +[ "$(dev_root 'id -u' | tail -n 1)" = "0" ] || skip "no root (su)" +curl -s -m 3 "http://127.0.0.1:$HTTP/health" | grep -q '"ok": *true' || skip "adhd not running on :$HTTP" + +ORIGINAL_FLAG="$(flag_state)" + +cold_start() { + adb -s "$SERIAL" shell am force-stop "$PKG" >/dev/null 2>&1 + sleep 1 + adb -s "$SERIAL" shell monkey -p "$PKG" -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1 +} + +# Newest online agent for the package's MAIN process (companions have a ':' in the name). +wait_agent() { + node - "$HTTP" "$PKG" <<'EOF' +const [http, pkg] = process.argv.slice(2); +const base = `http://127.0.0.1:${http}`; +const deadline = Date.now() + 30000; +for (;;) { + try { + const agents = await (await fetch(`${base}/api/agents`)).json(); + const a = agents.filter(x => x.package === pkg && x.process === pkg && x.online) + .sort((x, y) => y.connectedAt - x.connectedAt)[0]; + if (a) { console.log(`${a.sessionId} ${a.pid}`); process.exit(0); } + } catch {} + if (Date.now() > deadline) { console.log('NO_AGENT'); process.exit(0); } + await new Promise(r => setTimeout(r, 500)); +} +EOF +} + +trace() { + node - "$HTTP" "$1" <<'EOF' +const [http, session] = process.argv.slice(2); +const url = `http://127.0.0.1:${http}/api/trace/qbdi?session=${session}&symLib=libc.so&symbol=getpid`; +try { + const r = await fetch(url); + const j = await r.json(); + console.log(JSON.stringify(j)); +} catch (e) { console.log(JSON.stringify({ ok: false, error: String(e) })); } +EOF +} + +restore() { + if [ "$ORIGINAL_FLAG" = "on" ]; then dev_root "touch $FLAG"; else dev_root "rm -f $FLAG"; fi + adb -s "$SERIAL" shell am force-stop "$PKG" >/dev/null 2>&1 +} +trap restore EXIT + +# --- A. default (off): refused with an actionable error, no fd delivered ------------------------- +dev_root "rm -f $FLAG" +cold_start +read -r SESSION PID <<<"$(wait_agent)" +[ "$SESSION" != "NO_AGENT" ] || fail "no agent connected for $PKG (off phase)" +echo "A. flag off: session=$SESSION pid=$PID" +A_OUT="$(trace "$SESSION")" +echo "A. trace reply: $(echo "$A_OUT" | cut -c1-260)" +echo "$A_OUT" | grep -q 'delivery is off' || fail "flag off must refuse with 'delivery is off', got: $A_OUT" +FDS="$(dev_root "ls -l /proc/$PID/fd" 2>/dev/null)" +echo "$FDS" | grep -q 'libQBDI.so' && fail "flag off still delivered a QBDI fd" +echo "A. PASS (refused, no fd)" + +# --- B. opt-in (on): fd delivered, trace works, library released after --------------------------- +dev_root "mkdir -p /data/adb/adh && touch $FLAG" +cold_start +read -r SESSION PID <<<"$(wait_agent)" +[ "$SESSION" != "NO_AGENT" ] || fail "no agent connected for $PKG (on phase)" +echo "B. flag on: session=$SESSION pid=$PID" +FDS="$(dev_root "ls -l /proc/$PID/fd" 2>/dev/null)" +echo "$FDS" | grep -q 'libQBDI.so' || fail "flag on but no QBDI fd was delivered to pid $PID" +echo "B. delivered: $(echo "$FDS" | grep 'libQBDI.so' | head -n1 | sed 's/^ *//')" +B_OUT="$(trace "$SESSION")" +echo "B. trace reply: $(echo "$B_OUT" | cut -c1-260)" +echo "$B_OUT" | grep -q '"ok":true' || fail "trace failed with the payload enabled: $B_OUT" +RET="$(echo "$B_OUT" | sed -n 's/.*"retval":\([0-9]*\).*/\1/p')" +[ "$RET" = "$PID" ] || fail "libc getpid should return the target pid ($PID), got '$RET'" +MAPS="$(dev_root "cat /proc/$PID/maps" 2>/dev/null)" +echo "$MAPS" | grep -q 'libQBDI' && fail "standalone trace must dlclose the tracer, but it is still mapped" +echo "B. PASS (trace retval=$RET, library released)" + +echo "✅ v129 QBDI delivery PASS (default refused; opt-in delivered, traced, released)" +echo "RESULT:PASS" +exit 0 diff --git a/tools/verify_v130_scope_analyze.sh b/tools/verify_v130_scope_analyze.sh new file mode 100644 index 0000000..6e5a3e2 --- /dev/null +++ b/tools/verify_v130_scope_analyze.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# v130 — scope control + one-call app analysis: component contract (host only). +# +# What this gates: +# - the allowlist merge rules (the C++ companion parses this JSON on a hot path, so a malformed +# package name must never reach the file); +# - the analysis-session pick (main process wins over a companion process); +# - the three new MCP tools exist with the registry shape the client contract requires. +# +# It deliberately does NOT touch the device: writing scope.json and cold-starting an app are product +# actions and are covered by verify_v129/int1 acceptance, not by a daily host gate. +set -uo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/verify_common.sh" +verify_resolve_env_host + +set +e +OUT="$(ADH_SKIP_ARTIFACT_LOAD=1 node --input-type=module - "$ROOT" <<'EOF' +import { pathToFileURL } from 'node:url'; +const root = process.argv[2]; +const src = (p) => pathToFileURL(`${root}/daemon/src/${p}`).href; +const { mergeScope, parseScopePackages } = await import(src('scope_list.ts')); +const { pickAnalysisSession } = await import(src('app_analyze.ts')); +const { MCP_TOOLS } = await import(src('mcp.ts')); + +const chk = []; +const eq = (name, got, want) => chk.push({ name, ok: JSON.stringify(got) === JSON.stringify(want), got }); +eq('merge add/dedupe', mergeScope(['com.a.app'], { add: ['com.b.app', 'com.a.app'] }), ['com.a.app', 'com.b.app']); +eq('remove wins', mergeScope(['com.a.app', 'com.b.app'], { add: ['com.a.app'], remove: ['com.a.app'] }), ['com.b.app']); +eq('junk refused', mergeScope([], { add: ['bad name', 'com..x', 'com.adh.manager', 'com.ok.app'] }), ['com.ok.app']); +eq('parse drops manager', parseScopePackages('{"packages":["com.a.app","com.a.app","com.adh.manager"]}'), ['com.a.app']); +eq('main process wins', pickAnalysisSession([ + { package: 'com.x.app', process: 'com.x.app:push', online: true }, + { package: 'com.x.app', process: 'com.x.app', online: true }, +])?.process, 'com.x.app'); + +for (const name of ['analyze_app', 'scope_list', 'scope_set']) { + const t = MCP_TOOLS.find((x) => x.name === name); + const shape = !!t && t.inputSchema?.type === 'object' && !!t.inputSchema.properties && + typeof t.handler === 'function' && String(t.description || '').length > 40; + chk.push({ name: `tool ${name}`, ok: shape, got: t ? 'present' : 'MISSING' }); +} + +const bad = chk.filter((c) => !c.ok); +for (const c of chk) console.log(` ${c.ok ? 'ok ' : 'FAIL'} ${c.name} -> ${JSON.stringify(c.got)}`); +console.log(`checks ${chk.length - bad.length}/${chk.length}`); +console.log(bad.length ? 'RESULT:FAIL' : 'RESULT:PASS'); +EOF +)" +echo "$OUT" | tail -12 +if echo "$OUT" | grep -q 'RESULT:PASS'; then + echo "✅ v130 scope control + analyze_app contract PASS" + exit 0 +fi +echo "❌ v130 scope control + analyze_app contract FAIL" +exit 1 From 96cf68cdd260422679db74f77adc7b729bf77da4 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:17:12 +0800 Subject: [PATCH 08/24] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E7=A1=AC?= =?UTF-8?q?=E4=BB=B6=E8=A7=82=E5=AF=9F=E5=86=85=E5=AD=98=E5=BF=AB=E7=85=A7?= =?UTF-8?q?=E6=97=B6=E5=BA=8F=E5=B9=B6=E9=9A=94=E7=A6=BB=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E8=A1=A8=E9=97=A8=E7=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/src/MAP.md | 4 ++++ daemon/src/mcp.ts | 2 +- daemon/src/root_watch.ts | 39 ++++++++++++++++++++++++++++++++ daemon/test/root_watch.test.ts | 35 ++++++++++++++++++++++++++++ docs/PROGRESS.md | 10 ++++++++ docs/mcp-tools.md | 4 ++++ tools/MAP.md | 4 ++++ tools/native/root_watch.c | 10 ++++---- tools/verify_v71_mcp_registry.sh | 7 +++++- 9 files changed, 108 insertions(+), 7 deletions(-) diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index d50e0c9..886dbec 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -100,3 +100,7 @@ through the existing daemon and serves the new MCP handler over an isolated HTTP ### backends.ts (module W) Shared injection-backend matrix: `backendMatrix()` (sessions by entry + Zygisk pointers) and `classifySession()` (zygisk / self_load from the agent's maps). Frida Gadget is not advertised. Used by REST `GET /api/backends` and MCP `backends`. + +### root_watch 内存时序 + +`projectRootSample` 优先使用同条 perf 记录的用户栈解析 `mem`,所有指针跳与目标字节均在快照范围内时才标 `snapshotConsistent:true`。其他窗口保留异步进程读数并标 `false`。不能把 collector 处理记录时读到的堆值当作事件时刻状态。回归测试覆盖已经变化的栈、部分栈、堆指针和带偏移的指针链。 diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index ef9d8b2..36508a4 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -118,7 +118,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } throw new Error('unknown trace_session action'); } }, - { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. The callchain arrives as each event chain[]: the runtime caller stack in absolute addresses, which is the fastest way to learn which functions actually run (see analysis_guide(topic=callgraph)). Use chain instead of native_backtrace when the target obfuscates sp, because frame-pointer walking fails there while the kernel unwind still succeeds. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector at the moment of each hit, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. The returned bytes belong to the sampled state instead of to a later re-read. There are no asynchronous heap snapshots. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: N, limit: N, registers: { type: 'boolean' }, stackAddress: S, stackSize: N }, required: ['action'] }, handler: async (a) => { + { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. The callchain arrives as each event chain[]: the runtime caller stack in absolute addresses, which is the fastest way to learn which functions actually run (see analysis_guide(topic=callgraph)). Use chain instead of native_backtrace when the target obfuscates sp, because frame-pointer walking fails there while the kernel unwind still succeeds. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector after the target resumes, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. For mem, source=kernel-stack-sample and snapshotConsistent:true mean every pointer hop and requested byte came from the kernel stack snapshot. Other mem windows are asynchronous process reads (source=process-memory-after-sample, snapshotConsistent:false); never use them as proof of event-time heap or VM state. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: { ...N, minimum: 0, maximum: 2048 }, limit: { ...N, minimum: 1, maximum: 32 }, registers: { type: 'boolean' }, stackAddress: S, stackSize: { ...N, minimum: 0, maximum: 2048 } }, required: ['action'] }, handler: async (a) => { if (a.action === 'prepare') return prepareRootWatch(a.serial); if (a.action === 'start') { const s = sessions.get(String(a.session ?? '')); diff --git a/daemon/src/root_watch.ts b/daemon/src/root_watch.ts index 5c2e0cb..976efd6 100644 --- a/daemon/src/root_watch.ts +++ b/daemon/src/root_watch.ts @@ -171,8 +171,47 @@ export function rootWatchStatus(id: string) { summary: r.summary ?? null, error: r.error, output: r.file, serial: r.serial, pid: r.target.pid, starttimeTicks: r.starttimeTicks, sessionGenerationVerified: r.sessionGenerationVerified }; } +// perf snapshots registers and the user stack in the kernel. In contrast, the +// helper's process_vm_readv happens later, after the target has resumed. Recover +// windows from the kernel stack when every dereference and byte is covered; +// never label an asynchronous heap read as an event-time snapshot. +function projectMemoryWindow(window: any, regs: string[], stack: any) { + const delayed = { ...window, source: 'process-memory-after-sample', snapshotConsistent: false }; + const match = /^(@{0,3})(x(?:[0-9]|[12][0-9]|30)|sp|lr|pc)([+-](?:0x[0-9a-f]+|\d+))?((?:@(?:0x[0-9a-f]+|\d+))*)(?::(0x[0-9a-f]+|\d+))?$/i.exec(window.spec ?? ''); + if (!match || !Array.isArray(regs) || typeof stack?.hex !== 'string') return delayed; + const reg = match[2].toLowerCase(); + const index = reg === 'sp' ? 31 : reg === 'pc' ? 32 : reg === 'lr' ? 30 : Number(reg.slice(1)); + if (typeof regs[index] !== 'string' || !/^0x[0-9a-f]+$/i.test(regs[index])) return delayed; + const bytes = Buffer.from(stack.hex, 'hex'); + const available = Math.min(bytes.length, Number(stack.got) || 0); + const base = BigInt(stack.addr); + const read = (at: bigint, size: number): Buffer | null => { + const offset = at - base; + return offset >= 0n && offset + BigInt(size) <= BigInt(available) + ? bytes.subarray(Number(offset), Number(offset) + size) : null; + }; + const offsetText = match[3]; + const initialOffset = !offsetText ? 0n : (offsetText[0] === '-' ? -1n : 1n) * BigInt(offsetText.slice(1)); + let at = BigInt.asUintN(64, BigInt(regs[index]) + initialOffset); + const hops = match[4] ? match[4].slice(1).split('@').map(value => BigInt(value)) : []; + if (hops.length > match[1].length) return delayed; + for (let i = 0; i < match[1].length; i++) { + const pointer = read(at, 8); + if (!pointer || pointer.readBigUInt64LE() === 0n) return delayed; + at = BigInt.asUintN(64, pointer.readBigUInt64LE() + (hops[i] ?? 0n)); + } + const size = match[5] ? Number(match[5]) : 16; + if (!Number.isSafeInteger(size) || size < 1 || size > 256) return delayed; + const captured = read(at, size); + if (!captured) return delayed; + const { error: _error, ...original } = window; + return { ...original, addr: '0x' + at.toString(16), hex: captured.toString('hex'), + source: 'kernel-stack-sample', snapshotConsistent: true }; +} + export function projectRootSample(record: any, a: Record) { const { regs, stack, ...event } = record; + if (Array.isArray(record.mem)) event.mem = record.mem.map((window: any) => projectMemoryWindow(window, regs, stack)); if (a.registers === true) event.regs = regs; const size = integer(a.stackSize, 0, 0, 2048, 'stackSize'); event.stack = { addr: stack.addr, requested: stack.requested, got: stack.got, short: stack.got < stack.requested }; diff --git a/daemon/test/root_watch.test.ts b/daemon/test/root_watch.test.ts index 274e9c3..50f36ae 100644 --- a/daemon/test/root_watch.test.ts +++ b/daemon/test/root_watch.test.ts @@ -50,3 +50,38 @@ test('kernel stack windows are bounded and cannot silently read another address' assert.throws(() => projectRootSample(record, { stackSize: 2049 })); assert.equal(record.stack.hex, '41424344'); }); + +test('event-time stack bytes replace stale process reads without mutating the raw evidence', () => { + const record = { regs: ['0x1001'], stack: { addr: '0x1000', got: 4, requested: 4, hex: '00656600' }, + mem: [{ spec: 'x0:2', addr: '0x1001', hex: '2020' }] }; + const projected = projectRootSample(record, {}); + assert.deepEqual(projected.mem, [{ spec: 'x0:2', addr: '0x1001', hex: '6566', + source: 'kernel-stack-sample', snapshotConsistent: true }]); + assert.equal(record.mem[0].hex, '2020'); + assert.equal(projected.regs, undefined); +}); + +test('heap reads and partially captured windows remain explicitly asynchronous', () => { + const record = { regs: ['0x2000', '0x1003'], + stack: { addr: '0x1000', got: 4, requested: 16, hex: '00656600' }, + mem: [{ spec: 'x0:1', addr: '0x2000', hex: 'aa' }, { spec: 'x1:2', addr: '0x1003', hex: 'bbcc' }] }; + const { mem } = projectRootSample(record, {}); + assert.deepEqual(mem.map((window: any) => [window.hex, window.source, window.snapshotConsistent]), + [['aa', 'process-memory-after-sample', false], ['bbcc', 'process-memory-after-sample', false]]); +}); + +test('pointer chains use only captured stack pointers and honor hop offsets', () => { + const bytes = Buffer.alloc(48); + bytes.writeBigUInt64LE(0x1008n, 0); + bytes.writeBigUInt64LE(0x1020n, 16); + bytes[32] = 0x61; + const record = { regs: ['0x1000'], + stack: { addr: '0x1000', got: bytes.length, requested: bytes.length, hex: bytes.toString('hex') }, + mem: [{ spec: '@@x0@8:1', addr: '0x9000', error: 'unreadable' }] }; + const projected = projectRootSample(record, {}); + assert.deepEqual(projected.mem[0], { spec: '@@x0@8:1', addr: '0x1020', hex: '61', + source: 'kernel-stack-sample', snapshotConsistent: true }); + bytes.writeBigUInt64LE(0x2000n, 0); + record.stack.hex = bytes.toString('hex'); + assert.equal(projectRootSample(record, {}).mem[0].snapshotConsistent, false); +}); diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 659ae38..9e4e0c0 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4905,3 +4905,13 @@ v0.2–v1.0 的阶段状态与逐轮日志已移至 [`archive/PROGRESS_V0.2_V1.0 ? ???QBDI ????/????????stopReason=ran-away????????????????????????????????????????? ? **??????2026-11-13?**?agent ???????????`agent/src/runtime/mem_read.c` ?? `sigaction`+`SA_SIGINFO` handler?SIGSEGV/SIGBUS??? fault ????`agent/src/trace/qbdi_trace.c` + `commands.c` ?? QBDI ???/??/??????????P2 ??????`SIGUSR2` handler?`SA_SIGINFO`?? `ucontext_t`???????? QBDI VM?`setGPRState` ? ucontext ? pc/sp ????????? ??? agent ???? `trace_hit`?? tid/limit/timebudget??host ? MCP ????????? ?docs/mcp-tools.md ?????????agent ?? 400?600 ? C?host ?? 150?250 ? TS??? sandbox ??? + +## 2026-11-16:root_watch 内存窗口的事件时序修正 + +在用户授权的真实目标分析中,同一次返回值的 55 次字符写入全部出现异步 `mem` 与内核栈字节不符;内核栈字节可逐字节重建返回值。根因已核对:perf 同步保存寄存器与用户栈,collector 收到记录后才调用 `process_vm_readv`/`pread`,目标早已继续执行。此前将这些进程内存读取描述为命中瞬间快照不准确。 + +Host 现在优先从同条 perf 内核栈记录解析内存窗口,且每次指针解引用也必须完全位于该快照;成功时标 `source=kernel-stack-sample`、`snapshotConsistent:true`。其他窗口保留为异步读取并明确标 `snapshotConsistent:false`;原始记录不覆盖。原生 collector 同样标注异步读取来源。MCP 描述改为准确时序,并声明分页上限 32。目标特有数据与运行时地址保留在仓外,本节不复制。验证结果在本轮完成后追加。 + +本轮验证:Host 类型检查通过;完整单测 **464 passed / 0 failed / 0 skipped**;MCP 注册表门禁通过(91 工具 / 0 问题);root collector 构建与专用 root 机硬件自测通过(2 样本、无丢失/限流);仓外真实采样重放 **55/55 个窗口修正后与原始返回值一致**。运行中的 Host 保留现有会话,分析侧直接使用修复后的投影函数处理原始采样,未为热更新而重启 Host。 + +同时修复 v71 注册表门禁的隔离:导入 MCP 会触发 state 的历史捕获保留策略,原版门禁本轮曾报告按 14 天策略裁掉 1000 条旧捕获。现于子进程导入前启用测试存储并清除继承的 ADH_DATA_DIR;带有过期捕获的操作者目录哨兵已验证逐字节保留。历史 events.jsonl 仍在,但事件中缺少完整原始捕获字段,不能声称已恢复被裁记录;未以不完整元数据伪造捕获。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 80ec4c5..5673e74 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -95,3 +95,7 @@ Generated from the live ADH Daemon registry (91 tools). Endpoint: `POST /mcp` (J | `analyze_app` | One call from a package name to a bounded report: adds the package to the phone injection allowlist when needed (reported as scopeAdded), cold starts it, waits for the Zygisk-injected agent, then runs triage (caps / maps size / dex files / capture window / module loads / detection surface) plus optional unpack (dump every DEX) and httpCaptureMs (a TLS traffic window). Use it when the caller knows only the app name, not a session id. Every phase reports ok/error and one failed phase does not discard the others. The target must be an installed third-party app: system packages and the ADH manager are refused. | package, autoScope, forceRestart, captureMs, unpack, httpCaptureMs, timeoutMs, settleMs | | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | — | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set | + +## root_watch 内存窗口时序(2026-11-16) + +`root_watch` 的寄存器、调用链及 `stackWindow` 来自 perf 的内核采样。`mem` 只有在整个窗口及全部指针解引用均被同一内核栈快照覆盖时,才返回 `source: "kernel-stack-sample"`、`snapshotConsistent: true`。其余 `mem` 来自 collector 收到事件后的进程读取,标为 `source: "process-memory-after-sample"`、`snapshotConsistent: false`,不能据此判定某个堆字段在事件时刻的值。`read.limit` 为 1–32;用 `nextSeq`/`hasMore` 分页。 diff --git a/tools/MAP.md b/tools/MAP.md index 31b774b..74704b4 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -193,3 +193,7 @@ event-limit accounting, explicit stop and wrong-TID refusal. It does not run the - `verify_v131_root_watch_mem.sh` ? root_watch ?**??? + ???????**???device?fixture App ??? SKIP???? TID ? 2 ????????? `x0:8` ? `@x0:8`??? 4 ????`bp` ???? 0/1???????????????????? 0x1122? / 0x8877???? `root_watch.test.ts`?3 ????????? spec ????????? + +### root_watch 内存窗口时序补充(2026-11-16) + +`native/root_watch.c` 的 `emit_mem` 在收到 perf 事件后读取目标进程,不是内核事件时刻的堆快照;原始窗口明确标为 `source=process-memory-after-sample`、`snapshotConsistent:false`。同事件内核栈可用时,由 Host `projectRootSample` 恢复确定的栈窗口。自测的固定内存值通过不能证明动态目标的异步窗口同步正确。 diff --git a/tools/native/root_watch.c b/tools/native/root_watch.c index def69f1..00fe7ae 100644 --- a/tools/native/root_watch.c +++ b/tools/native/root_watch.c @@ -2,10 +2,10 @@ // function replay, SELinux change, or in-process agent dependency is involved. // // 2026-11-13: a run may watch up to four hardware slots on the same thread and, on every -// event, snapshot small memory windows derived from the sampled registers. The second part -// is what makes a stateful VM tractable: the kernel record keeps the registers of the hit, -// and the collector reads the fields they point at *at the moment of the hit*, instead of -// leaving the caller to re-read memory after the target has moved on. +// event, read small memory windows derived from the sampled registers. These process reads +// happen AFTER perf delivers the record; the target has already resumed. Only the register +// set and PERF_SAMPLE_STACK_USER are kernel snapshots of the hit. The Host can resolve +// windows wholly covered by that stack snapshot; heap reads are asynchronous evidence. #define _GNU_SOURCE #include #include @@ -194,7 +194,7 @@ static void emit_mem(pid_t pid, const uint64_t *regs) { } unsigned char buf[MAX_MEM_BYTES]; if (!err && read_target(pid, addr, buf, m->len)) err = "unreadable"; - printf("%s{\"spec\":\"%s\",\"addr\":\"0x%llx\"", i ? "," : "", m->text, (unsigned long long)addr); + printf("%s{\"spec\":\"%s\",\"addr\":\"0x%llx\",\"source\":\"process-memory-after-sample\",\"snapshotConsistent\":false", i ? "," : "", m->text, (unsigned long long)addr); if (err) printf(",\"error\":\"%s\"}", err); else { printf(",\"hex\":\""); print_hex(buf, m->len); printf("\"}"); } } diff --git a/tools/verify_v71_mcp_registry.sh b/tools/verify_v71_mcp_registry.sh index d7e0d2d..0877ff7 100644 --- a/tools/verify_v71_mcp_registry.sh +++ b/tools/verify_v71_mcp_registry.sh @@ -17,6 +17,11 @@ verify_resolve_env_host OUT="$(node --input-type=module - "$ROOT" <<'EOF' const [root] = process.argv.slice(2); +// Importing state.ts loads settings and enforces capture retention. A registry +// shape check must never load/prune the operator's real analysis data, including +// when the invoking shell happens to have a production ADH_DATA_DIR configured. +process.env.ADH_SKIP_ARTIFACT_LOAD = '1'; +delete process.env.ADH_DATA_DIR; const url = 'file:///' + String(root).replace(/\\/g, '/').replace(/^\//, '') + '/daemon/src/mcp.ts'; let tools; try { @@ -45,4 +50,4 @@ console.log(problems.length === 0 ? 'RESULT:PASS' : 'RESULT:FAIL'); EOF )" echo "$OUT" -verify_gate "v4.34 MCP registry sanity (import + per-tool shape)" 0 \ No newline at end of file +verify_gate "v4.34 MCP registry sanity (import + per-tool shape)" 0 From 5d85e4dd3a2bb606ed9f822d63370905d5d2840d Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:25:17 +0800 Subject: [PATCH 09/24] =?UTF-8?q?docs:=20=E8=AE=B0=E5=BD=95=E7=A1=AC?= =?UTF-8?q?=E4=BB=B6=E4=BA=8B=E4=BB=B6=E6=8E=92=E5=BA=8F=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E4=B8=8E=E7=AE=97=E6=B3=95=E9=AA=8C=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/src/mcp.ts | 2 +- docs/PROGRESS.md | 6 ++++++ docs/mcp-tools.md | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 36508a4..c6e3392 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -118,7 +118,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h } throw new Error('unknown trace_session action'); } }, - { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. The callchain arrives as each event chain[]: the runtime caller stack in absolute addresses, which is the fastest way to learn which functions actually run (see analysis_guide(topic=callgraph)). Use chain instead of native_backtrace when the target obfuscates sp, because frame-pointer walking fails there while the kernel unwind still succeeds. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector after the target resumes, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. For mem, source=kernel-stack-sample and snapshotConsistent:true mean every pointer hop and requested byte came from the kernel stack snapshot. Other mem windows are asynchronous process reads (source=process-memory-after-sample, snapshotConsistent:false); never use them as proof of event-time heap or VM state. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: { ...N, minimum: 0, maximum: 2048 }, limit: { ...N, minimum: 1, maximum: 32 }, registers: { type: 'boolean' }, stackAddress: S, stackSize: { ...N, minimum: 0, maximum: 2048 } }, required: ['action'] }, handler: async (a) => { + { name: 'root_watch', description: 'To find who writes a known buffer, follow analysis_guide(topic=writer); runtime_diagnostics lists existing thread candidates, which are not automatically the writer. Optional ROOT-SIDE hardware observation, for an existing target thread when app-domain perf is denied. prepare uploads the locally built collector (bash tools/build_root_watch.sh) and runs a deterministic hardware self-test. start needs an explicit session, tid, addr and width (1/2/4/8, aligned); mode w/r/rw watches data, x requires width 4 and watches execution. This uses perf from a separate root process: no ptrace, target patches, function replay or SELinux changes. The KERNEL records pc, x0..x30/sp/pc, callchain and optional user-stack bytes at the event. The callchain arrives as each event chain[]: the runtime caller stack in absolute addresses, which is the fastest way to learn which functions actually run (see analysis_guide(topic=callgraph)). Use chain instead of native_backtrace when the target obfuscates sp, because frame-pointer walking fails there while the kernel unwind still succeeds. Up to 3 extra hardware slots may be watched on the same TID (breakpoints), and up to 4 memory windows (mem) are read by the collector after the target resumes, grammar [@[@[@]]]REG[+/-OFFSET][@HOPOFFSET][@HOPOFFSET][:LEN] with x0..x30/sp/lr/pc; each @ reads the pointer first (up to three levels) and an @HOPOFFSET after a @ is added to that hop pointer before dereferencing it, so @@x12@8:0x40 reads [[x12]+8] - the only way to reach a register file hung off an object field. For mem, source=kernel-stack-sample and snapshotConsistent:true mean every pointer hop and requested byte came from the kernel stack snapshot. Other mem windows are asynchronous process reads (source=process-memory-after-sample, snapshotConsistent:false); never use them as proof of event-time heap or VM state. Scope is ONE EXISTING TID, not future threads or the whole process. durationMs <=30000, maxEvents <=2048, stackBytes <=16384. start returns promptly with an id; status reports running/lost/throttles/complete and stopReason (event-limit is incomplete). read pages by afterSeq/limit, exposes registers only with registers:true, and returns a bounded stack window with stackAddress/stackSize <=2048. Raw records stay under ADH_DATA_DIR/root-watch. Multiple hardware slots use separate perf rings: seq is a pagination cursor in collector-read order, not execution order. Read all pages and sort by timeNs for cross-slot analysis. stop terminates only the collector. Root/SELinux/kernel failures are explicit; hardware watchpoints and execution breakpoints are not guaranteed on every ROM.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['prepare', 'start', 'status', 'read', 'stop'] }, session: S, serial: S, id: S, tid: N, addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] }, breakpoints: { type: 'array', maxItems: 3, items: { type: 'object', properties: { addr: S, width: N, mode: { type: 'string', enum: ['w', 'r', 'rw', 'x'] } }, required: ['addr'] } }, mem: { type: 'array', maxItems: 4, items: { type: 'string' } }, durationMs: N, maxEvents: N, stackBytes: N, afterSeq: { ...N, minimum: 0, maximum: 2048 }, limit: { ...N, minimum: 1, maximum: 32 }, registers: { type: 'boolean' }, stackAddress: S, stackSize: { ...N, minimum: 0, maximum: 2048 } }, required: ['action'] }, handler: async (a) => { if (a.action === 'prepare') return prepareRootWatch(a.serial); if (a.action === 'start') { const s = sessions.get(String(a.session ?? '')); diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 9e4e0c0..9649054 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4915,3 +4915,9 @@ Host 现在优先从同条 perf 内核栈记录解析内存窗口,且每次指 本轮验证:Host 类型检查通过;完整单测 **464 passed / 0 failed / 0 skipped**;MCP 注册表门禁通过(91 工具 / 0 问题);root collector 构建与专用 root 机硬件自测通过(2 样本、无丢失/限流);仓外真实采样重放 **55/55 个窗口修正后与原始返回值一致**。运行中的 Host 保留现有会话,分析侧直接使用修复后的投影函数处理原始采样,未为热更新而重启 Host。 同时修复 v71 注册表门禁的隔离:导入 MCP 会触发 state 的历史捕获保留策略,原版门禁本轮曾报告按 14 天策略裁掉 1000 条旧捕获。现于子进程导入前启用测试存储并清除继承的 ADH_DATA_DIR;带有过期捕获的操作者目录哨兵已验证逐字节保留。历史 events.jsonl 仍在,但事件中缺少完整原始捕获字段,不能声称已恢复被裁记录;未以不完整元数据伪造捕获。 + +## 2026-11-16:用户授权目标的独立算法验收 + +已在当前得物 6.3.0(1162)定位实际 native 入口,完成当前构建的纯 Python 计算路径:加盐 MD5、标准 SM4、显式 nonce 与 nibble 封装。76 条完整原生样本在两个进程逐字节一致,其中 10 条 nonce 来自编码前的内核栈,未由输出反推;覆盖 UTF-8、边界长度和 Android ID 后缀变化,另验空输入行为与标准 SM4 向量。交付实现、合成测试输入和说明保存在用户指定仓外分析工作区,未将目标密钥、转储或请求数据放入本仓。结论限定当前构建与已验证检测位,不承诺其他版本或服务端验证。 + +多槽采样分析还核到另一项语义:原生 collector 逐 perf fd 排空 ring 后分配 seq,跨槽 seq 不是执行顺序。已在 MCP 描述与说明中要求完整分页后按 timeNs 排序;没有更改分页游标含义。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 5673e74..453bcf6 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -99,3 +99,5 @@ Generated from the live ADH Daemon registry (91 tools). Endpoint: `POST /mcp` (J ## root_watch 内存窗口时序(2026-11-16) `root_watch` 的寄存器、调用链及 `stackWindow` 来自 perf 的内核采样。`mem` 只有在整个窗口及全部指针解引用均被同一内核栈快照覆盖时,才返回 `source: "kernel-stack-sample"`、`snapshotConsistent: true`。其余 `mem` 来自 collector 收到事件后的进程读取,标为 `source: "process-memory-after-sample"`、`snapshotConsistent: false`,不能据此判定某个堆字段在事件时刻的值。`read.limit` 为 1–32;用 `nextSeq`/`hasMore` 分页。 + +多硬件槽各有独立 perf ring;`seq` 是 collector 读出顺序的分页游标,不能表示槽之间的执行先后。跨槽分析应读完所有页面,再按 `timeNs` 排序;分页继续使用原 `nextSeq`。 From ca4f92ec99e8ec13fc13fbc7f0a24a5919248d6a Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:37:05 +0800 Subject: [PATCH 10/24] =?UTF-8?q?docs:=20=E8=AE=B0=E5=BD=95=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E7=AD=96=E7=95=A5=E8=A7=A6=E5=8F=91=E5=90=8E=E7=9A=84?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E6=81=A2=E5=A4=8D=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/PROGRESS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 9649054..2cbf003 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4921,3 +4921,9 @@ Host 现在优先从同条 perf 内核栈记录解析内存窗口,且每次指 已在当前得物 6.3.0(1162)定位实际 native 入口,完成当前构建的纯 Python 计算路径:加盐 MD5、标准 SM4、显式 nonce 与 nibble 封装。76 条完整原生样本在两个进程逐字节一致,其中 10 条 nonce 来自编码前的内核栈,未由输出反推;覆盖 UTF-8、边界长度和 Android ID 后缀变化,另验空输入行为与标准 SM4 向量。交付实现、合成测试输入和说明保存在用户指定仓外分析工作区,未将目标密钥、转储或请求数据放入本仓。结论限定当前构建与已验证检测位,不承诺其他版本或服务端验证。 多槽采样分析还核到另一项语义:原生 collector 逐 perf fd 排空 ring 后分配 seq,跨槽 seq 不是执行顺序。已在 MCP 描述与说明中要求完整分页后按 timeNs 排序;没有更改分页游标含义。 + +### 同日保留策略审计与恢复 + +首次默认服务启动期间,历史工件加载数从 41 降到 27,最近缺失的 14 份 DEX 共 166.81 MiB,与过期回收条件对应。已用仓外已有副本恢复全部 14 份;其中 2 份补齐原始零填充后得到完全相同的 SHA-256。逐份重新验证完整 SHA-256、长度和原事件来源元数据,14/14 通过。没有把目标转储纳入版本控制。 + +v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺原始捕获字段,未用元数据伪造原记录;本机无可用卷影副本。隔离修复的操作者目录哨兵验证通过。算法交付包已在独立目录、Python 隔离模式下通过 76 条原生 fixture、标准 SM4 向量、空输入和 CLI 验收。 From c0c976157fa2d986e5418851164cbf86a97d741b Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:59:14 +0800 Subject: [PATCH 11/24] =?UTF-8?q?docs:=20=E6=A2=B3=E7=90=86=20ADH=20?= =?UTF-8?q?=E8=83=BD=E5=8A=9B=E7=8A=B6=E6=80=81=E4=B8=8E=20AI=20=E4=BC=98?= =?UTF-8?q?=E5=85=88=E6=94=B9=E9=80=A0=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/AI_FIRST_CAPABILITY_INVENTORY.json | 4453 +++++++++++++++++++++++ docs/AI_FIRST_REFACTOR_AUDIT.md | 224 ++ docs/DEVELOPMENT_PLAN.md | 1 + docs/PROGRESS.md | 13 + 4 files changed, 4691 insertions(+) create mode 100644 docs/AI_FIRST_CAPABILITY_INVENTORY.json create mode 100644 docs/AI_FIRST_REFACTOR_AUDIT.md diff --git a/docs/AI_FIRST_CAPABILITY_INVENTORY.json b/docs/AI_FIRST_CAPABILITY_INVENTORY.json new file mode 100644 index 0000000..d64fd85 --- /dev/null +++ b/docs/AI_FIRST_CAPABILITY_INVENTORY.json @@ -0,0 +1,4453 @@ +{ + "schemaVersion": 1, + "auditDate": "2026-11-16", + "method": "Static TypeScript AST and source-text inspection only; no ADH module imported and no device/service calls. Endpoint coverage is syntactic, not proof of execution or semantic parity.", + "baseCommit": "ca4f92ec99e8ec13fc13fbc7f0a24a5919248d6a", + "cliCommit": "3cf83996cd8a0221b3248048025870f785cd5852", + "counts": { + "mcp": 91, + "routeEntries": 106, + "uiLiteralFetches": 26, + "publicCliCommands": 7, + "deviceAidlMethods": 15, + "agentAdvertisedOps": 38 + }, + "tools": [ + { + "name": "analysis_guide", + "source": "daemon/src/mcp.ts", + "line": 60, + "properties": [ + "action", + "topic", + "session", + "hookId", + "buffer", + "tid" + ], + "required": [], + "handlerCalls": [ + "analysisGuide", + "assessAnalysis", + "sendCmd" + ], + "directAgentOps": [ + "native_hook" + ], + "group": "guidance" + }, + { + "name": "crypto_evidence", + "source": "daemon/src/mcp.ts", + "line": 68, + "properties": [ + "action", + "observations", + "candidates", + "loss", + "label", + "id", + "offset", + "limit", + "includePayload" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Array.isArray", + "Math.max", + "Object.hasOwn", + "String", + "[a.loss?.note,...unknown].filter", + "[a.loss?.note,...unknown].filter(Boolean).join", + "[a.loss?.storeLoss,...notes].filter", + "[a.loss?.storeLoss,...notes].filter(Boolean).join", + "a.observations.map", + "analyzeCryptoEvidence", + "bytes", + "capStats.get", + "dropCryptoEvidence", + "listCryptoEvidence", + "liveSessions.add", + "notes.push", + "readCryptoEvidence", + "saveCryptoEvidence", + "selectCaptureBytes", + "storeLossNote", + "unknown.push", + "v.map" + ], + "directAgentOps": [], + "group": "evidence" + }, + { + "name": "runtime_diagnostics", + "source": "daemon/src/mcp.ts", + "line": 99, + "properties": [ + "session", + "serial", + "afterTid", + "limit", + "timeoutMs" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "String", + "diagnoseRuntime", + "sessions.get" + ], + "directAgentOps": [], + "group": "diagnostics" + }, + { + "name": "trace_session", + "source": "daemon/src/mcp.ts", + "line": 103, + "properties": [ + "action", + "session", + "id", + "path", + "confirm", + "addr", + "symLib", + "symbol", + "args", + "budget", + "timeMs", + "capacity", + "afterSeq", + "limit", + "pc", + "minPc", + "maxPc", + "mnemonic", + "register", + "beforeSeq", + "maxScan" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "agentCmd", + "assertCallableAddress", + "dropTrace", + "listTraces", + "queryTrace", + "recordTrace", + "sessions.get", + "sliceTrace", + "target.caps?.ops?.includes", + "traceStats" + ], + "directAgentOps": [ + "load_so" + ], + "group": "watch_and_trace" + }, + { + "name": "root_watch", + "source": "daemon/src/mcp.ts", + "line": 121, + "properties": [ + "action", + "session", + "serial", + "id", + "tid", + "addr", + "width", + "mode", + "breakpoints", + "mem", + "durationMs", + "maxEvents", + "stackBytes", + "afterSeq", + "limit", + "registers", + "stackAddress", + "stackSize" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "prepareRootWatch", + "readRootWatch", + "rootWatchStatus", + "sessions.get", + "startRootWatch", + "stopRootWatch" + ], + "directAgentOps": [], + "group": "watch_and_trace" + }, + { + "name": "process_list", + "source": "daemon/src/mcp.ts", + "line": 134, + "properties": [], + "required": [], + "handlerCalls": [ + "sessions.values" + ], + "directAgentOps": [], + "group": "inventory" + }, + { + "name": "backends", + "source": "daemon/src/mcp.ts", + "line": 135, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "backendMatrix", + "classifySession" + ], + "directAgentOps": [], + "group": "inventory" + }, + { + "name": "dumps_list", + "source": "daemon/src/mcp.ts", + "line": 136, + "properties": [], + "required": [], + "handlerCalls": [ + "dumps.values" + ], + "directAgentOps": [], + "group": "artifacts" + }, + { + "name": "compat_probe", + "source": "daemon/src/mcp.ts", + "line": 137, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "compat_probe" + ], + "group": "diagnostics" + }, + { + "name": "jni_onload", + "source": "daemon/src/mcp.ts", + "line": 138, + "properties": [ + "session", + "action", + "module", + "confirm", + "skipOriginal", + "returnValue" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Promise.resolve", + "String", + "agentCmd" + ], + "directAgentOps": [ + "jni_onload" + ], + "group": "jni" + }, + { + "name": "jni_hook", + "source": "daemon/src/mcp.ts", + "line": 139, + "properties": [ + "session", + "action" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "jni_hook" + ], + "group": "jni" + }, + { + "name": "jni_env_hook", + "source": "daemon/src/mcp.ts", + "line": 140, + "properties": [ + "session", + "setValue", + "action", + "function" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "jni_env_hook" + ], + "group": "jni" + }, + { + "name": "javahook_probe", + "source": "daemon/src/mcp.ts", + "line": 141, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "javahook_probe" + ], + "group": "java" + }, + { + "name": "java_hook", + "source": "daemon/src/mcp.ts", + "line": 142, + "properties": [ + "session", + "action", + "hookId", + "className", + "method", + "params", + "skipOriginal", + "returnValue", + "argIndex", + "argValue", + "stack", + "limit" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "java_hook" + ], + "group": "java" + }, + { + "name": "java_enum", + "source": "daemon/src/mcp.ts", + "line": 143, + "properties": [ + "session", + "className" + ], + "required": [ + "className" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "java_enum" + ], + "group": "java" + }, + { + "name": "java_call", + "source": "daemon/src/mcp.ts", + "line": 144, + "properties": [ + "session", + "className", + "method", + "params", + "field", + "args", + "detach" + ], + "required": [ + "className", + "method" + ], + "handlerCalls": [ + "JSON.stringify", + "agentCmd", + "ops.includes", + "pickSid", + "sessions.get" + ], + "directAgentOps": [ + "java_call" + ], + "group": "java" + }, + { + "name": "java_call_result", + "source": "daemon/src/mcp.ts", + "line": 145, + "properties": [ + "session", + "callId", + "waitMs" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "Date.now", + "Math.max", + "Math.min", + "Number", + "agentCmd", + "pickSid", + "setTimeout" + ], + "directAgentOps": [ + "java_call_result" + ], + "group": "java" + }, + { + "name": "hw_watch", + "source": "daemon/src/mcp.ts", + "line": 146, + "properties": [ + "session", + "action", + "addr", + "len", + "mode", + "slot", + "hookId", + "spec" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "Number", + "agentCmd" + ], + "directAgentOps": [ + "hw_watch" + ], + "group": "watch_and_trace" + }, + { + "name": "native_hook", + "source": "daemon/src/mcp.ts", + "line": 147, + "properties": [ + "session", + "action", + "hookId", + "mode", + "module", + "symbol", + "addr", + "skipOriginal", + "returnValue", + "argIndex", + "argValue", + "confirm", + "hard", + "sites", + "scope", + "slotsWritable", + "backtrace", + "throttleMs", + "maxEvents", + "sampleEvery", + "tid", + "returnAddress", + "mem", + "memAfter", + "filter", + "writeReg", + "writeOff", + "writeHex", + "errno", + "traceInsns", + "traceFrom", + "traceWatch" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "/^[0-9a-fA-F]+$/.test", + "/^x([0-8])(?:\\+(\\d{1,5}))?:(\\d{1,4})$/.exec", + "/^x([0-8])\\s*=\\s*(0x[0-9a-fA-F]+|[0-9]+)$/.exec", + "BigInt", + "BigInt(m[2]).toString", + "Math.max", + "Math.trunc", + "Number", + "Number.isFinite", + "Number.isInteger", + "String", + "String((a as any).filter).trim", + "String(a.memAfter).trim", + "agentCmd", + "assertCallableAddress", + "classifyAddress", + "cls.path.split", + "cls.path.split('/').pop", + "ensureNativeObservationSupport", + "nativeTracePayload", + "normalizeThrottleMs", + "parseMemWindows", + "pickSid", + "sendCmd" + ], + "directAgentOps": [ + "maps", + "native_hook" + ], + "group": "native_runtime" + }, + { + "name": "recipe", + "source": "daemon/src/mcp.ts", + "line": 251, + "properties": [ + "session", + "action", + "name", + "options" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "listRecipes", + "runRecipe" + ], + "directAgentOps": [], + "group": "host_control" + }, + { + "name": "module_watch", + "source": "daemon/src/mcp.ts", + "line": 255, + "properties": [ + "session", + "action", + "limit" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Number", + "agentCmd", + "moduleLoads", + "pickSid" + ], + "directAgentOps": [ + "module_watch" + ], + "group": "module" + }, + { + "name": "memory_write", + "source": "daemon/src/mcp.ts", + "line": 264, + "properties": [ + "session", + "addr", + "hex", + "force" + ], + "required": [ + "addr", + "hex" + ], + "handlerCalls": [ + "pickSid", + "writeMem" + ], + "directAgentOps": [], + "group": "memory" + }, + { + "name": "memory_restore", + "source": "daemon/src/mcp.ts", + "line": 265, + "properties": [ + "session", + "addr" + ], + "required": [], + "handlerCalls": [ + "listWriteUndo", + "pickSid", + "restoreMem" + ], + "directAgentOps": [], + "group": "memory" + }, + { + "name": "capabilities", + "source": "daemon/src/mcp.ts", + "line": 266, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "autoAntiDebugEnabled", + "pickSid", + "sessions.get" + ], + "directAgentOps": [], + "group": "inventory" + }, + { + "name": "settings", + "source": "daemon/src/mcp.ts", + "line": 267, + "properties": [ + "action", + "patch" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "autoAntiDebugEnabled", + "mergeSettings", + "saveSettings" + ], + "directAgentOps": [], + "group": "host_control" + }, + { + "name": "native_look", + "source": "daemon/src/mcp.ts", + "line": 274, + "properties": [ + "session", + "action", + "hookId", + "seq", + "beforeSeq", + "limit", + "mode", + "module", + "symbol", + "addr", + "confirm", + "mem", + "backtrace", + "hard", + "maxEvents", + "sampleEvery", + "tid", + "returnAddress", + "traceInsns", + "traceFrom", + "traceWatch" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Number", + "String", + "assertCallableAddress", + "nativeLookArm", + "nativeLookRead", + "nativeLookStop", + "pickSid" + ], + "directAgentOps": [], + "group": "native_runtime" + }, + { + "name": "syscall_digest", + "source": "daemon/src/mcp.ts", + "line": 291, + "properties": [ + "session", + "hookIds", + "expected", + "sinceMs", + "limit", + "maxGroups", + "decode", + "decodeLimit" + ], + "required": [], + "handlerCalls": [ + "pickSid", + "syscallDigest" + ], + "directAgentOps": [], + "group": "watch_and_trace" + }, + { + "name": "java_trace", + "source": "daemon/src/mcp.ts", + "line": 292, + "properties": [ + "session", + "action", + "className", + "method", + "params", + "limit", + "stack", + "hookIds", + "sinceCaptureId", + "maxTimeline", + "maxMethods", + "maxCallers" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "javaTraceDigest", + "javaTraceStart", + "javaTraceStop", + "pickSid" + ], + "directAgentOps": [], + "group": "java" + }, + { + "name": "native_hook_all", + "source": "daemon/src/mcp.ts", + "line": 293, + "properties": [ + "session", + "action", + "module", + "prefix", + "contains", + "exact", + "exclude", + "limit", + "backtrace", + "throttleMs", + "maxEvents", + "sampleEvery", + "tid", + "returnAddress", + "skipOriginal", + "returnValue", + "argIndex", + "argValue", + "hookIds", + "confirm" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "nativeHookAll", + "nativeUnhookAll", + "pickSid" + ], + "directAgentOps": [], + "group": "native_runtime" + }, + { + "name": "syscall_trace", + "source": "daemon/src/mcp.ts", + "line": 294, + "properties": [ + "session", + "action", + "module", + "syscalls", + "limit", + "throttleMs", + "hookIds", + "expected", + "sinceMs", + "decode", + "decodeLimit", + "maxGroups" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "String", + "pickSid", + "syscallTraceDigest", + "syscallTraceStart", + "syscallTraceStop" + ], + "directAgentOps": [], + "group": "watch_and_trace" + }, + { + "name": "trace_digest", + "source": "daemon/src/mcp.ts", + "line": 295, + "properties": [ + "session", + "symLib", + "symbol", + "addr", + "args" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "String", + "pickSid", + "traceDigest" + ], + "directAgentOps": [], + "group": "watch_and_trace" + }, + { + "name": "native_backtrace", + "source": "daemon/src/mcp.ts", + "line": 296, + "properties": [ + "session", + "hookId", + "fp", + "lr", + "maxFrames" + ], + "required": [], + "handlerCalls": [ + "nativeBacktrace", + "pickSid" + ], + "directAgentOps": [], + "group": "native_runtime" + }, + { + "name": "native_symbols", + "source": "daemon/src/mcp.ts", + "line": 297, + "properties": [ + "session", + "module", + "kind", + "contains", + "limit", + "offset" + ], + "required": [ + "module" + ], + "handlerCalls": [ + "String", + "moduleSymbols", + "pickSid" + ], + "directAgentOps": [], + "group": "native_runtime" + }, + { + "name": "native_call", + "source": "daemon/src/mcp.ts", + "line": 298, + "properties": [ + "session", + "module", + "symbol", + "addr", + "args", + "confirm" + ], + "required": [], + "handlerCalls": [ + "(a.args ?? []).map", + "(a.args ?? []).map((v: any) => String(v)).join", + "String", + "agentCmd", + "assertCallableAddress", + "pickSid" + ], + "directAgentOps": [ + "native_call" + ], + "group": "native_runtime" + }, + { + "name": "stealth", + "source": "daemon/src/mcp.ts", + "line": 308, + "properties": [ + "session", + "action", + "confirm" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Promise.resolve", + "String", + "agentCmd" + ], + "directAgentOps": [ + "stealth" + ], + "group": "native_runtime" + }, + { + "name": "syscall_watch", + "source": "daemon/src/mcp.ts", + "line": 309, + "properties": [ + "session", + "module", + "limit", + "throttleMs", + "syscalls" + ], + "required": [ + "module" + ], + "handlerCalls": [ + "pickSid", + "watchSyscalls" + ], + "directAgentOps": [], + "group": "watch_and_trace" + }, + { + "name": "got_enum", + "source": "daemon/src/mcp.ts", + "line": 310, + "properties": [ + "session", + "module", + "filter" + ], + "required": [ + "module" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "got_enum" + ], + "group": "native_runtime" + }, + { + "name": "memory_maps", + "source": "daemon/src/mcp.ts", + "line": 311, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "maps" + ], + "group": "memory" + }, + { + "name": "maps_query", + "source": "daemon/src/mcp.ts", + "line": 312, + "properties": [ + "session", + "path", + "perm", + "exec", + "anon", + "minSize", + "maxSize", + "limit", + "addr" + ], + "required": [], + "handlerCalls": [ + "Array.isArray", + "Number", + "String", + "agentCmd", + "pickSid", + "queryMaps" + ], + "directAgentOps": [ + "maps" + ], + "group": "memory" + }, + { + "name": "mem_backend", + "source": "daemon/src/mcp.ts", + "line": 313, + "properties": [ + "session", + "backend" + ], + "required": [ + "backend" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "mem_backend" + ], + "group": "memory" + }, + { + "name": "memory_read", + "source": "daemon/src/mcp.ts", + "line": 314, + "properties": [ + "session", + "addr", + "size", + "via" + ], + "required": [ + "addr", + "size" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "read" + ], + "group": "memory" + }, + { + "name": "memory_disasm", + "source": "daemon/src/mcp.ts", + "line": 315, + "properties": [ + "session", + "addr", + "size", + "module", + "offset" + ], + "required": [], + "handlerCalls": [ + "liveDisasm", + "pickSid" + ], + "directAgentOps": [], + "group": "memory" + }, + { + "name": "memory_search", + "source": "daemon/src/mcp.ts", + "line": 316, + "properties": [ + "session", + "hex", + "text", + "limit", + "minAddr", + "maxAddr" + ], + "required": [], + "handlerCalls": [ + "Buffer.from", + "Buffer.from(String(a.text ?? ''), 'utf8').toString", + "String", + "agentCmd" + ], + "directAgentOps": [ + "search" + ], + "group": "memory" + }, + { + "name": "memory_scan_magic", + "source": "daemon/src/mcp.ts", + "line": 317, + "properties": [ + "session", + "minAddr", + "maxAddr" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "scan_magic" + ], + "group": "memory" + }, + { + "name": "art_dexfiles", + "source": "daemon/src/mcp.ts", + "line": 318, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "art_dexfiles" + ], + "group": "dex_analysis" + }, + { + "name": "capture_start", + "source": "daemon/src/mcp.ts", + "line": 319, + "properties": [ + "session", + "cryptoModule", + "fileModule", + "sysModule", + "force" + ], + "required": [], + "handlerCalls": [ + "pickSid", + "setCapture" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "capture_stop", + "source": "daemon/src/mcp.ts", + "line": 320, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "pickSid", + "setCapture" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "file_probe", + "source": "daemon/src/mcp.ts", + "line": 321, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "file_probe" + ], + "group": "capture_and_network" + }, + { + "name": "object_inspect", + "source": "daemon/src/mcp.ts", + "line": 322, + "properties": [ + "session", + "className", + "field" + ], + "required": [ + "className", + "field" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "object_inspect" + ], + "group": "objects" + }, + { + "name": "dex_search", + "source": "daemon/src/mcp.ts", + "line": 323, + "properties": [ + "b64", + "sha", + "query", + "kinds" + ], + "required": [ + "query" + ], + "handlerCalls": [ + "dumpBuf", + "parseDex", + "searchDex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_index", + "source": "daemon/src/mcp.ts", + "line": 324, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "dumpBuf", + "ensureDexIndex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_index_search", + "source": "daemon/src/mcp.ts", + "line": 325, + "properties": [ + "sha", + "query", + "limit" + ], + "required": [ + "sha", + "query" + ], + "handlerCalls": [ + "String", + "searchDexIndex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_reflections", + "source": "daemon/src/mcp.ts", + "line": 326, + "properties": [ + "sha", + "limit" + ], + "required": [ + "sha" + ], + "handlerCalls": [ + "String", + "listDexReflections" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_xref", + "source": "daemon/src/mcp.ts", + "line": 327, + "properties": [ + "b64", + "sha", + "method" + ], + "required": [ + "method" + ], + "handlerCalls": [ + "String", + "String(a.method).toLowerCase", + "c.toLowerCase", + "c.toLowerCase().includes", + "cs.slice", + "dumpBuf", + "invokeXref", + "parseDex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_crypto_scan", + "source": "daemon/src/mcp.ts", + "line": 328, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "cryptoScan", + "dumpBuf", + "parseDex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "native_xref", + "source": "daemon/src/mcp.ts", + "line": 329, + "properties": [ + "b64", + "sha", + "offset", + "window" + ], + "required": [ + "offset" + ], + "handlerCalls": [ + "Number", + "Number.isFinite", + "Number.parseInt", + "String", + "String(a.offset).replace", + "dumpBuf", + "dv.getUint32", + "elfSegments", + "findReferences", + "r.site.toString", + "r.value.toString", + "refs.map", + "s.fileOffset.toString", + "s.fileSize.toString", + "s.vaddr.toString", + "segs.find", + "segs.map", + "segs.some", + "target.toString" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "native_disasm", + "source": "daemon/src/mcp.ts", + "line": 330, + "properties": [ + "b64", + "sha", + "symbol" + ], + "required": [ + "symbol" + ], + "handlerCalls": [ + "Date.now", + "disasmSo", + "dumpBuf", + "join", + "tmpdir", + "unlinkSync", + "writeFileSync" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "native_analyze", + "source": "daemon/src/mcp.ts", + "line": 331, + "properties": [ + "b64", + "sha", + "maxStrings", + "stringsOffset", + "minLen", + "maxStringChars" + ], + "required": [], + "handlerCalls": [ + "Date.now", + "analyzeSo", + "dumpBuf", + "join", + "tmpdir", + "unlinkSync", + "writeFileSync" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "native_crypto_const", + "source": "daemon/src/mcp.ts", + "line": 332, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "cryptoConstScan", + "dumpBuf" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "crypto_variant_scan", + "source": "daemon/src/mcp.ts", + "line": 333, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "dumpBuf", + "scanCryptoVariants" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "native_syscall_scan", + "source": "daemon/src/mcp.ts", + "line": 334, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "BigInt", + "Number", + "attributeSite", + "dumpBuf", + "hits.filter", + "scan.hits.map", + "svcScan", + "syscallName" + ], + "directAgentOps": [], + "group": "native_analysis" + }, + { + "name": "memory_dump", + "source": "daemon/src/mcp.ts", + "line": 335, + "properties": [ + "session", + "addr", + "size" + ], + "required": [ + "addr", + "size" + ], + "handlerCalls": [ + "Number", + "String", + "String(a.addr).replace", + "dumpRegion", + "pickSid" + ], + "directAgentOps": [], + "group": "artifacts" + }, + { + "name": "http_exchanges", + "source": "daemon/src/mcp.ts", + "line": 336, + "properties": [ + "session", + "package" + ], + "required": [], + "handlerCalls": [ + "String", + "assembleHttpExchanges", + "capturePackage", + "captures.filter", + "list.filter", + "list.map", + "pickSid" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "flow_correlate", + "source": "daemon/src/mcp.ts", + "line": 343, + "properties": [ + "session", + "sinceMs", + "sinceCaptureId", + "maxPairs" + ], + "required": [], + "handlerCalls": [ + "flowCorrelate", + "pickSid" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "object_set", + "source": "daemon/src/mcp.ts", + "line": 344, + "properties": [ + "session", + "className", + "field", + "targetField", + "value" + ], + "required": [ + "session", + "className", + "field", + "targetField", + "value" + ], + "handlerCalls": [ + "String", + "agentCmd" + ], + "directAgentOps": [ + "object_set" + ], + "group": "objects" + }, + { + "name": "jni_field_digest", + "source": "daemon/src/mcp.ts", + "line": 345, + "properties": [ + "session", + "sinceMs", + "limit", + "maxGroups" + ], + "required": [], + "handlerCalls": [ + "jniFieldDigest", + "pickSid" + ], + "directAgentOps": [], + "group": "jni" + }, + { + "name": "object_invoke", + "source": "daemon/src/mcp.ts", + "line": 346, + "properties": [ + "session", + "className", + "field", + "method" + ], + "required": [ + "className", + "field", + "method" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "object_invoke" + ], + "group": "objects" + }, + { + "name": "dex_method_code", + "source": "daemon/src/mcp.ts", + "line": 347, + "properties": [ + "b64", + "sha", + "class", + "method", + "disasm", + "maxInsns" + ], + "required": [ + "class" + ], + "handlerCalls": [ + "String", + "disassembleDex", + "dumpBuf", + "extractMethodCode", + "parseDex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dex_repair", + "source": "daemon/src/mcp.ts", + "line": 348, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "dumpBuf", + "persistArtifact", + "repairDexHeader" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "crypto_identify", + "source": "daemon/src/mcp.ts", + "line": 350, + "properties": [], + "required": [], + "handlerCalls": [ + "cryptoIdentify" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "detect_summary", + "source": "daemon/src/mcp.ts", + "line": 351, + "properties": [ + "session", + "package" + ], + "required": [], + "handlerCalls": [ + "detectionReport" + ], + "directAgentOps": [], + "group": "detection" + }, + { + "name": "detect_modules", + "source": "daemon/src/mcp.ts", + "line": 352, + "properties": [ + "session", + "package" + ], + "required": [ + "package" + ], + "handlerCalls": [ + "String", + "pickSid", + "planDetectModules" + ], + "directAgentOps": [], + "group": "detection" + }, + { + "name": "detect_java", + "source": "daemon/src/mcp.ts", + "line": 353, + "properties": [ + "session", + "confirm", + "families" + ], + "required": [], + "handlerCalls": [ + "Array.isArray", + "String", + "String(a.families ?? '').split", + "String(a.families ?? '').split(',').map", + "String(a.families ?? '').split(',').map((s: string) => s.trim()).filter", + "armDetectJava", + "detectJavaPlan", + "pickSid", + "s.trim" + ], + "directAgentOps": [], + "group": "detection" + }, + { + "name": "live_captures", + "source": "daemon/src/mcp.ts", + "line": 354, + "properties": [ + "limit", + "category", + "session", + "package", + "since", + "hookId", + "includeText", + "encoding" + ], + "required": [], + "handlerCalls": [ + "Number", + "String", + "all.filter", + "asciiOf", + "asciiOf(c.hex).slice", + "b64Of", + "c.hex.slice", + "filterLiveCaptures", + "list.slice", + "list.slice(-(Number(a.limit) || 50)).map", + "pickSid" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "capture_detail", + "source": "daemon/src/mcp.ts", + "line": 355, + "properties": [ + "id" + ], + "required": [ + "id" + ], + "handlerCalls": [ + "Buffer.from", + "Buffer.from(c.hex, 'hex').toString", + "Number", + "captures.find" + ], + "directAgentOps": [], + "group": "capture_and_network" + }, + { + "name": "dex_coverage", + "source": "daemon/src/mcp.ts", + "line": 357, + "properties": [ + "b64", + "sha" + ], + "required": [], + "handlerCalls": [ + "analyzeCoverage", + "dumpBuf", + "parseDex" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "dump_all_dex", + "source": "daemon/src/mcp.ts", + "line": 358, + "properties": [ + "session" + ], + "required": [], + "handlerCalls": [ + "dumpAllDex", + "pickSid" + ], + "directAgentOps": [], + "group": "artifacts" + }, + { + "name": "unpack_package", + "source": "daemon/src/mcp.ts", + "line": 359, + "properties": [ + "package", + "session", + "launch", + "forceRestart" + ], + "required": [], + "handlerCalls": [ + "runUnpackBundle" + ], + "directAgentOps": [], + "group": "artifacts" + }, + { + "name": "dex_recover", + "source": "daemon/src/mcp.ts", + "line": 360, + "properties": [ + "baseB64", + "baseSha", + "restoredB64", + "restoredSha" + ], + "required": [], + "handlerCalls": [ + "Date.now", + "createHash", + "createHash('sha256').update", + "createHash('sha256').update(rb.dex).digest", + "dumpBuf", + "existsSync", + "join", + "outSha.slice", + "parseDex", + "rebuildStandardDex", + "recoverFromSnapshots", + "rememberDump", + "writeFileSync" + ], + "directAgentOps": [], + "group": "dex_analysis" + }, + { + "name": "trigger", + "source": "daemon/src/mcp.ts", + "line": 362, + "properties": [ + "session", + "class", + "method", + "level" + ], + "required": [ + "class" + ], + "handlerCalls": [ + "Number", + "agentCmd" + ], + "directAgentOps": [ + "trigger" + ], + "group": "active_trigger" + }, + { + "name": "qbdi_trace", + "source": "daemon/src/mcp.ts", + "line": 363, + "properties": [ + "session", + "symLib", + "symbol", + "addr", + "args" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "(a.args ?? []).map", + "(a.args ?? []).map((v: any) => String(v)).join", + "String", + "agentCmd" + ], + "directAgentOps": [ + "qbdi_trace" + ], + "group": "watch_and_trace" + }, + { + "name": "agent_ping", + "source": "daemon/src/mcp.ts", + "line": 364, + "properties": [ + "session" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "agentPing", + "pickSid" + ], + "directAgentOps": [], + "group": "diagnostics" + }, + { + "name": "engine_selftest", + "source": "daemon/src/mcp.ts", + "line": 365, + "properties": [ + "session" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "hookEngineSelftest", + "pickSid" + ], + "directAgentOps": [], + "group": "diagnostics" + }, + { + "name": "protocol_selftest", + "source": "daemon/src/mcp.ts", + "line": 366, + "properties": [ + "session", + "kb" + ], + "required": [ + "session" + ], + "handlerCalls": [ + "pickSid", + "protocolSelfTest" + ], + "directAgentOps": [], + "group": "diagnostics" + }, + { + "name": "fs_list", + "source": "daemon/src/mcp.ts", + "line": 367, + "properties": [ + "session", + "path" + ], + "required": [ + "session", + "path" + ], + "handlerCalls": [ + "String", + "listDeviceDir", + "pickSid" + ], + "directAgentOps": [], + "group": "filesystem" + }, + { + "name": "fs_read", + "source": "daemon/src/mcp.ts", + "line": 368, + "properties": [ + "session", + "path", + "includeBase64", + "includeText", + "previewBytes" + ], + "required": [ + "session", + "path" + ], + "handlerCalls": [ + "String", + "pickSid", + "readDeviceFile" + ], + "directAgentOps": [], + "group": "filesystem" + }, + { + "name": "load_library", + "source": "daemon/src/mcp.ts", + "line": 369, + "properties": [ + "session", + "path", + "symbol" + ], + "required": [ + "path" + ], + "handlerCalls": [ + "agentCmd" + ], + "directAgentOps": [ + "load_so" + ], + "group": "module" + }, + { + "name": "oracle", + "source": "daemon/src/mcp.ts", + "line": 370, + "properties": [ + "session", + "action", + "id", + "className", + "method", + "params", + "field", + "args", + "extract", + "patches", + "variants", + "repeat", + "timeoutMs" + ], + "required": [ + "action" + ], + "handlerCalls": [ + "Array.isArray", + "Number", + "String", + "dropOracle", + "listOracles", + "oracleDiff", + "oracleRecord", + "oracleReplay", + "oracleStability", + "pickSid" + ], + "directAgentOps": [], + "group": "evidence" + }, + { + "name": "analyze_app", + "source": "daemon/src/mcp.ts", + "line": 394, + "properties": [ + "package", + "autoScope", + "forceRestart", + "captureMs", + "unpack", + "httpCaptureMs", + "timeoutMs", + "settleMs" + ], + "required": [ + "package" + ], + "handlerCalls": [ + "Number", + "String", + "analyzePackage" + ], + "directAgentOps": [], + "group": "scope_and_launch" + }, + { + "name": "scope_list", + "source": "daemon/src/mcp.ts", + "line": 395, + "properties": [], + "required": [], + "handlerCalls": [ + "readScopeFile" + ], + "directAgentOps": [], + "group": "scope_and_launch" + }, + { + "name": "scope_set", + "source": "daemon/src/mcp.ts", + "line": 396, + "properties": [ + "add", + "remove", + "set" + ], + "required": [], + "handlerCalls": [ + "Array.isArray", + "before.filter", + "before.includes", + "mergeScope", + "readScopeFile", + "w.packages.filter", + "w.packages.includes", + "writeScopePackages" + ], + "directAgentOps": [], + "group": "scope_and_launch" + } + ], + "routes": [ + { + "path": "/api/apps", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 38, + "handlerCalls": [ + "listCaptureArmProtected", + "scopedApps", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/scope", + "method": "GET", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 48, + "handlerCalls": [ + "readScopeFile", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/scope", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 52, + "handlerCalls": [ + "Array.isArray", + "JSON.parse", + "before.filter", + "before.includes", + "mergeScope", + "readBody", + "readScopeFile", + "send", + "w.packages.filter", + "w.packages.includes", + "writeScopePackages" + ], + "directAgentOps": [] + }, + { + "path": "/api/analyze-app", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 71, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "String(body.package ?? '').trim", + "analyzePackage", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/health", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 89, + "handlerCalls": [ + "[...sessions.values()].map", + "process.uptime", + "send", + "sessions.values", + "webUrls" + ], + "directAgentOps": [] + }, + { + "path": "/mcp", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 98, + "handlerCalls": [ + "handleMcp", + "readBody" + ], + "directAgentOps": [] + }, + { + "path": "/wechat-follow.png", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 99, + "handlerCalls": [ + "servePublic" + ], + "directAgentOps": [] + }, + { + "path": "/raven.svg", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 100, + "handlerCalls": [ + "servePublic" + ], + "directAgentOps": [] + }, + { + "path": "/raven.png", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 101, + "handlerCalls": [ + "servePublic" + ], + "directAgentOps": [] + }, + { + "path": "/favicon.ico", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 102, + "handlerCalls": [ + "servePublic" + ], + "directAgentOps": [] + }, + { + "path": "/api/http/exchanges", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 104, + "handlerCalls": [ + "assembleHttpExchanges", + "capturePackage", + "captures.filter", + "list.filter", + "list.map", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/captures", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 117, + "handlerCalls": [ + "Math.min", + "Number", + "captureHealth", + "capturePackage", + "captures.filter", + "cryptoView", + "list.filter", + "list.slice", + "list.slice(-limit).map", + "previewForCapture", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/captures/", + "method": "*", + "prefix": true, + "source": "daemon/src/http/routes_system.ts", + "line": 143, + "handlerCalls": [ + "Buffer.from", + "Buffer.from(c.hex, 'hex').toString", + "Number", + "captures.find", + "cryptoView", + "hexToPreview", + "send", + "url.pathname.slice" + ], + "directAgentOps": [] + }, + { + "path": "/api/events", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 153, + "handlerCalls": [ + "Math.min", + "Number", + "eventPackage", + "events.filter", + "list.filter", + "list.slice", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/export/report", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 163, + "handlerCalls": [ + "[...dumps.values()].map", + "[...sessions.values()].map", + "dumps.values", + "new Date().toISOString", + "process.uptime", + "send", + "sessions.values" + ], + "directAgentOps": [] + }, + { + "path": "/api/config", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 171, + "handlerCalls": [ + "JSON.parse", + "applyCaptureEnabled", + "applyCaptureEnabled().catch", + "applyCaptureRetainCap", + "configStats", + "log", + "mergeSettings", + "readBody", + "saveSettings", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/settings/export", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 184, + "handlerCalls": [ + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/settings/import", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 185, + "handlerCalls": [ + "Array.isArray", + "JSON.parse", + "applyCaptureEnabled", + "applyCaptureEnabled().catch", + "applyCaptureRetainCap", + "log", + "mergeSettings", + "readBody", + "saveSettings", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/captures/packages", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 197, + "handlerCalls": [ + "packageCaptureDiskStats", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/captures/export", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 198, + "handlerCalls": [ + "String", + "exportPackageCapturesJsonl", + "pkg.replace", + "res.end", + "res.writeHead", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/data/clear", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 209, + "handlerCalls": [ + "JSON.parse", + "String", + "String(body.package || '').trim", + "[...dumps.values()].filter", + "broadcast", + "clearCaptureStore", + "clearPackageCaptureStore", + "configStats", + "dumps.delete", + "dumps.values", + "errors.join", + "errors.push", + "existsSync", + "log", + "readBody", + "send", + "unlinkSync", + "writeFileSync" + ], + "directAgentOps": [] + }, + { + "path": "/api/mcp/doc", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 234, + "handlerCalls": [ + "MCP_TOOLS.map", + "Object.keys", + "Object.keys(t.inputSchema.properties ?? {}).join", + "String", + "String(value ?? '—').replaceAll", + "String(value ?? '—').replaceAll('|', '\\\\|').replace", + "['# ADH MCP Tools', '', `Generated from the live ADH Daemon registry (${MCP_TOOLS.length} tools). Endpoint: \\`POST /mcp\\` (JSON-RPC 2.0).`, '',\n '| Tool | Description | Args |', '|---|---|---|',\n ...MCP_TOOLS.map(t => `| \\`${t.name}\\` | ${cell(t.description)} | ${cell(Object.keys(t.inputSchema.properties ?? {}).join(', ') || '—')} |`), ''].join", + "cell", + "res.end", + "res.writeHead" + ], + "directAgentOps": [] + }, + { + "path": "/api/crypto/identify", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 241, + "handlerCalls": [ + "cryptoIdentify", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/detect/summary", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 242, + "handlerCalls": [ + "detectionReport", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/mcp/config", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 246, + "handlerCalls": [ + "baseFromHost", + "isValidPackage", + "mcpOnboarding", + "send", + "url.searchParams.get", + "webUrls" + ], + "directAgentOps": [] + }, + { + "path": "/api/agents", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 255, + "handlerCalls": [ + "send", + "sessions.values" + ], + "directAgentOps": [] + }, + { + "path": "/api/backends", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_system.ts", + "line": 256, + "handlerCalls": [ + "backendMatrix", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/agents/", + "method": "*", + "prefix": true, + "source": "daemon/src/http/routes_system.ts", + "line": 257, + "handlerCalls": [ + "send", + "sessions.get", + "url.pathname.split" + ], + "directAgentOps": [] + }, + { + "path": "/api/debug/frame_echo", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 36, + "handlerCalls": [ + "Math.max", + "Math.min", + "Number", + "pickSid", + "protocolSelfTest", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/agent/ping", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 47, + "handlerCalls": [ + "agentPing", + "pickSid", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/process/maps", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 53, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "sessions.get", + "url.searchParams.get" + ], + "directAgentOps": [ + "maps" + ] + }, + { + "path": "/api/java/probe", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 62, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "javahook_probe" + ] + }, + { + "path": "/api/java/call", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 68, + "handlerCalls": [ + "JSON.parse", + "JSON.stringify", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "java_call" + ] + }, + { + "path": "/api/native/got_enum", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 79, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "got_enum" + ] + }, + { + "path": "/api/native/hook", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 86, + "handlerCalls": [ + "JSON.parse", + "Number", + "assertCallableAddress", + "ensureNativeObservationSupport", + "parseMemSpec", + "parseThrottleMs", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "native_hook" + ] + }, + { + "path": "/api/native/call", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 127, + "handlerCalls": [ + "Array.isArray", + "JSON.parse", + "String", + "args.map", + "args.map((v: any) => String(v)).join", + "assertCallableAddress", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "native_call" + ] + }, + { + "path": "/api/native/stealth", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 145, + "handlerCalls": [ + "JSON.parse", + "String", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "stealth" + ] + }, + { + "path": "/api/syscall/trace", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 160, + "handlerCalls": [ + "JSON.parse", + "parseThrottleMs", + "pickSid", + "readBody", + "send", + "syscallTraceDigest", + "syscallTraceStart", + "syscallTraceStop" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/hook_all", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 176, + "handlerCalls": [ + "JSON.parse", + "nativeHookAll", + "nativeObservationPayload", + "nativeUnhookAll", + "parseThrottleMs", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/java/trace", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 192, + "handlerCalls": [ + "JSON.parse", + "String", + "javaTraceDigest", + "javaTraceStart", + "javaTraceStop", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/jni/field_digest", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 204, + "handlerCalls": [ + "JSON.parse", + "jniFieldDigest", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/syscall/digest", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 212, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "syscallDigest" + ], + "directAgentOps": [] + }, + { + "path": "/api/trace/digest", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 221, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "traceDigest" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/backtrace", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 230, + "handlerCalls": [ + "JSON.parse", + "nativeBacktrace", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/syscall_watch", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 239, + "handlerCalls": [ + "JSON.parse", + "parseThrottleMs", + "pickSid", + "readBody", + "send", + "watchSyscalls" + ], + "directAgentOps": [] + }, + { + "path": "/api/jni/onload", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 250, + "handlerCalls": [ + "JSON.parse", + "String", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "jni_onload" + ] + }, + { + "path": "/api/jni/hook", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 260, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "jni_hook" + ] + }, + { + "path": "/api/jni/env_hook", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 269, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "jni_env_hook" + ] + }, + { + "path": "/api/java/enum", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 280, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "java_enum" + ] + }, + { + "path": "/api/java/hook", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 287, + "handlerCalls": [ + "JSON.parse", + "Number", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "java_hook" + ] + }, + { + "path": "/api/object/inspect", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 309, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "object_inspect" + ] + }, + { + "path": "/api/object/set", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 317, + "handlerCalls": [ + "JSON.parse", + "String", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "object_set" + ] + }, + { + "path": "/api/object/invoke", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 328, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "object_invoke" + ] + }, + { + "path": "/api/compat/probe", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 336, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "compat_probe" + ] + }, + { + "path": "/api/trace/qbdi", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 342, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "qbdi_trace" + ] + }, + { + "path": "/api/file/probe", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 359, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "file_probe" + ] + }, + { + "path": "/api/fs/list", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 367, + "handlerCalls": [ + "String", + "String(url.searchParams.get('package') || '').trim", + "listDeviceDir", + "listSandboxDir", + "pickSid", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/fs/read", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 380, + "handlerCalls": [ + "Buffer.from", + "Buffer.from(r.b64 ?? '', 'base64').toString", + "Buffer.from(r.b64, 'base64').toString", + "JSON.parse", + "String", + "String(parsed.package || '').trim", + "pickSid", + "readBody", + "readDeviceFile", + "readSandboxFile", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/hook/selftest", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 406, + "handlerCalls": [ + "hookEngineSelftest", + "pickSid", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/art/dexfiles", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 412, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "art_dexfiles" + ] + }, + { + "path": "/api/art/dump", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 418, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "String(begin).replace", + "dumpRegion", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/memory/scan_magic", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 428, + "handlerCalls": [ + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "scan_magic" + ] + }, + { + "path": "/api/memory/read", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 436, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "read" + ] + }, + { + "path": "/api/memory/write", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 448, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "writeMem" + ], + "directAgentOps": [] + }, + { + "path": "/api/memory/restore", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 458, + "handlerCalls": [ + "JSON.parse", + "listWriteUndo", + "pickSid", + "readBody", + "restoreMem", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/capabilities", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 469, + "handlerCalls": [ + "autoAntiDebugEnabled", + "pickSid", + "send", + "sessions.get", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/recipes", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 476, + "handlerCalls": [ + "listRecipes", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/recipes/run", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 477, + "handlerCalls": [ + "JSON.parse", + "String", + "readBody", + "runRecipe", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/module/watch", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 487, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "['start', 'stop', 'status', 'list'].includes", + "moduleLoads", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "module_watch" + ] + }, + { + "path": "/api/memory/disasm", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 505, + "handlerCalls": [ + "JSON.parse", + "liveDisasm", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/inventory", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 517, + "handlerCalls": [ + "inventoryUnpack", + "pickSid", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/dump-one", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 523, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "pickSid", + "readBody", + "send", + "unpackOneDex" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/dump-so-one", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 532, + "handlerCalls": [ + "JSON.parse", + "String", + "dumpOneAppSo", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/pull-so", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 541, + "handlerCalls": [ + "JSON.parse", + "String", + "String(body.name ?? '').trim", + "String(body.package ?? '').trim", + "String(body.path ?? '').trim", + "pullPackageSo", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/dump-all", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 550, + "handlerCalls": [ + "JSON.parse", + "dumpAllDex", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/run", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 557, + "handlerCalls": [ + "JSON.parse", + "Number", + "Number.isFinite", + "body.package.trim", + "pickSid", + "readBody", + "runUnpackBundle", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/history", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 574, + "handlerCalls": [ + "listUnpackBundles", + "listUnpackRuns", + "send", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/api/unpack/dump-so", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 584, + "handlerCalls": [ + "JSON.parse", + "dumpAppSo", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/agent/load_so", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 591, + "handlerCalls": [ + "JSON.parse", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "load_so" + ] + }, + { + "path": "/api/unpack/trigger", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 598, + "handlerCalls": [ + "Number", + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "trigger" + ] + }, + { + "path": "/api/memory/search", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 609, + "handlerCalls": [ + "Buffer.from", + "Buffer.from(String(text), 'utf8').toString", + "JSON.parse", + "Number", + "String", + "pickSid", + "readBody", + "send", + "sendCmd" + ], + "directAgentOps": [ + "search" + ] + }, + { + "path": "/api/memory/dump", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_runtime.ts", + "line": 620, + "handlerCalls": [ + "JSON.parse", + "Number", + "String", + "String(addr).replace", + "dumpRegion", + "pickSid", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/syscall_scan", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 33, + "handlerCalls": [ + "JSON.parse", + "dumpBuf", + "r.hits.slice", + "readBody", + "send", + "svcScan" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/crypto_const", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 41, + "handlerCalls": [ + "JSON.parse", + "Object.keys", + "cryptoConstScan", + "dumpBuf", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/crypto_variants", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 54, + "handlerCalls": [ + "JSON.parse", + "dumpBuf", + "readBody", + "scanCryptoVariants", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/analyze", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 61, + "handlerCalls": [ + "JSON.parse", + "String", + "a.exports.filter", + "a.exports.slice", + "a.imports.filter", + "a.imports.slice", + "a.strings.filter", + "a.strings.slice", + "analyzeSo", + "dumpBufPath", + "readBody", + "rx.test", + "send", + "unlinkSync" + ], + "directAgentOps": [] + }, + { + "path": "/api/native/disasm", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 78, + "handlerCalls": [ + "JSON.parse", + "disasmSo", + "dumpBufPath", + "insns.slice", + "readBody", + "send", + "unlinkSync" + ], + "directAgentOps": [] + }, + { + "path": "/api/modules", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 89, + "handlerCalls": [ + "modulesFromMaps", + "pickSid", + "send", + "sendCmd", + "url.searchParams.get" + ], + "directAgentOps": [ + "maps" + ] + }, + { + "path": "/api/module/dump", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 98, + "handlerCalls": [ + "Date.now", + "JSON.parse", + "String", + "broadcast", + "createHash", + "createHash('sha256').update", + "createHash('sha256').update(buf).digest", + "dumps.get", + "existsSync", + "join", + "modulesFromMaps", + "pickSid", + "readBody", + "reconstructSo", + "rememberDump", + "resolveModule", + "send", + "sendCmd", + "sessions.get", + "sha.slice", + "writeFile" + ], + "directAgentOps": [ + "maps" + ] + }, + { + "path": "/api/dex/method_code", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 136, + "handlerCalls": [ + "JSON.parse", + "Math.max", + "Math.min", + "Math.trunc", + "Number", + "String", + "codes.filter", + "codes.slice", + "dumpBuf", + "extractMethodCode", + "parseDex", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/index", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 154, + "handlerCalls": [ + "JSON.parse", + "dumpBuf", + "ensureDexIndex", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/index/search", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 161, + "handlerCalls": [ + "JSON.parse", + "String", + "readBody", + "searchDexIndex", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/index/reflections", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 167, + "handlerCalls": [ + "JSON.parse", + "String", + "listDexReflections", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/xref", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 173, + "handlerCalls": [ + "JSON.parse", + "Object.keys", + "String", + "String(method).toLowerCase", + "callee.toLowerCase", + "callee.toLowerCase().includes", + "callers.slice", + "dumpBuf", + "invokeXref", + "parseDex", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/coverage", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 186, + "handlerCalls": [ + "(cov.recoveryRate * 100).toFixed", + "JSON.parse", + "Number", + "analyzeCoverage", + "cov.missing.slice", + "dumpBuf", + "parseDex", + "readBody", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/recover", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 196, + "handlerCalls": [ + "Date.now", + "JSON.parse", + "Promise.resolve", + "broadcast", + "createHash", + "createHash('sha256').update", + "createHash('sha256').update(rb.dex).digest", + "dumpBuf", + "dumps.get", + "existsSync", + "join", + "load", + "outSha.slice", + "parseDex", + "readBody", + "rebuildStandardDex", + "recoverFromSnapshots", + "rememberDump", + "send", + "writeFile" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/strip", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 218, + "handlerCalls": [ + "JSON.parse", + "Number", + "dumpBuf", + "readBody", + "send", + "stripMethodCode", + "stripped.toString" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/rebuild", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 225, + "handlerCalls": [ + "Array.isArray", + "Date.now", + "JSON.parse", + "broadcast", + "createHash", + "createHash('sha256').update", + "createHash('sha256').update(res.dex).digest", + "dumpBuf", + "existsSync", + "join", + "outSha.slice", + "parseDex", + "readBody", + "rebuildStandardDex", + "rememberDump", + "send", + "writeFile" + ], + "directAgentOps": [] + }, + { + "path": "/api/dex/parse", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 243, + "handlerCalls": [], + "directAgentOps": [] + }, + { + "path": "/api/dex/crypto_scan", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 244, + "handlerCalls": [], + "directAgentOps": [] + }, + { + "path": "/api/dex/search", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 245, + "handlerCalls": [], + "directAgentOps": [] + }, + { + "path": "/api/dex/repair", + "method": "POST", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 246, + "handlerCalls": [ + "JSON.parse", + "dumpBuf", + "persistArtifact", + "readBody", + "repairDexHeader", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dumps", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 256, + "handlerCalls": [ + "dumps.values", + "send" + ], + "directAgentOps": [] + }, + { + "path": "/api/dumps/download", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 257, + "handlerCalls": [ + "createReadStream", + "createReadStream(m.path).pipe", + "dumps.get", + "res.writeHead", + "send", + "sha.slice", + "url.searchParams.get" + ], + "directAgentOps": [] + }, + { + "path": "/", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 264, + "handlerCalls": [ + "serveDashboard" + ], + "directAgentOps": [] + }, + { + "path": "/index.html", + "method": "*", + "prefix": false, + "source": "daemon/src/http/routes_analysis.ts", + "line": 265, + "handlerCalls": [ + "serveDashboard" + ], + "directAgentOps": [] + } + ], + "uiLiteralFetches": [ + { + "path": "/api/unpack/history?package=", + "line": 872 + }, + { + "path": "/api/unpack/inventory?session=", + "line": 901 + }, + { + "path": "/api/unpack/run", + "line": 924 + }, + { + "path": "/api/unpack/dump-so-one", + "line": 956 + }, + { + "path": "/api/unpack/pull-so", + "line": 974 + }, + { + "path": "/api/captures/", + "line": 1048 + }, + { + "path": "/api/captures/", + "line": 1159 + }, + { + "path": "/api/detect/summary?package=", + "line": 1188 + }, + { + "path": "/api/http/exchanges?package=", + "line": 1201 + }, + { + "path": "/api/captures?since=", + "line": 1360 + }, + { + "path": "/api/fs/list?package=", + "line": 1513 + }, + { + "path": "/api/fs/read", + "line": 1534 + }, + { + "path": "/api/fs/read", + "line": 1548 + }, + { + "path": "/api/mcp/config${q}", + "line": 1614 + }, + { + "path": "/api/backends", + "line": 1671 + }, + { + "path": "/api/modules?session=", + "line": 1684 + }, + { + "path": "/api/config", + "line": 1697 + }, + { + "path": "/api/captures/packages", + "line": 1707 + }, + { + "path": "/api/config", + "line": 1715 + }, + { + "path": "/api/data/clear", + "line": 1728 + }, + { + "path": "/api/data/clear", + "line": 1740 + }, + { + "path": "/api/settings/export", + "line": 1756 + }, + { + "path": "/api/settings/import", + "line": 1768 + }, + { + "path": "/api/apps", + "line": 1826 + }, + { + "path": "/api/events?package=", + "line": 1844 + }, + { + "path": "/api/config", + "line": 1971 + } + ], + "publicCliCommands": [ + { + "name": "connect", + "line": 27 + }, + { + "name": "disconnect", + "line": 33 + }, + { + "name": "devices", + "line": 37 + }, + { + "name": "status", + "line": 41 + }, + { + "name": "tools", + "line": 46 + }, + { + "name": "mcp", + "line": 50 + }, + { + "name": "call", + "line": 53 + } + ], + "deviceAidlMethods": [ + { + "name": "getProtocolVersion", + "returns": "int", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 3 + }, + { + "name": "getScopeJson", + "returns": "String", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 4 + }, + { + "name": "setScopeJson", + "returns": "boolean", + "arguments": "String json", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 5 + }, + { + "name": "isModulePresent", + "returns": "boolean", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 6 + }, + { + "name": "isLoaderActive", + "returns": "boolean", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 7 + }, + { + "name": "getModuleVersion", + "returns": "String", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 8 + }, + { + "name": "listApplications", + "returns": "String", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 10 + }, + { + "name": "getApplicationIconPng", + "returns": "byte[]", + "arguments": "String packageName", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 12 + }, + { + "name": "controlPackage", + "returns": "String", + "arguments": "String packageName, String action", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 18 + }, + { + "name": "getHostEndpoint", + "returns": "String", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 20 + }, + { + "name": "setHostEndpoint", + "returns": "boolean", + "arguments": "String endpoint", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 22 + }, + { + "name": "listCaCerts", + "returns": "String", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 24 + }, + { + "name": "putCaCert", + "returns": "int", + "arguments": "in byte[] encoded", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 29 + }, + { + "name": "deleteCaCert", + "returns": "boolean", + "arguments": "String fileName", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 31 + }, + { + "name": "rebootDevice", + "returns": "boolean", + "arguments": "", + "source": "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl", + "line": 33 + } + ], + "agentAdvertisedOps": [ + "maps", + "read", + "write", + "jni_hook", + "jni_onload", + "jni_env_hook", + "java_hook", + "java_enum", + "java_call", + "java_call_result", + "hw_watch", + "native_hook", + "native_call", + "got_enum", + "stealth", + "javahook_probe", + "gothook_selftest", + "capture_start", + "capture_drain", + "capture_stop", + "trigger", + "load_so", + "file_probe", + "qbdi_trace", + "qbdi_read", + "compat_probe", + "object_inspect", + "object_set", + "object_invoke", + "art_dexfiles", + "list_dir", + "read_file", + "scan_magic", + "mem_backend", + "search", + "frame_echo", + "ping", + "module_watch" + ], + "sourceSha256": { + "daemon/src/mcp.ts": "aec283d8da3cbdb0fb4948b39ae46ae6488d7276b943d02de36bee14b548598e", + "daemon/src/http/routes_system.ts": "fbb0268791a40073019f497e1587d108af0359cab88a4d0b968fad6e97bf1c25", + "daemon/src/http/routes_runtime.ts": "29c20d803b6503995a4548f3c723fd06838940dc978001f971b072e7d67c1db7", + "daemon/src/http/routes_analysis.ts": "c06e9d7918054c9be7297fb3645fa886fce2a0a07b02bc0f19cc8f15350cb68f", + "daemon/public/index.html": "df0cec2903f5a4ec166a75a203946ef21df49e91ac8bb9743e6bcc412a15e44a", + "../adh-cli/src/adh/cli.py": "bbd6ab4aa1711d51b1372a33b50ab1408f5904f260125fb2e736d7c3e4457789", + "device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl": "7e15a818a7cf78520cd7f2b864dc1c5e1adbc08dfcde240728ef684cfba8d656", + "agent/src/bootstrap/agent_main.c": "e0a4810f171dfd35cfc5758184acb5310572a77eebd030649c16436482af3675", + "daemon/src/index.ts": "5388d3af0ae3d7b7dc8cc8dfa4a06300b9ba63135824220839f8657e84970b78", + "daemon/src/state.ts": "adb5718de31b4a1edf5f9a7680f634bc1f4032cddf66520e9a2fee4979366143", + "daemon/src/service.ts": "b8e4e149c08fc2e63b8473d9e6feed609c11f53e12f6e2a8988c01c240e71ce9", + "daemon/src/scope_list.ts": "d2efb1b8eb41f8c85166783c81932e48a7821ff88b8ae40943d177f659194ab3", + "daemon/src/app_launch.ts": "d721087b4b784f2a02d0adf97b22f393a3a81f3c5e334f37b69d85adf9fdec0c", + "daemon/src/app_analyze.ts": "cb45780827f5a53be689f031b17879e4836559bd5e9ce15ba8c7ac14ba1aa14f", + "daemon/src/memory.ts": "1d5198a5b0e73bc036fadcf23330d8c53f1006adc1a76df2437ac3ab70bdfa5d", + "daemon/src/root_watch.ts": "9d60ec4bde00e5a9152c83bc9b93e09251611ca35a671872acf68c169f96ce59", + "daemon/src/trace_store.ts": "c676e816ea941a936182d7f79431050c405f35c9e651658def6771d061f2e990", + "daemon/src/crypto_evidence.ts": "3930d37e40dbddd8a73da843c7f29d4274de348c9864aa811700c317019599c3", + "daemon/src/capture_persist.ts": "7b04bafb93240685eebdd328f93cb46de69fcb20144eee55f85c2587cd7ca43d", + "daemon/src/analysis_assist.ts": "2ca8eaa02aafa5020eb82b21637c84e46e689d6553bd8c3a4ae1a359ac9d40da", + "daemon/src/recipes.ts": "e3853b9da21862b3cee37e754fd89373f5b3102380f81c8e0671383f7567b202", + "agent/src/bootstrap/io.c": "e1ca358db6975f0520a566a86cc1e03b672994361d1217a6334fe26a135bb479", + "device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt": "8fa2e3042ee297065f9167a25349d41e25c8b6cd6ea0eed815f3a18202ddabcc", + "device/core/src/main/java/com/adh/core/AdhPaths.kt": "5ae854640c47bb2156eda1d8bf701e2b176ae6800bcfa5355f86c57ee21747f6", + "device/core/src/main/java/com/adh/core/CaptureFamilies.kt": "b8da7286cd28ca714f74281a880d2b74d8be501b129e8cd0f8a75f0d4928cf2a", + "device/core/src/main/java/com/adh/core/ScopeJson.kt": "aada14c8477dbb1ef7700d8e59877a8989352fe94401259f821cc6475cdddbd8", + "injector/zygisk/jni/main.cpp": "f286420af1edeb8607e99b06c152fc95db936a6f7044f3f416c547152c19ffee", + "injector/zygisk/module/post-fs-data.sh": "7c313e58cbd76d50aba8ed54ccf4e95a5c31bf5a4cf33f8341fc699274658cce", + "injector/zygisk/module/service.sh": "ec60d07cc2b4c19f01c6ae753a67296dedd2f10fa5e8e4295bae2303ef4b9153", + "../adh-cli/src/adh/status.py": "1f7a466681462bc76370ac26f3df17f366c5bf718af513454d5d6f14c72bdb83", + "../adh-cli/src/adh/stdio.py": "d4c0a521b1a3e069e1005179ae2cf63bc436a28988f953228c6290200ad8d1a4", + "../adh-cli/src/adh/config.py": "2a2e39fb73d9320b0a99f6530ec41bcd55bc5d5cec18ee060b18ce660bee3368", + "daemon/src/trace_digest.ts": "a122788cfca30801b14edf6fd07c101743cf48e02a3b0f8a81200572c33d410c", + "daemon/src/oracle.ts": "b0428378dbe2e4683b973a8d689a534fa3797bee956e6e3b0da54969a62a92ed", + "daemon/src/native_hook_all.ts": "34cc9bbf20b8c97fba2b181c69cf1ed9580c1f1180746778d5337e94d72a46b3", + "daemon/src/error_codes.ts": "e9dbbcc25d4b5affdf4d15d24c3f80a6ab354635da0a6428602028e9343b962d", + "daemon/src/http/router.ts": "3fc7a7c7867c56b3362d418829d6754a29ab332e4f9026695aceccde614b536f", + "device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt": "2efb463c6ee2c54437735688c62a0aff8ca592063d77fb9bfd5fd6dc5df54ac0", + "device/daemon/src/main/java/com/adh/daemon/CallerAuthorizer.kt": "c902d1ec65546fa43bdb5f7a006d6781fe8c4f7bd112be509d0bcc2680092286", + "device/manager/src/main/java/com/adh/manager/data/DaemonScopeRepository.kt": "dc91f0199edeed0290b5d11f9660f774b8eb1eb99bd73d20d75beabb2e84722b", + "device/manager/src/main/java/com/adh/manager/ui/scope/HookConfigScreen.kt": "674c771d83280c3066fb0f4a290727e29640c3fe1a954ac2d35ca133fefbb188", + "../adh-cli/src/adh/endpoint.py": "67d3e3e13580a64aa3807e9f3ee586e0576194a38623c5f8c64e2a8664608d5f", + "../DecryptHub-DSH/packages/mcp/decrypthub-components/src/inventory.ts": "31224a5c9ec1084f1251d96fd7e9e975bef5b25dada83a1e6a64631b9d92bc50", + "../DecryptHub-DSH/packages/mcp/decrypthub-components/src/index.ts": "ddd7b31777648c76370d719bbeca9fddc9540c4b1f72eacfc44fa36a52076881", + "../DecryptHub-DSH/packages/mcp/decrypthub-components/src/types.ts": "ba1aae44b14ea9942588fa83ceb381bfbbbc5a61a7defccc5da584ed9acaf0ab" + }, + "capabilityGroups": { + "guidance": [ + "analysis_guide" + ], + "inventory": [ + "process_list", + "backends", + "capabilities" + ], + "diagnostics": [ + "compat_probe", + "runtime_diagnostics", + "agent_ping", + "engine_selftest", + "protocol_selftest" + ], + "scope_and_launch": [ + "analyze_app", + "scope_list", + "scope_set" + ], + "capture_and_network": [ + "capture_start", + "capture_stop", + "live_captures", + "capture_detail", + "http_exchanges", + "flow_correlate", + "file_probe", + "crypto_identify" + ], + "detection": [ + "detect_summary", + "detect_modules", + "detect_java" + ], + "java": [ + "javahook_probe", + "java_hook", + "java_enum", + "java_call", + "java_call_result", + "java_trace" + ], + "jni": [ + "jni_onload", + "jni_hook", + "jni_env_hook", + "jni_field_digest" + ], + "native_runtime": [ + "native_hook", + "native_hook_all", + "native_look", + "native_call", + "native_backtrace", + "native_symbols", + "got_enum", + "stealth" + ], + "memory": [ + "memory_maps", + "maps_query", + "mem_backend", + "memory_read", + "memory_disasm", + "memory_search", + "memory_scan_magic", + "memory_write", + "memory_restore" + ], + "watch_and_trace": [ + "trace_session", + "root_watch", + "hw_watch", + "qbdi_trace", + "syscall_trace", + "syscall_watch", + "syscall_digest", + "trace_digest" + ], + "module": [ + "module_watch", + "load_library" + ], + "objects": [ + "object_inspect", + "object_set", + "object_invoke" + ], + "dex_analysis": [ + "art_dexfiles", + "dex_search", + "dex_index", + "dex_index_search", + "dex_reflections", + "dex_xref", + "dex_crypto_scan", + "dex_method_code", + "dex_repair", + "dex_coverage", + "dex_recover" + ], + "native_analysis": [ + "native_xref", + "native_disasm", + "native_analyze", + "native_crypto_const", + "crypto_variant_scan", + "native_syscall_scan" + ], + "artifacts": [ + "dumps_list", + "memory_dump", + "dump_all_dex", + "unpack_package" + ], + "evidence": [ + "crypto_evidence", + "oracle" + ], + "host_control": [ + "settings", + "recipe" + ], + "filesystem": [ + "fs_list", + "fs_read" + ], + "active_trigger": [ + "trigger" + ] + }, + "uiLiteralApiReferences": [ + { + "path": "/api/export/report", + "line": 715 + }, + { + "path": "/api/dumps/download?sha=${encodeURIComponent(sha)}", + "line": 791 + }, + { + "path": "/api/dumps/download?sha=", + "line": 852 + }, + { + "path": "/api/unpack/history?package=", + "line": 872 + }, + { + "path": "/api/unpack/inventory?session=", + "line": 901 + }, + { + "path": "/api/unpack/run", + "line": 924 + }, + { + "path": "/api/unpack/dump-so-one", + "line": 956 + }, + { + "path": "/api/unpack/pull-so", + "line": 974 + }, + { + "path": "/api/captures/", + "line": 1048 + }, + { + "path": "/api/captures/", + "line": 1159 + }, + { + "path": "/api/detect/summary?package=", + "line": 1188 + }, + { + "path": "/api/http/exchanges?package=", + "line": 1201 + }, + { + "path": "/api/captures?since=", + "line": 1360 + }, + { + "path": "/api/fs/list?package=", + "line": 1513 + }, + { + "path": "/api/fs/read", + "line": 1534 + }, + { + "path": "/api/fs/read", + "line": 1548 + }, + { + "path": "/api/mcp/config${q}", + "line": 1614 + }, + { + "path": "/api/backends", + "line": 1671 + }, + { + "path": "/api/modules?session=", + "line": 1684 + }, + { + "path": "/api/config", + "line": 1697 + }, + { + "path": "/api/captures/packages", + "line": 1707 + }, + { + "path": "/api/config", + "line": 1715 + }, + { + "path": "/api/data/clear", + "line": 1728 + }, + { + "path": "/api/data/clear", + "line": 1740 + }, + { + "path": "/api/captures/export?package=", + "line": 1750 + }, + { + "path": "/api/settings/export", + "line": 1756 + }, + { + "path": "/api/settings/import", + "line": 1768 + }, + { + "path": "/api/apps", + "line": 1826 + }, + { + "path": "/api/events?package=", + "line": 1844 + }, + { + "path": "/api/config", + "line": 1971 + } + ], + "limitations": [ + "Tool/route presence is static, not live availability or passing integration evidence.", + "Literal UI references omit dynamic API expressions; neither fetch count nor string references prove a rendered control.", + "Route method * means no method property in the table; handlers may still branch by method.", + "Handler calls and direct agent ops are lexical within that handler, not a transitive execution graph.", + "Package-pinned //mcp and dashboard fallbacks are router branches outside the 106 static route entries." + ], + "validation": { + "staticChecks": { + "passed": 9, + "failed": 0 + }, + "hostTypecheck": { + "exitCode": 0 + }, + "hostTests": { + "passed": 464, + "failed": 0, + "skipped": 0, + "exitCode": 0 + }, + "isolation": "ADH_SKIP_ARTIFACT_LOAD=1 and inherited ADH_DATA_DIR removed in child shell; existing launcher assigns per-test-process temporary data roots. No live service/device calls or dynamic ADH imports for inventory.", + "scope": "Static audit plus unchanged Host regression suite, not device/USB/LAN integration acceptance." + }, + "desktopConsumerCommit": "7b2f2c0814933215fe43767f418314a99cf8b540" +} diff --git a/docs/AI_FIRST_REFACTOR_AUDIT.md b/docs/AI_FIRST_REFACTOR_AUDIT.md new file mode 100644 index 0000000..5e7ab06 --- /dev/null +++ b/docs/AI_FIRST_REFACTOR_AUDIT.md @@ -0,0 +1,224 @@ +# ADH 代码审计与 AI 优先改造方案 + +核验日期:2026-11-16。审计基线:ADH `ca4f92ec99e8ec13fc13fbc7f0a24a5919248d6a`;adh-cli `3cf83996cd8a0221b3248048025870f785cd5852`。 + +本文是 `DEVELOPMENT_PLAN.md` 的审计附录和后续实施输入。当前行为、静态发现、拟议设计分开描述;新模块与新命令均未实施,不代表运行现场已升级。用户本轮明确的产品方向:**AI 自主决定分析流程,人类面板可以查看、修改和接管,USB 与局域网共用设备能力。** + +## 1. 结论与审计边界 + +保留 agent、Zygisk、Device Daemon 和 Host 分层,先在现有 Host 内统一操作入口、任务与状态,再补齐设备管理通信。AI 的规划放在外部 Agent/Harness;ADH 不再内置另一套强制分析流程。电脑端面板是同一执行面的人工客户端,手机 Manager 保留配对、状态、撤销授权与紧急停用。 + +本轮只读取源码、静态解析注册表并写文档。不调用 ADH/ADB、不请求运行服务、不启停进程、不改 reverse、不安装 APK/模块、不读目标 dump/捕获内容。没有用运行时 import 获取工具清单。未重新验证真机能力、网络可达性或 ROM 兼容性。 + +静态清单见 [AI_FIRST_CAPABILITY_INVENTORY.json](AI_FIRST_CAPABILITY_INVENTORY.json):记录注册项、源码行号、handler 的直接调用、参数名、分组及源文件 SHA-256。TypeScript 用 AST 解析,Python/Kotlin/C/HTML 用限定文本扫描;不执行业务模块。 + +| 静态入口 | 数量 | 解释 | +| --- | ---: | --- | +| MCP 工具 | 91 | `MCP_TOOLS` 的真实注册对象;不代表当前运行 daemon 或目标 agent 支持全部能力 | +| HTTP 路由表项 | 106 | 三个 `routes_*.ts` 数组,含资源、首页、前缀路由;不是 106 种独立分析能力 | +| Agent 宣告操作 | 38 | `ADH_AGENT_OPS`;运行目标必须再查询自己的 caps | +| Device AIDL 方法 | 15 | 本地 Manager→特权服务;目前不是 LAN 设备 API | +| Python CLI 子命令 | 7 | connect/disconnect/devices/status/tools/mcp/call | + +`//mcp` 与包固定首页是 router 的额外分支,不计入 106 项。HTTP 条目未声明 method 的标为 `*`,并不表示只读。HTML literal fetch/路径统计会漏动态表达式,不能当作按钮覆盖率。直接调用名不是跨函数的完整执行图。 + +## 2. 需要优先处理的源码发现 + +| 编号 | 源码确认的行为 | 影响与优先级 | +| --- | --- | --- | +| F01 | Host `scope_list.ts:302` 的 `writeScopePackages()` 只序列化 version/mode/packages,再用 adb cp 覆盖文件;Device `ScopeJson.kt:8` 会保存 policy | **P0**:Host 改包名单会丢掉手机已保存的非默认 Hook policy,回到默认 crypto ON 语义。这里是字段丢失的静态证明,本轮没有写真机复现 | +| F02 | MCP `settings` handler 只 merge/save;REST `/api/config` 与 settings/import 还调用 retain 和 `applyCaptureEnabled()` | **P0**:相同配置从 AI 与面板提交,运行效果不同;REST 修改还可能影响所有在线目标。必须共用配置应用函数与结果模型 | +| F03 | `AgentSession` 无 deviceId;`process_list` 返回 agent sessions;`pickSid()` 默认从全部在线会话选主进程;多个 root/ADB 模块依赖全局 serial | **P0**:设备、连接、目标进程混用,不能据此可靠支持多设备或跨 USB/LAN 去重。包固定路径也不能替代权限或设备身份 | +| F04 | `state.ts` import 会 mkdir、加载配置/工件、回填元数据、按年龄裁剪捕获;`index.ts` 启动及定时回收工件、每 15 秒重设 reverse | **P0**:只想读取注册表或启动旁路服务,也可能触发数据或连接变更。仅设 ADH_DATA_DIR 不能隔离正常模式的 CAPTURES 路径 | +| F05 | hello 后 `applyStartupHooks()`→`startCaptureLoop()`;默认 capture.enabled/autoDumpDex 为 true;作用域读取失败时 auto-arm 存在 fail-open 路径 | **P1**:发现连接和执行策略耦合;重连不是纯状态操作。需迁入显式、可查询的启动方案,保留已授权任务的必要行为 | +| F06 | `pending`/`inflight` 是内存表,sendCmd 超时只删除等待并报告终态;MCP notifications/cancelled 直接返回 202 | **P1**:超时和取消通知都不能证明目标已停止。缺少可持久化的任务控制、跨入口控制权与不确定执行状态 | +| F07 | 文档称 Web 只读,`public/index.html` 实际已调用 config、settings/import、data/clear、unpack/run 等写入口 | **P1**:规则与实现漂移。人工操作面板已有部分基础,应接入统一执行层;无需另造一套业务后端 | +| F08 | agent 用 loopback→保存的 Host IPv4 回拨;scope、进程控制、诊断、root_watch 等仍直接执行 ADB | **P1**:采集 TCP 可走 LAN,不等于完整 LAN 独立控制。重构必须覆盖全部 ADB 消费者,不能只让 process_list 通过 | +| F09 | `/api/trace/qbdi`、`/api/unpack/trigger`、hook/selftest 未限定 POST;handler 会执行目标操作 | **P1**:HTTP 方法不能充当副作用分类。需逐 action 描述效果,再统一到写操作执行入口 | +| F10 | Python `adh` 与 daemon/src/cli.ts 是两套命令入口;前者 devices 保存 Host 地址,后者提供 doctor/target/unpack | **P2**:用户概念和目标解析分散。保留已发布 stdio 入口,逐步把公共命令收敛到 adh-cli,开发 CLI 薄兼容 | + +关键复核点:[scope 写入](../daemon/src/scope_list.ts)、[MCP](../daemon/src/mcp.ts)、[REST 配置](../daemon/src/http/routes_system.ts)、[状态与加载](../daemon/src/state.ts)、[启动](../daemon/src/index.ts)、[执行与采集](../daemon/src/service.ts)。F05 的默认值不代表当前现场配置;本轮没有读取现场 settings。 + +当前两处 family 配置也不能混为一谈:Device `CaptureFamilies` 决定哪些 Hook **根本不安装**;Host `settings.capture.families` 在接收侧过滤记录,不能证明相应 Hook 已卸载。新的面板需分别显示方案、实际安装和输出过滤,避免用户关闭显示后误以为停止了目标观测。 + +## 3. 能力对照 + +以下 20 组完整覆盖 91 个 MCP 注册项,每项只归一组;逐项名称、参数和调用位置在 JSON。Python `adh call`/`adh mcp` 能转发全部注册工具,不表示有对应专用子命令。REST 列描述直接路由,不把 `/mcp` 的间接可达重复算作 REST 对等。面板列只确认源码中的现有入口,不声称本轮浏览器验收通过。 + +| 能力组(MCP 数) | AI / CLI 当前入口 | 电脑面板 / REST 当前情况 | 手机侧与副作用 | +| --- | --- | --- | --- | +| 分析指南(1) | analysis_guide,含 assess | 无独立指南面板;可经 MCP | Host 元数据;assess 可有界查询 Hook 状态,不执行建议 | +| 目标与能力(3) | process_list/backends/capabilities | agents/backends/capabilities | 列 agent 会话,不是物理设备或所有 Android 进程 | +| 诊断与自检(5) | runtime_diagnostics、compat_probe、ping、engine/protocol_selftest | 有 ping/probe/selftest 等;root 诊断缺直接 REST 对等 | 诊断走 ADB/root;自检可能临时安装 Hook/分配资源,应单独标效果 | +| 作用域与启动(3) | scope_list/scope_set/analyze_app | scope、analyze-app REST | Manager 可本地编辑 scope/启停;analyze_app 缺在线 agent 时会 cold-start,并可加作用域 | +| 采集与网络(8) | capture_start/stop、live_captures、capture_detail、http_exchanges、flow_correlate、file_probe、crypto_identify | 捕获/HTTP/配置/文件探测等;面板可改全局采集配置 | 安装/卸载 GOT Hook,drain 消耗 ring;网络重组在 Host | +| 检测观察(3) | detect_summary/modules/java | 有 summary,部分安装能力仅 MCP | 检测 Hook 会改变目标执行环境;不把观察结果等同于反检测结论 | +| Java(6) | javahook_probe、java_hook/enum/call/call_result/trace | probe/hook/enum/call/trace REST | agent ART/JNI 机制;call/trace 主动执行,兼容性取决于运行构建和 ROM | +| JNI(4) | jni_onload/hook/env_hook/field_digest | 对应 JNI REST | 注册、表槽 Hook/事件读取;宽匹配可能耗尽事件预算 | +| Native 运行时(8) | native_hook/hook_all/look/call/backtrace/symbols、got_enum、stealth | hook/call/backtrace/stealth 等;并非全组独立 REST 对等 | GOT/inline Hook、参数改写、主动调用和返回控制;符号解析在 Host | +| 内存(9) | maps/maps_query、read/search/scan/disasm、write/restore、mem_backend | 多数有直接 REST;高级 maps_query 无同名路由 | 写入最多 4096 字节;force 可临时改保护;undo 是 Host 内存记录,不是持久事务 | +| 观察与追踪(8) | root_watch、hw_watch、trace_session、qbdi_trace、syscall_trace/watch/digest、trace_digest | 一部分 trace/syscall REST;无 root_watch/trace_session 直接同等路由 | root_watch 外部 helper 走 ADB;QBDI 主动调用与 Hook 回放必须区分 | +| 模块(2) | module_watch/load_library | module/watch、agent/load_so | watch 状态与 dlopen 有副作用;不是单纯读取模块列表 | +| 活体对象(3) | object_inspect/set/invoke | 对应 REST | set 改值;invoke 执行方法;inspect 也依赖活体运行时访问 | +| DEX(11) | art_dexfiles 与 dex_search/index/index_search/reflections/xref/crypto_scan/method_code/repair/coverage/recover | DEX/ART REST;还有 strip/rebuild/parse 等 REST-only 操作 | ART 枚举在 agent;解析/索引/修复在 Host,可写索引与新工件 | +| Native 离线分析(6) | native_xref/disasm/analyze/crypto_const、crypto_variant_scan、native_syscall_scan | 多数有对应分析路由;native_xref 无同名入口 | Host 解析/反汇编;临时文件与缓存也要归属任务 | +| 工件(4) | dumps_list/memory_dump/dump_all_dex/unpack_package | dump/download、模块 dump、unpack/inventory/run 等 | dump 落盘并可能触发保留策略;unpack 可启停目标、暂停采集、保护自动布防 | +| 证据与 oracle(2) | crypto_evidence/oracle | 缺直接同等 REST/专用面板 | Host 保存原始配对证据;oracle record/replay 主动调用 Java 门面;drop 删除文件 | +| Host 控制(2) | settings/recipe | 配置/导入/导出、recipes/run | 设置全局共享;recipe 可多步骤写入/调用,应返回每步真实效果 | +| 文件(2) | fs_list/fs_read | 面板及 REST 还支持无 session 的包沙盒路径 | agent 自身权限读取,或 Host 通过 ADB/root 读取;两条路径权限不同 | +| 主动触发(1) | trigger | unpack/trigger | 调用目标函数;当前 REST 允许查询参数驱动执行,不能按 GET 视作只读 | + +未被 91 个 MCP 项完整覆盖的产品能力: + +- **设备清单、设备属性、已安装应用/图标**:Device AIDL 有本地应用目录;Host 没有统一物理设备服务;process_list 不能代替它。 +- **证书生命周期**:listCaCerts/putCaCert/deleteCaCert/rebootDevice 共四个 AIDL 方法,Manager 有页面,公共 CLI/MCP 无同等受管入口;系统 CA 与应用证书校验 Hook 分开。 +- **持久任务、控制权、取消、断点、结果关联**:目前有命令进度与事件日志,但不足以组成可恢复、可接管任务。 +- **数据生命周期**:面板/REST 有清理和导出,MCP settings 能改部分策略,但没有统一的维护任务模型。 +- **自定义分析代码**:外部 Agent 可使用自己的终端、Python/Capstone/仿真器;ADH 不是通用 JS 脚本引擎。新执行机制应独立评估,不能以双传输重构为由默认引入 Frida/Gadget。 + +## 4. 状态、写入者与副作用清单 + +| 状态/资源 | 当前所有者与存储 | 当前写入者/触发 | 一致性或副作用问题;迁移目标 | +| --- | --- | --- | --- | +| 设备身份与连接 | 缺统一实体;ADB serial/env、Host endpoint、session 分散 | Host 连接与工具各自选目标 | 增 Device/Connection/Target 三实体;同设备 USB/LAN 去重,禁止有歧义的默认选择 | +| 注入 scope 与 family policy | `/data/adb/adh/scope.json`;Kotlin core 定义,C++ 手工镜像 | Binder 整体替换;Host ADB 只写 packages | F01;改为设备端单写入者、带版本 patch,保留未知字段和逐包策略,冲突拒绝 | +| 手机 Hook 编辑草稿 | Manager ScopeDraft 与 ScopeRepository | 人类页面修改并保存 | 无跨电脑/手机 revision;保存前需检测旧草稿冲突 | +| Host 回拨地址 | `/data/adb/adh/host.endpoint` | Manager→Binder;Zygisk 读取并传给 agent | IPv4 单地址;不是手机设备地址。新 broker 建立后保留为 legacy 回拨配置,分清方向 | +| CA 与生效挂载 | cacerts 目录、启动脚本的 tmpfs/bind mount | Manager→特权服务,启动脚本,reboot | 安装到磁盘不等于所有进程已信任;报告 pending-reboot/有效挂载;私钥不进入普通事件 | +| 模块/QBDI 可选载荷 | module.prop、开机标记、qbdi.enabled、Zygisk fd | 构建/部署脚本、启动脚本、companion | 部署与启用不同;版本/能力按实际目标上报,不热换正在执行的 .so | +| session/caps/socket | Host state.ts 内存 Map | hello/caps/disconnect/prune | PID/UID/starttimeTicks 已存在,应保留;补 deviceId/bootId/connectionId;重连 SID 变化不丢任务绑定 | +| pending/inflight | Host Map、cmd.start/progress/done | sendCmd、超时、断连 | 仅请求生命周期,无 actor/task/fencing;超时不能确认目标没执行;接入操作账本 | +| 全局 settings | state.ts 内存与 DATA_DIR/settings.json | MCP merge/save、REST 配置/导入 | F02;先改内存再存盘,save 非原子;需统一提交、版本、持久化与实际应用分开报告 | +| 启动 Hook 与采集定时器 | startupHooks、captureTimers、延迟 widening | hello、applyStartupHooks、startCaptureLoop | 连接有隐式执行;迁为有 owner、显式启用的启动方案;状态浏览不触发安装 | +| 采集停止/解包保护 | service.ts 的 pending/protect/suppression 等内存集合 | setCapture、unpack、hello | 多处按 package 键控,未来须加 device;保护不能丢,否则重连可能重新布防 | +| 实际 Hook/断点/回放 | agent .so 的运行时表、ring、QBDI 页 | 所有 Hook/trace 类操作与自动布防 | 方案 desired 与 agent observed 分开;读实际 Hook ID、模块 build-id、安装结果,禁止只显示配置已保存 | +| 内存写 undo | service.ts writeUndo,按 session+addr,每 session 64 项 | memory_write/restore | Host 重启丢失;不能自动覆盖之后的人类/目标改动。恢复前校验进程代次及当前字节,支持条件恢复 | +| 捕获记录与计数 | captures 内存、每包 captures.jsonl、capStats | drain 消耗 agent ring,push/trim/age-prune | retain/年龄会丢记录;每包键需要 device/任务隔离;保留丢失计数和窗口基线 | +| dump 与来源元数据 | CAPTURES 下 bytes/.meta.json、dumps Map | dump/persist/load/backfill/prune | 正常 CAPTURES 固定仓库目录,与 DATA_DIR 分离;统一 StorageContext 后显式迁移,加载不删除 | +| 事件与设置回放 | DATA_DIR/events.jsonl,内存 events | recordEvent、启动载入、REST clear | 不是完整操作事务;任务操作日志独立保存 actor/请求/结果引用,不能靠清展示事件抹掉执行记录 | +| DEX/ELF 索引与缓存 | Host 分析模块、缓存/工件关联 | index/analyze、工件回收 | 派生数据可重建,原始证据受任务 pin 保护;失效时不能清掉唯一证据 | +| trace/evidence/oracle | DATA_DIR 下各模块文件与局部缓存 | record/replay/query/drop | 能力已有;统一任务关联、权限、保留与分页,不重复写一套证据引擎 | +| root_watch 执行 | Host runs Map、ADB 子进程、设备 helper、Host JSONL | prepare/start/stop | prepare 上传+chmod+硬件自检;start 验代次并占用断点;stop 终止 collector。全 LAN 需替换这些 ADB 步骤 | +| CLI 已存 Host | adh/config.py 的 connections.json | connect/disconnect | devices 实为 Host 列表;保留旧 schema/语义的兼容期,不静默把 Host 地址解释为手机地址 | + +重点源码:[内存/命令](../daemon/src/service.ts)、[capture 持久化](../daemon/src/capture_persist.ts)、[root_watch](../daemon/src/root_watch.ts)、[设备 Binder](../device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt)、[证书挂载](../injector/zygisk/module/post-fs-data.sh)。 + +副作用需要按 **action + 参数** 描述:native_hook.status 和 install 不同;trace_session.query 与 record 不同;crypto_evidence.verify/save/drop 不同;“读取采集”也可能 drain ring。建议效果集合为 `host-read / host-write / device-read / device-config / target-observe / target-mutate / target-invoke / process-control / maintenance`,并声明资源占用、可取消方式、可恢复条件;不是一把 readOnly 布尔值。 + +## 5. 目标架构与 AI/人类协调 + +```mermaid +flowchart TD + AI["外部 AI / DecryptHub Harness"] --> MCP["adh mcp / adh call"] + Human["人类电脑面板"] --> HTTP["Host API / 事件订阅"] + MCP --> Host["现有 Host 内统一操作层\n任务、权限、控制权、执行账本"] + HTTP --> Host + Host --> Analyze["电脑分析与证据模块"] + Host --> USB["USB adapter:ADB forward"] + Host --> LAN["LAN adapter:配对 TLS/TCP"] + USB --> Device["现有 Device Daemon\n认证、设备能力、会话路由"] + LAN --> Device + Manager["轻量 Manager:状态/配对/停用"] --> Device + Device --> Agent["本地通道 → 进程内 agent"] + Zygisk["Zygisk 按作用域注入"] --> Agent +``` + +### 5.1 一个执行面,AI 自主规划 + +- 现有 Host 进程内增加协调模块,不新建队列服务/数据库服务器;MCP/REST/CLI/面板调用统一业务函数。业务原语继续复用现有 service/analysis 模块。 +- 91 工具逐 action 登记能力和效果。先保留稳定工具名,handler 逐步变薄。面板常用能力使用表单,高级能力可使用同一 schema 的参数编辑器;AI 不受按钮数量限制。 +- 授权按任务的设备、应用、目录与允许效果授予;授权内自主组合、批处理、运行实验,避免逐工具确认。当前 confirm:true 是调用意图标志,不可当作身份鉴权。 +- actor 从已认证的入口和服务端任务授权取得,不能信任 AI/页面在 JSON 中自称 human。Host 本地接口与远程接口都要纳入权限检查;现有公开 HTTP、宽 CORS 不能直接承担高权限任务授权。 +- 自定义 Python/反汇编/仿真任务由外部 Harness 或 Host worker 运行,可登记 task/operation/资源与产物。带外 adb/shell 无法凭空获得完整可追踪性;受管执行提供 wrapper,发现外部改动后刷新 observed 并使旧计划失效。 + +### 5.2 共享状态与人工接管 + +- `Task` 保存目标、任务授权、当前方案引用、阶段/实验摘要、operation 与 evidence 引用。AI 可以随时更新分析路线;不要求先固定完整 DAG。 +- `TargetRef` 至少绑定 deviceId、bootId、PID、UID、starttimeTicks;模块操作另绑模块 build-id。`Connection` 是可更换传输,不是设备身份。旧 agent 缺字段时显式标 legacy/identityUnverified。 +- desired 配置和 observed 运行结果分别保存 revision。安装部分失败、只保存未应用、待重启、离线未知均有明确状态。 +- 事件保留来源时间、接收时间、游标所属顺序域、完整性与快照来源。root_watch 的分页 seq 不是跨槽执行顺序,异步读取的目标内存也不是命中瞬间快照;统一事件模型不能抹掉这些区别。 +- 首版按目标进程串行调度冲突写操作;设备配置另锁设备。独立只读/离线分析可以并行,后续再细化到 Hook/内存范围;不用一把全局锁阻塞所有设备。 +- 人类修改提交新 revision、推进控制 epoch,暂停受影响任务的后续冲突写入并发事件。AI 旧请求在执行层返回 conflict,重读并重规划;不能自动把人工关闭的 Hook 又开回来。 +- Host 阶段只能阻止尚未派发的旧请求,不能撤回已在 agent 执行的命令。新协议在执行端检查 epoch 后,才可声明跨重连拒绝旧命令。UI 必须区分这两个保证。 +- pause 停止新派发;cancel_requested 表示已请求取消;仅在执行端确认停止后记录 cancelled。不可取消的在途调用继续报告 running/unknown,不能伪造“已停止”。 + +拟议请求元数据:`taskId / operationId / idempotencyKey / TargetRef / expectedRevision / controlEpoch / deadline / arguments`。拟议状态:`queued → running → succeeded | failed | cancelled | unknown`,另有任务 paused。超时但已派发的副作用操作记 unknown,通过状态核对解决,禁止自动重放 native_call/Java 调用。不能承诺跨崩溃的任意副作用 exactly-once。 + +### 5.3 Hook 方案与证书 + +电脑持有版本化 Hook 方案与预设;agent 保留 Native/JNI/ART 执行机制与能力上限。新增目标、过滤、采样规则尽量只改方案;新增底层执行机制仍需 agent 发布,不能承诺“任意 Hook 永不升级手机”。 + +早期 Hook 使用电脑下发、明确启用、绑定包/版本/能力的设备缓存方案。缓存需原子提交、校验哈希、可撤销、记录 applied/failed;断线保留策略写入方案。现有 Host hello 布防无法覆盖 .init_array,更早执行不能仅靠缓存文件声明支持,须在 agent/Zygisk 专用路径另行验证。 + +先保留并完整迁移现有 policy;等方案覆盖、兼容和启动路径验证完成,再移除手机固定 family 编辑器。Agent 重连默认只对账,是否安装由显式任务/启动方案决定,不能偷偷恢复旧全局默认。 + +CA 安装/删除、挂载状态、待重启与重启操作由设备域服务执行,CLI/MCP/面板共用它。设备传输配对证书和用于目标抓包的系统 CA 必须分开;不把配置写成功当成目标已信任。 + +### 5.4 USB 与 LAN 的真实统一范围 + +- USB 使用 Host→Device RPC 的 ADB forward,LAN 使用同一 Device RPC 的配对 TLS/TCP。上层选 deviceId,两种 adapter 只负责连接/断连/流传输,不各写一套业务逻辑。 +- 优先扩展现有 Device Daemon 的逻辑模块,不另起一个同职责 root daemon。设备目录、应用目录、scope、证书、进程控制先通过同一域服务提供;Binder 继续服务本机 Manager。 +- 当前 Binder 只允许经签名/UID 校验的 Manager,不能直接开放到 TCP、伪造 Manager 身份或删除 verifier。把域操作从 RootScopeBinder 提取,Binder 和网络入口分别认证后调用。 +- agent 改连设备本地通道,Device 只路由/执行,不做 MCP、索引或重分析。Unix socket 的 SELinux、UID 验证、Zygisk specialization 前后 fd 生命周期、服务未就绪行为必须先在专用 fixture 验收;本轮不声称各 ROM 已支持。 +- 控制与 bulk 数据分流或有界复用,dump/trace 分块、背压、丢失计数和校验;设备不把大块数据长期积压到 Java 堆。断线时有限缓冲,如实报告缺口。 +- root_watch helper 的部署/运行/停止、procfs 诊断、沙盒文件读取、应用启停、scope、模块/QBDI 状态都需要 Device adapter;遗漏任何一项都不能称“全功能 LAN”。不恢复已退休的手机 UI 自动化模块 X。 +- legacy agent→Host TCP/reverse 保留为明确选择的兼容后端;旧目标保持连接至任务结束。新通道先用独立 fixture/隔离端口验收,不在现有 session 上热切。 + +## 6. 具体模块改造表 + +下列新增路径均为建议,不是本轮已落地代码。 + +| 位置 | 改造职责 | 复用/兼容要求 | +| --- | --- | --- | +| `daemon/src/operations.ts`(新增) | OperationSpec、按 action 效果/资源、统一 execute/查询、统一错误 | MCP/HTTP 只做协议转换;保留原语,不一次重写 91 handler | +| `daemon/src/tasks.ts`、`task_store.ts`(新增) | Task/Operation 持久状态、事件游标、幂等记录、任务/证据关联 | 首版用 Host 原子文件/追加日志即可;崩溃恢复先对账,不自动重放副作用 | +| `daemon/src/control.ts`、`access_context.ts`(新增) | revision、目标级调度、control epoch、人工接管、任务授权 | 身份从认证边界传入;Host 和设备执行端逐步补 fencing | +| `daemon/src/host_lifecycle.ts`、`storage.ts`(新增) | 显式 init/start/stop、StorageContext、非破坏性恢复、独立 retention job | state import 不 I/O;CAPTURES/DATA_DIR 同根可配置;旧数据先只读导入/备份,不移动删除 | +| `daemon/src/state.ts` | 拆类型/仓储状态与启动 I/O;为设备/目标/任务分键 | 保留旧事件/工件读取;采集 complete/drop/来源语义不降级 | +| `daemon/src/service.ts` | sendCmd 接操作上下文、状态与取消能力;capture/startup/undo 接统一操作层 | 先加 facade,再逐域拆;超时 unknown,条件 undo,实际应用结果可查 | +| `daemon/src/settings_service.ts`(新增) | 共用读取/patch/持久化/运行时应用 | 首先修 F02;返回 persisted/applied/failed/affectedTargets,不把全局设置自动扩散当成功 | +| `daemon/src/devices.ts`、`transport/*.ts`(新增) | 设备注册、发现、选择与 USB/LAN/legacy adapter | 将 serial 从进程 env 下沉为每次 TargetContext;重连去重与代次校验 | +| `scope_list.ts`、`app_launch.ts`、`sandbox_fs.ts`、`runtime_diagnostics.ts`、`root_watch.ts` | 通过 DeviceClient 做设备控制、读文件、诊断、helper 生命周期 | 列出并迁完所有 ADB 消费者;legacy ADB adapter 仍显式可用,业务模块不自行择设备 | +| `mcp.ts`、`http/routes_*.ts`、`error_codes.ts` | 统一 OperationSpec、效果说明、分页/限额、错误与任务接口;取消映射 | 稳定工具名优先;副作用 GET 逐步迁 POST,兼容层也走同一执行检查 | +| `daemon/public/index.html` → `public/app/*`(按需拆) | 设备/任务/实际 Hook/证据、方案编辑、暂停/接管、冲突提示 | 先贯通一组真实操作;复用现有显示,不先做整站视觉重写 | +| `device/core/...` | Device/Connection/Target 与协议能力、版本化配置 patch 契约 | Kotlin/C++ 路径与 schema 同步;保留旧 policy、未知字段策略与版本拒绝机制 | +| `device/daemon/.../DeviceOperations.kt`(新增)及 `RootScopeBinder.kt` | 设备域单写入者,Binder/network 共用;scope CAS、证书/应用/进程操作 | 保留 ManagerCallerVerifier;原子写入不等于并发版本检查,两者都要 | +| `device/daemon/.../rpc/*`(新增) | 配对/撤销/鉴权、USB/LAN 同协议、会话路由/限额、helper runner | 不放分析/MCP;root helper 按授权/载荷哈希登记,不能暴露匿名任意 root shell | +| `device/manager/.../data` 与 `ui/*` | 同一设备状态源;方案/授权状态、配对、停用,逐步退役固定 family 编辑器 | 手机本地操作同样产生 revision/事件;断开电脑仍能撤销/停止 | +| `agent/src/bootstrap/io.c`、`agent_main.c`、caps/dispatch | 本地传输与协议握手、代次/epoch、可报告的取消/安装状态 | 38 旧 op 的语义保持;新增能力如实协商,不为改通信把分析塞进 .so | +| `injector/zygisk/jni/main.cpp`、启动脚本 | 设备本地连接引导、已授权启动方案交付/撤销、fd/SELinux 生命周期 | 不热改旧进程;agent/模块版本及 exports 契约一起验证 | +| `adh-cli/src/adh/{cli,status,endpoint,http_mcp,stdio}.py` | 统一公共 CLI;hosts/device/tasks/hook/cert;JSON、任务/事件查询 | 保持零第三方运行依赖;新传输的 TLS 在 Host,CLI 仍 stdio→Host;旧连接配置显式迁移 | +| `daemon/src/cli.ts` | 开发命令薄兼容/逐步退役 | doctor/target/unpack 迁入公共 CLI;不增加第二个 mcp 子命令 | + +桌面端消费边界已经只读核对:`DecryptHub-DSH/packages/mcp/decrypthub-components/src/inventory.ts` 只解析 schemaVersion=1,`index.ts` 调用 status --json,并把旧 devices 配置当 Host endpoints。新增设备/任务字段需同步 parser/types/测试;不能直接输出 v2 导致桌面卡片失败,也不能假设未声明字段会保留。先提供显式 v2 协商、默认保留 v1,消费者迁移后再切默认。公共 devices 语义同样需要兼容期:先增加 hosts 与 device list,不能静默改旧 JSON 含义。此轮没有修改跨仓契约。 + +## 7. 实施顺序与验收条件 + +| 阶段 | 实施范围与交付 | 通过条件 | 依赖/现场安排 | +| --- | --- | --- | --- | +| P0:保护数据与修一致性 | 显式生命周期/StorageContext;scope 保留 policy;统一 settings 应用;效果清单 | import/列表不删证据、不改隧道、不装 Hook;非默认 policy 往返保留;同一 patch 经 MCP/HTTP 得到相同状态与失败结果 | 最先做;纯 Host 测试/合成配置;不升级运行实例 | +| P1:共享操作与任务核心 | OperationSpec、任务账本、revision/Host 控制权;现有 REST/MCP 逐步接入 | 同幂等键不重复派发;冲突操作串行;人类改动阻止旧排队请求;超时/取消真实;旧入口没有写入绕路 | P0 后;fake agent/隔离端口;AI 自主规划,recipe 可选 | +| P2:人类接管最小闭环 | 任务/Hook 方案/运行状态/证据界面,AI 任务事件;基础 device/target 实体 | AI 安装→面板见实际 Hook→人工关闭→旧 AI 操作 conflict→AI 重读继续;暂停不再发新写;未知执行状态可见 | P1 后;先测 fake agent,再独立 native fixture;此时先用 legacy 设备后端也可验证协作 | +| P3:统一设备控制与 USB | 提取 DeviceOperations、scope/证书/应用/进程服务、设备身份;USB forward 设备 RPC;agent 本地通道原型 | 设备离线/无目标仍可列出信息;两个设备不串;Binder/RPC 结果一致;UDS/fd/SELinux 原型通过;无分析进设备 | P1 后,可与 P2 独立开发;专用 fixture/新测试进程,保留所有当前 session | +| P4:LAN 与完整能力对等 | 同一 RPC 上的 TLS/配对/撤销;迁完诊断/fs/helper 等 ADB 调用;流式 bulk、断线对账 | 撤去测试设备 ADB 可达性后,设备清单、scope、证书、目标操作、诊断/root_watch/dump 均能工作;USB/LAN 对同 deviceId 去重;无重复调用;撤销授权有效 | P3 后;仅隔离测试设备/连接。未迁能力明确 unsupported,不能悄悄走 ADB 后宣称 LAN 通过 | +| P5:Hook 方案与公共入口收敛 | 电脑方案库、经验证的早期缓存、手机编辑器退役;公共 CLI、桌面 schema 迁移;旧默认与文档收口 | 新/旧配置迁移可逆;缺能力/旧协议明确拒绝;未授权方案不自动安装;断线策略按方案执行;CLI/面板/AI 同效果;早期能力有真实路径证据 | P2/P4 后;运行任务结束后再安排产品升级,兼容窗口内不删除 legacy | + +每阶段是一组可独立评审的提交,先做完整的一小组操作再扩展覆盖。P2 的闭环先选择可查询、可卸载的 native Hook,不用重启现有目标证明接管。两层验证分开:Host 合成协议检验协调逻辑;后续专用真实第三方目标检验注入/ROM/传输,不用沙盒通过代替真实目标证据。 + +P4 核心对等矩阵:设备信息/应用清单、scope patch/冲突、Hook install/status/remove、内存读写/条件恢复、主动调用不重试、dump 分块哈希、事件丢失计数、root helper 生命周期、证书 pending-reboot、重连代次、撤销授权。对每格分别记录 USB/LAN pass/fail/unsupported;有副作用的项仅在测试目标和授权范围内执行。 + +## 8. 规则同步、迁移与尚未验证项 + +- 用户方向明确改变“电脑面板只读”的旧产品定位。进入相应实施阶段时同步 `REQUIREMENTS.md`、`DEVELOPMENT_PLAN.md`、`AGENTS.md`/`CLAUDE.md`、device/MAP 与工具说明,保留 agent 轻量、分析在 Host、模块 X/Gadget 退休等有效边界。当前审计没有把这些规则静默改成已实现状态。 +- 不改现有 scope 路径、默认端口、stdio onboarding 或桌面 status schema;本轮只记录所需迁移。协议、配置、消费者变更在对应阶段一起提交与验证。 +- 旧运行会话保持旧后端至自然结束;新 Host 先用独立端口/独立全部数据根/fake transport 验收。不能在旁路服务里运行自动 reverse,也不能共享真实 captures 根。 +- 仍需未来实验:手机本地 socket 在目标 ROM 的 SELinux/UID/fd 可行性、Device Daemon 大数据转发开销、执行端取消和 epoch 覆盖、启动早期 Hook 的可达时机、完整断线对账、TLS 配对生命周期、多设备真机隔离。本轮只给设计与静态证据。 +- 生命周期初始化与任务日志迁移必须先预览/备份;只读恢复不执行年龄删除。保留策略作为可见维护任务运行,任务引用的原始证据有 pin,所有删除带清单和原因。 + +## 9. 本轮检查记录 + +本轮结果:静态清单与文档一致性 **9 passed / 0 failed**;`npm run typecheck` 退出 0;`npm test` **464 passed / 0 failed / 0 skipped**;`git diff --check` 通过。 + +静态检查覆盖:工具唯一性、20 组无遗漏/重复、路由/agent/AIDL/CLI 数量一致、清单中全部源码 SHA-256 未变、MCP 行号定位、文档链接存在、F01–F10/P0–P5 齐全,以及 F01/F02 的源码结构证据。它们不冒充真机集成测试。 + +Host 单测启动前在子进程设 `ADH_SKIP_ARTIFACT_LOAD=1` 并移除继承的 `ADH_DATA_DIR`,沿用既有 launcher 的每测试进程临时数据根,避免加载/裁剪操作者捕获目录。没有运行设备验收、注册表动态导入脚本或完整设备门禁,没有启动服务。新增清单和报告不改变任何运行功能。 diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md index b95b284..7e24290 100644 --- a/docs/DEVELOPMENT_PLAN.md +++ b/docs/DEVELOPMENT_PLAN.md @@ -3,6 +3,7 @@ > **定位**:**通用 Android 运行时逆向分析工具** — 对高对抗目标(反调试/root/签名检测/混淆/加密传输)具备实战能力。 > **功能需求**:见 [`REQUIREMENTS.md`](REQUIREMENTS.md)(唯一权威规格,模块 A–W;本文档只管架构与排期)。 > **跨会话进度**:见 [`PROGRESS.md`](PROGRESS.md)。 +> **2026-11-16 用户确定的后续方向**:AI 自主规划分析,人类电脑面板可查看、修改和接管,USB/LAN 共用设备能力。现状对照、状态/副作用、具体模块与 P0–P5 实施顺序见本计划的[代码审计附录](AI_FIRST_REFACTOR_AUDIT.md),逐项入口见[静态清单](AI_FIRST_CAPABILITY_INVENTORY.json)。附录区分当前实现与拟议设计;下面旧“只读面板”等描述属于待迁移基线,不代表本轮已完成运行改造。进入实施阶段同步需求与工程规则,仍保持 agent 轻量、分析在 Host;本轮不改当前分析现场。 > **参考项目**:[`REFERENCE_IOS.md`](REFERENCE_IOS.md)([ios-decrypt-helper](https://github.com/taisuii/ios-decrypt-helper))。 > **一句话**:运行在目标进程内的 native agent,配合本机 daemon、Web UI 和 MCP Server,实现运行时 dex/so/memory dump、ART 结构级脱壳、Java/native hook、明文边界加密观测、活体对象自省、反分析行为观测、函数/指令 trace、Capstone 反汇编与搜索;Zygisk / Gadget 多种注入方式。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 2cbf003..2c7acd0 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4927,3 +4927,16 @@ Host 现在优先从同条 perf 内核栈记录解析内存窗口,且每次指 首次默认服务启动期间,历史工件加载数从 41 降到 27,最近缺失的 14 份 DEX 共 166.81 MiB,与过期回收条件对应。已用仓外已有副本恢复全部 14 份;其中 2 份补齐原始零填充后得到完全相同的 SHA-256。逐份重新验证完整 SHA-256、长度和原事件来源元数据,14/14 通过。没有把目标转储纳入版本控制。 v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺原始捕获字段,未用元数据伪造原记录;本机无可用卷影副本。隔离修复的操作者目录哨兵验证通过。算法交付包已在独立目录、Python 隔离模式下通过 76 条原生 fixture、标准 SM4 向量、空输入和 CLI 验收。 + + +## 2026-11-16:AI 优先、人工可接管与 USB/LAN 统一的代码审计 + +用户要求先梳理 ADH 现有代码,交付能力对照、状态/副作用清单、具体模块和实施顺序,不影响当前分析现场。本轮只读源码/AST,不调用 ADH 或 ADB、不请求运行服务、不重启/部署/改 reverse,不读取目标捕获与转储内容。 + +新增 `docs/AI_FIRST_REFACTOR_AUDIT.md` 与 `docs/AI_FIRST_CAPABILITY_INVENTORY.json`;开发计划链接此审计附录。静态完整清点 91 MCP 工具、106 路由表项(含资源/首页/前缀)、38 宣告 agent op、15 AIDL 方法、7 公共 CLI 子命令;20 组覆盖所有 MCP 项。计数不代表当前运行服务支持或真机验收通过。 + +确认两处优先一致性问题:Host `writeScopePackages` 只保留 version/mode/packages,会覆盖 Device 保存的非默认 policy;MCP settings merge/save 与 REST 的即时 applyCaptureEnabled/retain 行为不同。另记录状态 import/启动回收、hello 自动布防、超时/取消语义、缺少 deviceId 与全局 serial、只读 UI 文档与实际写入口、部分副作用 GET、双 CLI 和桌面 status v1 消费边界。均未在本轮修改运行实现。 + +拟议 P0–P5:数据/配置保护 → Host 共享操作与持久任务 → 人工修改/接管最小闭环 → 设备域服务和 USB RPC → TLS LAN 与完整 ADB 能力迁移 → Hook 方案/启动缓存和公共入口收敛。AI 规划仍由外部 Harness 决定,recipe 可选;人类修改靠 revision/控制 epoch 阻止旧操作覆盖,取消不伪造停止,旧运行会话保留旧后端。 + +验证:静态清单/来源哈希/链接/分组与 F01/F02 结构证据 **9 passed / 0 failed**;`npm run typecheck` rc=0;`npm test` **464 passed / 0 failed / 0 skipped**(子进程设置 ADH_SKIP_ARTIFACT_LOAD=1、移除继承 ADH_DATA_DIR,使用既有每测试进程临时根);`git diff --check` 通过。没有运行设备门禁或启动服务;没有改变作用域契约、默认端口、stdio onboarding、桌面 status schema 或已部署服务。 From 7f71626d17f255784aeac2f59963c85d5c79389b Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:29:11 +0800 Subject: [PATCH 12/24] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E4=BD=9C?= =?UTF-8?q?=E7=94=A8=E5=9F=9F=E7=AD=96=E7=95=A5=E5=B9=B6=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E4=B8=8E=E9=9D=9E=E7=A0=B4=E5=9D=8F=E6=80=A7?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/src/MAP.md | 10 + daemon/src/capture_persist.ts | 30 ++ daemon/src/dex_index.ts | 8 +- daemon/src/host_lifecycle.ts | 6 + daemon/src/http/routes_analysis.ts | 9 +- daemon/src/http/routes_system.ts | 34 +- daemon/src/index.ts | 13 +- daemon/src/maintenance.ts | 18 + daemon/src/mcp.ts | 19 +- daemon/src/scope_list.ts | 699 ++++++++++++++------------- daemon/src/service.ts | 62 ++- daemon/src/settings_service.ts | 50 ++ daemon/src/state.ts | 187 +++---- daemon/src/storage.ts | 43 ++ daemon/test/p0_lifecycle.test.ts | 102 ++++ daemon/test/run.mjs | 10 +- daemon/test/scope_update.test.ts | 38 ++ daemon/test/settings_service.test.ts | 179 +++++++ docs/AI_FIRST_REFACTOR_AUDIT.md | 2 + docs/DEVELOPMENT_PLAN.md | 2 + docs/FEATURE_STATUS.md | 2 + docs/P0_HOST_STATE.md | 58 +++ docs/PROGRESS.md | 13 + docs/REQUIREMENTS.md | 2 + docs/mcp-tools.md | 2 +- 25 files changed, 1074 insertions(+), 524 deletions(-) create mode 100644 daemon/src/host_lifecycle.ts create mode 100644 daemon/src/maintenance.ts create mode 100644 daemon/src/settings_service.ts create mode 100644 daemon/src/storage.ts create mode 100644 daemon/test/p0_lifecycle.test.ts create mode 100644 daemon/test/scope_update.test.ts create mode 100644 daemon/test/settings_service.test.ts create mode 100644 docs/P0_HOST_STATE.md diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index 886dbec..72f9950 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -2,6 +2,16 @@ ADH Daemon / `adhd` (Node 24 + TypeScript, runs `.ts` directly, no build step). HTTP/WS `8088`, agent TCP `8761`. App pin: `GET /` and `POST //mcp`. +## P0 Host lifecycle / shared settings (2026-11-16) + +- `storage.ts`: pure path resolution; explicit ADH_DATA_DIR isolates captures too; optional ADH_CAPTURES_DIR for legacy layouts. Atomic settings/text writes use temporary files, fsync and rename. +- `host_lifecycle.ts`: index.ts explicitly initializes recovery before listening. state/MCP imports do not create directories, load history, clean data or open the DEX SQLite cache. Recovery is idempotent and does not rewrite provenance sidecars. +- `settings_service.ts`: the SAME serialized save→publish→runtime-apply path for MCP settings, panel config and settings import. Persistence failure leaves memory/targets untouched; per-target errors are returned, not fire-and-forgotten. UI/retention patches do not re-arm hooks. +- `maintenance.ts`: explicit preview/confirmed retention. No age/size deletion at import, boot, periodic session sweep, settings save, dump write or capture append. Memory views remain bounded; disk maintenance is opt-in through settings(action=maintenance) or /api/maintenance. +- `scope_list.ts`: re-read and preserve the COMPLETE scope document, replace only packages, stage/rename on device, verify full readback. ScopeIO enables host regression tests without ADB. This does not add cross-writer CAS or change the phone schema. + +Behavior, migration and test boundaries: [`docs/P0_HOST_STATE.md`](../../docs/P0_HOST_STATE.md). The 2026-11-16 capability inventory is a historical baseline, not a live source-hash gate. + ## Module layout (post-split) Analysis additions (2026-10-24): `trace_store.ts` drains bounded `qbdi_read` pages into Host JSONL, diff --git a/daemon/src/capture_persist.ts b/daemon/src/capture_persist.ts index 4ed1183..d183a31 100644 --- a/daemon/src/capture_persist.ts +++ b/daemon/src/capture_persist.ts @@ -1,3 +1,4 @@ +import { atomicWriteText } from './storage.ts'; // Package-scoped capture log on disk. Agent still only rings+drains; Host owns the durable store. // Layout: {dataDir}/packages//captures.jsonl — one JSON object per line. import { @@ -62,6 +63,35 @@ export function trimPackageCapturesFile(dataDir: string, pkg: string, retain: nu renameSync(tmp, path); } +/** Preview or explicitly enforce both disk rules. Read failures are reported, never success. */ +export function retainCaptureFiles(dataDir: string, policy: { retain: number; maxAgeDays: number }, dryRun = true, now = Date.now()) { + const packages: { package: string; before: number; remaining: number; removed: number }[] = []; + const errors: string[] = []; + const root = join(dataDir, 'packages'); + if (!existsSync(root)) return { packages, removed: 0, errors }; + for (const name of readdirSync(root)) { + if (!safePackageDirName(name)) continue; + const path = join(root, name, 'captures.jsonl'); + if (!existsSync(path)) continue; + try { + const lines = readFileSync(path, 'utf8').split('\n').filter(Boolean); + const cutoff = policy.maxAgeDays > 0 ? now - policy.maxAgeDays * 86400000 : 0; + let kept = lines.filter(line => { + try { const ts = Number(JSON.parse(line).ts) || 0; return !cutoff || !ts || ts >= cutoff; } + catch { return true; } + }); + if (policy.retain > 0) kept = kept.slice(-policy.retain); + const removed = lines.length - kept.length; + if (!dryRun && removed) { + if (kept.length) atomicWriteText(path, kept.join('\n') + '\n'); + else unlinkSync(path); + } + packages.push({ package: name, before: lines.length, remaining: kept.length, removed }); + } catch (error) { errors.push(`${name}: ${(error as Error).message}`); } + } + return { packages, removed: packages.reduce((n, p) => n + p.removed, 0), errors }; +} + // Load durable captures from every packages//captures.jsonl (newest retain lines each). export function loadCapturesFromDisk(dataDir: string, retain: number): PersistedCapture[] { const root = join(dataDir, 'packages'); diff --git a/daemon/src/dex_index.ts b/daemon/src/dex_index.ts index 67186ac..384e5af 100644 --- a/daemon/src/dex_index.ts +++ b/daemon/src/dex_index.ts @@ -2,7 +2,7 @@ // injected agent only supplies bytes. Rows are keyed by dex SHA + parser version so stale // indexes are rebuilt explicitly instead of returning plausible but mismatched results. import { createHash } from 'node:crypto'; -import { unlinkSync } from 'node:fs'; +import { mkdirSync, unlinkSync } from 'node:fs'; import { join } from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import { DATA_DIR, log } from './state.ts'; @@ -52,6 +52,7 @@ function discardIndexFile(reason: string): void { } function openIndexDb(): DatabaseSync { + mkdirSync(DATA_DIR, { recursive: true }); const opened = new DatabaseSync(DEX_INDEX_FILE); try { createSchema(opened); return opened; } catch (error) { @@ -129,8 +130,8 @@ function createSchema(target: DatabaseSync) { `); } -let db = openIndexDb(); -let getDocument = db.prepare('SELECT * FROM dex_documents WHERE sha = ?'); +let db: DatabaseSync | undefined; +let getDocument: ReturnType; /** * Run one index operation against the live handle. SQLite can report corruption at query time (see @@ -138,6 +139,7 @@ let getDocument = db.prepare('SELECT * FROM dex_documents WHERE sha = ?'); * the schema, and give the caller one clean attempt. Non-corruption errors are rethrown untouched. */ function withIndex(operation: (database: DatabaseSync) => T): T { + if (!db) { db = openIndexDb(); getDocument = db.prepare('SELECT * FROM dex_documents WHERE sha = ?'); } try { return operation(db); } catch (error) { if (!isCorruptDbError(error)) throw error; diff --git a/daemon/src/host_lifecycle.ts b/daemon/src/host_lifecycle.ts new file mode 100644 index 0000000..5811b8e --- /dev/null +++ b/daemon/src/host_lifecycle.ts @@ -0,0 +1,6 @@ +import { restoreHostState } from './state.ts'; + +/** Called by the executable before listeners start. Never prunes or configures a device. */ +export function initializeHost() { + return restoreHostState(); +} diff --git a/daemon/src/http/routes_analysis.ts b/daemon/src/http/routes_analysis.ts index 0953a97..9e35cbf 100644 --- a/daemon/src/http/routes_analysis.ts +++ b/daemon/src/http/routes_analysis.ts @@ -1,3 +1,4 @@ +import { captureFile } from '../storage.ts'; import { createHash } from 'node:crypto'; import { createReadStream, existsSync, unlinkSync } from 'node:fs'; import { writeFile } from 'node:fs/promises'; @@ -15,7 +16,7 @@ import { ensureDexIndex, listDexReflections, searchDexIndex } from '../dex_index import {dumpBuf, dumpBufPath, modulesFromMaps, persistArtifact, pickSid, reconstructSo, repairDexHeader, sendCmd,} from '../service.ts'; import { resolveModule, ModuleAmbiguousError } from '../memory.ts'; -import { broadcast, CAPTURES, dumps, readBody, rememberDump, sessions } from '../state.ts'; +import { broadcast, dumps, readBody, rememberDump, sessions } from '../state.ts'; import type { DumpMeta } from '../state.ts'; import type { Route, RouteContext, SendResponse } from './types.ts'; @@ -125,7 +126,7 @@ export function analysisRoutes({ req, res, url, send }: RouteContext): Route[] { size: buf.length, requestedSize: buf.length, complete: true, addr: mod.base, tag: mod.name, sessionId: sid, package: sessions.get(sid)?.package ?? existing.package ?? '?' }); const s = sessions.get(sid); - const path = join(CAPTURES, `${sha.slice(0, 16)}.so`); + const path = captureFile(`${sha.slice(0, 16)}.so`); if (!existsSync(path)) await writeFile(path, buf); const meta: DumpMeta = { sha256: sha, size: buf.length, requestedSize: buf.length, complete: true, source: 'so-reassembly', note: 'reassembled from memory: offsets == vaddrs, section headers dropped, not byte-exact', addr: mod.base, tag: mod.name, sessionId: sid, package: s?.package ?? '?', capturedAt: Date.now(), path, kind: 'so' }; rememberDump(meta); @@ -207,7 +208,7 @@ export function analysisRoutes({ req, res, url, send }: RouteContext): Route[] { let rb; try { rb = rebuildStandardDex(base, captures); } catch (e) { return send(422, { error: (e as Error).message }); } let parseOk = true; try { parseDex(rb.dex); } catch { parseOk = false; } const outSha = createHash('sha256').update(rb.dex).digest('hex'); - const path = join(CAPTURES, `${outSha.slice(0, 16)}.dex`); + const path = captureFile(`${outSha.slice(0, 16)}.dex`); if (!existsSync(path)) await writeFile(path, rb.dex); const meta: DumpMeta = { sha256: outSha, size: rb.dex.length, source: 'dex-recover', addr: '0', tag: 'recovered', sessionId: '', package: '', capturedAt: Date.now(), path, kind: 'dex' }; rememberDump(meta); broadcast('dump.new', meta); @@ -231,7 +232,7 @@ export function analysisRoutes({ req, res, url, send }: RouteContext): Route[] { let parseOk = true, methods = 0; try { const pd = parseDex(res.dex); methods = pd.counts.methods; } catch { parseOk = false; } const outSha = createHash('sha256').update(res.dex).digest('hex'); - const path = join(CAPTURES, `${outSha.slice(0, 16)}.dex`); + const path = captureFile(`${outSha.slice(0, 16)}.dex`); if (!existsSync(path)) await writeFile(path, res.dex); const meta: DumpMeta = { sha256: outSha, size: res.dex.length, source: 'dex-rebuild', addr: '0', tag: 'rebuilt', sessionId: '', package: '', capturedAt: Date.now(), path, kind: 'dex' }; rememberDump(meta); broadcast('dump.new', meta); diff --git a/daemon/src/http/routes_system.ts b/daemon/src/http/routes_system.ts index e6b0746..e7fb94f 100644 --- a/daemon/src/http/routes_system.ts +++ b/daemon/src/http/routes_system.ts @@ -1,3 +1,5 @@ +import { patchSettings, settingsHttpStatus } from '../settings_service.ts'; +import { maintainData } from '../maintenance.ts'; import { existsSync, unlinkSync, writeFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; @@ -12,12 +14,12 @@ import { baseFromHost, isValidPackage, mcpOnboarding } from '../mcp_onboarding.t import { handleMcp, MCP_TOOLS } from '../mcp.ts'; import { scopedApps, mergeScope, readScopeFile, writeScopePackages } from '../scope_list.ts'; import { analyzePackage } from '../app_analyze.ts'; -import { applyCaptureEnabled, listCaptureArmProtected } from '../service.ts'; +import { listCaptureArmProtected } from '../service.ts'; import { - applyCaptureRetainCap, broadcast, captureHealth, capturePackage, captures, captureTimers, + broadcast, captureHealth, capturePackage, captures, captureTimers, clearCaptureStore, clearPackageCaptureStore, configStats, cryptoIdentify, dumps, eventPackage, - events, EVENTS_FILE, exportPackageCapturesJsonl, hexToPreview, log, mergeSettings, packageCaptureDiskStats, - previewForCapture, readBody, saveSettings, sessions, settings, + events, EVENTS_FILE, exportPackageCapturesJsonl, hexToPreview, log, packageCaptureDiskStats, + previewForCapture, readBody, sessions, settings, } from '../state.ts'; import type { Route, RouteContext } from './types.ts'; @@ -172,12 +174,8 @@ export function systemRoutes({ req, res, url, send }: RouteContext): Route[] { if (req.method === 'POST') { let patch: any = {}; try { patch = JSON.parse((await readBody(req)) || '{}'); } catch { return send(400, { error: 'bad json' }); } - const applied = mergeSettings(patch); - applyCaptureRetainCap(); - applyCaptureEnabled().catch((e) => log('[settings] applyCaptureEnabled:', (e as Error).message)); - try { saveSettings(); } - catch (e) { return send(500, { error: '设置已在内存生效,但写入磁盘失败(重启后丢失): ' + (e as Error).message, applied, settings, persisted: false }); } - return send(200, { ok: true, applied, settings, stats: configStats(), persisted: true }); + const result = await patchSettings(patch); + return send(settingsHttpStatus(result), result); } return send(200, { settings, stats: configStats() }); } }, @@ -186,13 +184,15 @@ export function systemRoutes({ req, res, url, send }: RouteContext): Route[] { let obj: any; try { obj = JSON.parse((await readBody(req)) || '{}'); } catch { return send(400, { error: 'JSON 格式错误' }); } if (typeof obj !== 'object' || Array.isArray(obj)) return send(400, { error: '顶层必须是对象' }); - const applied = mergeSettings(obj); - if (!applied.length) return send(400, { error: '没有可应用的板块(capture/ui/artifacts)' }); - applyCaptureRetainCap(); - applyCaptureEnabled().catch((e) => log('[settings] applyCaptureEnabled:', (e as Error).message)); - try { saveSettings(); } - catch (e) { return send(500, { error: '导入已在内存生效,但写入磁盘失败(重启后丢失): ' + (e as Error).message, applied, settings, persisted: false }); } - return send(200, { ok: true, applied, settings, persisted: true }); + const result = await patchSettings(obj); + return send(settingsHttpStatus(result), result); + } }, + { method: 'GET', path: '/api/maintenance', handler: () => send(200, maintainData()) }, + { method: 'POST', path: '/api/maintenance', handler: async () => { + let body: any; + try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return send(400, { error: 'bad json' }); } + const result = maintainData(body ?? {}); + return send(result.ok ? 200 : 400, result); } }, { path: '/api/captures/packages', handler: () => send(200, { packages: packageCaptureDiskStats() }) }, { path: '/api/captures/export', handler: () => { diff --git a/daemon/src/index.ts b/daemon/src/index.ts index e29649c..1ad1e68 100644 --- a/daemon/src/index.ts +++ b/daemon/src/index.ts @@ -5,7 +5,8 @@ import net from 'node:net'; import { AGENT_PORT, HTTP_PORT, webUrls } from './config.ts'; import { handleHttp } from './http/router.ts'; import { ensureAdbReverse } from './scope_list.ts'; -import { startCaptureLoop, forgetCaptureSession, pruneArtifactsAndIndex, clearCaptureArmProtect, applyStartupHooks } from './service.ts'; +import { startCaptureLoop, forgetCaptureSession, clearCaptureArmProtect, applyStartupHooks } from './service.ts'; +import { initializeHost } from './host_lifecycle.ts'; import { agentSockets, broadcast, captureTimers, failPendingFor, frameJson, FRAME_JSON, FRAME_MAX, log, nextId, pending, pruneSessions, sessions, wss, @@ -154,6 +155,7 @@ httpServer.on('upgrade', (req, socket, head) => { // ---- boot ----------------------------------------------------------------- +initializeHost(); agentServer.listen(AGENT_PORT, '0.0.0.0', () => log(`ADH Daemon agent TCP listening on :${AGENT_PORT}`)); httpServer.listen(HTTP_PORT, '0.0.0.0', () => { const w = webUrls(); @@ -174,13 +176,10 @@ httpServer.listen(HTTP_PORT, '0.0.0.0', () => { process.on('SIGINT', () => { log('shutting down'); process.exit(0); }); // Periodic session sweep: closes can be missed (kill -9, lost sockets), so bound the map anyway. -// The same tick enforces artifact retention: the dump helpers prune right after they write, but a -// few routes write artifacts directly, so a periodic sweep is what keeps captures/ bounded no -// matter which path produced the file. +// Data retention is an explicit maintenance operation, never part of startup/session sweeps. setInterval(() => { const dropped = pruneSessions(); if (dropped.length) log(`session prune: dropped ${dropped.length} stale offline session(s)`); - pruneArtifactsAndIndex(); }, 60_000).unref(); // The injected agent only reaches this process through adb reverse. Re-apply it on a @@ -188,7 +187,3 @@ setInterval(() => { const keepReverse = () => ensureAdbReverse([AGENT_PORT, HTTP_PORT], (line) => log(line)); keepReverse(); setInterval(keepReverse, 15_000).unref(); - -// Boot-time reconciliation: adopt what is already on disk (the module body of state.ts does the -// load) and apply retention once, so a daemon that was down while files piled up starts bounded. -pruneArtifactsAndIndex(); diff --git a/daemon/src/maintenance.ts b/daemon/src/maintenance.ts new file mode 100644 index 0000000..bb24d92 --- /dev/null +++ b/daemon/src/maintenance.ts @@ -0,0 +1,18 @@ +// Destructive retention is reachable only through an explicit operation, never import/boot/save. +import { retainCaptureFiles } from './capture_persist.ts'; +import { applyCaptureRetainCap, DATA_DIR, previewArtifactRetention, settings } from './state.ts'; +import { pruneArtifactsAndIndex } from './service.ts'; + +export function maintainData(options: { dryRun?: boolean; confirm?: boolean } = {}) { + const dryRun = options.dryRun !== false; + if (!dryRun && options.confirm !== true) return { ok: false, dryRun, error: 'retention requires confirm:true; preview first' }; + const plan = previewArtifactRetention(); + const captures = retainCaptureFiles(DATA_DIR, settings.capture, dryRun); + if (dryRun) return { + ok: captures.errors.length === 0, dryRun, policy: structuredClone({ capture: settings.capture, artifacts: settings.artifacts }), + artifacts: { count: plan.evict.length, bytes: plan.evict.reduce((n, a) => n + a.size, 0), remainingBytes: plan.remainingBytes }, captures, + }; + const artifacts = pruneArtifactsAndIndex(); + applyCaptureRetainCap(); + return { ok: !!artifacts && artifacts.failed === 0 && captures.errors.length === 0, dryRun, artifacts, captures }; +} diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index c6e3392..3deb755 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -1,3 +1,6 @@ +import { patchSettings } from './settings_service.ts'; +import { maintainData } from './maintenance.ts'; +import { captureFile } from './storage.ts'; // mcp.ts — MCP Server (Streamable HTTP / JSON-RPC). // Exposes the workbench Service Layer as MCP tools for AI clients. Shares the same // logic as the REST API (no duplicate business logic) — handlers delegate to service.ts @@ -49,7 +52,7 @@ import { syscallTraceStart, syscallTraceDigest, syscallTraceStop } from './sysca import { backendMatrix, classifySession } from './backends.ts'; import { armDetectJava, detectJavaPlan, detectionReport, planDetectModules } from './detect.ts'; import { assembleHttpExchanges, type TlsChunk } from './http_exchange.ts'; -import { sessions, dumps, captures, capturePackage, filterLiveCaptures, captureTimers, capStats, storeLossNote, events, DATA_DIR, CAPTURES, cryptoIdentify, rememberDump, MAX_BODY_BYTES, mergeSettings, saveSettings, settings } from './state.ts'; +import { sessions, dumps, captures, capturePackage, filterLiveCaptures, captureTimers, capStats, storeLossNote, events, DATA_DIR, cryptoIdentify, rememberDump, MAX_BODY_BYTES, settings } from './state.ts'; import type { DumpMeta } from './state.ts'; const S = { type: 'string' }, N = { type: 'number' }; @@ -264,12 +267,11 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h { name: 'memory_write', description: 'Write bytes into the target process (1..4096 per call, even-length hex). The write side of memory_read: this is how a branch, a dispatch-table entry or a decrypted buffer gets CHANGED, which hooking alone cannot do. A non-writable mapping is refused with its perms in the error; pass force:true to patch it - the original protection is restored immediately and code pages get an I-cache flush. The reply carries before (the bytes that were replaced) and the host remembers it, so memory_restore can put them back. Unmapped addresses, ranges that leave their mapping, and malformed hex are refused; a prefix is never written.', inputSchema: { type: 'object', properties: { session: S, addr: S, hex: S, force: { type: 'boolean' } }, required: ['addr', 'hex'] }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return writeMem(sid, a.addr, a.hex, a.force === true); } }, { name: 'memory_restore', description: 'Undo a memory_write: the host kept the bytes each write replaced, so restoring needs only the address. Without addr it lists what this session can still restore (newest last) instead of guessing. Returns the agent reply plus restored:true, or why nothing was restored.', inputSchema: { type: 'object', properties: { session: S, addr: S } }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); if (!a.addr) return { ok: false, undo: listWriteUndo(sid), hint: 'pass addr to restore one of these' }; const r: any = await restoreMem(sid, a.addr); return r?.ok === true ? { ...r, restored: true } : r; } }, { name: 'capabilities', description: 'What the RUNNING agent can do: every op it dispatches plus the limits that decide whether a plan is feasible (hook slots, memory windows, max write size, frame size), and the daemon limits that apply on the host side. Call this first when you do not know which operations a session supports. The answer comes from the agent itself, not from documentation: two processes can run different builds.', inputSchema: { type: 'object', properties: { session: S } }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) return { ok: false, error: 'no session' }; const s = sessions.get(sid); return { ok: true, session: sid, package: s?.package, agentVer: s?.agentVer, caps: s?.caps ?? null, startupHooks: s?.startupHooks ?? null, host: { bodyMaxBytes: MAX_BODY_BYTES, autoAntiDebug: autoAntiDebugEnabled(), preArmPackages: settings.startup.packages } }; } }, -{ name: 'settings', description: 'Read or patch daemon settings. action:"get" returns the live settings; action:"patch" merges ONLY the sections present in patch (capture + families, ui, artifacts, startup) and persists them. startup is the host-side pre-arm applied to every NEW session at hello: startup.antiDebug (default false) + startup.module + startup.extraTargets + startup.packages (empty = all). Its default plan is ptrace only, because neutralizing access/faccessat during initialization kills apps (measured); widenAfterMs + widenTargets install those LATER, on the settled process, without another command. Enabling this makes every path check in the app fail - that is the point, but it is per-target, not a default.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['get', 'patch'] }, patch: { type: 'object' } }, required: ['action'] }, handler: async (a) => { +{ name: 'settings', description: 'Get or patch Host settings through the same persisted-and-applied service as the panel. A patch waits for per-target capture results; persisted:true with ok:false means the config was saved but target application failed. Retention changes do not delete evidence. action:maintenance previews current retention by default; dryRun:false requires confirm:true and explicitly deletes old/over-budget data. Startup settings apply to future hello, not already installed startup hooks.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['get', 'patch', 'maintenance'] }, patch: { type: 'object' }, dryRun: { type: 'boolean' }, confirm: { type: 'boolean' } }, required: ['action'] }, handler: async (a) => { if (a.action === 'get') return { ok: true, settings, autoAntiDebug: autoAntiDebugEnabled() }; - if (a.action !== 'patch') return { ok: false, error: 'action must be get|patch' }; - const applied = mergeSettings(a.patch ?? {}); - saveSettings(); - return { ok: true, applied, settings, autoAntiDebug: autoAntiDebugEnabled() }; + if (a.action === 'maintenance') return maintainData(a); + if (a.action !== 'patch') return { ok: false, error: 'action must be get|patch|maintenance' }; + return patchSettings(a.patch ?? {}); } }, { name: 'native_look', description: 'The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with the NEWEST hit by default: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from that same hit, and retained.total says how many numbered hits are still stored. Pass seq for one earlier hit, or beforeSeq plus limit (1..50) to page older hits; nextBeforeSeq is the cursor. Do not re-run the operation to recover an earlier call. argIndex rewrites an argument and is not a filter. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name.', inputSchema: { type: 'object', properties: { session: S, action: { type: 'string', enum: ['arm', 'read', 'stop'] }, hookId: N, seq: N, beforeSeq: N, limit: N, mode: { type: 'string', enum: ['got', 'inline', 'sites', 'vtable'] }, module: S, symbol: S, addr: S, confirm: { type: 'boolean' }, mem: S, backtrace: { type: 'boolean' }, hard: { type: 'boolean' }, maxEvents:N, sampleEvery:N, tid:N, returnAddress:S, traceInsns: N, traceFrom: S, traceWatch:S }, required: ['action'] }, handler: async (a) => { const sid = pickSid(a.session); @@ -357,7 +359,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h { name: 'dex_coverage', description: '方法恢复率报告 — per-method state (native/abstract/present/extracted) + recovery rate over a dumped dex', inputSchema: { type: 'object', properties: { b64: S, sha: S }, required: [] }, handler: async (a) => { const buf = await dumpBuf(a); return analyzeCoverage(buf, parseDex(buf)); } }, { name: 'dump_all_dex', description: '单进程 dump 已加载 DEX(ART 枚举 + SHA-256 去重)。不会冷启动、不会扫同包其它进程、不会抑制捕获布防。产品「一键脱壳」请用 unpack_package。', inputSchema: { type: 'object', properties: { session: S } }, handler: async (a) => { const sid = pickSid(a.session); if (!sid) throw new Error('no session'); return dumpAllDex(sid); } }, { name: 'unpack_package', description: '产品一键脱壳:按包冷启动(可关)、抑制本包自动布防防加固闪退、扫该包全部在线进程、去重打 zip。返回 didSkipAutoArm / captureNote。不等于 dump_all_dex。', inputSchema: { type: 'object', properties: { package: S, session: S, launch: { type: 'boolean' }, forceRestart: { type: 'boolean' } } }, handler: async (a) => runUnpackBundle({ package: a.package, session: a.session, launch: a.launch !== false, forceRestart: a.forceRestart === true }) }, - { name: 'dex_recover', description: 'Recover extracted CodeItems from a restored snapshot into a base dex + rebuild (baseSha/baseB64 + restoredSha/restoredB64)', inputSchema: { type: 'object', properties: { baseB64: S, baseSha: S, restoredB64: S, restoredSha: S } }, handler: async (a) => { const base = await dumpBuf({ b64: a.baseB64, sha: a.baseSha }); const restored = await dumpBuf({ b64: a.restoredB64, sha: a.restoredSha }); const pd = parseDex(base); const { captures: caps, report } = recoverFromSnapshots(base, restored, pd); const rb = rebuildStandardDex(base, caps); const outSha = createHash('sha256').update(rb.dex).digest('hex'); const path = join(CAPTURES, `${outSha.slice(0, 16)}.dex`); if (!existsSync(path)) writeFileSync(path, rb.dex); const meta: DumpMeta = { sha256: outSha, size: rb.dex.length, source: 'dex-recover', addr: '0', tag: 'recovered', sessionId: '', package: '', capturedAt: Date.now(), path, kind: 'dex' }; rememberDump(meta); return { ...report, injected: rb.injected, sha256: outSha }; } }, + { name: 'dex_recover', description: 'Recover extracted CodeItems from a restored snapshot into a base dex + rebuild (baseSha/baseB64 + restoredSha/restoredB64)', inputSchema: { type: 'object', properties: { baseB64: S, baseSha: S, restoredB64: S, restoredSha: S } }, handler: async (a) => { const base = await dumpBuf({ b64: a.baseB64, sha: a.baseSha }); const restored = await dumpBuf({ b64: a.restoredB64, sha: a.restoredSha }); const pd = parseDex(base); const { captures: caps, report } = recoverFromSnapshots(base, restored, pd); const rb = rebuildStandardDex(base, caps); const outSha = createHash('sha256').update(rb.dex).digest('hex'); const path = captureFile(`${outSha.slice(0, 16)}.dex`); if (!existsSync(path)) writeFileSync(path, rb.dex); const meta: DumpMeta = { sha256: outSha, size: rb.dex.length, source: 'dex-recover', addr: '0', tag: 'recovered', sessionId: '', package: '', capturedAt: Date.now(), path, kind: 'dex' }; rememberDump(meta); return { ...report, injected: rb.injected, sha256: outSha }; } }, // ---- axis 3: everything the AI needs to drive a reversing session ---- { name: 'trigger', description: 'Actively load a class (level 1) and invoke a safe static no-arg method (level 3) to force code paths — a trigger source for unpacking', inputSchema: { type: 'object', properties: { session: S, class: S, method: S, level: N }, required: ['class'] }, handler: (a) => agentCmd(a.session, 'trigger', { className: a.class, method: a.method ?? '', level: Number(a.level ?? 1) }, 20_000) }, { name: 'qbdi_trace', description: 'QBDI instruction-level dynamic trace of a native function (per-instruction disassembly + return value), invoked with up to 8 unsigned integer/pointer args. Name the target EITHER as symLib+symbol (an exported symbol) OR as addr (absolute hex): the interesting functions in a stripped/obfuscated library are frequently not exported at all — libjdg registers its dispatcher through RegisterNatives, so its address only comes from the static method table or a backtrace. QBDI itself is loaded in the target with dlopen("libQBDI.so"), so push that library and load it first when the target does not ship it.', inputSchema: { type: 'object', properties: { session: S, symLib: S, symbol: S, addr: S, args: { type: 'array' } }, required: ['session'] }, handler: (a) => { if (!a.addr && (!a.symLib || !a.symbol)) throw new Error('qbdi_trace needs symLib+symbol or addr'); return agentCmd(a.session, 'qbdi_trace', { symLib: a.symLib ?? '', symbol: a.symbol ?? '', addr: a.addr ?? '', args: (a.args ?? []).map((v: any) => String(v)).join(',') }, 30_000); } }, @@ -433,7 +435,8 @@ export async function handleMcp(reqBody: string, res: ServerResponse, opts?: { p ? { ...(out as object), code: classifyError((out as any).error ?? (out as any).message ?? '') } : out; if (t.raw) return reply(coded); - return reply({ content: [{ type: 'text', text: JSON.stringify(coded, null, 2) }] }); + return reply({ content: [{ type: 'text', text: JSON.stringify(coded, null, 2) }], + ...((coded as any)?.ok === false ? { isError: true } : {}) }); } catch (e) { return reply({ content: [{ type: 'text', text: JSON.stringify(errorPayload(e)) }], isError: true }); } } return reply(undefined, { code: -32601, message: `method not found: ${msg.method}` }); diff --git a/daemon/src/scope_list.ts b/daemon/src/scope_list.ts index e94bc87..0d0fd35 100644 --- a/daemon/src/scope_list.ts +++ b/daemon/src/scope_list.ts @@ -1,334 +1,365 @@ -// The web switcher lists the packages checked in the phone's injection scope -// (/data/adb/adh/scope.json). That file is root-only; adb is how the host reads it. -// Display names come from each base APK's manifest (aapt), cached per package. -import { execFile } from 'node:child_process'; -import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir, homedir } from 'node:os'; -import { join } from 'node:path'; -import { promisify } from 'node:util'; -import { crc32 } from 'node:zlib'; - -const execFileP = promisify(execFile); -const SCOPE_PATH = '/data/adb/adh/scope.json'; -const MANAGER_PKG = 'com.adh.manager'; -const CACHE_MS = 3000; - -export interface ScopedApp { package: string; label: string } - -export function parseScopePackages(raw: string): string[] { - const start = raw.indexOf('{'); - const end = raw.lastIndexOf('}'); - const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); - if (!text) return []; - const obj = JSON.parse(text) as { packages?: unknown }; - if (!Array.isArray(obj.packages)) throw new Error('scope JSON has no packages array'); - const out: string[] = []; - for (const item of obj.packages) { - const pkg = String(item ?? '').trim(); - if (!pkg || pkg === MANAGER_PKG || out.includes(pkg)) continue; - out.push(pkg); - } - return out; -} - -/** aapt `dump badging` → the launcher name. Prefer a zh label when one is present. */ -export function applicationLabel(badging: string): string { - const lines = badging.split(/\r?\n/); - const pick = (prefix: string) => { - const line = lines.find(l => l.startsWith(prefix)); - const matched = line?.match(/:'(.*)'\s*$/); - return matched ? matched[1].replace(/\\'/g, "'") : ''; - }; - return pick('application-label-zh') || pick('application-label:') || ''; -} - -let cache: { at: number; packages: string[]; error: string | null } | null = null; -// The job's value is the label write, not the label: `resolveLabel` is consumed inside the .then. -const labelJobs = new Map>(); - -function adbBase(): string[] { - const serial = process.env.ANDROID_SERIAL || process.env.ADH_SERIAL || ''; - return serial ? ['-s', serial] : []; -} - -async function adbShell(command: string): Promise { - const { stdout } = await execFileP('adb', [...adbBase(), 'shell', command], { - timeout: 15000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, - }); - return String(stdout ?? ''); -} - -async function adbOut(command: string): Promise { - const { stdout } = await execFileP('adb', [...adbBase(), 'exec-out', command], { - timeout: 30000, windowsHide: true, maxBuffer: 80 * 1024 * 1024, encoding: 'buffer', - }); - return stdout as Buffer; -} - -function findAapt(): string | null { - const root = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME - || join(homedir(), 'AppData', 'Local', 'Android', 'Sdk'); - const tools = join(root, 'build-tools'); - if (!existsSync(tools)) return null; - const versions = readdirSync(tools).sort().reverse(); - for (const version of versions) { - const exe = join(tools, version, process.platform === 'win32' ? 'aapt.exe' : 'aapt'); - if (existsSync(exe)) return exe; - } - return null; -} - -function storedZip(files: { name: string; data: Buffer }[]): Buffer { - const locals: Buffer[] = []; - const central: Buffer[] = []; - let offset = 0; - for (const file of files) { - const name = Buffer.from(file.name); - const crc = crc32(file.data) >>> 0; - const local = Buffer.alloc(30); - local.writeUInt32LE(0x04034b50, 0); - local.writeUInt16LE(20, 4); - local.writeUInt32LE(crc, 14); - local.writeUInt32LE(file.data.length, 18); - local.writeUInt32LE(file.data.length, 22); - local.writeUInt16LE(name.length, 26); - const cen = Buffer.alloc(46); - cen.writeUInt32LE(0x02014b50, 0); - cen.writeUInt16LE(20, 4); - cen.writeUInt16LE(20, 6); - cen.writeUInt32LE(crc, 16); - cen.writeUInt32LE(file.data.length, 20); - cen.writeUInt32LE(file.data.length, 24); - cen.writeUInt16LE(name.length, 28); - cen.writeUInt32LE(offset, 42); - locals.push(local, name, file.data); - central.push(cen, name); - offset += local.length + name.length + file.data.length; - } - const centralBuf = Buffer.concat(central); - const end = Buffer.alloc(22); - end.writeUInt32LE(0x06054b50, 0); - end.writeUInt16LE(files.length, 8); - end.writeUInt16LE(files.length, 10); - end.writeUInt32LE(centralBuf.length, 12); - end.writeUInt32LE(offset, 16); - return Buffer.concat([...locals, centralBuf, end]); -} - -async function resolveLabel(pkg: string): Promise { - const aapt = findAapt(); - if (!aapt) return pkg; - const listed = await adbShell(`pm path ${pkg}`); - const lines = listed.split(/\r?\n/).map(s => s.trim()).filter(s => s.startsWith('package:')); - const apk = lines.find(s => s.endsWith('/base.apk')) ?? lines[0]; - if (!apk) return pkg; - const path = apk.slice('package:'.length).replace(/'/g, ''); - const quoted = `'${path}'`; - const manifest = await adbOut(`su -c "unzip -p ${quoted} AndroidManifest.xml"`); - const arsc = await adbOut(`su -c "unzip -p ${quoted} resources.arsc"`); - if (manifest.length < 8 || arsc.length < 8) return pkg; - const dir = mkdtempSync(join(tmpdir(), 'adh-label-')); - try { - const zipPath = join(dir, 'base.apk'); - writeFileSync(zipPath, storedZip([ - { name: 'AndroidManifest.xml', data: manifest }, - { name: 'resources.arsc', data: arsc }, - ])); - const { stdout } = await execFileP(aapt, ['dump', 'badging', zipPath], { - timeout: 20000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, - }); - return applicationLabel(String(stdout ?? '')) || pkg; - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - -const resolvedLabels = new Map(); - -/** Names already known. A package with no name yet is still listed; the lookup fills in later. */ -export function scopeSwitcherApps(packages: string[], labels: ReadonlyMap = resolvedLabels): ScopedApp[] { - return packages.map(pkg => ({ package: pkg, label: labels.get(pkg) || pkg })); -} - -function startLabel(pkg: string): void { - if (resolvedLabels.has(pkg) || labelJobs.has(pkg)) return; - const job = resolveLabel(pkg).then(label => { - resolvedLabels.set(pkg, label || pkg); - }).catch(() => { - resolvedLabels.set(pkg, pkg); - }); - labelJobs.set(pkg, job); -} - -// The agent dials 127.0.0.1 on the phone. That only reaches this daemon while -// `adb reverse` is in place, and the tunnel disappears on USB reconnect. -let reverseBusy = false; -let reverseState = ''; -export function ensureAdbReverse(ports: number[], log: (line: string) => void): void { - if (reverseBusy || !ports.length) return; - reverseBusy = true; - const args = adbBase(); - const finish = (state: string, line: string) => { - if (state !== reverseState) { - reverseState = state; - log(line); - } - reverseBusy = false; - }; - execFile('adb', [...args, 'get-state'], { timeout: 4000, windowsHide: true }, (err, stdout) => { - if (err || String(stdout ?? '').trim() !== 'device') { - finish('no-device', 'adb reverse: 没有在线设备,目标进程连不上本机'); - return; - } - let left = ports.length; - let failed = ''; - for (const port of ports) { - execFile('adb', [...args, 'reverse', `tcp:${port}`, `tcp:${port}`], { timeout: 8000, windowsHide: true }, (e) => { - if (e && !failed) failed = e instanceof Error ? e.message.split('\n')[0] : String(e); - if (--left > 0) return; - if (failed) finish('fail', `adb reverse 失败: ${failed.slice(0, 180)}`); - else finish('ok', `adb reverse: ${ports.map(p => 'tcp:' + p).join(' ')} → 本机`); - }); - } - }); -} - -/** Cached allowlist packages only — never merge capture-disk history into this list. */ -export function cachedScopePackages(): string[] { - return cache?.packages ? [...cache.packages] : []; -} - -/** - * Pure rule: may the Host auto-arm capture for this session? - * - * - `entry === 'jni_onload'` is the self-load path (the sandbox dlopens the agent): always - * allowed, because 模拟注入 targets are usually not in scope.json. - * - a scope that was never read successfully fails open, so Zygisk sessions still arm. - * - otherwise the package must be in the checked scope list. - * - * This used to special-case the sandbox PACKAGE NAME, which put a target's identity inside the - * daemon; the red-line gate could not see it (it only scanned C/C++ in the daemon tree). The - * agent already reports HOW it was loaded, so keying on that is both target-agnostic and truer: - * any process that loaded the agent itself is a deliberate self-injection. - */ -export function autoArmAllowed( - pkg: string, - entry: string | undefined, - scope: { packages: string[]; error: string | null } | null, -): boolean { - if (!pkg || pkg === '?') return false; - if (entry === 'jni_onload') return true; - if (!scope) return true; - if (scope.error && scope.packages.length === 0) return true; - return scope.packages.includes(pkg); -} - -/** Whether Host should auto-arm capture for this package. */ -export function shouldAutoArmPackage(pkg: string, entry?: string): boolean { - return autoArmAllowed(pkg, entry, cache); -} - -/** Packages currently checked on the attached phone, with launcher names. */ -export async function scopedApps(now = Date.now()): Promise<{ apps: ScopedApp[]; error: string | null }> { - if (!cache || now - cache.at >= CACHE_MS) { - try { - const stdout = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); - cache = { at: now, packages: parseScopePackages(stdout), error: null }; - } catch (e) { - const message = e instanceof Error ? e.message : String(e); - // A failed read must not wipe the list the page is already showing. - cache = { at: now, packages: cache?.packages ?? [], error: message.split('\n')[0].slice(0, 240) }; - } - } - for (const pkg of cache.packages) startLabel(pkg); - // Switcher truth = scope.json only. Capture history on disk must not invent checked apps. - return { apps: scopeSwitcherApps(cache.packages), error: cache.error }; -} - -// --- scope write (host = the AI/operator channel) ------------------------------------------------ -// The Zygisk companion reads scope.json at process specialization, so a package added here is only -// injected after its next cold start. The device daemon owns the file at runtime; writing it through -// adb+su is the host-side equivalent of the Manager switch and keeps "analyze any app" scriptable. - -const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/; - -export interface ScopeFile { packages: string[]; version: number; mode: string; error: string | null } - -/** Full scope.json (packages + version/mode), read through root. Never throws: errors are reported. */ -export async function readScopeFile(): Promise { - try { - const raw = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); - const start = raw.indexOf('{'); - const end = raw.lastIndexOf('}'); - const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); - const obj = text ? JSON.parse(text) as { packages?: unknown; version?: unknown; mode?: unknown } : {}; - return { - packages: parseScopePackages(raw), - version: Number(obj.version) || 2, - mode: typeof obj.mode === 'string' && obj.mode ? obj.mode : 'allowlist', - error: null, - }; - } catch (e) { - return { packages: [], version: 2, mode: 'allowlist', error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; - } -} - -/** Pure merge: `add` wins over `remove`? No — an explicit remove in the same call wins. */ -export function mergeScope(current: string[], op: { add?: unknown[]; remove?: unknown[] }): string[] { - const clean = (list: unknown[] | undefined) => (list ?? []) - .map((p) => String(p ?? '').trim()) - .filter((p) => PKG_RE.test(p) && p !== MANAGER_PKG); - const out = new Set(current.filter((p) => PKG_RE.test(p))); - for (const p of clean(op.add)) out.add(p); - for (const p of clean(op.remove)) out.delete(p); - return [...out]; -} - -export async function packageInstalled(pkg: string): Promise { - if (!PKG_RE.test(pkg)) return false; - try { - const out = await adbShell(`pm path ${pkg}`); - return /^package:/m.test(out); - } catch { - return false; - } -} - -/** - * Replace the allowlist. Read back after writing: a silent half-write would mean the next cold start - * is not injected and the analysis then looks like "the app refused the agent" (a false negative we - * cannot afford). The file's SELinux label is part of the write, not an afterthought. - */ -export async function writeScopePackages( - packages: string[], - meta: { version?: number; mode?: string } = {}, -): Promise<{ ok: boolean; packages: string[]; error?: string }> { - const clean = [...new Set(packages.map((p) => p.trim()).filter((p) => PKG_RE.test(p)))]; - const body = `${JSON.stringify({ version: meta.version ?? 2, mode: meta.mode ?? 'allowlist', packages: clean }, null, 2)}\n`; - const dir = mkdtempSync(join(tmpdir(), 'adh-scope-')); - const local = join(dir, 'scope.json'); - try { - writeFileSync(local, body, 'utf8'); - await execFileP('adb', [...adbBase(), 'push', local, '/data/local/tmp/adh-scope.json'], { - timeout: 20000, windowsHide: true, maxBuffer: 1024 * 1024, - }); - await adbShell("su -c 'cp /data/local/tmp/adh-scope.json /data/adb/adh/scope.json'"); - await adbShell("su -c 'chown root:root /data/adb/adh/scope.json && chmod 644 /data/adb/adh/scope.json'"); - // Label is explicit: `cp` may otherwise inherit the temp file's label and the companion's read - // then fails closed (no injection, no error the operator can see). - await adbShell("su -c 'chcon u:object_r:adb_data_file:s0 /data/adb/adh/scope.json'"); - await adbShell("rm -f /data/local/tmp/adh-scope.json"); - const back = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); - const got = parseScopePackages(back); - if (JSON.stringify(got) !== JSON.stringify(clean)) { - return { ok: false, packages: clean, error: `scope write did not stick (wrote ${clean.length}, read back ${got.length})` }; - } - cache = { at: Date.now(), packages: got, error: null }; - return { ok: true, packages: got }; - } catch (e) { - return { ok: false, packages: clean, error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; - } finally { - try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp cleanup only */ } - } -} - +// The web switcher lists the packages checked in the phone's injection scope +// (/data/adb/adh/scope.json). That file is root-only; adb is how the host reads it. +// Display names come from each base APK's manifest (aapt), cached per package. +import { execFile } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir, homedir } from 'node:os'; +import { join } from 'node:path'; +import { isDeepStrictEqual, promisify } from 'node:util'; +import { crc32 } from 'node:zlib'; + +const execFileP = promisify(execFile); +const SCOPE_PATH = '/data/adb/adh/scope.json'; +const MANAGER_PKG = 'com.adh.manager'; +const CACHE_MS = 3000; + +export interface ScopedApp { package: string; label: string } + +export function parseScopePackages(raw: string): string[] { + const start = raw.indexOf('{'); + const end = raw.lastIndexOf('}'); + const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); + if (!text) return []; + const obj = JSON.parse(text) as { packages?: unknown }; + if (!Array.isArray(obj.packages)) throw new Error('scope JSON has no packages array'); + const out: string[] = []; + for (const item of obj.packages) { + const pkg = String(item ?? '').trim(); + if (!pkg || pkg === MANAGER_PKG || out.includes(pkg)) continue; + out.push(pkg); + } + return out; +} + +/** aapt `dump badging` → the launcher name. Prefer a zh label when one is present. */ +export function applicationLabel(badging: string): string { + const lines = badging.split(/\r?\n/); + const pick = (prefix: string) => { + const line = lines.find(l => l.startsWith(prefix)); + const matched = line?.match(/:'(.*)'\s*$/); + return matched ? matched[1].replace(/\\'/g, "'") : ''; + }; + return pick('application-label-zh') || pick('application-label:') || ''; +} + +let cache: { at: number; packages: string[]; error: string | null } | null = null; +// The job's value is the label write, not the label: `resolveLabel` is consumed inside the .then. +const labelJobs = new Map>(); + +function adbBase(): string[] { + const serial = process.env.ANDROID_SERIAL || process.env.ADH_SERIAL || ''; + return serial ? ['-s', serial] : []; +} + +async function adbShell(command: string): Promise { + const { stdout } = await execFileP('adb', [...adbBase(), 'shell', command], { + timeout: 15000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, + }); + return String(stdout ?? ''); +} + +async function adbOut(command: string): Promise { + const { stdout } = await execFileP('adb', [...adbBase(), 'exec-out', command], { + timeout: 30000, windowsHide: true, maxBuffer: 80 * 1024 * 1024, encoding: 'buffer', + }); + return stdout as Buffer; +} + +function findAapt(): string | null { + const root = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME + || join(homedir(), 'AppData', 'Local', 'Android', 'Sdk'); + const tools = join(root, 'build-tools'); + if (!existsSync(tools)) return null; + const versions = readdirSync(tools).sort().reverse(); + for (const version of versions) { + const exe = join(tools, version, process.platform === 'win32' ? 'aapt.exe' : 'aapt'); + if (existsSync(exe)) return exe; + } + return null; +} + +function storedZip(files: { name: string; data: Buffer }[]): Buffer { + const locals: Buffer[] = []; + const central: Buffer[] = []; + let offset = 0; + for (const file of files) { + const name = Buffer.from(file.name); + const crc = crc32(file.data) >>> 0; + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(file.data.length, 18); + local.writeUInt32LE(file.data.length, 22); + local.writeUInt16LE(name.length, 26); + const cen = Buffer.alloc(46); + cen.writeUInt32LE(0x02014b50, 0); + cen.writeUInt16LE(20, 4); + cen.writeUInt16LE(20, 6); + cen.writeUInt32LE(crc, 16); + cen.writeUInt32LE(file.data.length, 20); + cen.writeUInt32LE(file.data.length, 24); + cen.writeUInt16LE(name.length, 28); + cen.writeUInt32LE(offset, 42); + locals.push(local, name, file.data); + central.push(cen, name); + offset += local.length + name.length + file.data.length; + } + const centralBuf = Buffer.concat(central); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(files.length, 8); + end.writeUInt16LE(files.length, 10); + end.writeUInt32LE(centralBuf.length, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, centralBuf, end]); +} + +async function resolveLabel(pkg: string): Promise { + const aapt = findAapt(); + if (!aapt) return pkg; + const listed = await adbShell(`pm path ${pkg}`); + const lines = listed.split(/\r?\n/).map(s => s.trim()).filter(s => s.startsWith('package:')); + const apk = lines.find(s => s.endsWith('/base.apk')) ?? lines[0]; + if (!apk) return pkg; + const path = apk.slice('package:'.length).replace(/'/g, ''); + const quoted = `'${path}'`; + const manifest = await adbOut(`su -c "unzip -p ${quoted} AndroidManifest.xml"`); + const arsc = await adbOut(`su -c "unzip -p ${quoted} resources.arsc"`); + if (manifest.length < 8 || arsc.length < 8) return pkg; + const dir = mkdtempSync(join(tmpdir(), 'adh-label-')); + try { + const zipPath = join(dir, 'base.apk'); + writeFileSync(zipPath, storedZip([ + { name: 'AndroidManifest.xml', data: manifest }, + { name: 'resources.arsc', data: arsc }, + ])); + const { stdout } = await execFileP(aapt, ['dump', 'badging', zipPath], { + timeout: 20000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, + }); + return applicationLabel(String(stdout ?? '')) || pkg; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const resolvedLabels = new Map(); + +/** Names already known. A package with no name yet is still listed; the lookup fills in later. */ +export function scopeSwitcherApps(packages: string[], labels: ReadonlyMap = resolvedLabels): ScopedApp[] { + return packages.map(pkg => ({ package: pkg, label: labels.get(pkg) || pkg })); +} + +function startLabel(pkg: string): void { + if (resolvedLabels.has(pkg) || labelJobs.has(pkg)) return; + const job = resolveLabel(pkg).then(label => { + resolvedLabels.set(pkg, label || pkg); + }).catch(() => { + resolvedLabels.set(pkg, pkg); + }); + labelJobs.set(pkg, job); +} + +// The agent dials 127.0.0.1 on the phone. That only reaches this daemon while +// `adb reverse` is in place, and the tunnel disappears on USB reconnect. +let reverseBusy = false; +let reverseState = ''; +export function ensureAdbReverse(ports: number[], log: (line: string) => void): void { + if (reverseBusy || !ports.length) return; + reverseBusy = true; + const args = adbBase(); + const finish = (state: string, line: string) => { + if (state !== reverseState) { + reverseState = state; + log(line); + } + reverseBusy = false; + }; + execFile('adb', [...args, 'get-state'], { timeout: 4000, windowsHide: true }, (err, stdout) => { + if (err || String(stdout ?? '').trim() !== 'device') { + finish('no-device', 'adb reverse: 没有在线设备,目标进程连不上本机'); + return; + } + let left = ports.length; + let failed = ''; + for (const port of ports) { + execFile('adb', [...args, 'reverse', `tcp:${port}`, `tcp:${port}`], { timeout: 8000, windowsHide: true }, (e) => { + if (e && !failed) failed = e instanceof Error ? e.message.split('\n')[0] : String(e); + if (--left > 0) return; + if (failed) finish('fail', `adb reverse 失败: ${failed.slice(0, 180)}`); + else finish('ok', `adb reverse: ${ports.map(p => 'tcp:' + p).join(' ')} → 本机`); + }); + } + }); +} + +/** Cached allowlist packages only — never merge capture-disk history into this list. */ +export function cachedScopePackages(): string[] { + return cache?.packages ? [...cache.packages] : []; +} + +/** + * Pure rule: may the Host auto-arm capture for this session? + * + * - `entry === 'jni_onload'` is the self-load path (the sandbox dlopens the agent): always + * allowed, because 模拟注入 targets are usually not in scope.json. + * - a scope that was never read successfully fails open, so Zygisk sessions still arm. + * - otherwise the package must be in the checked scope list. + * + * This used to special-case the sandbox PACKAGE NAME, which put a target's identity inside the + * daemon; the red-line gate could not see it (it only scanned C/C++ in the daemon tree). The + * agent already reports HOW it was loaded, so keying on that is both target-agnostic and truer: + * any process that loaded the agent itself is a deliberate self-injection. + */ +export function autoArmAllowed( + pkg: string, + entry: string | undefined, + scope: { packages: string[]; error: string | null } | null, +): boolean { + if (!pkg || pkg === '?') return false; + if (entry === 'jni_onload') return true; + if (!scope) return true; + if (scope.error && scope.packages.length === 0) return true; + return scope.packages.includes(pkg); +} + +/** Whether Host should auto-arm capture for this package. */ +export function shouldAutoArmPackage(pkg: string, entry?: string): boolean { + return autoArmAllowed(pkg, entry, cache); +} + +/** Packages currently checked on the attached phone, with launcher names. */ +export async function scopedApps(now = Date.now()): Promise<{ apps: ScopedApp[]; error: string | null }> { + if (!cache || now - cache.at >= CACHE_MS) { + try { + const stdout = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); + cache = { at: now, packages: parseScopePackages(stdout), error: null }; + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + // A failed read must not wipe the list the page is already showing. + cache = { at: now, packages: cache?.packages ?? [], error: message.split('\n')[0].slice(0, 240) }; + } + } + for (const pkg of cache.packages) startLabel(pkg); + // Switcher truth = scope.json only. Capture history on disk must not invent checked apps. + return { apps: scopeSwitcherApps(cache.packages), error: cache.error }; +} + +// --- scope write (host = the AI/operator channel) ------------------------------------------------ +// The Zygisk companion reads scope.json at process specialization, so a package added here is only +// injected after its next cold start. The device daemon owns the file at runtime; writing it through +// adb+su is the host-side equivalent of the Manager switch and keeps "analyze any app" scriptable. + +const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/; + +export interface ScopeFile { packages: string[]; version: number; mode: string; error: string | null } + +/** Keep the complete document: phone policy and future fields are not Host-owned. */ +export function parseScopeDocument(raw: string): Record { + const start = raw.indexOf('{'), end = raw.lastIndexOf('}'); + const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); + const doc = JSON.parse(text); + if (!doc || typeof doc !== 'object' || Array.isArray(doc) || !Array.isArray(doc.packages)) { + throw new Error('scope JSON has no packages array'); + } + return doc; +} + +export function scopeWithPackages(raw: string, packages: string[], meta: { version?: number; mode?: string } = {}) { + const doc = parseScopeDocument(raw); + return { + version: meta.version ?? 2, mode: meta.mode ?? 'allowlist', ...doc, + packages: [...new Set(packages.map(p => p.trim()).filter(p => PKG_RE.test(p) && p !== MANAGER_PKG))], + }; +} + +export interface ScopeIO { read(): Promise; write(body: string): Promise } +const scopeIO: ScopeIO = { + read: () => adbShell(`su -c 'cat ${SCOPE_PATH}'`), + async write(body) { + const dir = mkdtempSync(join(tmpdir(), 'adh-scope-')); + const local = join(dir, 'scope.json'); + const token = randomUUID(); + const uploaded = `/data/local/tmp/adh-scope-${token}.json`; + const staged = `/data/adb/adh/.scope-${token}.tmp`; + try { + writeFileSync(local, body, 'utf8'); + await execFileP('adb', [...adbBase(), 'push', local, uploaded], { + timeout: 20000, windowsHide: true, maxBuffer: 1024 * 1024, + }); + // Set ownership/label BEFORE the atomic rename; never expose a truncated scope file. + await adbShell(`su -c 'cp ${uploaded} ${staged} && chown root:root ${staged} && chmod 644 ${staged} && chcon u:object_r:adb_data_file:s0 ${staged} && mv -f ${staged} ${SCOPE_PATH}'`); + } finally { + try { await adbShell(`su -c 'rm -f ${uploaded} ${staged}'`); } catch { /* staging only */ } + rmSync(dir, { recursive: true, force: true }); + } + }, +}; + +/** Full scope.json (packages + version/mode), read through root. Never throws: errors are reported. */ +export async function readScopeFile(): Promise { + try { + const raw = await adbShell(`su -c 'cat ${SCOPE_PATH}'`); + const start = raw.indexOf('{'); + const end = raw.lastIndexOf('}'); + const text = (start >= 0 && end > start ? raw.slice(start, end + 1) : raw).trim(); + const obj = text ? JSON.parse(text) as { packages?: unknown; version?: unknown; mode?: unknown } : {}; + return { + packages: parseScopePackages(raw), + version: Number(obj.version) || 2, + mode: typeof obj.mode === 'string' && obj.mode ? obj.mode : 'allowlist', + error: null, + }; + } catch (e) { + return { packages: [], version: 2, mode: 'allowlist', error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; + } +} + +/** Pure merge: `add` wins over `remove`? No — an explicit remove in the same call wins. */ +export function mergeScope(current: string[], op: { add?: unknown[]; remove?: unknown[] }): string[] { + const clean = (list: unknown[] | undefined) => (list ?? []) + .map((p) => String(p ?? '').trim()) + .filter((p) => PKG_RE.test(p) && p !== MANAGER_PKG); + const out = new Set(current.filter((p) => PKG_RE.test(p))); + for (const p of clean(op.add)) out.add(p); + for (const p of clean(op.remove)) out.delete(p); + return [...out]; +} + +export async function packageInstalled(pkg: string): Promise { + if (!PKG_RE.test(pkg)) return false; + try { + const out = await adbShell(`pm path ${pkg}`); + return /^package:/m.test(out); + } catch { + return false; + } +} + +/** + * Replace the allowlist. Read back after writing: a silent half-write would mean the next cold start + * is not injected and the analysis then looks like "the app refused the agent" (a false negative we + * cannot afford). The file's SELinux label is part of the write, not an afterthought. + */ +export async function writeScopePackages( + packages: string[], + meta: { version?: number; mode?: string } = {}, + io: ScopeIO = scopeIO, +): Promise<{ ok: boolean; packages: string[]; error?: string }> { + const clean = [...new Set(packages.map((p) => p.trim()).filter((p) => PKG_RE.test(p) && p !== MANAGER_PKG))]; + try { + // Re-read immediately before writing. Missing/corrupt/unreadable input refuses the update. + const next = scopeWithPackages(await io.read(), clean, meta); + await io.write(`${JSON.stringify(next, null, 2)}\n`); + const back = await io.read(); + const got = parseScopePackages(back); + if (!isDeepStrictEqual(parseScopeDocument(back), next)) { + return { ok: false, packages: got, error: 'scope write did not stick: complete document differs (including hook policy)' }; + } + cache = { at: Date.now(), packages: got, error: null }; + return { ok: true, packages: got }; + } catch (e) { + return { ok: false, packages: clean, error: (e instanceof Error ? e.message : String(e)).split('\n')[0].slice(0, 240) }; + } +} diff --git a/daemon/src/service.ts b/daemon/src/service.ts index 209da81..3fbf5f1 100644 --- a/daemon/src/service.ts +++ b/daemon/src/service.ts @@ -1,3 +1,4 @@ +import { captureFile } from './storage.ts'; // service.ts — ADH Daemon service layer: agent-command transport + dump engine + capture ops. // Imported by mcp.ts (MCP handlers) and index.ts (REST routes + agent TCP + boot). // Imports ONLY from state.ts (+ dex.ts / so_select.ts pure layers + dex_index.ts for artifact @@ -11,7 +12,7 @@ import { basename, join } from 'node:path'; import { frameJson, agentSockets, pending, nextCmdId, sessions, dumps, log, rememberDump, captureTimers, captureModules, settings, recentJavaIn, captures, - pushCapture, broadcast, hexToPreview, previewForCapture, classify, categoryOf, capStats, CAPTURES, + pushCapture, broadcast, hexToPreview, previewForCapture, classify, categoryOf, capStats, pruneArtifacts, DATA_DIR, } from './state.ts'; import { shouldAutoArmPackage, scopedApps } from './scope_list.ts'; @@ -611,7 +612,7 @@ export async function dumpOneAppSo(sid: string, base: string, name: string) { const sha = createHash('sha256').update(buf).digest('hex'); const existing = dumps.get(sha); if (existing) return { name, base, saved: true, dedup: true, sha256: sha, size: buf.length, elf: true }; - const path = join(CAPTURES, `${sha.slice(0, 16)}.so`); + const path = captureFile(`${sha.slice(0, 16)}.so`); if (!existsSync(path)) await writeFile(path, buf); const meta: DumpMeta = { sha256: sha, size: buf.length, requestedSize: buf.length, complete: true, @@ -621,7 +622,7 @@ export async function dumpOneAppSo(sid: string, base: string, name: string) { }; rememberDump(meta); broadcast('dump.new', meta); - pruneArtifactsAndIndex(sha); + return { name, base, saved: true, dedup: false, sha256: sha, size: buf.length, elf: true }; } catch (e) { const message = (e as Error).message; @@ -650,7 +651,7 @@ export async function dumpAppSo(sid: string) { modules.push({ name: mod.name, path: mod.path, sha256: sha, size: buf.length, dedup: true }); continue; } - const path = join(CAPTURES, `${sha.slice(0, 16)}.so`); + const path = captureFile(`${sha.slice(0, 16)}.so`); if (!existsSync(path)) await writeFile(path, buf); const meta: DumpMeta = { sha256: sha, size: buf.length, requestedSize: buf.length, complete: true, @@ -659,7 +660,7 @@ export async function dumpAppSo(sid: string) { }; rememberDump(meta); broadcast('dump.new', meta); - pruneArtifactsAndIndex(sha); + dumped++; modules.push({ name: mod.name, path: mod.path, sha256: sha, size: buf.length, dedup: false }); } catch (e) { @@ -697,9 +698,8 @@ export function repairDexHeader(buf: Buffer): { fileSize: number; checksum: stri return { fileSize, checksum: checksum.toString(16).padStart(8, '0'), signature: sig.toString('hex'), magicOk }; } -// Artifact retention, wired to the dex index. Called after a NEW artifact lands (a dedup hit kept -// the file that was already there, so there is nothing to reclaim) and once at boot. Retention -// failing must never break a dump that already succeeded, but it must not be silent either. +// Explicit artifact maintenance, wired to the dex index. Never called by import, startup, +// settings patches or artifact writes. Failures remain observable to the maintenance caller. export function pruneArtifactsAndIndex(protectSha?: string) { try { const r = pruneArtifacts((sha) => { @@ -733,7 +733,7 @@ export async function persistArtifact( const existing = dumps.get(sha); if (existing) return { meta: existing, dedup: true }; const kind = inferKind(buf); - const path = join(CAPTURES, `${sha.slice(0, 16)}.${kind}.bin`); + const path = captureFile(`${sha.slice(0, 16)}.${kind}.bin`); if (!existsSync(path)) await writeFile(path, buf); const meta: DumpMeta = { sha256: sha, size: buf.length, @@ -744,7 +744,7 @@ export async function persistArtifact( }; rememberDump(meta); broadcast('dump.new', meta); - pruneArtifactsAndIndex(sha); // a new file landed: enforce the on-disk budget now + return { meta, dedup: false }; } @@ -782,7 +782,7 @@ export async function dumpRegion(sid: string, addrHex: string, size: number, tag } const s = sessions.get(sid); const kind = inferKind(buf); - const path = join(CAPTURES, `${sha.slice(0, 16)}.${kind}.bin`); + const path = captureFile(`${sha.slice(0, 16)}.${kind}.bin`); if (!existsSync(path)) await writeFile(path, buf); const complete = buf.length === size; const meta: DumpMeta = { @@ -791,7 +791,7 @@ export async function dumpRegion(sid: string, addrHex: string, size: number, tag }; rememberDump(meta); broadcast('dump.new', meta); - pruneArtifactsAndIndex(sha); // a new file landed: enforce the on-disk budget now + return { meta, dedup: false }; } @@ -812,27 +812,21 @@ function recordCaptureHooks(sid: string, r: any) { // Apply the capture.enabled toggle to already-connected sessions. // enabled=false → force-stop hooks everywhere. enabled=true → re-arm only packages that // should auto-arm (scope allowlist / sandbox), using setCapture for a clean drain→stop→start. -export async function applyCaptureEnabled() { - if (!settings.capture.enabled) { - for (const s of sessions.values()) { - if (!s.online) continue; - try { await setCapture(s.sessionId, false); } - catch (e) { log(`[settings] capture_stop 会话 ${s.sessionId} 失败:`, (e as Error).message); } - } - return; - } - try { await scopedApps(); } catch { /* cache may still help */ } - for (const s of sessions.values()) { - if (!s.online) continue; - if (!shouldAutoArmPackage(s.package, s.entry)) continue; - // Skip just-unpacked / in-unpack packages — flipping the global switch must not crash SecNeo. - if (captureArmBlockedReason(s.package)) { - log(`[settings] capture_start skip ${s.sessionId} (unpack protect ${s.package})`); - continue; - } - try { await setCapture(s.sessionId, true); } - catch (e) { log(`[settings] capture_start 会话 ${s.sessionId} 失败:`, (e as Error).message); } - } +export async function applyCaptureEnabled(): Promise<{ + ok: boolean; targets: { session: string; ok: boolean; skipped?: string; error?: string }[]; error?: string; +}> { + const on = settings.capture.enabled; + if (on) { try { await scopedApps(); } catch { /* cache may still help */ } } + const targets = await Promise.all([...sessions.values()].filter(s => s.online).map(async s => { + if (on && !shouldAutoArmPackage(s.package, s.entry)) return { session: s.sessionId, ok: true, skipped: 'outside scope' }; + const blocked = on ? captureArmBlockedReason(s.package) : null; + if (blocked) return { session: s.sessionId, ok: true, skipped: blocked }; + try { + const result = await setCapture(s.sessionId, on); + return { session: s.sessionId, ok: result.ok, ...(!result.ok ? { error: String((result as any).error || (result as any).reply?.error || 'capture operation failed') } : {}) }; + } catch (error) { return { session: s.sessionId, ok: false, error: (error as Error).message }; } + })); + return { ok: targets.every(t => t.ok), targets }; } // ---- capture_start / capture_stop (the tools' one implementation) -------------------------- @@ -1093,6 +1087,8 @@ function captureArmBlockedReason(pkg: string): string | null { } export function startCaptureLoop(sid: string, opts?: { skipArm?: boolean }) { + // Recovery now happens explicitly after module imports; resume above restored IDs. + capSeq = captures.reduce((max, capture) => Math.max(max, Number(capture.id) || 0), capSeq); if (captureTimers.has(sid)) return; // already streaming if (!opts?.skipArm && captureLoopPending.has(sid)) return; const pkgNow = sessions.get(sid)?.package ?? ''; diff --git a/daemon/src/settings_service.ts b/daemon/src/settings_service.ts new file mode 100644 index 0000000..fb5a936 --- /dev/null +++ b/daemon/src/settings_service.ts @@ -0,0 +1,50 @@ +import { applyCaptureEnabled, autoAntiDebugEnabled } from './service.ts'; +import { configStats, mergeSettings, saveSettings, settings } from './state.ts'; + +// Serialize save→publish→apply across MCP and HTTP. A second patch cannot change the +// global settings while the first is still applying them to targets. +let tail: Promise = Promise.resolve(); +export function patchSettings(patch: unknown, applyCapture = applyCaptureEnabled) { + const run = tail.then(async () => { + if (!patch || typeof patch !== 'object' || Array.isArray(patch)) { + return { ok: false, code: 'INVALID_SETTINGS', error: 'settings patch must be an object', persisted: false, applied: [] as string[] }; + } + if (['capture', 'ui', 'artifacts', 'startup'].some(key => Object.hasOwn(patch, key) + && (!(patch as any)[key] || typeof (patch as any)[key] !== 'object' || Array.isArray((patch as any)[key])))) { + return { ok: false, code: 'INVALID_SETTINGS', error: 'settings sections must be objects', persisted: false, applied: [] as string[] }; + } + const candidate = structuredClone(settings); + const applied = mergeSettings(patch, candidate); + if (!applied.length) return { ok: false, code: 'INVALID_SETTINGS', error: 'no supported settings sections', persisted: false, applied }; + try { saveSettings(candidate); } + catch (error) { + return { ok: false, code: 'SETTINGS_PERSIST_FAILED', error: `settings were not saved or applied: ${(error as Error).message}`, persisted: false, applied: [] as string[], settings: structuredClone(settings) }; + } + Object.assign(settings, candidate); + const capture = (patch as Record).capture; + // Output filters apply on ingestion; startup/auto-dump changes apply at the next + // explicit start/hello. A UI-only or retention patch must not re-install hooks. + const needsCaptureApply = typeof capture?.enabled === 'boolean' + || ['cryptoModule', 'fileModule', 'sysModule'].some(key => typeof capture?.[key] === 'string'); + let runtime: Awaited> = { ok: true, targets: [] }; + if (needsCaptureApply) { + try { runtime = await applyCapture(); } + catch (error) { runtime = { ok: false, targets: [], error: (error as Error).message }; } + } + return { + ok: runtime.ok, applied, persisted: true, runtimeApplied: runtime.ok, runtime, + settings: structuredClone(settings), stats: configStats(), autoAntiDebug: autoAntiDebugEnabled(), + deferred: [ ...(applied.includes('startup') ? ['startup:next-hello'] : []), + ...(typeof capture?.autoDumpDex === 'boolean' ? ['autoDumpDex:next-automatic-capture-loop'] : []) ], + maintenanceRequired: applied.includes('artifacts') || !!capture && ['retain', 'maxAgeDays'].some(key => Object.hasOwn(capture, key)), + ...(!runtime.ok ? { code: 'SETTINGS_APPLY_FAILED', error: runtime.error || 'settings saved; some target operations failed' } : {}), + }; + }); + tail = run.catch(() => {}); + return run; +} + +export function settingsHttpStatus(result: { ok: boolean; code?: string }) { + return result.ok ? 200 : result.code === 'SETTINGS_PERSIST_FAILED' ? 500 + : result.code === 'SETTINGS_APPLY_FAILED' ? 502 : 400; +} diff --git a/daemon/src/state.ts b/daemon/src/state.ts index 624a198..b70c7d7 100644 --- a/daemon/src/state.ts +++ b/daemon/src/state.ts @@ -3,12 +3,11 @@ // Imported by everyone. Everything that holds runtime state or is a leaf helper lives here; // functions that issue agent commands (sendCmd/capture loop/unpack/dump) live in service.ts. import net from 'node:net'; +import { atomicWriteJson, storagePaths } from './storage.ts'; import type { IncomingMessage } from 'node:http'; import { mkdirSync, writeFileSync, existsSync, appendFileSync, readFileSync, readdirSync, statSync, unlinkSync, openSync, readSync, closeSync } from 'node:fs'; import { createHash } from 'node:crypto'; -import { fileURLToPath } from 'node:url'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; +import { join } from 'node:path'; import { WebSocketServer, WebSocket } from 'ws'; import { artifactKindOf, artifactSidecarPath, parseArtifactProvenance, planArtifactEviction } from './artifacts.ts'; import type { ArtifactProvenance } from './artifacts.ts'; @@ -16,19 +15,11 @@ import type { ArtifactEntry } from './artifacts.ts'; import { appendCaptureLine, clearAllPersistedCaptures, clearPackagePersistedCaptures, enforcePerPackageRetain, evictPackageFromMemory, listPackageCaptureStats, - loadCapturesFromDisk, pruneCapturesOlderThan, readPackageCapturesJsonl, - trimPackageCapturesFile, + loadCapturesFromDisk, readPackageCapturesJsonl, } from './capture_persist.ts'; import { memCapturePreview } from './native_hook_args.ts'; -const __dirname = dirname(fileURLToPath(import.meta.url)); -// The test runner gives every test FILE its own process (test/run.mjs sets ADH_SKIP_ARTIFACT_LOAD). -// Without a private root they all write the same captures/ and adhd-data/ files; on Windows a second -// writer makes the first fail with a sharing violation, which surfaced as a random test file failing -// at ~2.7s with fewer tests counted. Under the flag everything goes to OS temp instead of the checkout. -const _testRoot = process.env.ADH_SKIP_ARTIFACT_LOAD === '1' ? join(tmpdir(), `adh-test-${process.pid}`) : ''; -export const CAPTURES = _testRoot ? join(_testRoot, 'captures') : join(__dirname, '..', '..', 'captures'); -mkdirSync(CAPTURES, { recursive: true }); +export const CAPTURES = storagePaths.capturesDir; // ---- wire framing (v2.0, WS-D): [u32 len BE][u8 type][payload] ------------- // Control/cmd/cmdResult ride as FRAME_JSON; binary/bulk types reserved for later @@ -222,31 +213,15 @@ export const nextId = () => `s_${(++seq).toString(36)}${Date.now().toString(36). export const nextCmdId = () => `c${(++cmdSeq).toString(36)}`; // ---- event store (session record/replay) --------------------------------- -const _dataRoot = join(__dirname, '..', '..'); -// Where artifacts, the event log, settings and the dex index live. Overridable because this tree is -// worked from a SHARED SMB folder, and that is a bad home for a SQLite database: measured -// 2026-09-30, `adhd-data/dex-index.sqlite` came back SQLITE_CORRUPT while the same tree was open on -// two machines, and on SMB the corrupt file could not even be renamed away from Linux (`mv` → -// "device or resource busy") because the other host still held it. Point ADH_DATA_DIR at local disk -// on any machine sharing this checkout. Default is unchanged for single-machine use. -export const DATA_DIR = process.env.ADH_DATA_DIR ?? (_testRoot ? join(_testRoot, 'adhd-data') : join(_dataRoot, 'adhd-data')); -mkdirSync(DATA_DIR, { recursive: true }); +export const DATA_DIR = storagePaths.dataDir; export const EVENTS_FILE = join(DATA_DIR, 'events.jsonl'); interface Ev { seq: number; ts: number; type: string; data: any } export const events: Ev[] = []; export let evSeq = 0; -try { // replay: load persisted events on startup so a session survives restarts - if (existsSync(EVENTS_FILE)) { - const lines = readFileSync(EVENTS_FILE, 'utf8').split('\n').filter(Boolean).slice(-5000); - let corrupt = 0; - for (const l of lines) { try { const e = JSON.parse(l); events.push(e); if (e.seq > evSeq) evSeq = e.seq; } catch { corrupt++; } } - if (corrupt) log(`[events] replay: ${corrupt}/${lines.length} 行损坏已跳过 (${EVENTS_FILE})`); - } -} catch (e) { log(`[events] replay 失败 (${EVENTS_FILE}) — 从空事件起步:`, (e as Error).message); } export function recordEvent(type: string, data: any) { const e: Ev = { seq: ++evSeq, ts: Date.now(), type, data }; events.push(e); if (events.length > 5000) events.shift(); - try { appendFileSync(EVENTS_FILE, JSON.stringify(e) + '\n'); } + try { mkdirSync(DATA_DIR, { recursive: true }); appendFileSync(EVENTS_FILE, JSON.stringify(e) + '\n'); } catch (err) { log(`[events] 持久化失败 (${EVENTS_FILE}):`, (err as Error).message); } } @@ -290,56 +265,56 @@ export const DEFAULT_SETTINGS: Settings = { }; export let settings: Settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS)); // section-merge (like IDH /api/settings/import): only the segments present in `patch` apply. -export function mergeSettings(patch: any): string[] { +export function mergeSettings(patch: any, target: Settings = settings): string[] { const applied: string[] = []; if (!patch || typeof patch !== 'object') return applied; if (patch.capture && typeof patch.capture === 'object') { const c = patch.capture; - if (typeof c.enabled === 'boolean') settings.capture.enabled = c.enabled; - if (typeof c.autoDumpDex === 'boolean') settings.capture.autoDumpDex = c.autoDumpDex; - if (Number.isFinite(c.retain)) settings.capture.retain = Math.max(50, Math.min(100000, Math.floor(c.retain))); - if (Number.isFinite(c.maxAgeDays)) settings.capture.maxAgeDays = Math.max(0, Math.min(365, Math.floor(c.maxAgeDays))); - if (typeof c.cryptoModule === 'string') settings.capture.cryptoModule = c.cryptoModule.trim(); - if (typeof c.fileModule === 'string') settings.capture.fileModule = c.fileModule.trim(); - if (typeof c.sysModule === 'string') settings.capture.sysModule = c.sysModule.trim(); + if (typeof c.enabled === 'boolean') target.capture.enabled = c.enabled; + if (typeof c.autoDumpDex === 'boolean') target.capture.autoDumpDex = c.autoDumpDex; + if (Number.isFinite(c.retain)) target.capture.retain = Math.max(50, Math.min(100000, Math.floor(c.retain))); + if (Number.isFinite(c.maxAgeDays)) target.capture.maxAgeDays = Math.max(0, Math.min(365, Math.floor(c.maxAgeDays))); + if (typeof c.cryptoModule === 'string') target.capture.cryptoModule = c.cryptoModule.trim(); + if (typeof c.fileModule === 'string') target.capture.fileModule = c.fileModule.trim(); + if (typeof c.sysModule === 'string') target.capture.sysModule = c.sysModule.trim(); if (c.families && typeof c.families === 'object') - for (const k of Object.keys(settings.capture.families)) - if (typeof c.families[k] === 'boolean') settings.capture.families[k] = c.families[k]; + for (const k of Object.keys(target.capture.families)) + if (typeof c.families[k] === 'boolean') target.capture.families[k] = c.families[k]; applied.push('capture'); } if (patch.ui && typeof patch.ui === 'object') { - if (Number.isFinite(patch.ui.displayCap)) settings.ui.displayCap = Math.max(50, Math.min(5000, Math.floor(patch.ui.displayCap))); + if (Number.isFinite(patch.ui.displayCap)) target.ui.displayCap = Math.max(50, Math.min(5000, Math.floor(patch.ui.displayCap))); applied.push('ui'); } if (patch.artifacts && typeof patch.artifacts === 'object') { const a = patch.artifacts; - if (Number.isFinite(a.maxBytes)) settings.artifacts.maxBytes = Math.max(256 * 1024 ** 2, Math.min(512 * 1024 ** 3, Math.floor(a.maxBytes))); - if (Number.isFinite(a.maxAgeDays)) settings.artifacts.maxAgeDays = Math.max(0, Math.min(365, Math.floor(a.maxAgeDays))); + if (Number.isFinite(a.maxBytes)) target.artifacts.maxBytes = Math.max(256 * 1024 ** 2, Math.min(512 * 1024 ** 3, Math.floor(a.maxBytes))); + if (Number.isFinite(a.maxAgeDays)) target.artifacts.maxAgeDays = Math.max(0, Math.min(365, Math.floor(a.maxAgeDays))); applied.push('artifacts'); } if (patch.startup && typeof patch.startup === 'object') { const s = patch.startup; - if (typeof s.antiDebug === 'boolean') settings.startup.antiDebug = s.antiDebug; - if (typeof s.module === 'string') settings.startup.module = s.module.trim() || 'libc.so'; + if (typeof s.antiDebug === 'boolean') target.startup.antiDebug = s.antiDebug; + if (typeof s.module === 'string') target.startup.module = s.module.trim() || 'libc.so'; if (Array.isArray(s.extraTargets)) { // Only symbol names: the return/errno pair is a policy decision made in service.ts, not // something a settings patch can invent. - settings.startup.extraTargets = s.extraTargets + target.startup.extraTargets = s.extraTargets .filter((x: unknown) => typeof x === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(x)) .slice(0, 16); } if (Array.isArray(s.packages)) { // Empty = every package. A non-empty list is the safe form: pre-arming neutralizes path // checks process-wide, so it is a per-target choice, not a daemon-wide default. - settings.startup.packages = s.packages + target.startup.packages = s.packages .filter((x: unknown) => typeof x === 'string' && /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(x)) .slice(0, 32); } // Delayed widening: install the checks that are unsafe during initialization once the app has // settled (see service.ts startupWidenPlan). 0 = off, max 10 minutes. - if (Number.isFinite(s.widenAfterMs)) settings.startup.widenAfterMs = Math.max(0, Math.min(600000, Math.floor(s.widenAfterMs))); + if (Number.isFinite(s.widenAfterMs)) target.startup.widenAfterMs = Math.max(0, Math.min(600000, Math.floor(s.widenAfterMs))); if (Array.isArray(s.widenTargets)) { - settings.startup.widenTargets = s.widenTargets + target.startup.widenTargets = s.widenTargets .filter((x: unknown) => typeof x === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(x)) .slice(0, 8); } @@ -347,22 +322,8 @@ export function mergeSettings(patch: any): string[] { } return applied; } -// Load persisted settings. Fail LOUD: if the file is present but corrupt/unreadable we must not -// silently run on defaults (that masks lost config as "working"). Absent file is normal (defaults). -try { - if (existsSync(SETTINGS_FILE)) mergeSettings(JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'))); -} catch (e) { - log(`[settings] ${SETTINGS_FILE} 载入失败,已回退默认值 — 磁盘上的配置未生效:`, (e as Error).message); -} -// Migrate ONE legacy default: before 2026-10-11 the daemon defaulted sysModule to -// 'libadhdetect.so' — the SANDBOX's mock detector lib, built by tools/build_detect.sh. Nothing -// outside the sandbox ships that name, so a persisted value equal to it can only have come from -// that default (a target-specific choice would be a real lib). Keeping it would make every real -// target report six zero-installs for hooks nobody asked for. fileModule's old default -// ('libjavacore.so') is a genuine Android lib, so it is left alone — only the default changes. -if (settings.capture.sysModule === 'libadhdetect.so') settings.capture.sysModule = ''; // Persist. Throws on failure — callers MUST surface it so the UI never claims "已保存" on a failed write. -export function saveSettings() { writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2)); } +export function saveSettings(next: Settings = settings) { atomicWriteJson(SETTINGS_FILE, next); } // ---- on-disk artifact store -------------------------------------------------------------- // Adopt artifacts that are already on disk into the runtime map. @@ -420,13 +381,17 @@ export function loadArtifactsFromDisk(): { loaded: number; skipped: number; byte // on disk, so a failed delete is reported rather than quietly forgotten. // `onDelete` lets a caller drop related state it owns (the dex index row) without state.ts having to // import the indexer, which would be a cycle (dex_index.ts imports this file). -export function pruneArtifacts(onDelete?: (sha: string) => void, protectSha?: string): { removed: number; bytesFreed: number; remainingBytes: number; kept: number; failed: number } { +export function previewArtifactRetention(protectSha?: string) { const mtimeOf = (p: string) => { try { return Math.round(statSync(p).mtimeMs); } catch { return 0; } }; const entries: ArtifactEntry[] = [...dumps.values()].map((m) => ({ sha256: m.sha256, path: m.path, size: Number(m.size) || 0, mtime: mtimeOf(m.path) || Number(m.capturedAt) || 0, })); - const plan = planArtifactEviction(entries, settings.artifacts, Date.now(), protectSha); + return planArtifactEviction(entries, settings.artifacts, Date.now(), protectSha); +} + +export function pruneArtifacts(onDelete?: (sha: string) => void, protectSha?: string): { removed: number; bytesFreed: number; remainingBytes: number; kept: number; failed: number } { + const plan = previewArtifactRetention(protectSha); let removed = 0, bytesFreed = 0, failed = 0; for (const e of plan.evict) { try { unlinkSync(e.path); } @@ -446,7 +411,7 @@ export function pruneArtifacts(onDelete?: (sha: string) => void, protectSha?: st } // One pass over the event log for artifacts adopted without a package. dump.new already recorded -// the real package; this writes it into the sidecar so the next boot does not scan again. +// the real package; recovery updates memory only, never rewrites evidence during initialization. function backfillUnlabeledDumps(): number { const need = new Set(); for (const d of dumps.values()) if (!d.package) need.add(d.sha256); @@ -495,26 +460,11 @@ function backfillUnlabeledDumps(): number { if (typeof prov.requestedSize === 'number') meta.requestedSize = prov.requestedSize; if (typeof prov.complete === 'boolean') meta.complete = prov.complete; if (prov.note) meta.note = prov.note; - rememberDump(meta); labeled++; } return labeled; } -{ // re-adopt what is already on disk (see loadArtifactsFromDisk) - // Tests (and CI) must not depend on whatever sits in the developer's captures/ directory: every - // test process would scan ~1.2 GiB at import, which made the parallel suite flaky under I/O - // contention (a file would occasionally fail with no useful output). `npm test` runs through - // test/run.mjs, which sets this before the runner spawns the per-file processes. - if (process.env.ADH_SKIP_ARTIFACT_LOAD === '1') { - log('[artifacts] ADH_SKIP_ARTIFACT_LOAD=1 - starting with an empty artifact store'); - } else { - const a = loadArtifactsFromDisk(); - const labeled = backfillUnlabeledDumps(); - if (a.loaded || a.skipped) log(`[artifacts] 从磁盘恢复 ${a.loaded} 个工件(跳过 ${a.skipped},${(a.bytes / 1048576).toFixed(1)} MiB,${a.ms}ms)`); - if (labeled) log(`[artifacts] 从事件日志补上 ${labeled} 个工件的包名`); - } -} /** Retention accounting for the in-memory capture list. Pass a session for that session's view. */ export function captureStoreStats(session?: string) { if (session) { @@ -581,10 +531,6 @@ export function pushCapture(entry: Capture): boolean { captureEvicted++; bumpSession(dropped.sessionId, 'evicted'); } - if (pkg && evicted.length) { - try { trimPackageCapturesFile(DATA_DIR, pkg, retain); } - catch (err) { log(`[captures] 裁剪失败 (${pkg}):`, (err as Error).message); } - } return true; } @@ -611,25 +557,20 @@ export function exportPackageCapturesJsonl(pkg: string): string | null { return readPackageCapturesJsonl(DATA_DIR, pkg); } -/** After settings.retain / maxAgeDays change: enforce caps in memory and on disk. */ +/** Explicit maintenance of the bounded in-memory view; disk cleanup is separate. */ export function applyCaptureRetainCap(): void { - try { pruneCapturesOlderThan(DATA_DIR, settings.capture.maxAgeDays); } - catch (err) { log(`[captures] 天龄裁剪失败:`, (err as Error).message); } - const retain = settings.capture.retain; - const pkgs = new Set(); - for (const c of captures) pkgs.add(c.package && c.package !== '?' ? c.package : ''); - // Drop from memory anything older than maxAgeDays. + const before = captures.slice(); if (settings.capture.maxAgeDays > 0) { const cutoff = Date.now() - settings.capture.maxAgeDays * 86400000; for (let i = captures.length - 1; i >= 0; i--) { if (Number(captures[i].ts) && Number(captures[i].ts) < cutoff) captures.splice(i, 1); } } - enforcePerPackageRetain(captures, retain); - for (const pkg of pkgs) { - if (!pkg) continue; - try { trimPackageCapturesFile(DATA_DIR, pkg, retain); } - catch (err) { log(`[captures] 裁剪失败 (${pkg}):`, (err as Error).message); } + enforcePerPackageRetain(captures, settings.capture.retain); + const kept = new Set(captures); + for (const capture of before) { + if (kept.has(capture)) continue; + captureEvicted++; bumpSession(capture.sessionId, 'evicted'); } } // The persistent-hook target modules the agent should use. Sent with every capture_start so @@ -745,16 +686,6 @@ export function knownApps(): KnownApp[] { return [...by.values()].sort((a, b) => b.lastSeen - a.lastSeen || a.package.localeCompare(b.package)); } export const captures: Capture[] = []; -// Replay durable captures so a daemon restart keeps hook history (per package). -{ - try { - const aged = pruneCapturesOlderThan(DATA_DIR, settings.capture.maxAgeDays); - if (aged) log(`[captures] 按天龄裁掉 ${aged} 条(>${settings.capture.maxAgeDays} 天)`); - } catch (e) { log(`[captures] 天龄裁剪失败:`, (e as Error).message); } - const loaded = loadCapturesFromDisk(DATA_DIR, settings.capture.retain); - for (const c of loaded) captures.push(c as Capture); - if (loaded.length) log(`[captures] 从磁盘恢复 ${loaded.length} 条(按包保留上限 ${settings.capture.retain})`); -} // Store accounting (v4.93): the in-memory list is capped by settings.capture.retain (per package // since 2026-10-20), and an evicted record is gone for every digest that runs later. Counting // pushes and evictions lets a digest admit that its window may be missing events. @@ -1083,3 +1014,41 @@ export function readBody(req: IncomingMessage, cap = MAX_BODY_BYTES): Promise evSeq) evSeq = e.seq; } catch { corrupt++; } } + if (corrupt) log(`[events] replay: ${corrupt}/${lines.length} 行损坏已跳过 (${EVENTS_FILE})`); + } + } catch (e) { log(`[events] replay 失败 (${EVENTS_FILE}) — 从空事件起步:`, (e as Error).message); } + // Load persisted settings. Fail LOUD: if the file is present but corrupt/unreadable we must not + // silently run on defaults (that masks lost config as "working"). Absent file is normal (defaults). + try { + if (existsSync(SETTINGS_FILE)) mergeSettings(JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'))); + } catch (e) { + log(`[settings] ${SETTINGS_FILE} 载入失败,已回退默认值 — 磁盘上的配置未生效:`, (e as Error).message); + } + // Migrate ONE legacy default: before 2026-10-11 the daemon defaulted sysModule to + // 'libadhdetect.so' — the SANDBOX's mock detector lib, built by tools/build_detect.sh. Nothing + // outside the sandbox ships that name, so a persisted value equal to it can only have come from + // that default (a target-specific choice would be a real lib). Keeping it would make every real + // target report six zero-installs for hooks nobody asked for. fileModule's old default + // ('libjavacore.so') is a genuine Android lib, so it is left alone — only the default changes. + if (settings.capture.sysModule === 'libadhdetect.so') settings.capture.sysModule = ''; + + if (process.env.ADH_SKIP_ARTIFACT_LOAD !== '1') { + loadArtifactsFromDisk(); + backfillUnlabeledDumps(); + } + captures.push(...loadCapturesFromDisk(DATA_DIR, settings.capture.retain) as Capture[]); + restored = { events: events.length, captures: captures.length, artifacts: dumps.size }; + return { ...restored, alreadyInitialized: false }; +} diff --git a/daemon/src/storage.ts b/daemon/src/storage.ts new file mode 100644 index 0000000..ef9cc36 --- /dev/null +++ b/daemon/src/storage.ts @@ -0,0 +1,43 @@ +// Resolving paths is pure. Only explicit writes/initialization create directories. +import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import { dirname, join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; + +export function resolveStoragePaths(env: NodeJS.ProcessEnv = process.env) { + const repository = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); + const testRoot = env.ADH_SKIP_ARTIFACT_LOAD === '1' ? join(tmpdir(), `adh-test-${process.pid}`) : ''; + const dataDir = resolve(env.ADH_DATA_DIR || (testRoot ? join(testRoot, 'adhd-data') : join(repository, 'adhd-data'))); + // Preserve the old default layout; an explicitly isolated data root isolates dumps too. + const capturesDir = resolve(env.ADH_CAPTURES_DIR || (env.ADH_DATA_DIR ? join(dataDir, 'captures') + : testRoot ? join(testRoot, 'captures') : join(repository, 'captures'))); + return { dataDir, capturesDir }; +} + +export const storagePaths = resolveStoragePaths(); + +export function captureFile(name: string): string { + mkdirSync(storagePaths.capturesDir, { recursive: true }); + return join(storagePaths.capturesDir, name); +} + +export function atomicWriteJson(path: string, value: unknown): void { + atomicWriteText(path, JSON.stringify(value, null, 2) + '\n'); +} + +export function atomicWriteText(path: string, value: string): void { + mkdirSync(dirname(path), { recursive: true }); + const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`; + let fd: number | undefined; + try { + fd = openSync(temporary, 'wx', 0o600); + writeFileSync(fd, value); + fsyncSync(fd); + closeSync(fd); fd = undefined; + renameSync(temporary, path); + } finally { + if (fd !== undefined) closeSync(fd); + try { unlinkSync(temporary); } catch { /* renamed or never created */ } + } +} diff --git a/daemon/test/p0_lifecycle.test.ts b/daemon/test/p0_lifecycle.test.ts new file mode 100644 index 0000000..673562c --- /dev/null +++ b/daemon/test/p0_lifecycle.test.ts @@ -0,0 +1,102 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { resolveStoragePaths } from '../src/storage.ts'; + +const mcpUrl = pathToFileURL(resolve('src/mcp.ts')).href; +const stateUrl = pathToFileURL(resolve('src/state.ts')).href; +const lifecycleUrl = pathToFileURL(resolve('src/host_lifecycle.ts')).href; +const maintenanceUrl = pathToFileURL(resolve('src/maintenance.ts')).href; +const serviceUrl = pathToFileURL(resolve('src/service.ts')).href; +const guard = ` + import assert from 'node:assert/strict'; + import fs from 'node:fs'; + import cp from 'node:child_process'; + import net from 'node:net'; + import {syncBuiltinESMExports} from 'node:module'; + cp.execFile = cp.spawn = () => { throw Error('device/child execution forbidden in lifecycle fixture'); }; + net.Server.prototype.listen = () => { throw Error('listeners forbidden in lifecycle fixture'); }; + syncBuiltinESMExports(); +`; +function child(root: string, code: string) { + const result = spawnSync(process.execPath, ['--input-type=module', '-e', guard + code], { + encoding: 'utf8', timeout: 20000, windowsHide: true, + env: { ...process.env, ADH_DATA_DIR: root, ADH_CAPTURES_DIR: join(root, 'captures'), ADH_SKIP_ARTIFACT_LOAD: '0' }, + }); + assert.equal(result.status, 0, `${result.error ?? ''}\n${result.stdout}\n${result.stderr}`); +} +function cleanup(root: string) { + assert.ok(root.startsWith(join(tmpdir(), 'adh-p0-'))); + rmSync(root, { recursive: true, force: true }); +} + +test('path resolution isolates all storage with ADH_DATA_DIR and preserves the legacy default', () => { + const isolated = resolveStoragePaths({ ADH_DATA_DIR: join(tmpdir(), 'adh-isolated') }); + assert.equal(isolated.capturesDir, join(isolated.dataDir, 'captures')); + assert.equal(resolveStoragePaths({}).capturesDir, resolve('..', 'captures')); +}); + +test('importing MCP into an absent data root creates no files, dirs, database, listener or device calls', () => { + const root = mkdtempSync(join(tmpdir(), 'adh-p0-')); + try { + const absent = join(root, 'absent'); + child(absent, `await import(${JSON.stringify(mcpUrl)}); assert.equal(fs.existsSync(process.env.ADH_DATA_DIR), false);`); + } finally { cleanup(root); } +}); + +test('recovery retains expired evidence and corrupt index bytes; cleanup needs a separate explicit call', () => { + const root = mkdtempSync(join(tmpdir(), 'adh-p0-')); + try { + const capDir = join(root, 'captures'); mkdirSync(capDir); + const bytes = Buffer.from('synthetic expired artifact'); + const sha = createHash('sha256').update(bytes).digest('hex'); + const artifact = join(capDir, `${sha.slice(0, 16)}.dex.bin`); + writeFileSync(artifact, bytes); utimesSync(artifact, 1000, 1000); + const pkg = 'com.example.fixture'; const pkgDir = join(root, 'packages', pkg); mkdirSync(pkgDir, { recursive: true }); + const rows = Array.from({ length: 70 }, (_, n) => JSON.stringify({ id: n + 1, ts: 1000, package: pkg, sessionId: 'old', hex: '41' })).join('\n') + '\n'; + writeFileSync(join(pkgDir, 'captures.jsonl'), rows); + writeFileSync(join(root, 'settings.json'), JSON.stringify({ capture: { enabled: false, autoDumpDex: false, retain: 50, maxAgeDays: 14 }, artifacts: { maxAgeDays: 14 } })); + writeFileSync(join(root, 'dex-index.sqlite'), 'corrupt derived index sentinel'); + writeFileSync(join(root, 'events.jsonl'), JSON.stringify({ seq: 1, ts: 1000, type: 'dump.new', data: { sha256: sha, package: pkg, source: 'fixture' } }) + '\n'); + child(root, ` + const root = process.env.ADH_DATA_DIR; + const snapshot = () => { + const files = []; + const walk = p => { for(const n of fs.readdirSync(p)) { const f=p+'/'+n, st=fs.statSync(f); if(st.isDirectory())walk(f); else files.push([f,fs.readFileSync(f).toString('base64'),st.mtimeMs]); } }; + walk(root); return files; + }; + const before = snapshot(); + await import(${JSON.stringify(mcpUrl)}); + assert.deepEqual(snapshot(), before, 'module imports must not change existing bytes or metadata'); + const state = await import(${JSON.stringify(stateUrl)}); + assert.equal(state.captures.length, 0); assert.equal(state.dumps.size, 0); + const {initializeHost} = await import(${JSON.stringify(lifecycleUrl)}); + assert.equal(initializeHost().alreadyInitialized, false); + assert.equal(initializeHost().alreadyInitialized, true); + assert.equal(state.captures.length, 50); assert.equal(state.dumps.size, 1); + assert.equal(state.settings.capture.enabled, false); + assert.equal([...state.dumps.values()][0].package, ${JSON.stringify(pkg)}); + assert.deepEqual(snapshot(), before, 'recovery must not age-prune, trim, rewrite sidecars or rebuild indexes'); + const {persistArtifact} = await import(${JSON.stringify(serviceUrl)}); + const added = await persistArtifact(Buffer.from('new synthetic artifact'), {source:'fixture',addr:'',tag:'new',sessionId:'fixture',package:${JSON.stringify(pkg)}}); + assert.equal(fs.existsSync(${JSON.stringify(artifact)}),true, 'writing new artifacts cannot delete historical evidence'); + assert.equal(fs.readFileSync(${JSON.stringify(join(pkgDir, 'captures.jsonl'))},'utf8'),${JSON.stringify(rows)}); + const afterWrite = snapshot(); + const {maintainData} = await import(${JSON.stringify(maintenanceUrl)}); + const preview=maintainData(); assert.equal(preview.dryRun, true); assert.equal(preview.artifacts.count,1); assert.equal(preview.captures.removed,70); + assert.equal(maintainData({dryRun:false}).ok,false); + assert.deepEqual(snapshot(), afterWrite, 'preview and refused cleanup must preserve evidence'); + fs.unlinkSync(root+'/dex-index.sqlite'); // only the synthetic corrupt cache, after preservation assertions + assert.equal(maintainData({dryRun:false,confirm:true}).ok,true); + assert.equal(fs.existsSync(${JSON.stringify(artifact)}),false); + assert.equal(fs.existsSync(${JSON.stringify(join(pkgDir, 'captures.jsonl'))}),false); + assert.equal(fs.existsSync(added.meta.path),true, 'maintenance preserves unexpired artifacts'); + `); + // All assertions and cleanup operate only on generated temporary fixtures. + } finally { cleanup(root); } +}); diff --git a/daemon/test/run.mjs b/daemon/test/run.mjs index 98e94de..1446493 100644 --- a/daemon/test/run.mjs +++ b/daemon/test/run.mjs @@ -1,19 +1,17 @@ // Test launcher. Sets the environment the suite needs BEFORE the runner spawns one process per // test file, then hands over to `node --test`. // -// Why this exists: state.ts re-adopts every artifact in captures/ at import time, which on a working -// machine is ~1.2 GiB. Twelve test processes doing that at once made the parallel suite flaky (a -// file would occasionally fail with no useful output) and slow. CI has an empty tree and never hit -// it, but a gate that is only green on a clean machine is not a gate. ADH_SKIP_ARTIFACT_LOAD makes -// the store start empty, so the suite is hermetic and order-independent. +// Imports are now non-destructive; explicit test operations must still never use an inherited +// operator data/capture root. The flag assigns each test process its own temporary default root. // // `stdio: 'inherit'` (not a pipe) matters: the harness forbids capturing a child's piped output. import { spawn } from 'node:child_process'; const args = ['--test', ...process.argv.slice(2)]; +const { ADH_DATA_DIR, ADH_CAPTURES_DIR, ...isolatedEnv } = process.env; const child = spawn(process.execPath, args, { stdio: 'inherit', - env: { ...process.env, ADH_SKIP_ARTIFACT_LOAD: '1' }, + env: { ...isolatedEnv, ADH_SKIP_ARTIFACT_LOAD: '1' }, }); child.on('error', (e) => { console.error(`test launcher: failed to start node --test: ${e.message}`); diff --git a/daemon/test/scope_update.test.ts b/daemon/test/scope_update.test.ts new file mode 100644 index 0000000..5fd20f1 --- /dev/null +++ b/daemon/test/scope_update.test.ts @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { scopeWithPackages, writeScopePackages } from '../src/scope_list.ts'; + +const original = { + version: 2, mode: 'allowlist', packages: ['com.example.old'], + policy: { 'com.example.old': { c: { d: false, h: false, t: false }, future: [1, { enabled: false }] } }, + futureExtension: { flags: [false, '值'], revision: 19 }, +}; + +test('the production scope writer retains phone policy and unknown fields, including removed packages', async () => { + let body = JSON.stringify(original), writes = 0; + const io = { read: async () => 'su: warning\n' + body, write: async (text: string) => { writes++; body = text; } }; + const out = await writeScopePackages(['com.example.new', 'com.example.new', 'bad name', 'com.adh.manager'], {}, io); + assert.equal(out.ok, true); assert.equal(writes, 1); + assert.deepEqual(JSON.parse(body), { ...original, packages: ['com.example.new'] }); + assert.deepEqual(original.packages, ['com.example.old']); + assert.equal(scopeWithPackages(body, [], { version: 1 }).version, 2, 'current document wins over stale metadata'); +}); + +test('unreadable/corrupt/empty scope refuses to write instead of replacing it with defaults', async () => { + for (const raw of ['', '{broken', '[]', '{"packages":null}']) { + let writes = 0; + const out = await writeScopePackages(['com.example.new'], {}, { read: async () => raw, write: async () => { writes++; } }); + assert.equal(out.ok, false); assert.equal(writes, 0); + } + const out = await writeScopePackages([], {}, { read: async () => { throw new Error('denied'); }, write: async () => assert.fail('must not write') }); + assert.equal(out.ok, false); assert.match(out.error!, /denied/); +}); + +test('a matching package readback does not hide lost hook policy', async () => { + let reads = 0; + const out = await writeScopePackages(['com.example.new'], {}, { + read: async () => JSON.stringify(reads++ ? { version: 2, mode: 'allowlist', packages: ['com.example.new'] } : original), + write: async () => {}, + }); + assert.equal(out.ok, false); assert.match(out.error!, /complete document differs/); +}); diff --git a/daemon/test/settings_service.test.ts b/daemon/test/settings_service.test.ts new file mode 100644 index 0000000..57bd994 --- /dev/null +++ b/daemon/test/settings_service.test.ts @@ -0,0 +1,179 @@ +import test, { after, before } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import cp from 'node:child_process'; +import { syncBuiltinESMExports } from 'node:module'; +import { promisify } from 'node:util'; +import { mkdirSync, existsSync, readFileSync, rmSync, statSync, unlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +const realExec = cp.execFile; +const realSpawn = cp.spawn; +cp.execFile = (() => { throw Error('ADB/device calls forbidden in settings fixture'); }) as unknown as typeof cp.execFile; +Object.defineProperty(cp.execFile, promisify.custom, { value: async (file: string, args: string[]) => { + if (file === 'adb' && args.some(a => a.includes('cat /data/adb/adh/scope.json'))) { + return { stdout: JSON.stringify({ version: 2, mode: 'allowlist', packages: ['com.example.fixture'] }), stderr: '' }; + } + throw Error('real subprocess execution forbidden in settings fixture'); +} }); +cp.spawn = (() => { throw Error('child execution forbidden in settings fixture'); }) as unknown as typeof cp.spawn; +syncBuiltinESMExports(); +// Block subprocesses BEFORE service modules capture/promisify the builtin bindings. +const { handleHttp } = await import('../src/http/router.ts'); +const { handleMcp } = await import('../src/mcp.ts'); +const { patchSettings } = await import('../src/settings_service.ts'); +const { drainSession, forgetCaptureSession, startCaptureLoop } = await import('../src/service.ts'); +const { appendCaptureLine } = await import('../src/capture_persist.ts'); +const { agentSockets, captureTimers, captures, DATA_DIR, DEFAULT_SETTINGS, pending, sessions, SETTINGS_FILE, settings } = await import('../src/state.ts'); + +const server = http.createServer((req, res) => { handleHttp(req, res).catch(error => { res.writeHead(500); res.end(String(error)); }); }); +let address: string; +before(async () => { + assert.ok(resolve(DATA_DIR).startsWith(resolve(tmpdir()) + '\\') || resolve(DATA_DIR).startsWith(resolve(tmpdir()) + '/'), 'tests require a temporary data root'); + await new Promise(done => server.listen(0, '127.0.0.1', done)); + address = `http://127.0.0.1:${(server.address() as { port: number }).port}`; +}); +after(async () => { + cp.execFile = realExec; cp.spawn = realSpawn; syncBuiltinESMExports(); + for (const timer of captureTimers.values()) clearInterval(timer); + captureTimers.clear(); agentSockets.clear(); sessions.clear(); + await new Promise((done, reject) => server.close(error => error ? reject(error) : done())); +}); + +function reset() { + for (const timer of captureTimers.values()) clearInterval(timer); + captureTimers.clear(); forgetCaptureSession('fixture'); + Object.assign(settings, structuredClone(DEFAULT_SETTINGS)); + sessions.clear(); agentSockets.clear(); captures.length = 0; + if (existsSync(SETTINGS_FILE)) { + // This path was verified as temporary before any test could run. + const st = statSync(SETTINGS_FILE); + if (st.isDirectory()) rmSync(SETTINGS_FILE, { recursive: true }); else unlinkSync(SETTINGS_FILE); + } +} + +function fakeAgent(fail = false, native: any[] = []) { + const calls: string[] = []; + sessions.set('fixture', { sessionId: 'fixture', online: true, package: 'com.example.fixture', process: 'com.example.fixture', pid: 1 } as any); + agentSockets.set('fixture', { destroyed: false, write(frame: Buffer) { + const msg = JSON.parse(frame.subarray(5).toString('utf8')); calls.push(msg.op); + queueMicrotask(() => pending.get(msg.id)?.resolve(msg.op === 'capture_drain' + ? { ok: true, jcaptures: [], captures: native, count: native.length, complete: true, dropped: 0, seq: native.length, backlog: 0, drained: native.length } + : fail ? { ok: false, error: 'fixture refused capture_stop' } + : msg.op === 'capture_start' ? { ok: true, evp: 1 } : { ok: true })); + return true; + } } as any); + startCaptureLoop('fixture', { skipArm: true }); + return calls; +} + +async function via(entry: string, patch: unknown): Promise<{ status: number; body: any; isError?: boolean }> { + if (entry === 'mcp') { + let output: any; + const response = { writeHead() { return this; }, end(text: string) { output = JSON.parse(text); } }; + await handleMcp(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'settings', arguments: { action: 'patch', patch } } }), response as any); + return { status: 200, body: JSON.parse(output.result.content[0].text), isError: output.result.isError }; + } + const response = await fetch(address + entry, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch) }); + return { status: response.status, body: await response.json() }; +} + +for (const entry of ['mcp', '/api/config', '/api/settings/import']) { + test(`${entry}: enable installs on the simulated scoped target`, async () => { + reset(); settings.capture.enabled = false; const calls = fakeAgent(); + const result = await via(entry, { capture: { enabled: true } }); + assert.equal(result.body.ok, true); assert.equal(result.body.runtimeApplied, true); + assert.ok(calls.includes('capture_start')); assert.equal(result.body.runtime.targets[0].ok, true); + assert.equal(settings.capture.enabled, true); + }); + + test(`${entry}: disable waits for drain+stop and returns actual runtime application`, async () => { + reset(); const calls = fakeAgent(); + const result = await via(entry, { capture: { enabled: false } }); + assert.equal(result.body.ok, true); assert.equal(result.body.persisted, true); + assert.deepEqual(calls, ['capture_drain', 'capture_stop']); + assert.deepEqual(result.body.runtime.targets, [{ session: 'fixture', ok: true }]); + assert.equal(JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')).capture.enabled, false); + }); + + test(`${entry}: saved config does not hide a failed target operation`, async () => { + reset(); const calls = fakeAgent(true); + const result = await via(entry, { capture: { enabled: false } }); + assert.equal(result.body.ok, false); assert.equal(result.body.persisted, true); + assert.equal(result.body.runtimeApplied, false); assert.equal(result.body.runtime.targets[0].ok, false); + assert.match(result.body.runtime.targets[0].error, /fixture refused/); + assert.equal(entry === 'mcp' ? result.isError : result.status, entry === 'mcp' ? true : 502); + assert.deepEqual(calls, ['capture_drain', 'capture_stop']); + }); + + test(`${entry}: persist failure changes neither live settings nor target`, async () => { + reset(); mkdirSync(SETTINGS_FILE, { recursive: true }); const calls = fakeAgent(); + const result = await via(entry, { capture: { enabled: false } }); + assert.equal(result.body.ok, false); assert.equal(result.body.persisted, false); + assert.equal(settings.capture.enabled, true); assert.deepEqual(calls, []); + assert.equal(entry === 'mcp' ? result.isError : result.status, entry === 'mcp' ? true : 500); + rmSync(SETTINGS_FILE, { recursive: true }); + }); + + test(`${entry}: retention/UI patch preserves disk evidence and does not reinstall hooks`, async () => { + reset(); const calls = fakeAgent(); + const pkg = 'com.example.retention'; + appendCaptureLine(DATA_DIR, { id: 1, ts: 1000, package: pkg, sessionId: 'old', hex: '41' } as any); + const path = join(DATA_DIR, 'packages', pkg, 'captures.jsonl'); + const before = readFileSync(path); + const result = await via(entry, { capture: { retain: 50, maxAgeDays: 1 }, ui: { displayCap: 70 } }); + assert.equal(result.body.ok, true); assert.equal(result.body.maintenanceRequired, true); + assert.deepEqual(readFileSync(path), before); assert.deepEqual(calls, []); + assert.equal(settings.ui.displayCap, 70); + }); +} + +test('overlapping settings patches serialize persistence and runtime application', async () => { + reset(); + let release!: () => void; let started!: () => void; + const ready = new Promise(r => { started = r; }); + const gate = new Promise(r => { release = r; }); + const first = patchSettings({ capture: { enabled: false } }, async () => { started(); await gate; return { ok: true, targets: [] }; }); + await ready; + const second = patchSettings({ ui: { displayCap: 77 } }); + await Promise.resolve(); + assert.equal(settings.ui.displayCap, DEFAULT_SETTINGS.ui.displayCap); + release(); await first; await second; + assert.equal(settings.ui.displayCap, 77); assert.equal(settings.capture.enabled, false); +}); + +test('invalid sections do not save a config or issue target operations', async () => { + reset(); const calls = fakeAgent(); + const out = await patchSettings({ capture: [] }); + assert.equal(out.ok, false); assert.equal(out.persisted, false); + assert.deepEqual(calls, []); assert.equal(existsSync(SETTINGS_FILE), false); +}); + +test('capture IDs continue above restored history after explicit initialization', async () => { + reset(); captures.push({ id: 900000, package: 'com.example.old' } as any); + fakeAgent(false, [{ func: 'SSL_write', hex: '41', tid: 1 }]); + const out = await drainSession('fixture'); + assert.equal(out.ok, true); + const emitted = captures.find(c => c.sessionId === 'fixture'); + assert.ok(emitted && emitted.id > 900000, 'new records must not reuse persisted capture IDs'); +}); + +test('MCP and HTTP maintenance default to preview; deleting requires explicit confirmation', async () => { + reset(); const calls = fakeAgent(); + const pkg = 'com.example.maintenance'; + appendCaptureLine(DATA_DIR, { id: 1, ts: 1000, package: pkg, hex: '41' } as any); + const path = join(DATA_DIR, 'packages', pkg, 'captures.jsonl'); const bytes = readFileSync(path); + for (const args of [{ action: 'maintenance' }, { action: 'maintenance', dryRun: false }]) { + let response: any; + await handleMcp(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'settings', arguments: args } }), { + writeHead() { return this; }, end(text: string) { response = JSON.parse(text); }, + } as any); + const body = JSON.parse(response.result.content[0].text); + assert.equal(body.ok, args.dryRun === undefined); + assert.deepEqual(readFileSync(path), bytes); + } + const preview = await (await fetch(address + '/api/maintenance')).json() as { dryRun: boolean; ok: boolean }; + assert.equal(preview.dryRun, true); assert.equal(preview.ok, true); + const refused = await fetch(address + '/api/maintenance', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"dryRun":false}' }); + assert.equal(refused.status, 400); assert.deepEqual(readFileSync(path), bytes); assert.deepEqual(calls, []); +}); diff --git a/docs/AI_FIRST_REFACTOR_AUDIT.md b/docs/AI_FIRST_REFACTOR_AUDIT.md index 5e7ab06..385e2b3 100644 --- a/docs/AI_FIRST_REFACTOR_AUDIT.md +++ b/docs/AI_FIRST_REFACTOR_AUDIT.md @@ -2,6 +2,8 @@ 核验日期:2026-11-16。审计基线:ADH `ca4f92ec99e8ec13fc13fbc7f0a24a5919248d6a`;adh-cli `3cf83996cd8a0221b3248048025870f785cd5852`。 +> 后续实施校注:同日 P0 已在 Host 源码修复 F01/F02/F04,见 [P0 实施与迁移](P0_HOST_STATE.md);尚未部署到当前运行服务。本文及 JSON 保留原审计基线与源文件哈希,不重新包装为新代码的实时清单。设备身份等其余发现仍待对应阶段处理。 + 本文是 `DEVELOPMENT_PLAN.md` 的审计附录和后续实施输入。当前行为、静态发现、拟议设计分开描述;新模块与新命令均未实施,不代表运行现场已升级。用户本轮明确的产品方向:**AI 自主决定分析流程,人类面板可以查看、修改和接管,USB 与局域网共用设备能力。** ## 1. 结论与审计边界 diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md index 7e24290..03af1ed 100644 --- a/docs/DEVELOPMENT_PLAN.md +++ b/docs/DEVELOPMENT_PLAN.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 开发计划 +> **2026-11-16 P0 实施**:F01 作用域策略保留、F02 共享设置应用、F04 非破坏性显式恢复与独立清理已在 Host 源码落地,见 [P0 实现与迁移](P0_HOST_STATE.md)。当前分析现场不升级;设备身份、人工接管与 USB/LAN 新协议仍为后续工作。 + > **定位**:**通用 Android 运行时逆向分析工具** — 对高对抗目标(反调试/root/签名检测/混淆/加密传输)具备实战能力。 > **功能需求**:见 [`REQUIREMENTS.md`](REQUIREMENTS.md)(唯一权威规格,模块 A–W;本文档只管架构与排期)。 > **跨会话进度**:见 [`PROGRESS.md`](PROGRESS.md)。 diff --git a/docs/FEATURE_STATUS.md b/docs/FEATURE_STATUS.md index 908319d..d6da2ff 100644 --- a/docs/FEATURE_STATUS.md +++ b/docs/FEATURE_STATUS.md @@ -1,5 +1,7 @@ # ADH 功能状态(2026-10-24 更新:通用原生分析与证据核验;各轮实测范围见 §2) +> **2026-11-16 P0**:Host 作用域完整保留、MCP/面板共享设置、显式非破坏性初始化与独立维护已实现并纳入隔离回归;详情与验证见 [P0_HOST_STATE.md](P0_HOST_STATE.md) / PROGRESS.md。未部署、未重启当前服务、未执行真机升级验收;不要将源码状态当成当前运行实例状态。 + > 这份文件回答一个问题:**现在到底有什么、什么是验证过的、什么是没验证的、什么还没做完。** > 判定要有可复跑的 pass/fail 信号;优先跑命中的验收。`tools/verify_all.sh` 当前注册 **136 个脚本 = 40 host + 96 device**,这个数字不代表本轮全量通过。 > 规格见 `REQUIREMENTS.md`,架构与排期见 `DEVELOPMENT_PLAN.md`,跨会话进度见 `PROGRESS.md`。 diff --git a/docs/P0_HOST_STATE.md b/docs/P0_HOST_STATE.md new file mode 100644 index 0000000..210f1bb --- /dev/null +++ b/docs/P0_HOST_STATE.md @@ -0,0 +1,58 @@ +# P0:作用域、设置与非破坏性初始化 + +2026-11-16。本文描述已实现的 Host 源码行为;未部署到当前运行服务。对应审计 F01、F02、F04;设备身份/多设备控制、任务控制权与 USB/LAN 统一仍按后续阶段实施。 + +## 作用域更新 + +`writeScopePackages` 写入前重新读取完整 scope.json,只替换 packages。现有 policy(含 false 开关、暂不在 scope 的旧条目)和未知顶层/嵌套字段保持不变;版本/模式以最新文档为准。输入缺失、不可读或损坏时拒绝更新。 + +默认 ADB writer 使用独立上传/暂存文件,在 root 目录设 owner/mode/SELinux label 后 rename 替换,不再 cp 覆盖正在读取的配置。回读核对完整 JSON,而非只核对包名单。ScopeIO 注入点用于测试,产品调用继续使用既有 ADB 路径。 + +本轮没有改手机协议、Kotlin/C++ 常量或 Manager 的写入方式;不能据 atomic rename 宣称已解决跨手机/Host 的并发覆盖。共享 revision/CAS 属于后续控制层改造。 + +## 设置统一入口 + +MCP `settings(action=patch)`、HTTP `POST /api/config` 和 `POST /api/settings/import` 全部调用 `settings_service.patchSettings`: + +1. 在独立候选配置中规范化 patch,同一进程的提交排队串行执行。 +2. 临时文件写入、fsync、rename 原子保存;保存失败不发布内存状态、不操作目标。 +3. 发布配置;涉及 enabled/目标模块时,等待所有相关目标的实际 capture 安装/停止结果。 +4. 返回 persisted、runtimeApplied、逐目标 runtime.targets、错误和延后生效字段。保存成功但目标失败时 ok=false、persisted=true;HTTP 为 502,MCP 标 isError。保存失败为 HTTP 500,非法配置为 400。 + +输出过滤即时作用于后续入库;ui/保留策略变更不重装 Hook。startup 对未来 hello 生效;autoDumpDex 对未来自动采集启动生效,响应 deferred 说明这一点。当前全局 capture.enabled 的作用范围保持原语义,目标级授权和接管在后续阶段收敛。 + +保留策略只保存配置并返回 maintenanceRequired,不在设置请求中删除历史记录。所有 MCP 工具返回 ok=false 的结果也会携带 isError=true,避免把业务失败包装成工具成功。 + +## 初始化与存储 + +- 导入 state、service、MCP/HTTP 模块不建目录、不重放历史、不打开 SQLite、不清理数据、不访问设备或监听端口。 +- 正常可执行入口 index.ts 在监听前调用 `initializeHost()`;恢复设置、事件、工件与有界内存捕获视图。恢复幂等,不按年龄/数量裁剪磁盘、不改来源 sidecar;缺少包来源时仅补内存视图。 +- DEX SQLite 在实际索引操作时按需打开。已有损坏缓存不会因工具注册表被导入就被重建。 +- 新建 dump/捕获写入保留磁盘历史;内存视图仍有界,并记录淘汰。启动和会话定时 sweep 不回收工件。捕获 ID 在新 drain loop 启动时接续已恢复历史。 +- 未设环境变量时保留旧布局:仓库 captures/ 与 adhd-data/。设置 ADH_DATA_DIR 后,dump 默认位于该根的 captures/,不再穿透到仓库 captures/。ADH_CAPTURES_DIR 可显式指定独立工件根。 +- **旧外置 DATA_DIR 用户升级**:旧版本的 dump 可能仍在仓库 captures/。新版不会移动或删除它们;如需继续读取旧目录,升级入口显式设置 ADH_CAPTURES_DIR 为旧目录,再另行安排数据迁移。不要为了测试而指定操作者旧目录。 + +新测试入口会移除继承的 ADH_DATA_DIR/ADH_CAPTURES_DIR,再给每个测试进程分配临时默认根。手工 import 只获取注册表,不再自动加载历史;需要完整历史的独立 Host 客户端应显式调用 initializeHost。 + +## 显式维护 + +以下接口以更新后的 Host 为前提,本轮未在当前现场执行: + +```text +MCP settings {"action":"maintenance"} # 预览 +MCP settings {"action":"maintenance","dryRun":false,"confirm":true} # 执行 +GET /api/maintenance # 预览 +POST /api/maintenance {"dryRun":false,"confirm":true} # 执行 +``` + +默认 dryRun=true。显式 dryRun=false 但没有 confirm=true 时拒绝执行。预览返回当时策略下的工件数量/字节、捕获逐包数量与错误,不返回捕获内容;执行时按当前策略重新计算,报告实际删除数和失败。它不是跨请求事务或任务 pin 系统,P1 以后再增加持久任务与证据引用保护。 + +本轮移除了启动、定时 sweep、新 dump、设置保存及捕获追加路径的磁盘自动裁剪。磁盘保留策略需通过上述维护入口显式执行;内存 ring/视图容量继续受限。已有 REST data/clear 是另一条显式删除入口,未改变其原有语义。 + +## 验证与边界 + +新增作用域 fake IO、MCP/面板/导入真实 HTTP handler + fake agent、临时文件子进程测试。设备子进程在业务模块导入前被替换/拒绝;HTTP 仅监听系统分配的 loopback 测试端口。旧捕获、旧工件、损坏 SQLite 均为生成的合成数据。 + +覆盖策略/未知字段保留、损坏输入拒写、完整回读、三入口启停/失败/保留策略一致、原子保存失败不改运行状态、并发设置提交、纯导入与幂等恢复保持文件字节/mtime、显式维护确认、新工件不清历史、新捕获 ID 不重复。Host 回归与类型检查结果见 PROGRESS.md;未运行真机注入/升级验收。 + +本轮最终信号:新增隔离回归 25/25,完整 Host 回归 489/489(0 fail / 0 skip),typecheck rc=0,v71 tools=91/problems=0,提交差异空白检查通过。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 2c7acd0..807bb54 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4940,3 +4940,16 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 拟议 P0–P5:数据/配置保护 → Host 共享操作与持久任务 → 人工修改/接管最小闭环 → 设备域服务和 USB RPC → TLS LAN 与完整 ADB 能力迁移 → Hook 方案/启动缓存和公共入口收敛。AI 规划仍由外部 Harness 决定,recipe 可选;人类修改靠 revision/控制 epoch 阻止旧操作覆盖,取消不伪造停止,旧运行会话保留旧后端。 验证:静态清单/来源哈希/链接/分组与 F01/F02 结构证据 **9 passed / 0 failed**;`npm run typecheck` rc=0;`npm test` **464 passed / 0 failed / 0 skipped**(子进程设置 ADH_SKIP_ARTIFACT_LOAD=1、移除继承 ADH_DATA_DIR,使用既有每测试进程临时根);`git diff --check` 通过。没有运行设备门禁或启动服务;没有改变作用域契约、默认端口、stdio onboarding、桌面 status schema 或已部署服务。 + + +## 2026-11-16:P0 作用域策略保留、共享设置与初始化/清理分离 + +用户要求从 P0 实现三项修复,用隔离环境验证并提交,不重启服务、不影响分析现场。实现集中于 Host,没有更改 agent、设备 APK/协议、默认端口、stdio 配置或目标 App。 + +- scope_list 的生产 writer 先读完整文档,仅改 packages,保留 false family policy 和未知字段;root 临时文件设标签后 rename,完整 JSON 回读拒绝策略丢失。增加 ScopeIO 合成测试,不调用 ADB。跨 Host/手机并发 CAS 仍待后续。 +- settings_service 统一 MCP patch、面板 config 与导入:候选配置→原子保存→发布→等待逐目标应用;保存失败不改内存/目标,应用失败不再伪报成功。提交串行,UI/retention 不重装 Hook,startup/autoDumpDex 延后生效字段可见;工具 ok:false 会标 isError。 +- storage + host_lifecycle 提供纯路径解析和显式恢复;state/MCP 导入不建目录/重放/裁剪/打开 SQLite,DEX 索引改为按需打开。恢复只补内存来源,不重写 sidecar;采集 ID 在恢复后继续递增。 +- 移除 import、启动、会话 sweep、新 dump、设置保存、捕获追加时的磁盘自动清理。maintenance 默认预览,执行需要 dryRun:false + confirm:true;内存视图仍有界,显式维护更新淘汰计数。DATA_DIR 显式隔离时 captures 同根,旧自定义布局可用 ADH_CAPTURES_DIR 显式选择,不移动删除旧数据。 +- 测试 launcher 移除继承的操作者 data/captures 根。新回归使用临时文件、fake ScopeIO、fake agent/进程接口和 loopback 随机测试端口;纯导入 fixture 禁止监听和设备子进程,过期证据/损坏索引都是合成数据。 + +源码/迁移/维护入口见 docs/P0_HOST_STATE.md。旧审计清单保留为基线快照。验证:新增隔离回归 25 项全部通过;完整 Host 回归 **489 passed / 0 failed / 0 skipped**;`npm run typecheck` rc=0;v71 注册表 **91 tools / 0 problems / PASS**;`git diff --check` 通过。当前 8088 的原非 watch Node 进程仍在;未运行 dev_up、设备门禁、刷机、目标启停或服务重启,没有把修复注入运行现场。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index a6c850d..b181dd3 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 功能需求说明 +> **2026-11-16 P0 可靠性口径**:作用域包名单更新必须保留完整 Hook policy/未知字段;MCP 与面板设置共用原子保存和逐目标应用结果;模块导入与历史恢复不删除或裁剪磁盘证据。保留策略通过显式维护预览/确认执行,旧文中启动/追加时自动磁盘清理的描述由此更正;内存容量限制保持。实现与升级路径见 [P0 Host 状态说明](P0_HOST_STATE.md)。本轮 Host 验证不等于当前服务已部署或真机验收。 + > **产品定位**:**通用 Android 运行时逆向分析工具** — 不是 demo,也不是「手机版 jadx」。 > 适用于任意 App 的运行时观测/dump/hook/trace,并**对高对抗目标(反调试、root/签名检测、代码混淆、加密传输)具备实战能力**。 > **参考项目**:[taisuii/ios-decrypt-helper](https://github.com/taisuii/ios-decrypt-helper)(IOSDecryptHub) diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 453bcf6..b728d27 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -28,7 +28,7 @@ Generated from the live ADH Daemon registry (91 tools). Endpoint: `POST /mcp` (J | `memory_write` | Write bytes into the target process (1..4096 per call, even-length hex). The write side of memory_read: this is how a branch, a dispatch-table entry or a decrypted buffer gets CHANGED, which hooking alone cannot do. A non-writable mapping is refused with its perms in the error; pass force:true to patch it - the original protection is restored immediately and code pages get an I-cache flush. The reply carries before (the bytes that were replaced) and the host remembers it, so memory_restore can put them back. Unmapped addresses, ranges that leave their mapping, and malformed hex are refused; a prefix is never written. | session, addr, hex, force | | `memory_restore` | Undo a memory_write: the host kept the bytes each write replaced, so restoring needs only the address. Without addr it lists what this session can still restore (newest last) instead of guessing. Returns the agent reply plus restored:true, or why nothing was restored. | session, addr | | `capabilities` | What the RUNNING agent can do: every op it dispatches plus the limits that decide whether a plan is feasible (hook slots, memory windows, max write size, frame size), and the daemon limits that apply on the host side. Call this first when you do not know which operations a session supports. The answer comes from the agent itself, not from documentation: two processes can run different builds. | session | -| `settings` | Read or patch daemon settings. action:"get" returns the live settings; action:"patch" merges ONLY the sections present in patch (capture + families, ui, artifacts, startup) and persists them. startup is the host-side pre-arm applied to every NEW session at hello: startup.antiDebug (default false) + startup.module + startup.extraTargets + startup.packages (empty = all). Its default plan is ptrace only, because neutralizing access/faccessat during initialization kills apps (measured); widenAfterMs + widenTargets install those LATER, on the settled process, without another command. Enabling this makes every path check in the app fail - that is the point, but it is per-target, not a default. | action, patch | +| `settings` | Read/patch Host settings through the same atomic-save and awaited per-target application service as the panel. Save failure does not change live settings; target failure returns persisted:true with ok:false. UI/retention changes do not re-arm hooks. Retention never deletes data during patch: action:maintenance previews by default, dryRun:false requires confirm:true for explicit cleanup. Startup applies at future hello. | action, patch, dryRun, confirm | | `native_look` | The front door for "show me what this native function was holding". action arm stands at module+symbol (or addr with confirm:true; mode defaults to inline) and copies pointer-like arguments (mem defaults to auto; backtrace defaults to true). traceInsns adds an in-hook QBDI trace of the hit (see native_hook) and read returns it as trace, with one line of it appended to text. action read takes the hookId arm returned and answers with the NEWEST hit by default: text is the line to show a person, windows are the copied bytes, regs are x0-x8 from that same hit, and retained.total says how many numbered hits are still stored. Pass seq for one earlier hit, or beforeSeq plus limit (1..50) to page older hits; nextBeforeSeq is the cursor. Do not re-run the operation to recover an earlier call. argIndex rewrites an argument and is not a filter. action stop removes that hook; for inline, hard defaults to false so the same target and stub shape can be armed again; other backends retire their exposed physical slot until process exit. Do not ask the operator to join NATIVE_HOOK with NATIVE_HOOK_MEM or to invent a register name. | session, action, hookId, seq, beforeSeq, limit, mode, module, symbol, addr, confirm, mem, backtrace, hard, maxEvents, sampleEvery, tid, returnAddress, traceInsns, traceFrom, traceWatch | | `syscall_digest` | Turn watched syscall hits into an answer: groups the NATIVE_HOOK events of the hooks you pass by (syscall number, CALLER frame) with counts, time window and threads, picks the first caller frame outside libc (that is the code that issued the syscall, which is what fingerprint-collection hunting needs), decodes the argument registers through the pointers the syscall actually uses (openat/faccessat/newfstatat paths, memfd_create names, uname utsname fields, connect IPv4/IPv6, ioctl request, socket domain/type) into a per-group example plus a paths histogram - which files does this code probe - and compares the runtime x8 with the statically attributed number so a wrong attribution shows up as a mismatch instead of a mislabel. Argument decoding reads target memory, so it is bounded by decodeLimit (default 40 samples) and can be turned off with decode:false. Install the watch with syscall_watch (it sets backtrace:true) and pass its hookIds plus expected {hookId: nr}.. Counters are reported as hits/throttled/emitted: a throttled watch counts every hit (from the authoritative agent hook status), so a thinned log cannot read as a quiet target | session, hookIds, expected, sinceMs, limit, maxGroups, decode, decodeLimit | | `java_trace` | Class-level Java tracing in three explicit phases. action:start hooks every matching method of a class (hook_all semantics: method/params are optional filters, "*"/empty = any) and returns hookIds + matched + a capture cursor, KEEPING the hooks installed. action:digest drains the agent capture ring and turns the JAVA_HOOK events of those hook ids into a digest: per-method counts, first/last timestamp, threads, last argument and return, error counts, a chronological timeline (newest window) and a caller histogram when the hooks were started with stack:true. action:stop unhooks exactly the given ids (id 0 means every Java hook in the agent and is refused). Pass the cursor from start as sinceCaptureId on digest to see only events newer than that point. The digest drains the agent ring through the shared drainSession path, so it never eats records that another consumer still needs; a failed drain is reported in drain.ok instead of silently returning an empty trace. Trigger the target or let natural traffic run between start and digest. | session, action, className, method, params, limit, stack, hookIds, sinceCaptureId, maxTimeline, maxMethods, maxCallers | From be80e29039a2d18476e19a84531c5d96c5b3f211 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:49:15 +0800 Subject: [PATCH 13/24] =?UTF-8?q?feat:=20=E7=BB=9F=E4=B8=80=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E6=89=A7=E8=A1=8C=E4=B8=8E=E6=8C=81=E4=B9=85=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E5=8F=8A=E4=BA=BA=E7=B1=BB=E6=8E=A7=E5=88=B6=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- CLAUDE.md | 2 +- daemon/public/index.html | 2 + daemon/public/operations.js | 99 ++++++ daemon/src/MAP.md | 7 + daemon/src/access_context.ts | 27 ++ daemon/src/analysis_guide.ts | 9 +- daemon/src/app_launch.ts | 5 +- daemon/src/cli.ts | 31 +- daemon/src/execution_context.ts | 26 ++ daemon/src/http/router.ts | 50 ++- daemon/src/http/routes_operations.ts | 22 ++ daemon/src/http/routes_system.ts | 33 +- daemon/src/index.ts | 4 +- daemon/src/maintenance.ts | 6 +- daemon/src/mcp.ts | 36 ++- daemon/src/operation_host.ts | 92 ++++++ daemon/src/operation_registry.ts | 69 ++++ daemon/src/operations.ts | 364 ++++++++++++++++++++++ daemon/src/root_watch.ts | 6 +- daemon/src/runtime_diagnostics.ts | 3 +- daemon/src/sandbox_fs.ts | 9 +- daemon/src/scope_list.ts | 19 +- daemon/src/service.ts | 36 ++- daemon/src/settings_service.ts | 5 +- daemon/src/state.ts | 10 +- daemon/src/task_store.ts | 59 ++++ daemon/test/cmd_progress.test.ts | 2 + daemon/test/fixtures/p1_panel.ts | 32 ++ daemon/test/operation_entrypoints.test.ts | 163 ++++++++++ daemon/test/operations.test.ts | 242 ++++++++++++++ daemon/test/run.mjs | 2 +- daemon/test/settings_service.test.ts | 12 +- docs/DEVELOPMENT_PLAN.md | 4 +- docs/FEATURE_STATUS.md | 2 + docs/P0_HOST_STATE.md | 2 +- docs/P1_OPERATIONS.md | 86 +++++ docs/PROGRESS.md | 14 + docs/REQUIREMENTS.md | 2 + docs/mcp-tools.md | 193 ++++++------ 40 files changed, 1617 insertions(+), 172 deletions(-) create mode 100644 daemon/public/operations.js create mode 100644 daemon/src/access_context.ts create mode 100644 daemon/src/execution_context.ts create mode 100644 daemon/src/http/routes_operations.ts create mode 100644 daemon/src/operation_host.ts create mode 100644 daemon/src/operation_registry.ts create mode 100644 daemon/src/operations.ts create mode 100644 daemon/src/task_store.ts create mode 100644 daemon/test/fixtures/p1_panel.ts create mode 100644 daemon/test/operation_entrypoints.test.ts create mode 100644 daemon/test/operations.test.ts create mode 100644 docs/P1_OPERATIONS.md diff --git a/AGENTS.md b/AGENTS.md index f74c51a..86c5bc6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ Never merge these layers. - `libadh_agent.so` (in target process) — **collect / execute only**: hook, trace, dump, maps scan, light RPC. Keep it minimal, low-memory, non-blocking. - **Host ADH Daemon** (`daemon/`, npm `adhd`) — HTTP / WebSocket / MCP / DB / index / disasm cache / analysis. - **Device** (`device/`: `:core` + `:daemon` + `:manager`) — injection scope + module status + target process stop/restart. No analysis. -- Web UI (browser) — observe / search / visualize (frozen as a READ-ONLY viewer, 2026-10-01). +- Web UI (browser) — observe / search / visualize and, per the 2026-11-16 user direction, edit / take control through the shared Host operation layer. P1 versions and operator credentials fence old AI writes; see docs/P1_OPERATIONS.md. The former read-only freeze is superseded for this scope. **Never** put HTTP, MCP, a database, the dex indexer, or Capstone/QBDI heavy analysis inside the agent `.so` or the Device Daemon/Manager. That causes target OOM/ANR and is easy to detect. diff --git a/CLAUDE.md b/CLAUDE.md index f070e49..afeed02 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,7 +49,7 @@ Never merge these layers. - `libadh_agent.so` (in target process) — **collect / execute only**: hook, trace, dump, maps scan, light RPC. Keep it minimal, low-memory, non-blocking. - **Host ADH Daemon** (`daemon/`, npm `adhd`) — HTTP / WebSocket / MCP / DB / index / disasm cache / analysis. - **Device** (`device/`: `:core` + `:daemon` + `:manager`) — injection scope + module status + target process stop/restart. No analysis. -- Web UI (browser) — observe / search / visualize (frozen as a READ-ONLY viewer, 2026-10-01). +- Web UI (browser) — observe / search / visualize and, per the 2026-11-16 user direction, edit / take control through the shared Host operation layer. P1 versions and operator credentials fence old AI writes; see docs/P1_OPERATIONS.md. The former read-only freeze is superseded for this scope. **Never** put HTTP, MCP, a database, the dex indexer, or Capstone/QBDI heavy analysis inside the agent `.so` or the Device Daemon/Manager. That causes target OOM/ANR and is easy to detect. diff --git a/daemon/public/index.html b/daemon/public/index.html index e052715..691da97 100644 --- a/daemon/public/index.html +++ b/daemon/public/index.html @@ -448,6 +448,7 @@

ADH

+ @@ -747,6 +748,7 @@

注入后端

+ + + + diff --git a/daemon/public/workbench.js b/daemon/public/workbench.js new file mode 100644 index 0000000..1a11e1a --- /dev/null +++ b/daemon/public/workbench.js @@ -0,0 +1,157 @@ +((scope) => { + const M=scope.AdhWorkbenchModel; + const element=(tag,text,className)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=String(text);if(className)node.className=className;return node;}; + const button=(text,fn,className)=>{const node=element('button',text,className);node.type='button';node.onclick=fn;return node;}; + const badge=state=>{const node=element('span',M.states[state]||state,'aw-state');node.dataset.state=state;node.title=state;return node;}; + const json=value=>JSON.stringify(value,null,2); + function download(value,name){const url=URL.createObjectURL(new Blob([json(value)],{type:'application/json;charset=utf-8'}));const link=element('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} + function mount(root,client,options={}) { + root.classList.add('adh-workbench'); + root.innerHTML=`
ADH / HUMAN CONSOLE

任务工作台

AI 自主分析 · 人类观察、修改与接管

+
操作员连接 · 凭据仅保留在当前页面内存

查看任务无需接管。只有明确修改、暂停或切换控制权时才使用操作员权限。

+ + +

正在读取控制状态…

+
+
选择一项任务AI 提交的任务会显示在左侧。查看任务不会暂停分析,也不会改变控制权。
+ `; + const $=id=>root.querySelector('#'+id),s={view:'tasks',visible:true,busy:false,listOffset:0,opOffset:0,taskId:null,task:null,opId:null,op:null,resultLoaded:false,resultSignature:'',draft:null,conflict:null,pending:null,intent:null,control:null,listGeneration:0,detailGeneration:0,operationGeneration:0}; + let timer,pendingTimer,searchTimer,controlGeneration=0,lastOpRender='',lastTaskRender='',lastListRender='',lastRowsRender=''; + const notice=(title,text,code='',tone='error',actions=[])=>{$('awNotice').hidden=false;$('awNotice').dataset.tone=tone;$('awNoticeTitle').textContent=title;$('awNoticeText').textContent=text;$('awNoticeCode').textContent=code;$('awNoticeCode').hidden=!code;$('awNoticeActions').replaceChildren(...actions);}; + function report(error){const messages={STALE_TASK:'任务状态已被其他操作更新。请刷新并核对后再操作;没有重发旧指令。',STALE_CONTROL:'状态版本或控制权已变化。请核对最新状态后重新决定;没有重发旧指令。',OPERATION_RUNNING:'Host 仍在等待已派发步骤,暂不能解除隔离。请等待处理结束并核对目标实际状态。',CONTROL_HELD:'当前范围由人类持有,AI 写入保持暂停。',UNKNOWN_EXECUTION:'存在未确认的执行结果,先检查副作用与目标实际状态。'};notice(error.code==='STALE_TASK'?'任务版本冲突':error.code==='STALE_CONTROL'?'控制版本冲突':error.transport?'请求结果未确认':'操作未完成',messages[error.code]||error.message,error.code);} + async function work(fn){if(s.busy)return;s.busy=true;permissions();try{await fn();}catch(error){report(error);}finally{s.busy=false;permissions();}} + function permissions(){ + $('awRole').textContent=client.operator?'操作员已连接':'观察模式';$('awRole').dataset.state=client.operator?'paused':'active'; + for(const node of root.querySelectorAll('[data-mutate]'))node.disabled=s.busy||!client.operator; + for(const node of root.querySelectorAll('[data-navigate]'))node.disabled=s.busy; + for(const id of ['awTasksTab','awConfigTab','awRefresh'])$(id).disabled=s.busy; + $('awScope').disabled=s.busy; + const editingBlocked=s.busy||!!s.pending||!!s.intent||!!s.checkingPending; + for(const node of $('awConfigForm').querySelectorAll('input,textarea'))node.disabled=editingBlocked; + $('awImport').disabled=editingBlocked;$('awImportButton').disabled=editingBlocked;$('awConfigRead').disabled=editingBlocked; + $('awDisconnect').disabled=!client.operator; + $('awTake').disabled ||= !s.control||s.control.owner==='operator'; + $('awRelease').disabled ||= !s.control||s.control.owner!=='operator'||!!s.control.uncertain; + $('awResolve').disabled ||= !s.control?.uncertain||!$('awAck').checked; + let dirty=false;try{dirty=!!s.draft&&!!Object.keys(s.draft.patch()).length;}catch{} + $('awSave').disabled ||= !dirty||!!s.conflict||!!s.pending||!!s.intent||!!s.checkingPending; + } + client.subscribe(permissions); + $('awAuthForm').onsubmit=event=>{event.preventDefault();work(async()=>{const key=$('awKey').value;$('awKey').value='';await client.connect(key);$('awAuth').open=false;notice('操作员已连接','尚未接管任何范围。AI 仍按现有控制状态继续分析。','','success');await refresh();});}; + $('awDisconnect').onclick=()=>{client.disconnect();notice('已断开操作员','页面已清除凭据。既有控制权不会自动释放,请在离开前按需交还 AI。','','success');}; + $('awNoticeDismiss').onclick=()=>{$('awNotice').hidden=true;}; + $('awClose').onclick=()=>options.close?options.close():location.assign('/'); + function view(name){s.view=name;$('awTasksView').hidden=name!=='tasks';$('awConfigView').hidden=name!=='configuration';$('awTasksTab').setAttribute('aria-pressed',String(name==='tasks'));$('awConfigTab').setAttribute('aria-pressed',String(name==='configuration'));if(name==='configuration'&&!s.draft)work(loadConfiguration);} + $('awTasksTab').onclick=()=>view('tasks');$('awConfigTab').onclick=()=>view('configuration'); + const filters=()=>({q:$('awSearch').value,state:$('awState').value,owner:$('awOwner').value}); + function filter(){s.listOffset=0;refreshList().catch(report);} + $('awSearch').oninput=()=>{clearTimeout(searchTimer);searchTimer=setTimeout(filter,250);};$('awState').onchange=filter;$('awOwner').onchange=filter; + $('awTaskPrev').onclick=()=>{s.listOffset=Math.max(0,s.listOffset-25);refreshList().catch(report);};$('awTaskNext').onclick=()=>{s.listOffset+=25;refreshList().catch(report);}; + $('awOpPrev').onclick=()=>{s.opOffset=Math.max(0,s.opOffset-25);refreshTask().catch(report);};$('awOpNext').onclick=()=>{s.opOffset+=25;refreshTask().catch(report);}; + $('awRefresh').onclick=()=>work(refresh);$('awScope').onchange=()=>work(async()=>{$('awAck').checked=false;await refreshControl();});$('awAck').onchange=permissions; + async function refreshControl(){const resource=$('awScope').value,generation=++controlGeneration; + if(s.control?.resource!==resource){s.control=null;$('awControlText').textContent='正在读取所选范围的控制状态…';$('awUncertain').hidden=true;permissions();} + const value=await client.management({action:'snapshot',resource});if(resource!==$('awScope').value||generation!==controlGeneration)return;s.control=value; + $('awControlText').textContent=`${value.owner==='operator'?'人类持有控制':'AI 拥有控制'}${value.uncertain?' · 写入已隔离':''} · 状态版本 ${value.revision} · 控制代次 ${value.epoch} · Host 代次 ${value.hostEpoch}`; + $('awUncertain').hidden=!value.uncertain;permissions();} + async function control(action){const observed=s.control;if(!observed)throw Error('请先读取控制状态');await client.controlAction(observed,action,$('awAck').checked);$('awAck').checked=false;notice(action==='release'?'已交还 AI':action==='resolve'?'已记录人工核对':'已接管所选范围',action==='release'?'已失效的旧指令不会自动重放。被人工暂停的任务仍需单独恢复。':action==='resolve'?'原 unknown 记录仍保留;这不证明目标命令已停止。':'旧 AI 写入已受版本约束;查询仍可继续。','','success');await refresh();} + $('awTake').onclick=()=>work(()=>control('takeover'));$('awRelease').onclick=()=>work(()=>control('release'));$('awResolve').onclick=()=>work(()=>control('resolve')); + $('awUnknownDetail').onclick=()=>work(()=>goOperation(s.control.uncertain)); + function addScope(resource,label){if(![...$('awScope').options].some(o=>o.value===resource))$('awScope').add(new Option(label||resource,resource));} + async function refreshAgents(){const {value}=await client.request('/api/agents');for(const a of value.filter(a=>a.online))addScope(`target:${a.sessionId}:${a.pid}:${a.uid}:${a.starttimeTicks||'legacy'}`,`${a.process||a.package} · PID ${a.pid}`);} + async function refreshList(){const generation=++s.listGeneration;const value=await client.management({action:'list',limit:25,offset:s.listOffset,...filters()});if(generation!==s.listGeneration)return; + $('awTaskCount').textContent=`${value.totalTasks} 项任务 · 第 ${Math.floor(s.listOffset/25)+1} 页`;$('awTaskPrev').disabled=s.listOffset===0;$('awTaskNext').disabled=value.nextTaskOffset===null; + const signature=json(value.tasks)+'|'+s.taskId;if(signature===lastListRender)return;lastListRender=signature; + const rows=value.tasks.map(task=>{const node=button('',()=>work(()=>selectTask(task.id)));node.dataset.navigate='';node.setAttribute('aria-current',String(task.id===s.taskId));node.append(element('span',task.title,'aw-task-title'));const meta=element('span',undefined,'aw-task-meta');meta.append(badge(task.state),element('span',(task.owner==='ai'?'AI':'人类')+` · v${task.revision??0}`));if(task.heldByOperator)meta.append(element('span','人类暂停'));node.append(meta);node.title=task.id;return node;}); + if(!rows.length)rows.push(element('p',value.totalTasks?'当前页没有任务':'没有匹配任务。AI 提交任务后会在此显示。','aw-empty')); + $('awTaskList').replaceChildren(...rows);permissions(); + } + async function selectTask(id){s.taskId=id;s.task=null;s.opId=null;s.op=null;s.opOffset=0;s.resultLoaded=false;lastOpRender='';lastTaskRender='';$('awOperationDetail').hidden=true;await refreshTask();await refreshList();} + async function taskAction(action){const observed=s.task;await client.taskAction(observed,action);notice(action==='pause'?'任务已暂停':action==='resume'?'任务已恢复':'已请求取消任务',action==='pause'?'后续副作用会在检查点停止。已派发的目标命令不会被撤回。':action==='resume'?'恢复任务不会释放控制权,也不会重放已失效的操作。':'请检查每条操作的实际状态;取消请求不等于目标已经停止。','','success');await refresh();} + async function refreshTask(){if(!s.taskId)return;const id=s.taskId,generation=++s.detailGeneration;const value=await client.management({action:'get',taskId:id,limit:25,offset:s.opOffset});if(id!==s.taskId||generation!==s.detailGeneration)return; + if(!Number.isSafeInteger(value.task?.revision)||!Array.isArray(value.task?.resources))throw new scope.AdhClientError('任务工作台需要配套 P2 Host,不能只更新静态页面。','TASK_VERSION_REQUIRED');s.task=value.task; + for(const resource of value.task.resources)addScope(resource); + const signature=json(value.task);if(signature!==lastTaskRender){lastTaskRender=signature;const head=element('div',undefined,'aw-task-heading');head.append(element('h2',value.task.title),element('div',value.task.id,'aw-mono')); + const row=element('div',undefined,'aw-row');row.append(badge(value.task.state),element('span',`任务版本 ${value.task.revision} · ${value.task.owner==='ai'?'AI':'人类'}负责`,'aw-muted'));if(value.task.heldByOperator)row.append(element('span','人类暂停,AI 不能自行恢复','aw-state'));head.append(row); + head.append(element('p',`创建 ${M.time(value.task.createdAt)} · 更新 ${M.time(value.task.updatedAt)} · ${value.task.totalOperations} 条操作`,'aw-muted')); + const actions=element('div',undefined,'aw-row');for(const [action,label]of [['pause','暂停任务'],['resume','恢复任务'],['cancel','取消整项任务']]){ + if(action==='pause'&&value.task.state!=='active'||action==='resume'&&value.task.state!=='paused'||action==='cancel'&&['completed','cancelled'].includes(value.task.state))continue; + const node=button(label,()=>work(()=>taskAction(action)),action==='cancel'?'aw-danger':'');node.dataset.mutate='';actions.append(node); + }head.append(actions);if(value.task.unresolved)head.append(element('p',`${value.task.unresolved} 条操作结果未知;先核对对应范围,不能用取消掩盖未知状态。`,'aw-muted')); + $('awTaskHead').className='';$('awTaskHead').replaceChildren(head); + } + $('awOperationsSection').hidden=false;$('awOperationCount').textContent=`${value.totalOperations} 条 · 第 ${Math.floor(s.opOffset/25)+1} 页`;$('awOpPrev').disabled=s.opOffset===0;$('awOpNext').disabled=value.nextOperationOffset===null; + const rowsSignature=json(value.operations)+'|'+s.opId; + if(rowsSignature!==lastRowsRender){lastRowsRender=rowsSignature; + const rows=value.operations.map(op=>{const row=element('tr');row.dataset.operation=op.id;row.setAttribute('aria-selected',String(op.id===s.opId));const name=element('td');name.append(element('div',op.name),element('div',op.id.slice(0,8),'aw-mono'));const status=element('td');status.append(badge(op.state));if(op.cancelRequested)status.append(element('div','已请求取消','aw-muted'));const actions=element('td'),open=button('查看详情',()=>work(()=>selectOperation(op.id)));open.dataset.navigate='';actions.append(open);row.append(name,status,element('td',`${op.owner==='ai'?'AI':'人类'} · ${op.source}`),element('td',M.time(op.createdAt)),actions);return row;}); + if(!rows.length){const cell=element('td','任务尚无执行记录。');cell.colSpan=5;const row=element('tr');row.append(cell);rows.push(row);}$('awOperationRows').replaceChildren(...rows);}permissions(); + if(s.opId)await refreshOperation(); + } + async function goOperation(id){const {operation}=await client.management({action:'get',id});view('tasks');if(s.taskId!==operation.taskId)await selectTask(operation.taskId);await selectOperation(id);} + async function selectOperation(id){s.opId=id;for(const row of $('awOperationRows').querySelectorAll('[data-operation]'))row.setAttribute('aria-selected',String(row.dataset.operation===id));s.op=null;s.resultLoaded=false;s.resultSignature='';lastOpRender='';await refreshOperation();} + async function refreshOperation(force=false){if(!s.opId)return;const id=s.opId,generation=++s.operationGeneration;let {operation}=await client.management({action:'get',id});if(id!==s.opId||generation!==s.operationGeneration)return; + const signature=(operation.resultFile||'')+'|'+(operation.lateResultFile||''); + if(s.resultLoaded&&(force||signature!==s.resultSignature)){({operation}=await client.management({action:'get',id,includeResult:true}));if(id!==s.opId||generation!==s.operationGeneration)return;s.resultSignature=signature;} + else if(s.resultLoaded){operation.result=s.op?.result;operation.lateResult=s.op?.lateResult;} + s.op=operation;const renderSignature=json(operation)+'|'+s.resultLoaded;if(renderSignature!==lastOpRender){lastOpRender=renderSignature;renderOperation();} + } + function facts(parent,pairs){const list=element('dl',undefined,'aw-facts');for(const [label,value]of pairs){const item=element('div');item.append(element('dt',label),element('dd',value));list.append(item);}parent.append(list);} + function renderOperation(){const op=s.op,area=$('awOperationDetail');area.hidden=false;area.replaceChildren();const heading=element('div',undefined,'aw-row aw-between');heading.append(element('h2',op.name),badge(op.state));area.append(heading,element('p',op.id,'aw-mono aw-spaced')); + if(op.state==='unknown'){const unknown=element('div',undefined,'aw-notice');unknown.append(element('h3',op.resolvedAt?'原执行结果未知,已人工核对':'执行结果未知,不能视为失败后安全重试'),element('p','目标可能已经执行。晚到结果不会把 unknown 自动改成成功;已派发步骤不会自动回滚。'));area.append(unknown);} + if(op.cancelRequested)area.append(element('p',op.state==='succeeded'?'取消请求到达时操作已完成,保留实际成功结果。':'已请求取消;是否已执行、是否仍有命令在等待,请以以下事实为准。','aw-muted aw-spaced')); + if(op.error)area.append(element('pre',op.error.code+': '+op.error.message)); + facts(area,[['所属任务',op.taskId],['调用来源',`${op.owner==='ai'?'AI':'人类'} · ${op.source} · ${op.actorId}`],['作用范围',op.resource],['效果分类',op.mode],['创建 / Host 开始',`${M.time(op.createdAt)} / ${M.time(op.startedAt)}`],['deadline / 终态记录',`${M.time(op.deadline)} / ${M.time(op.finishedAt)}`],['提交版本 / 应用版本',`${op.expectedRevision??'未要求'} / ${op.appliedRevision??'未记录'}`],['控制代次 / Host 代次',`${op.controlEpoch??'未要求'} / ${op.hostEpoch??'未要求'}`],['已派发受跟踪步骤',op.mayHaveExecuted?'是,可能已产生副作用':'没有派发记录'],['等待确认的步骤',String(op.inFlight??0)],['Host 处理是否结束',op.settled?'已结束':'尚未确认结束'],['部分步骤 / 人工核对',`${op.partialEffects?'部分步骤已派发':'无部分步骤标记'} / ${M.time(op.resolvedAt)}`],['幂等意图键',op.key]]); + const actions=element('div',undefined,'aw-row');actions.append(button('查看此范围控制权',()=>work(async()=>{addScope(op.resource);$('awScope').value=op.resource;$('awAck').checked=false;await refreshControl();}))); + if(!M.terminal(op.state)){const cancel=button('请求取消此操作',()=>work(async()=>{client.requireOperator();await client.management({action:'cancel',id:op.id});notice('已提交取消请求','请检查实际执行状态。此操作的取消不会取消整个具名任务。','','success');await refresh();}),'aw-danger');cancel.dataset.mutate='';actions.append(cancel);}area.append(actions); + const effects=element('section',undefined,'aw-detail-section');effects.append(element('h3','副作用记录'),element('p','这里只记录 Host 实际派发与确认的步骤,不推断目标最终状态,也不记录命令参数或密钥。','aw-muted aw-spaced')); + if(op.effects===undefined)effects.append(element('p','旧记录没有逐步骤日志;以上聚合标记不能还原完整副作用。','aw-muted aw-spaced')); + else if(!op.effects.length)effects.append(element('p','没有受跟踪的派发步骤。离线计算及未埋点的内部步骤不在此日志中。','aw-muted aw-spaced')); + else {const list=element('ol',undefined,'aw-effect-list');for(const effect of op.effects){const row=element('li');const state={dispatched:'已派发,等待确认',acknowledged:'已收到响应',failed:'Host 步骤失败',unknown:'未确认执行结果'}[effect.state];row.append(element('div',`${effect.kind} / ${effect.action} · ${state}`),element('small',`${M.time(effect.startedAt)} → ${M.time(effect.completedAt)}${effect.uncertainAt?' · 曾有未知状态 '+M.time(effect.uncertainAt):''}${effect.session?' · '+effect.session:''}`));list.append(row);}effects.append(list);} + if(op.effectsDropped)effects.append(element('p',`日志达到 64 条上限;另有 ${op.effectsDropped} 条派发步骤未逐条保存,不能把当前列表当成全部证据。`,'aw-muted aw-spaced'));area.append(effects); + const results=element('section',undefined,'aw-detail-section');results.append(element('h3','已保存结果与晚到证据'));if(!s.resultLoaded)results.append(button('加载已保存结果',()=>work(async()=>{s.resultLoaded=true;await refreshOperation(true);}),'aw-spaced')); + else {for(const [key,label]of [['result','原始结果'],['lateResult','晚到结果(不改变原终态)']]){const box=element('div',undefined,'aw-result-block');box.append(element('h3',label));if(op[key]===undefined)box.append(element('p','尚无已保存内容;不代表目标没有执行。'));else {const raw=json(op[key]);box.append(element('pre',raw.length>120000?raw.slice(0,120000)+'\n…界面预览已截断':raw));if(raw.length>120000)box.append(element('p','界面预览限制 120000 字符,下载可查看全部已保存内容。'));if(op[key]?.omitted)box.append(element('p','Host 只保存了结果摘要,下载文件也不包含被省略的原始数据。'));box.append(button('下载'+label,()=>download(op[key],`${op.id}-${key}.json`)));}results.append(box);}} + area.append(results);permissions(); + } + function buildFields(){const groups=new Map();for(const field of M.fields){if(!groups.has(field.group)){const fieldset=element('fieldset');fieldset.append(element('legend',field.group));const content=element('div',undefined,'aw-fields');fieldset.append(content);groups.set(field.group,{fieldset,content});} + const label=element('label',undefined,'aw-field'+(field.type==='boolean'?' aw-toggle':'')),input=element(['symbols','packages'].includes(field.type)?'textarea':'input');input.dataset.path=field.path;input.id='awField-'+field.path;input.setAttribute('aria-label',field.label); + if(input.tagName==='INPUT')input.type=field.type==='boolean'?'checkbox':field.type==='number'?'number':'text';if(field.type==='number'){input.min=field.min;input.max=field.max;input.step=1;} + if(field.type==='boolean')label.append(input,element('span',field.label));else label.append(element('span',field.label),input);input.oninput=draftChanged;groups.get(field.group).content.append(label); + }$('awConfigForm').replaceChildren(...[...groups.values()].map(g=>g.fieldset));$('awConfigForm').onsubmit=event=>event.preventDefault();} + function fillFields(){if(!s.draft)return;for(const field of M.fields){const input=root.querySelector('[data-path="'+field.path+'"]'),value=M.get(s.draft.draft,field.path);if(field.type==='boolean')input.checked=!!value;else input.value=Array.isArray(value)?value.join('\n'):value??'';}patchPreview();} + function draftChanged(){if(!s.draft)return;try{for(const field of M.fields){const input=root.querySelector('[data-path="'+field.path+'"]');let value=field.type==='boolean'?input.checked:field.type==='number'?(input.value===''?NaN:Number(input.value)):['symbols','packages'].includes(field.type)?input.value.split(/[\n,]/).map(v=>v.trim()).filter(Boolean):input.value.trim();M.set(s.draft.draft,field.path,value);} + patchPreview();}catch(error){$('awDraftHint').textContent=error.message;$('awSave').disabled=true;}} + function patchPreview(){try{const patch=s.draft.patch();$('awPatch').textContent=json(patch);$('awDraftHint').textContent=Object.keys(patch).length?'仅提交以上有变化的字段;其他配置保持当前值。':'草稿没有修改。';$('awConfigVersion').textContent=`草稿基于 Host 版本 ${s.draft.control.revision} · 控制代次 ${s.draft.control.epoch} · Host 代次 ${s.draft.control.hostEpoch}`;permissions();}catch(error){$('awDraftHint').textContent=error.message;$('awSave').disabled=true;}} + async function loadConfiguration(){const snapshot=await client.config();if(!s.draft){s.draft=new M.Draft(snapshot);fillFields();}else showCompare(snapshot);} + function showCompare(snapshot){s.conflict=snapshot;const box=$('awConfigCompare');box.hidden=false;box.replaceChildren(element('h3','核对最新配置与本地草稿'),element('p',`编辑版本 ${s.draft.control.revision}/${s.draft.control.epoch}/${s.draft.control.hostEpoch} → 当前版本 ${snapshot.control.revision}/${snapshot.control.epoch}/${snapshot.control.hostEpoch}。草稿尚未提交。`,'aw-muted aw-spaced')); + const table=element('table',undefined,'aw-table'),head=element('tr');for(const label of ['字段','编辑时','当前值','草稿意图'])head.append(element('th',label));const thead=element('thead');thead.append(head);table.append(thead);const body=element('tbody'); + for(const row of s.draft.compare(snapshot)){const tr=element('tr');for(const value of [row.path,json(row.before),json(row.current),row.local?json(row.draft):'保持当前值'])tr.append(element('td',value));body.append(tr);}table.append(body);box.append(table); + const actions=element('div',undefined,'aw-row aw-spaced');actions.append(button('保留修改,按最新版本重新核对',()=>{s.draft.rebase(snapshot);s.conflict=null;box.hidden=true;fillFields();notice('草稿已重新核对','只保留原本修改的字段,其余采用最新值。请检查待提交修改后再提交;此步骤没有执行写入。','','success');}),button('放弃草稿,载入最新配置',()=>{s.draft.reset(snapshot);s.conflict=null;box.hidden=true;fillFields();}));box.append(actions);permissions(); + } + async function configConflict(error){report(error);try{showCompare(await client.config());}catch(latestError){report(latestError);}} + async function saveConfiguration(){client.requireOperator();draftChanged();if(!$('awConfigForm').reportValidity())return;const patch=s.draft.patch();if(!Object.keys(patch).length)return; + s.intent=client.intent();$('awSaveStatus').textContent='正在提交,尚未确认执行结果…'; + try{const value=await client.submitSettings(patch,s.draft.control,s.intent);s.pending=value.operation;s.intent=null;$('awSaveStatus').textContent='已接受提交,等待实际执行结果';notice('配置操作已进入任务队列','提交被接受不代表应用成功,请查看实际终态。','','success',[button('查看本次操作',()=>work(()=>goOperation(s.pending.id)))]);await checkPending();} + catch(error){if(error.transport){const key=s.intent;notice('配置提交状态未确认','已保留草稿。请按意图键查询;未找到记录也不能证明一个尚未完成的请求不会执行。',key,'error',[button('按意图键查询',()=>work(async()=>{const value=await client.management({action:'get',idempotencyKey:key});s.pending=value.operation;s.intent=null;await checkPending();}))]);} + else{s.intent=null;$('awSaveStatus').textContent='未提交成功,草稿已保留';if(['STALE_CONTROL','CONTROL_HELD','UNKNOWN_EXECUTION'].includes(error.code))await configConflict(error);else report(error);}} + } + async function checkPending(){if(!s.pending||s.checkingPending)return;s.checkingPending=true;try{const id=s.pending.id;const {operation}=await client.management({action:'get',id,includeResult:true});if(s.pending?.id!==id)return;s.pending=operation;$('awSaveStatus').textContent=`${M.states[operation.state]||operation.state} · ${id.slice(0,8)}`; + if(M.terminal(operation.state)){s.pending=null;if(operation.state==='succeeded'){const current=await client.config();s.draft.reset(current);s.conflict=null;$('awConfigCompare').hidden=true;fillFields();notice('配置修改已确认完成','Host 已保存并返回应用结果。整个 Host 仍由人类持有控制,需要继续 AI 分析时显式交还。','','success',[button('查看保存与应用结果',()=>work(()=>goOperation(id)))]);await refreshControl();} + else{notice(operation.state==='unknown'?'配置执行结果未知':'配置操作未全部完成','草稿仍保留。请查看操作结果与副作用,先核对实际配置;不要直接重发写入。',operation.error?.code||operation.state,'error',[button('查看本次操作',()=>work(()=>goOperation(id)))]);try{showCompare(await client.config());}catch(error){report(error);}}permissions();} + }finally{s.checkingPending=false;permissions();}} + $('awConfigRead').onclick=()=>work(loadConfiguration);$('awSave').onclick=()=>work(saveConfiguration); + $('awExport').onclick=()=>{if(s.draft)download(s.draft.baseline,'adh-settings.json');else notice('尚未读取配置','先读取 Host 配置后导出。');}; + $('awImportButton').onclick=()=>$('awImport').click(); + $('awImport').onchange=event=>work(async()=>{const file=event.target.files[0];event.target.value='';if(!file)return;if(file.size>256*1024)throw Error('配置文件超过 256 KiB');if(!s.draft)await loadConfiguration();s.draft.import(JSON.parse(await file.text()));fillFields();notice('配置已导入草稿','尚未提交;请核对字段与版本。','','success');}); + if(options.legacySettings){$('awLegacy').hidden=false;$('awLegacy').onclick=options.legacySettings;} + async function refresh(){await Promise.all([refreshList(),refreshControl(),refreshAgents()]);await refreshTask();await checkPending();} + function start(){s.visible=true;if(timer)return;pendingTimer=setInterval(()=>{if(s.visible&&!document.hidden&&!s.busy&&s.pending)checkPending().catch(report);},1000);timer=setInterval(()=>{ + if(!s.visible||document.hidden||!$('awAuto').checked||s.busy||s.refreshing)return; + if(root.contains(document.activeElement)&&document.activeElement?.matches('input,textarea,select'))return; + s.refreshing=true;refresh().catch(report).finally(()=>s.refreshing=false); + },5000);} + buildFields();permissions();start();refresh().catch(report); + if(options.standalone){const params=new URLSearchParams(location.search);if(params.get('operation'))work(()=>goOperation(params.get('operation')));else if(params.get('task'))work(()=>selectTask(params.get('task')));} + return {open(name='tasks'){start();view(name);refresh().catch(report);},pause(){s.visible=false;clearInterval(timer);clearInterval(pendingTimer);timer=undefined;pendingTimer=undefined;},refresh}; + } + scope.AdhWorkbench={mount}; +})(globalThis); diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index ec435fc..4b82603 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -2,6 +2,13 @@ ADH Daemon / `adhd` (Node 24 + TypeScript, runs `.ts` directly, no build step). HTTP/WS `8088`, agent TCP `8761`. App pin: `GET /` and `POST //mcp`. +## P2 human workbench (2026-11-16) + +- `public/workbench.js`, `workbench.css`, `workbench.html`: the SAME task/configuration UI embedded in the live viewer and served at `/workbench`. `public/operations.js` is the thin live-view adapter; `operation-client.js` owns the shared credential/transport and legacy fetch guard. `workbench-model.js` isolates draft diff/validation/explicit rebase without DOM/I/O. +- Task get includes revision, resources and operation counts; panel task changes use `_operation.expectedTaskRevision`. Filtered lists expose independent task/operation pagination. Intent-key get is read-only recovery, never replay. +- `execution_context.ts` assigns bounded effect IDs so concurrent dispatch/acknowledgement pairs remain correct; `operations.ts` persists up to 64 metadata-only effect rows and omission counts. New operation timestamps are factual; missing legacy data stays missing. Do not include payloads/keys or turn an acknowledgement into proof of target success. +- UI is validated against a synthetic loopback Host, never the active service. Worktree isolation protects dynamically served static assets too. See [`docs/P2_WORKBENCH.md`](../../docs/P2_WORKBENCH.md). + ## P1 execution / durable tasks / operator control (2026-11-16) - `operation_registry.ts` classifies effects/resources for MCP and REST; `operation_host.ts` resolves target generations and shared API responses. `operations.ts` owns versions, scheduling, idempotency, cancellation, deadline/unknown/recovery and takeover. `task_store.ts` is an authoritative SQLite ledger, never a rebuildable cache. diff --git a/daemon/src/execution_context.ts b/daemon/src/execution_context.ts index 22d921c..5d18b3c 100644 --- a/daemon/src/execution_context.ts +++ b/daemon/src/execution_context.ts @@ -6,21 +6,22 @@ export class OperationError extends Error { } export interface ExecutionContext { checkpoint(session?: string): void; - dispatched(): void; - acknowledged(uncertain: boolean): void; + dispatched(description?: EffectDescription): string | void; + acknowledged(uncertain: boolean, id?: string | void, failed?: boolean): void; } +export interface EffectDescription { kind: string; action: string; session?: string } export const executionContext = new AsyncLocalStorage(); export function checkpoint(session?: string) { executionContext.getStore()?.checkpoint(session); } export function detached(fn: () => T): T { return executionContext.exit(fn); } -export async function trackedEffect(fn: () => Promise, session?: string): Promise { +export async function trackedEffect(fn: () => Promise, session?: string, description?: EffectDescription): Promise { const context = executionContext.getStore(); - context?.checkpoint(session); context?.dispatched(); - try { const value = await fn(); context?.acknowledged(false); return value; } - catch (error) { context?.acknowledged(true); throw error; } + context?.checkpoint(session); const id=context?.dispatched(description); + try { const value = await fn(); context?.acknowledged(false,id); return value; } + catch (error) { context?.acknowledged(true,id,true); throw error; } } -export function localEffect(fn: () => T): T { +export function localEffect(fn: () => T, description?: EffectDescription): T { const context = executionContext.getStore(); - context?.checkpoint(); context?.dispatched(); - try { const value = fn(); context?.acknowledged(false); return value; } - catch (error) { context?.acknowledged(false); throw error; } + context?.checkpoint(); const id=context?.dispatched(description || {kind:'host',action:'local mutation'}); + try { const value = fn(); context?.acknowledged(false,id); return value; } + catch (error) { context?.acknowledged(false,id,true); throw error; } } diff --git a/daemon/src/http/routes_system.ts b/daemon/src/http/routes_system.ts index 915b32a..f118a24 100644 --- a/daemon/src/http/routes_system.ts +++ b/daemon/src/http/routes_system.ts @@ -32,12 +32,17 @@ export function systemRoutes({ req, res, url, send }: RouteContext): Route[] { const buf = await readFile(file); res.writeHead(200, { 'content-type': contentType, - 'cache-control': 'public, max-age=86400', + 'cache-control': 'no-cache', 'access-control-allow-origin': '*', }); res.end(buf); }; return [ + { path:'/workbench',handler:servePublic('workbench.html','text/html; charset=utf-8') }, + { path:'/workbench.css',handler:servePublic('workbench.css','text/css; charset=utf-8') }, + { path:'/operation-client.js',handler:servePublic('operation-client.js','text/javascript; charset=utf-8') }, + { path:'/workbench-model.js',handler:servePublic('workbench-model.js','text/javascript; charset=utf-8') }, + { path:'/workbench.js',handler:servePublic('workbench.js','text/javascript; charset=utf-8') }, { path:'/operations.js',handler:servePublic('operations.js','text/javascript; charset=utf-8') }, { path: '/api/apps', handler: async () => { const scope = await scopedApps(); diff --git a/daemon/src/maintenance.ts b/daemon/src/maintenance.ts index 6248264..21fd3c1 100644 --- a/daemon/src/maintenance.ts +++ b/daemon/src/maintenance.ts @@ -9,12 +9,12 @@ export function maintainData(options: { dryRun?: boolean; confirm?: boolean } = if (!dryRun && options.confirm !== true) return { ok: false, dryRun, error: 'retention requires confirm:true; preview first' }; if(!dryRun)checkpoint(); const plan = previewArtifactRetention(); - const captures = dryRun ? retainCaptureFiles(DATA_DIR, settings.capture, true) : localEffect(() => retainCaptureFiles(DATA_DIR, settings.capture, false)); + const captures = dryRun ? retainCaptureFiles(DATA_DIR, settings.capture, true) : localEffect(() => retainCaptureFiles(DATA_DIR, settings.capture, false),{kind:'host',action:'maintenance.captures'}); if (dryRun) return { ok: captures.errors.length === 0, dryRun, policy: structuredClone({ capture: settings.capture, artifacts: settings.artifacts }), artifacts: { count: plan.evict.length, bytes: plan.evict.reduce((n, a) => n + a.size, 0), remainingBytes: plan.remainingBytes }, captures, }; - const artifacts = localEffect(() => pruneArtifactsAndIndex()); + const artifacts = localEffect(() => pruneArtifactsAndIndex(),{kind:'host',action:'maintenance.artifacts'}); applyCaptureRetainCap(); return { ok: !!artifacts && artifacts.failed === 0 && captures.errors.length === 0, dryRun, artifacts, captures }; } diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 20fce4f..14e7766 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -405,8 +405,13 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h // Optional at schema level because reads need no control token; writes enforce it at dispatch. for (const tool of MCP_TOOLS) { - (tool.inputSchema as any).properties._operation ??= { type:'object', properties:{ expectedRevision:{type:'integer'},controlEpoch:{type:'integer'},hostEpoch:{type:'integer'},taskId:{type:'string'},idempotencyKey:{type:'string'},timeoutMs:{type:'integer'} } }; + const metadata=(tool.inputSchema as any).properties._operation ??= { type:'object' }; + metadata.properties ??= { expectedRevision:{type:'integer'},controlEpoch:{type:'integer'},hostEpoch:{type:'integer'},taskId:{type:'string'},idempotencyKey:{type:'string'},timeoutMs:{type:'integer'},expectedTaskRevision:{type:'integer'} }; } +Object.assign(MCP_TOOLS.find(t=>t.name==='operations')!.inputSchema.properties,{ + q:{type:'string'},state:{type:'string'},owner:{type:'string',enum:['ai','operator']},idempotencyKey:{type:'string'}, +}); +MCP_TOOLS.find(t=>t.name==='operations')!.description+=' Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role\'s operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome.'; const requestOperations = new Map(); export const MCP_MAP = new Map(MCP_TOOLS.map(t => [t.name, t])); diff --git a/daemon/src/operation_host.ts b/daemon/src/operation_host.ts index eaf09bc..1ca5398 100644 --- a/daemon/src/operation_host.ts +++ b/daemon/src/operation_host.ts @@ -64,19 +64,18 @@ export async function manageOperations(a:any,principal:Principal,lookup?:ToolLoo return {ok:true,...engine.snapshot(a.resource || engine.resource(spec)),role:principal.role}; } if(a.action==='create')return {ok:true,task:engine.createTask(a.title,principal)}; - if(a.action==='list')return {ok:true,...engine.list(a.taskId,Math.max(1,Math.min(100,Number(a.limit)||50)),Math.max(0,Math.min(10000,Number(a.offset)||0)))}; + const page=()=>({limit:Math.max(1,Math.min(100,Math.floor(Number(a.limit)||50))),offset:Math.max(0,Math.min(10000,Math.floor(Number(a.offset)||0)))}); + if(a.action==='list')return {ok:true,...engine.list(a.taskId,page().limit,page().offset,{q:a.q,state:a.state,owner:a.owner})}; if(a.action==='get') { if(a.taskId) { - const tasks=engine.store.read().tasks; - const task=Object.hasOwn(tasks,a.taskId)?tasks[a.taskId]:undefined; - if(!task)throw new OperationError('TASK_NOT_FOUND','task does not exist'); - return {ok:true,task,...engine.list(a.taskId)}; + return {ok:true,task:engine.getTask(a.taskId),...engine.list(a.taskId,page().limit,page().offset)}; } + if(a.idempotencyKey)return {ok:true,operation:engine.findOperation(String(a.idempotencyKey),principal,a.includeResult===true)}; return {ok:true,operation:engine.getOperation(a.id,a.includeResult===true)}; } if(['pause','resume','cancel','complete'].includes(a.action)) { if(a.id && a.action==='cancel')return {ok:true,operation:engine.cancelOperation(a.id,principal)}; - return {ok:true,task:engine.taskAction(a.taskId,a.action,principal)}; + return {ok:true,task:engine.taskAction(a.taskId,a.action,principal,a._operation?.expectedTaskRevision)}; } if(['takeover','release','resolve','hold'].includes(a.action)) { return {ok:true,...engine.control(a.action==='hold'?'pause':a.action,a.resource || (a.session?targetResource(a.session):'host'),principal,a._operation || {},a.acknowledge===true)}; diff --git a/daemon/src/operations.ts b/daemon/src/operations.ts index 55b7e4e..8195cb4 100644 --- a/daemon/src/operations.ts +++ b/daemon/src/operations.ts @@ -11,6 +11,7 @@ export interface Principal { role: Role; id: string; source: string } export interface OperationMeta { expectedRevision?: number; controlEpoch?: number; hostEpoch?: number; idempotencyKey?: string; taskId?: string; timeoutMs?: number; + expectedTaskRevision?: number; } const terminal = new Set(['succeeded','failed','cancelled','unknown']); function canonical(value: any): string { @@ -19,6 +20,7 @@ function canonical(value: any): string { return JSON.stringify(value) ?? 'null'; } const fail = (code: string, message: string): never => { throw new OperationError(code, message); }; +function touchTask(task: Task) { task.revision=(task.revision ?? 0)+1;task.updatedAt=Date.now(); } function validResource(resource: string) { if(resource!=='host' && !/^target:[\w:.-]{1,400}$/.test(resource))fail('INVALID_RESOURCE','invalid control resource'); } @@ -56,10 +58,11 @@ export class Operations { op.state = op.state === 'queued' ? 'cancelled' : 'unknown'; op.error = { code: 'HOST_RESTARTED', message: 'Host stopped; execution is not replayed' }; op.updatedAt = Date.now(); + for(const effect of op.effects || [])if(effect.state==='dispatched'){effect.state='unknown';effect.uncertainAt=Date.now();} let control = data.controls[op.resource]; if (control?.active === op.id) delete control.active; if (op.mode === 'write' && op.state === 'unknown') (control ??= data.controls[op.resource] = freshControl()).uncertain = op.id; - if (data.tasks[op.taskId]) data.tasks[op.taskId].state = op.state === 'unknown' ? 'unknown' : 'paused'; + if (data.tasks[op.taskId]) {data.tasks[op.taskId].state = op.state === 'unknown' ? 'unknown' : 'paused';touchTask(data.tasks[op.taskId]);} } data.hosts[this.host] = { pid: process.pid, hostname: hostname(), active: true }; }); @@ -73,7 +76,7 @@ export class Operations { createTask(title: string, principal: Principal, implicit = false): Task { return this.store.update(data => { const task: Task = { id: randomUUID(), title: String(title || 'analysis').slice(0,256), owner: principal.role, - state: 'active', createdAt: Date.now(), updatedAt: Date.now(), implicit }; + state: 'active', createdAt: Date.now(), updatedAt: Date.now(), implicit, revision:0,createdBy:principal.id,source:principal.source }; data.tasks[task.id] = task; return task; }); } @@ -98,8 +101,8 @@ export class Operations { for (const op of Object.values(data.operations)) { if (op.owner !== 'ai' || op.state !== 'queued' || resource !== 'host' && op.resource !== resource) continue; op.state = 'failed'; op.error = { code: 'STALE_CONTROL', message: 'operator changed control before dispatch' }; - op.updatedAt = Date.now(); - if (data.tasks[op.taskId]) data.tasks[op.taskId].state = 'paused'; + op.updatedAt = Date.now();op.finishedAt=Date.now();op.settled=true; + if (data.tasks[op.taskId]) {data.tasks[op.taskId].state = 'paused';touchTask(data.tasks[op.taskId]);} } return control; } @@ -118,7 +121,7 @@ export class Operations { if (uncertain && !uncertain.settled && data.hosts[uncertain.host]?.active) fail('OPERATION_RUNNING','a timed-out handler is still awaiting target completion'); delete control.uncertain; control.epoch++; control.revision++; if(uncertain)uncertain.resolvedAt=Date.now(); - if(uncertain && data.tasks[uncertain.taskId]?.state==='unknown')data.tasks[uncertain.taskId].state='paused'; + if(uncertain && data.tasks[uncertain.taskId]?.state==='unknown'){data.tasks[uncertain.taskId].state='paused';touchTask(data.tasks[uncertain.taskId]);} } else fail('INVALID_ACTION', 'control action must be takeover|pause|release|resolve'); return { resource, ...control, hostEpoch: data.controls.host.epoch }; }); @@ -152,7 +155,7 @@ export class Operations { if (meta.taskId && !task) fail('TASK_NOT_FOUND', 'task does not exist'); if (task && (task.owner !== principal.role && principal.role !== 'operator' || task.state !== 'active')) fail('TASK_PAUSED', 'task is not active or is owned by the operator'); if (!task) { - task = { id: randomUUID(), title: spec.name, owner: principal.role, state: 'active', createdAt: Date.now(), updatedAt: Date.now(), implicit: true }; + task = { id: randomUUID(), title: spec.name, owner: principal.role, state: 'active', createdAt: Date.now(), updatedAt: Date.now(), implicit: true,revision:0,createdBy:principal.id,source:principal.source }; data.tasks[task.id] = task; } const timeout = meta.timeoutMs ?? 120000; @@ -160,7 +163,7 @@ export class Operations { const op: Operation = { id: randomUUID(), taskId: task.id, name: spec.name, resource, mode: spec.mode, owner: principal.role, actorId: principal.id, source: principal.source, host: this.host, state: 'queued', createdAt: Date.now(), updatedAt: Date.now(), deadline: Date.now() + timeout, ...expected, key, fingerprint, mayHaveExecuted: false, inFlight: 0, - uncertainEffect: false, cancelRequested: false, settled: false }; + uncertainEffect: false, cancelRequested: false, settled: false,effects:[],effectsDropped:0 }; data.operations[op.id] = op; return op; }); if (operation.host === this.host && operation.state === 'queued' && !this.completions.has(operation.id)) { @@ -184,16 +187,35 @@ export class Operations { if (includeResult && op.lateResultFile) out.lateResult = JSON.parse(readFileSync(op.lateResultFile, 'utf8')); return out; } - list(taskId?: string, limit = 50, offset = 0) { + findOperation(key: string, principal: Principal, includeResult = false) { + const op=Object.values(this.store.read().operations).find(op=>op.key===key && op.owner===principal.role); + if(!op)fail('OPERATION_NOT_FOUND','no operation is recorded for this intent key; pending transport is not proof of non-execution'); + return this.getOperation(op.id,includeResult); + } + getTask(id: string) { + const data=this.store.read(),task=Object.hasOwn(data.tasks,id)?data.tasks[id]:undefined; + if(!task)fail('TASK_NOT_FOUND','task does not exist'); + const ops=Object.values(data.operations).filter(op=>op.taskId===id),counts:Record={}; + for(const op of ops)counts[op.state]=(counts[op.state]||0)+1; + return {...task,revision:task.revision ?? 0,operationCounts:counts,totalOperations:ops.length, + resources:[...new Set(ops.map(op=>op.resource))],unresolved:ops.filter(op=>op.state==='unknown'&&!op.resolvedAt).length}; + } + list(taskId?: string, limit = 50, offset = 0, filters: {q?:string;state?:string;owner?:string} = {}) { const data = this.store.read(); - const tasks=Object.values(data.tasks).sort((a,b) => b.createdAt-a.createdAt || b.id.localeCompare(a.id)); - const operations=Object.values(data.operations).filter(op => !taskId || op.taskId === taskId).sort((a,b) => b.createdAt-a.createdAt || b.id.localeCompare(a.id)); + const query=String(filters.q||'').slice(0,256).toLowerCase(); + const tasks=Object.values(data.tasks).filter(t=>(!taskId||t.id===taskId)&&(!query||[t.title,t.id,t.source,t.createdBy].join(' ').toLowerCase().includes(query))&&(!filters.state||t.state===filters.state)&&(!filters.owner||t.owner===filters.owner)) + .sort((a,b) => b.createdAt-a.createdAt || b.id.localeCompare(a.id)).map(t=>({...t,revision:t.revision ?? 0})); + const selected=new Set(tasks.map(t=>t.id)); + const operations=Object.values(data.operations).filter(op => selected.has(op.taskId)).sort((a,b) => b.createdAt-a.createdAt || b.id.localeCompare(a.id)); return {tasks:tasks.slice(offset,offset+limit),operations:operations.slice(offset,offset+limit),totalTasks:tasks.length,totalOperations:operations.length, + nextTaskOffset:offset+limit { const task = Object.hasOwn(data.tasks,id)?data.tasks[id]:undefined; if (!task) fail('TASK_NOT_FOUND', 'task does not exist'); + if(expectedRevision!==undefined && (!Number.isSafeInteger(expectedRevision)||expectedRevision<0))fail('INVALID_TASK_VERSION','expectedTaskRevision must be a non-negative integer'); + if(expectedRevision!==undefined && expectedRevision!==(task.revision ?? 0))fail('STALE_TASK','task version changed; reload and review before changing its state'); if (principal.role !== 'operator' && task.owner !== principal.role) fail('OPERATOR_REQUIRED', 'task is owned by operator'); if(principal.role!=='operator' && task.heldByOperator)fail('OPERATOR_REQUIRED','operator paused this task; explicit operator resume required'); if(principal.role!=='operator' && Object.values(data.operations).some(op=>op.taskId===id && op.owner==='operator' && (!terminal.has(op.state)||op.state==='unknown'&&!op.resolvedAt)))fail('OPERATOR_REQUIRED','task contains unfinished operator work'); @@ -218,7 +240,7 @@ export class Operations { if (Object.values(data.operations).some(op=>op.taskId===id && op.state==='unknown' && !op.resolvedAt))task.state='unknown'; else if (!Object.values(data.operations).some(op => op.taskId === id && !terminal.has(op.state))) task.state = 'cancelled'; } else fail('INVALID_ACTION', 'task action must be pause|resume|cancel|complete'); - task.updatedAt = Date.now(); return task; + touchTask(task); return task; }); this.pump(); return out; } @@ -231,7 +253,7 @@ export class Operations { current.cancelRequested=true; if(current.state==='queued'){current.state='cancelled';current.settled=true;}else current.state='cancel_requested'; current.updatedAt=Date.now(); - if(data.tasks[current.taskId].implicit)data.tasks[current.taskId].state=current.state==='cancelled'?'cancelled':'cancel_requested'; + if(data.tasks[current.taskId].implicit){data.tasks[current.taskId].state=current.state==='cancelled'?'cancelled':'cancel_requested';touchTask(data.tasks[current.taskId]);} }); this.pump();return this.getOperation(id); } @@ -249,6 +271,9 @@ export class Operations { catch (failure) { state = 'unknown'; error = { code: 'RESULT_PERSIST_FAILED', message: (failure as Error).message }; } this.store.update(data => { const op = data.operations[id]; op.state = state; op.updatedAt = Date.now(); op.error = error; op.resultFile = file; + if(!this.running.has(id)&&!op.inFlight)op.settled=true; + op.finishedAt=Date.now(); + if(state==='unknown')for(const effect of op.effects || [])if(effect.state==='dispatched'){effect.state='unknown';effect.uncertainAt=Date.now();} const control = data.controls[op.resource]; if (control?.active === id) delete control.active; if (op.mode === 'write' && state === 'unknown') (data.controls[op.resource] ??= freshControl()).uncertain = id; @@ -258,7 +283,7 @@ export class Operations { task.state=Object.values(data.operations).some(x=>x.taskId===task.id && x.state==='unknown' && !x.resolvedAt)?'unknown':task.implicit && state==='succeeded'?'completed':'cancelled'; } else if (task.implicit && task.state === 'active') task.state = 'completed'; - task.updatedAt = Date.now(); + touchTask(task); }); this.notify(id); } @@ -294,7 +319,7 @@ export class Operations { if (control.uncertain || data.controls.host.uncertain || op.resource === 'host' && Object.values(data.controls).some(c => c.uncertain)) fail('UNKNOWN_EXECUTION','resource has unresolved side effects; inspect and resolve first'); control.revision++; control.active=op.id; op.appliedRevision=control.revision; } - op.state='running'; op.updatedAt=Date.now(); return op; + op.state='running'; op.startedAt=Date.now();op.updatedAt=Date.now(); return op; }); this.running.add(op.id); const targetEpochs = new Map(); @@ -321,8 +346,17 @@ export class Operations { } } }, - dispatched: () => this.store.update(data => { const x=data.operations[op.id]; x.mayHaveExecuted=true; x.inFlight++; }), - acknowledged: uncertain => { if(!this.closed)this.store.update(data => { const x=data.operations[op.id]; x.inFlight=Math.max(0,x.inFlight-1); x.uncertainEffect ||= uncertain; }); }, + dispatched: description => this.store.update(data => { + const x=data.operations[op.id];x.mayHaveExecuted=true;x.inFlight++; + if((x.effects?.length||0)>=64){x.effectsDropped=(x.effectsDropped||0)+1;return;} + const id=randomUUID();(x.effects??=[]).push({id,kind:String(description?.kind||'external').slice(0,40),action:String(description?.action||'external request').slice(0,160), + session:description?.session,state:'dispatched',startedAt:Date.now()});return id; + }), + acknowledged: (uncertain,id,failed) => { if(!this.closed)this.store.update(data => { + const x=data.operations[op.id];x.inFlight=Math.max(0,x.inFlight-1);x.uncertainEffect ||= uncertain; + const effect=id&&x.effects?.find(effect=>effect.id===id); + if(effect){effect.state=uncertain?'unknown':failed?'failed':'acknowledged';effect.completedAt=Date.now();if(uncertain)effect.uncertainAt=Date.now();} + }); }, }; const timer=setTimeout(() => { if(this.closed)return; diff --git a/daemon/src/service.ts b/daemon/src/service.ts index be44749..2dae5b1 100644 --- a/daemon/src/service.ts +++ b/daemon/src/service.ts @@ -85,7 +85,7 @@ export function sendCmd(sessionId: string, op: string, args: Record { diff --git a/daemon/src/settings_service.ts b/daemon/src/settings_service.ts index 579a30c..2af0dc2 100644 --- a/daemon/src/settings_service.ts +++ b/daemon/src/settings_service.ts @@ -18,7 +18,7 @@ export function patchSettings(patch: unknown, applyCapture = applyCaptureEnabled const applied = mergeSettings(patch, candidate); if (!applied.length) return { ok: false, code: 'INVALID_SETTINGS', error: 'no supported settings sections', persisted: false, applied }; checkpoint(); - try { localEffect(() => saveSettings(candidate)); } + try { localEffect(() => saveSettings(candidate),{kind:'host',action:'settings.save'}); } catch (error) { return { ok: false, code: 'SETTINGS_PERSIST_FAILED', error: `settings were not saved or applied: ${(error as Error).message}`, persisted: false, applied: [] as string[], settings: structuredClone(settings) }; } diff --git a/daemon/src/task_store.ts b/daemon/src/task_store.ts index b58bdb9..6677733 100644 --- a/daemon/src/task_store.ts +++ b/daemon/src/task_store.ts @@ -9,6 +9,14 @@ export interface Task { id: string; title: string; owner: Role; state: 'active' | 'paused' | 'cancel_requested' | 'cancelled' | 'completed' | 'unknown'; createdAt: number; updatedAt: number; implicit: boolean; heldByOperator?: boolean; + revision?: number; + createdBy?: string; + source?: string; +} +export interface Effect { + id: string; kind: string; action: string; session?: string; + state: 'dispatched' | 'acknowledged' | 'failed' | 'unknown'; + startedAt: number; completedAt?: number; uncertainAt?: number; } export interface Operation { id: string; taskId: string; name: string; resource: string; mode: 'read' | 'analysis' | 'write'; owner: Role; @@ -19,6 +27,7 @@ export interface Operation { lateResultFile?: string; partialEffects?: boolean; appliedRevision?: number; resolvedAt?: number; + startedAt?: number; finishedAt?: number; effects?: Effect[]; effectsDropped?: number; } export interface Ledger { schemaVersion: 1; controls: Record; tasks: Record; operations: Record; diff --git a/daemon/test/fixtures/p2_workbench.ts b/daemon/test/fixtures/p2_workbench.ts new file mode 100644 index 0000000..041801b --- /dev/null +++ b/daemon/test/fixtures/p2_workbench.ts @@ -0,0 +1,53 @@ +// Standalone synthetic workbench Host; no index.ts, real ADB, live data or real target. +import cp from 'node:child_process'; +import {syncBuiltinESMExports} from 'node:module'; +import {promisify} from 'node:util'; +import {mkdtempSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import http from 'node:http'; +process.env.ADH_DATA_DIR=mkdtempSync(join(tmpdir(),'adh-p2-panel-')); +delete process.env.ADH_CAPTURES_DIR;process.env.ADH_SKIP_ARTIFACT_LOAD='1';process.env.ADH_OPERATOR_TOKEN='synthetic-p2-operator-key'; +cp.execFile=(()=>{throw Error('real subprocess forbidden in P2 fixture');}) as unknown as typeof cp.execFile; +Object.defineProperty(cp.execFile,promisify.custom,{value:async(file:string,args:string[])=>{ + if(file==='adb'&&args.some(a=>a.includes('cat /data/adb/adh/scope.json')))return {stdout:'{"packages":[]}',stderr:''}; + throw Error('device subprocess forbidden in P2 fixture'); +}}); +cp.spawn=(()=>{throw Error('spawn forbidden in P2 fixture');}) as unknown as typeof cp.spawn;syncBuiltinESMExports(); +const {handleHttp}=await import('../../src/http/router.ts'); +const {sessions,agentSockets,pending,readBody}=await import('../../src/state.ts'); +const {getOperations,targetResource}=await import('../../src/operation_host.ts'); +const {trackedEffect}=await import('../../src/execution_context.ts'); +const {patchSettings}=await import('../../src/settings_service.ts'); +const {sendCmd}=await import('../../src/service.ts'); +const ai={role:'ai' as const,id:'synthetic-ai',source:'mcp'},human={role:'operator' as const,id:'synthetic-human',source:'panel'}; +for(const [sid,pid]of [['p2-fixture',42],['p2-uncertain',43]] as const){ + sessions.set(sid,{sessionId:sid,package:'com.example.fixture',process:'com.example.fixture',pid,uid:10001,starttimeTicks:'1',online:true,agentVer:'synthetic',abi:'arm64-v8a',android:'15',sdk:35,entry:'fixture'} as any); + agentSockets.set(sid,{destroyed:false,write(frame:Buffer){const m=JSON.parse(frame.subarray(5).toString());queueMicrotask(()=>pending.get(m.id)?.resolve({ok:true,before:'00',beforeReadable:true,wrote:1,regions:[]}));return true;}} as any); +} +const engine=getOperations(); +const meta=(resource='host')=>{const c=engine.snapshot(resource);return {expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch};}; +const task=engine.createTask('请求边界分析 · 合成样本',ai); +await engine.execute({name:'证据一致性检查',mode:'analysis'},{},ai,{taskId:task.id},async()=>({ok:true,matched:3,note:'合成结果,仅用于面板验收',untrustedText:''})); +await engine.execute({name:'memory_write',mode:'write',session:'p2-fixture'},{},ai,{taskId:task.id,...meta(targetResource('p2-fixture'))},()=>sendCmd('p2-fixture','write',{addr:'1000',hex:'41'})); +engine.taskAction(task.id,'complete',ai); +const paused=engine.createTask('等待下一轮实验',ai); +engine.submit({name:'待执行的合成观察',mode:'write',session:'p2-fixture'},{},ai,{taskId:paused.id,...meta(targetResource('p2-fixture'))},()=>sendCmd('p2-fixture','maps')); +engine.taskAction(paused.id,'pause',human); +let release!:()=>void;const gate=new Promise(r=>release=r); +const unknown=await engine.execute({name:'超时观察 · 合成样本',mode:'write',session:'p2-uncertain'},{},ai,{...meta(targetResource('p2-uncertain')),timeoutMs:1000},()=>trackedEffect(async()=>{await gate;return {ok:true,note:'晚到的合成结果'};},'p2-uncertain',{kind:'agent',action:'fixture observation',session:'p2-uncertain'})); +release();await new Promise(r=>setTimeout(r,20)); +const server=http.createServer((req,res)=>{ + const finish=(status:number,value:any)=>{res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify(value));}; + (async()=>{ + if(req.url==='/__fixture/state')return finish(200,{task:task.id,paused:paused.id,unknown:unknown.id,root:process.env.ADH_DATA_DIR}); + if(req.url==='/__fixture/ai-config'&&req.method==='POST'){ + const patch=JSON.parse(await readBody(req)||'{}');const result=await engine.execute({name:'settings',mode:'write',global:true},patch,ai,meta(),()=>patchSettings(patch));return finish(200,result); + } + if(req.url==='/__fixture/task-change'&&req.method==='POST')return finish(200,engine.taskAction(paused.id,'pause',human)); + return handleHttp(req,res); + })().catch(error=>finish(500,{error:String(error)})); +}); +server.listen(0,'127.0.0.1',()=>console.log('P2_WORKBENCH_URL=http://127.0.0.1:'+(server.address() as any).port)); +const stop=()=>{server.closeAllConnections();server.close();engine.close();process.exit(0);}; +process.on('SIGINT',stop);process.stdin.resume();process.stdin.on('data',line=>{if(String(line).trim()==='stop')stop();}); diff --git a/daemon/test/operation_entrypoints.test.ts b/daemon/test/operation_entrypoints.test.ts index 1f90f80..2365a63 100644 --- a/daemon/test/operation_entrypoints.test.ts +++ b/daemon/test/operation_entrypoints.test.ts @@ -5,6 +5,7 @@ import cp from 'node:child_process'; import {promisify} from 'node:util'; import {syncBuiltinESMExports} from 'node:module'; import {resolve,join} from 'node:path'; +import {existsSync} from 'node:fs'; const executeChild=promisify(cp.execFile),oldExec=cp.execFile,oldSpawn=cp.spawn; cp.execFile=(()=>{throw Error('device subprocess forbidden in P1 fixture');}) as unknown as typeof cp.execFile; @@ -109,9 +110,11 @@ test('MCP cancellation notification binds to the client request and reports a ru }); test('public Python CLI submits to this same Host, reads durable results and never upgrades AI using an inherited operator key',async t=>{ + const cliSource=process.env.ADH_CLI_SOURCE||resolve('../..','adh-cli','src'); + if(!existsSync(join(cliSource,'adh','__init__.py'))){t.skip('adjacent adh-cli source unavailable; set ADH_CLI_SOURCE in isolated worktrees');return;} try{await executeChild('python',['--version'],{timeout:5000,windowsHide:true});}catch(error){if((error as any).code==='ENOENT'){t.skip('Python unavailable');return;}throw error;} const session='entry-cli',fake=fakeSession(session); - const env={...process.env,PYTHONPATH:resolve('../..','adh-cli','src'),ADH_CONFIG_PATH:join(DATA_DIR,'cli-fixture.json'),PYTHONIOENCODING:'utf-8',ADH_OPERATOR_TOKEN:key}; + const env={...process.env,PYTHONPATH:cliSource,ADH_CONFIG_PATH:join(DATA_DIR,'cli-fixture.json'),PYTHONIOENCODING:'utf-8',ADH_OPERATOR_TOKEN:key}; async function cli(args:string[]) { const result=await executeChild('python',['-m','adh',...args,'--endpoint',base,'--json'],{env,timeout:15000,windowsHide:true}); return JSON.parse(String(result.stdout)); diff --git a/daemon/test/operations.test.ts b/daemon/test/operations.test.ts index 499ab7c..5bc8ac4 100644 --- a/daemon/test/operations.test.ts +++ b/daemon/test/operations.test.ts @@ -108,6 +108,7 @@ test('timeout records unknown, blocks retries and preserves late evidence withou release();await until(()=>f.engine.getOperation(result.id).settled); const observed=f.engine.getOperation(result.id,true); assert.equal(observed.state,'unknown');assert.equal(observed.lateResult.value,'late'); + assert.equal(observed.effects[0].state,'acknowledged');assert.ok(observed.effects[0].uncertainAt,'late acknowledgement must preserve prior uncertainty'); f.engine.control('resolve','target:one',human,metadata(f.engine),true); assert.equal((await f.engine.execute(spec,{},ai,metadata(f.engine),async()=>({ok:true}))).state,'succeeded'); }finally{f.close();} @@ -203,6 +204,7 @@ test('queued deadline expiration confirms nothing was sent, including while the await until(()=>f.engine.getOperation(op.id).state==='failed'); assert.equal(f.engine.getOperation(op.id).error.code,'DEADLINE_EXCEEDED'); assert.equal(f.engine.getOperation(op.id).mayHaveExecuted,false); + assert.equal(f.engine.getOperation(op.id).settled,true,'no Host handler was started for queued expiration'); }finally{f.close();} }); diff --git a/daemon/test/workbench_http.test.ts b/daemon/test/workbench_http.test.ts new file mode 100644 index 0000000..c80ab3f --- /dev/null +++ b/daemon/test/workbench_http.test.ts @@ -0,0 +1,53 @@ +import test,{before,after} from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import cp from 'node:child_process'; +import {syncBuiltinESMExports} from 'node:module'; + +const oldExec=cp.execFile,oldSpawn=cp.spawn; +cp.execFile=(()=>{throw Error('device subprocess forbidden in P2 HTTP fixture');}) as unknown as typeof cp.execFile; +cp.spawn=(()=>{throw Error('device subprocess forbidden in P2 HTTP fixture');}) as unknown as typeof cp.spawn;syncBuiltinESMExports(); +const {handleHttp}=await import('../src/http/router.ts'); +const {getOperations,operationsRoot}=await import('../src/operation_host.ts'); +const {initializeOperatorAccess}=await import('../src/access_context.ts'); +const key=initializeOperatorAccess(operationsRoot),engine=getOperations(); +const server=http.createServer((req,res)=>{handleHttp(req,res).catch(e=>{res.writeHead(500);res.end(JSON.stringify({error:String(e)}));});}); +let base:string; +before(async()=>{await new Promise(r=>server.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+(server.address() as any).port;}); +after(async()=>{await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));engine.close();cp.execFile=oldExec;cp.spawn=oldSpawn;syncBuiltinESMExports();}); +async function call(value:any,operator=false){const response=await fetch(base+'/api/operations',{method:'POST',headers:{'content-type':'application/json',...(operator?{'X-Adh-Operator-Key':key}:{})},body:JSON.stringify(value)});return {status:response.status,body:await response.json() as any};} +const metadata=()=>{const c=engine.snapshot();return {expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch};}; + +test('workbench assets load from the same isolated router without exposing an operator secret',async()=>{ + for(const path of ['/workbench','/workbench.css','/operation-client.js','/workbench-model.js','/workbench.js','/operations.js']){ + const response=await fetch(base+path);assert.equal(response.status,200);assert.equal(response.headers.get('cache-control'),'no-cache'); + const body=await response.text();assert.ok(!body.includes(key)); + } +}); + +test('task CAS, pagination and explicit operator resume have the same HTTP contract as MCP',async()=>{ + const created=(await call({action:'create',title:'human workbench'})).body.task; + let value=await call({action:'get',taskId:created.id,limit:1,offset:0});assert.equal(value.body.task.revision,0);assert.equal(value.body.totalTasks,1); + value=await call({action:'pause',taskId:created.id,_operation:{expectedTaskRevision:0}},true);assert.equal(value.status,200);assert.equal(value.body.task.revision,1); + value=await call({action:'resume',taskId:created.id,_operation:{expectedTaskRevision:0}},true);assert.equal(value.status,409);assert.equal(value.body.code,'STALE_TASK'); + value=await call({action:'resume',taskId:created.id,_operation:{expectedTaskRevision:1}});assert.equal(value.body.code,'OPERATOR_REQUIRED'); + value=await call({action:'resume',taskId:created.id,_operation:{expectedTaskRevision:1}},true);assert.equal(value.body.task.state,'active');assert.equal(value.body.task.heldByOperator,false); + assert.equal((await call({action:'list',q:'human workbench'})).body.totalTasks,1); +}); + +test('a stale configuration submit is rejected without changing settings; accepted intent can be queried by key',async()=>{ + const old=metadata(); + let response=await fetch(base+'/api/config',{method:'POST',headers:{'content-type':'application/json','X-Adh-Operation':JSON.stringify(old)},body:JSON.stringify({ui:{displayCap:377}})}); + assert.equal(response.status,200); + let result=await call({action:'submit',tool:'settings',arguments:{action:'patch',patch:{ui:{displayCap:411}}},_operation:old},true); + assert.equal(result.status,409);assert.equal(result.body.code,'STALE_CONTROL'); + let config=await (await fetch(base+'/api/config')).json() as any;assert.equal(config.settings.ui.displayCap,377); + result=await call({action:'submit',tool:'settings',arguments:{action:'patch',patch:{ui:{displayCap:411}}},_operation:{...metadata(),idempotencyKey:'reviewed-human-intent'}},true); + assert.equal(result.status,200);const id=result.body.operation.id; + for(let n=0;n<100&&!engine.getOperation(id).settled;n++)await new Promise(r=>setTimeout(r,5)); + const found=await call({action:'get',idempotencyKey:'reviewed-human-intent',includeResult:true},true); + assert.equal(found.body.operation.id,id);assert.equal(found.body.operation.state,'succeeded'); + assert.equal(found.body.operation.effects[0].action,'settings.save');assert.equal(found.body.operation.effects[0].state,'acknowledged'); + assert.equal((await call({action:'get',idempotencyKey:'reviewed-human-intent'})).body.code,'OPERATION_NOT_FOUND'); + config=await (await fetch(base+'/api/config')).json() as any;assert.equal(config.settings.ui.displayCap,411); +}); diff --git a/daemon/test/workbench_model.test.ts b/daemon/test/workbench_model.test.ts new file mode 100644 index 0000000..05f8b7c --- /dev/null +++ b/daemon/test/workbench_model.test.ts @@ -0,0 +1,58 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import vm from 'node:vm'; +import {webcrypto} from 'node:crypto'; + +const sandbox:any={console,AbortController,setTimeout,clearTimeout,Uint8Array,Headers,URL,crypto:webcrypto}; +vm.runInNewContext(readFileSync(new URL('../public/workbench-model.js',import.meta.url),'utf8'),sandbox); +vm.runInNewContext(readFileSync(new URL('../public/operation-client.js',import.meta.url),'utf8'),sandbox); +const M=sandbox.AdhWorkbenchModel,Client=sandbox.AdhOperationClient; +const plain=value=>JSON.parse(JSON.stringify(value)); +const baseline=()=>({settings:{ui:{displayCap:300},capture:{enabled:true,fileModule:''}},control:{resource:'host',revision:1,epoch:2,hostEpoch:2}}); + +test('a config draft submits only changed leaves and preserves unknown configuration',()=>{ + const snapshot=baseline();snapshot.settings['future']={preserve:true};const draft=new M.Draft(snapshot); + M.set(draft.draft,'ui.displayCap',411); + assert.deepEqual(plain(draft.patch()),{ui:{displayCap:411}}); + assert.deepEqual(draft.control.revision,1);assert.equal(draft.draft.future.preserve,true); + snapshot.control.revision=99;assert.equal(draft.control.revision,1,'read snapshots are not a mutable draft token'); +}); + +test('explicit rebase preserves human intent while adopting concurrent changes to untouched fields',()=>{ + const draft=new M.Draft(baseline());M.set(draft.draft,'ui.displayCap',411); + const latest=baseline();latest.control.revision=5;latest.settings.capture.fileModule='from-ai.so';latest.settings.ui.displayCap=377; + const rows=plain(draft.compare(latest));assert.ok(rows.find(row=>row.path==='capture.fileModule'&&!row.local)); + assert.equal(draft.control.revision,1,'comparison must not silently freshen a write'); + draft.rebase(latest); + assert.equal(draft.draft.capture.fileModule,'from-ai.so');assert.equal(draft.draft.ui.displayCap,411); + assert.deepEqual(plain(draft.patch()),{ui:{displayCap:411}});assert.equal(draft.control.revision,5); +}); + +test('invalid imports cannot become silently ignored settings or pollute prototypes',()=>{ + for(const value of [{ui:{displayCap:2}},{startup:{module:''}},{startup:{packages:['bad package']}},{capture:{families:{unknown:true}}},JSON.parse('{"__proto__":{"polluted":true}}')])assert.throws(()=>M.validatePatch(value)); + assert.equal({}['polluted'],undefined); + assert.doesNotThrow(()=>M.validatePatch({capture:{enabled:false},startup:{extraTargets:['access']}})); +}); + +test('panel submission preserves the observed versions and intent key across a stale response',async()=>{ + const calls:any[]=[],client=new Client(async(path,init)=>{calls.push({path,body:JSON.parse(init.body)});return new Response(JSON.stringify({ok:false,code:'STALE_CONTROL',error:'changed'}),{status:409});},webcrypto); + client.key='synthetic-key';const observed=baseline().control; + await assert.rejects(()=>client.submitSettings({ui:{displayCap:411}},observed,'one-intent'),(e:any)=>e.code==='STALE_CONTROL'); + assert.equal(calls.length,1);assert.deepEqual(plain(calls[0].body._operation),{expectedRevision:1,controlEpoch:2,hostEpoch:2,idempotencyKey:'one-intent'}); +}); + +test('transport failure remains unconfirmed and never automatically retries a write',async()=>{ + let calls=0;const client=new Client(async()=>{calls++;throw new TypeError('synthetic disconnect');},webcrypto);client.key='synthetic-key'; + await assert.rejects(()=>client.submitSettings({ui:{displayCap:411}},baseline().control,'pending-intent'),(e:any)=>e.transport===true&&e.code==='TRANSPORT_UNCONFIRMED'); + assert.equal(calls,1); +}); + +test('config reads require a Host version header; credentials and task revisions stay explicit',async()=>{ + const calls:any[]=[],client=new Client(async(path,init)=>{calls.push({path,init});return new Response(JSON.stringify({ok:true,settings:baseline().settings}),{status:200});},webcrypto); + await assert.rejects(()=>client.config(),(e:any)=>e.code==='CONTROL_REQUIRED'); + await assert.rejects(()=>client.taskAction({id:'task',revision:7},'pause'),(e:any)=>e.code==='OPERATOR_REQUIRED'); + client.key='synthetic-key';await client.taskAction({id:'task',revision:7},'pause'); + assert.equal(JSON.parse(calls.at(-1).init.body)._operation.expectedTaskRevision,7);client.disconnect();assert.equal(client.operator,false); + client.key='synthetic-key';await assert.rejects(()=>client.taskAction({id:'legacy-task'},'pause'),(e:any)=>e.code==='TASK_VERSION_REQUIRED'); +}); diff --git a/daemon/test/workbench_state.test.ts b/daemon/test/workbench_state.test.ts new file mode 100644 index 0000000..3a8a082 --- /dev/null +++ b/daemon/test/workbench_state.test.ts @@ -0,0 +1,76 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {Operations,type Principal} from '../src/operations.ts'; +import {trackedEffect,localEffect} from '../src/execution_context.ts'; + +const ai:Principal={role:'ai',id:'fixture-ai',source:'mcp'},human:Principal={role:'operator',id:'fixture-human',source:'panel'}; +function fixture(){const root=mkdtempSync(join(tmpdir(),'adh-p2-test-')),engine=new Operations(root);return {engine,close(){engine.close();assert.ok(root.startsWith(join(tmpdir(),'adh-p2-test-')));rmSync(root,{recursive:true,force:true});}};} +const delay=(ms:number)=>new Promise(resolve=>setTimeout(resolve,ms)); +async function until(fn:()=>boolean){for(let n=0;n<500&&!fn();n++)await delay(2);assert.ok(fn());} + +test('task revisions reject stale human controls without clearing an operator pause',()=>{ + const f=fixture();try{ + const task=f.engine.createTask('analysis',ai),observed=f.engine.getTask(task.id); + assert.equal(observed.revision,0);assert.equal(observed.source,'mcp'); + f.engine.taskAction(task.id,'pause',human,observed.revision); + assert.throws(()=>f.engine.taskAction(task.id,'resume',human,observed.revision),(e:any)=>e.code==='STALE_TASK'); + assert.equal(f.engine.getTask(task.id).heldByOperator,true);assert.equal(f.engine.getTask(task.id).state,'paused'); + const fresh=f.engine.getTask(task.id);f.engine.taskAction(task.id,'resume',human,fresh.revision); + assert.equal(f.engine.getTask(task.id).heldByOperator,false); + assert.throws(()=>f.engine.taskAction(task.id,'pause',human,-1),(e:any)=>e.code==='INVALID_TASK_VERSION'); + }finally{f.close();} +}); + +test('legacy tasks expose revision zero; search, task detail and operation pages cover retained records',async()=>{ + const f=fixture();try{ + const first=f.engine.createTask('older task',ai),last=f.engine.createTask('needle task',ai); + f.engine.store.update(data=>{delete data.tasks[first.id].revision;}); + assert.equal(f.engine.getTask(first.id).revision,0); + for(let n=0;n<7;n++)await f.engine.execute({name:'analysis '+n,mode:'analysis'},{},ai,{taskId:first.id},async()=>({ok:true,n})); + const page=f.engine.list(first.id,3,3);assert.equal(page.tasks.length,0);assert.equal(page.totalTasks,1); + assert.equal(page.operations.length,3);assert.equal(page.nextOperationOffset,6);assert.equal(page.nextTaskOffset,null); + assert.equal(f.engine.getTask(first.id).totalOperations,7); + assert.deepEqual(f.engine.getTask(first.id).operationCounts,{succeeded:7}); + assert.deepEqual(f.engine.list(undefined,10,0,{q:'needle'}).tasks.map(t=>t.id),[last.id]); + assert.equal(f.engine.list(undefined,10,0,{owner:'operator'}).totalTasks,0); + }finally{f.close();} +}); + +test('effect acknowledgements match concurrent dispatches and exclude command payloads',async()=>{ + const f=fixture();try{ + const task=f.engine.createTask('parallel reads',ai);let first!:()=>void,second!:()=>void; + const a=new Promise(r=>first=r),b=new Promise(r=>second=r); + const op=f.engine.submit({name:'inspect',mode:'analysis'},{privatePayload:'synthetic-private-bytes'},ai,{taskId:task.id},async()=>{ + await Promise.all([trackedEffect(()=>a,undefined,{kind:'agent',action:'maps'}),trackedEffect(()=>b,undefined,{kind:'agent',action:'read'})]);return {ok:true}; + }); + await until(()=>f.engine.getOperation(op.id).inFlight===2);second();await until(()=>f.engine.getOperation(op.id).inFlight===1); + let effects=f.engine.getOperation(op.id).effects;assert.equal(effects[0].state,'dispatched');assert.equal(effects[1].state,'acknowledged'); + first();await until(()=>f.engine.getOperation(op.id).settled);effects=f.engine.getOperation(op.id).effects; + assert.equal(effects[0].state,'acknowledged');assert.ok(effects[0].completedAt); + assert.ok(f.engine.getOperation(op.id).startedAt);assert.ok(f.engine.getOperation(op.id).finishedAt); + assert.ok(!JSON.stringify(f.engine.store.read()).includes('synthetic-private-bytes')); + }finally{f.close();} +}); + +test('effect journal is bounded and reports omitted steps without losing dispatch accounting',async()=>{ + const f=fixture();try{ + const value=await f.engine.execute({name:'bounded local work',mode:'analysis'},{},ai,{},async()=>{ + for(let n=0;n<67;n++)localEffect(()=>{}, {kind:'host',action:'fixture step'});return {ok:true}; + }); + assert.equal(value.effects.length,64);assert.equal(value.effectsDropped,3);assert.equal(value.inFlight,0);assert.equal(value.state,'succeeded'); + assert.ok(value.effects.every(e=>e.state==='acknowledged')); + }finally{f.close();} +}); + +test('intent lookup is read-only, uses the original role namespace and never resubmits',async()=>{ + const f=fixture();try{ + const op=await f.engine.execute({name:'saved analysis',mode:'analysis'},{},human,{idempotencyKey:'lost-ack'},async()=>({ok:true,value:42})); + assert.equal(f.engine.findOperation('lost-ack',human,true).result.value,42); + assert.equal(f.engine.findOperation('lost-ack',human).id,op.id); + assert.throws(()=>f.engine.findOperation('lost-ack',ai),(e:any)=>e.code==='OPERATION_NOT_FOUND'); + assert.equal(f.engine.list().totalOperations,1); + }finally{f.close();} +}); diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md index 38fc596..a577535 100644 --- a/docs/DEVELOPMENT_PLAN.md +++ b/docs/DEVELOPMENT_PLAN.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 开发计划 +> **2026-11-16 P2 实施**:完成同一工作台的独立/现场入口、任务详情/结果/副作用、配置草稿/并发冲突核对、任务 CAS 与暂停恢复、显式接管/交还及 unknown 核对。AI 规划与执行继续由外部 Harness 主导,面板不要求预先接管或固定 recipe。模块/边界见 [P2_WORKBENCH.md](P2_WORKBENCH.md);P3/P4 的设备域与新传输仍未实施,当前分析实例不升级。 + > **2026-11-16 P1 实施**:共享执行器、持久任务、状态版本/控制 epoch、人类接管、真实超时/取消反馈与最小面板控制入口已落地,见 [P1_OPERATIONS.md](P1_OPERATIONS.md)。P2 仍需完整任务工作台/编辑体验;P3/P4 的稳定设备身份和 USB/LAN 新 RPC、配对/TLS 尚未实现。本轮不替换当前运行实例。 > **2026-11-16 P0 实施记录**:F01 作用域策略保留、F02 共享设置应用、F04 非破坏性显式恢复与独立清理已在 Host 源码落地,见 [P0 实现与迁移](P0_HOST_STATE.md)。当前分析现场不升级;人工接管后续进展以上方 P1 条目为准。 diff --git a/docs/FEATURE_STATUS.md b/docs/FEATURE_STATUS.md index bcd486d..a9f44f2 100644 --- a/docs/FEATURE_STATUS.md +++ b/docs/FEATURE_STATUS.md @@ -1,5 +1,7 @@ # ADH 功能状态(2026-10-24 更新:通用原生分析与证据核验;各轮实测范围见 §2) +> **2026-11-16 P2**:人类任务工作台已在隔离 Host/浏览器验收,含任务搜索分页、详情/结果/下载、有限副作用日志、配置草稿与显式冲突核对、暂停恢复、接管/交还与 unknown。完整 Host **525 passed / 0 failed / 0 skipped**;模块与限制见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。交付在独立 worktree;原工作目录保留 P1,当前服务与真实设备未部署或升级。 + > **2026-11-16 P1**:统一操作执行层、SQLite 持久任务、revision/epoch 控制权、人类修改防旧写、超时 unknown/晚到证据、真实取消状态与最小面板已在隔离 Host 验证。公共 adh-cli 同步提供 run/tasks/control,尚未发布或替换本机安装包。接口/限制见 [P1_OPERATIONS.md](P1_OPERATIONS.md);完整计数见 PROGRESS.md。源码未加载到当前分析服务,USB/LAN 新协议与真机效果不在本轮验收范围。 > **2026-11-16 P0**:Host 作用域完整保留、MCP/面板共享设置、显式非破坏性初始化与独立维护已实现并纳入隔离回归;详情与验证见 [P0_HOST_STATE.md](P0_HOST_STATE.md) / PROGRESS.md。未部署、未重启当前服务、未执行真机升级验收;不要将源码状态当成当前运行实例状态。 diff --git a/docs/P1_OPERATIONS.md b/docs/P1_OPERATIONS.md index 585167f..1dc522a 100644 --- a/docs/P1_OPERATIONS.md +++ b/docs/P1_OPERATIONS.md @@ -1,5 +1,7 @@ # P1:统一操作、持久任务与控制权(2026-11-16) +后续 P2 已补齐人类工作台,并增补 task revision、结果/副作用查看和配置冲突核对,见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。下文保留 P1 实施边界;P2 的新增可选字段兼容旧账本和 CLI,不自动重写历史。 + 本次交付是 Host 源码与 CLI 源码,未部署到当前分析现场。没有更改 agent、设备 APK、TCP 线协议或 USB/LAN 传输。AI 仍自主规划,recipe 是可选工具;人类面板可以查看任务、提交修改、接管和释放。 配套 `adh-cli` 本地提交:`f086459`(未推送、未发布)。 diff --git a/docs/P2_WORKBENCH.md b/docs/P2_WORKBENCH.md new file mode 100644 index 0000000..cdab134 --- /dev/null +++ b/docs/P2_WORKBENCH.md @@ -0,0 +1,69 @@ +# P2:人类任务工作台(2026-11-16) + +P2 在 P1 的统一执行层上补齐人类工作台。AI 仍默认自主规划和执行;人类查看、搜索、下载结果及编辑本地草稿,不会自动暂停 AI。只有明确提交修改、暂停任务或接管范围才改变运行状态。 + +本次源码位于独立 worktree,原工作目录保持 P1 提交。原因是运行中的 Host 会按需读取 public 静态文件:仅保持 Node 进程不重启,仍不足以保护刷新中的现有面板。P2 没有部署到当前实例,没有更改真机或 USB/LAN 协议。 + +工作台需要配套 P2 Host,不能只替换静态资源;缺少 task revision 时面板拒绝修改任务。 + +## 人类工作流 + +- 现场页“任务工作台”打开工作台;“设置”进入同一工作台的配置编辑。也可直接访问 `/workbench`。现场页保留原数据维护/历史设置入口,不同时叠开两个设置界面。 +- 任务列表支持全库搜索、负责人/状态筛选及分页。任务详情显示名称、ID、版本、负责人、人工暂停标记、创建/更新时间和操作总数;操作记录独立分页,支持查看实际终态、来源、目标代际、deadline 和版本。 +- 操作详情按需读取已保存结果与 lateResult,可下载 JSON。界面最多预览 120000 字符,下载的是全部“已保存内容”;如果 Host 只保存了省略摘要,界面明确说明下载也无法恢复被省略的数据。未加载、尚无结果与执行未知分别呈现。结果/任务文本用 textContent 渲染,不解释目标提供的 HTML。 +- 人类暂停具名任务后,保留 heldByOperator;AI 不能自行恢复。人类显式恢复只允许后续工作,不自动重放失效、超时或取消的操作,也不释放资源控制权。取消单条操作和取消整项任务分开,已派发步骤不会自动回滚。 +- 控制权显示所选 Host/目标的已观察 revision、epoch、hostEpoch;接管、交还 AI、核对 unknown 都使用这次观察的版本,不在点击时暗中刷新。切换范围会先清空旧范围快照;新范围读取失败时不会误用旧目标进行控制。 +- unknown 以独立警示显示隔离状态。人类必须检查副作用、晚到结果和目标实际状态,再勾选确认并显式解除隔离;Host 处理仍在等待时后端拒绝解除。原 unknown 和 resolvedAt 保留,不把人工核对改写成原调用成功。 + +关闭工作台不取消任务,也不自动交还控制权。凭据仅保存在当前页面内存,现场与其工作台共享同一 client;独立工作台页面不继承其他页面权限。观察模式和连接操作员都不等于接管。角色与实际控制权分别显示,避免把“有凭据”误当成“已经暂停 AI”。 + +## 配置编辑与冲突 + +配置表单覆盖当前 Settings 的视图、捕获/类型/模块、保留策略和启动策略,继续调用共享 settings 服务。导入只合并进草稿;提交前校验已知字段、类型、范围、包名和符号,拒绝未知或会被静默过滤的值。导出的是最后读到的 Host 配置,未提交草稿不会混入导出。 + +每份草稿独立保存编辑时的 Host 版本,不受后台任务刷新影响。提交只发送实际修改的字段;不会把整份旧配置覆盖回去。例:编辑时 displayCap=300,人类改成 411;同时 AI 将该值改为 377 并设置 fileModule。旧版本提交被拒绝,草稿保留,界面并列显示“编辑时 / 当前值 / 草稿意图”。人类选择“保留修改,按最新版本重新核对”后,仅保留本来修改的 displayCap,未修改的 fileModule 采用 AI 的新值。重新核对不执行写入,必须再次明确提交。 + +提交返回 queued/running 只表示已接受。界面独立跟踪本次操作,即使关闭通用自动刷新也继续读取其实际终态。等待期间禁止修改/导入这份草稿,避免完成回读覆盖用户后续编辑。成功时读取实际配置并提示 Host 仍由人类持有;失败、部分应用或 unknown 时保留草稿与核对入口。配置保存不会自动删除历史采集。 + +若 HTTP 提交响应未确认,界面保留意图键,提供只读查询,不直接重发写入。查询未找到记录也不证明尚在途的请求永不执行;必须继续核对。全量重载页面会丢失本地草稿/凭据,已接受的任务与结果仍保存在 Host。 + +## 模块和协议增量 + +| 模块 | 增量 | +|---|---| +| `public/workbench.js` / `.css` / `.html` | 独立/嵌入两种工作台;任务、控制权、结果、副作用和配置视图;移动窄屏布局、焦点和禁用反馈 | +| `public/workbench-model.js` | 草稿差异、校验、并列比较与显式 rebase;无 DOM/I/O,可直接回归 | +| `public/operation-client.js` | 页面内存凭据、统一 HTTP 传输、明确的未确认响应、版本提交;现场旧动作也经过相同 guard | +| `public/operations.js` | 现场页薄适配;挂载同一工作台、共享 client,关闭时停止本地轮询 | +| `operations.ts` / `task_store.ts` | task revision、详情聚合、搜索分页、意图查询、有限副作用日志、开始/结束记录 | +| `execution_context.ts` / `service.ts` / settings/maintenance | 派发与确认关联到具体步骤;agent 命令名、Host 保存/维护动作,不记录参数载荷 | + +仍为 **92 个 MCP 工具**,`operations` 增加可选字段: + +- `list`: q/state/owner,全量过滤后分页;nextTaskOffset、nextOperationOffset 分别表示两种列表,保留旧 nextOffset。 +- `get(taskId, limit, offset)`: task 含 revision、operationCounts、resources、unresolved;操作独立分页。 +- 任务 pause/resume/cancel/complete: `_operation.expectedTaskRevision` 可做 CAS,冲突返回 STALE_TASK,不改变任务。面板始终携带;旧 CLI/MCP 省略时保持 P1 兼容,但人类暂停/未完成 operator 子操作的角色保护继续强制执行。 +- `get(idempotencyKey)`: 在当前调用角色的命名空间只读查找原 operation,支持未收到提交响应后的核对;不重新执行。 + +TaskStore schemaVersion 保持 1,增量字段可选。旧任务按 revision=0 读取,不为展示而重写历史;没有日志或开始/结束时间的旧操作明确标“未记录”。新操作初始化空 effects,区分“无受跟踪步骤”和“旧记录没有逐步日志”。Task 状态变化更新 revision;执行完成导致状态/汇总变化时也可能使旧面板观察失效。 + +startedAt/finishedAt 是 Host 开始处理和记录终态的时间。deadline 时记录终态不代表 handler 或目标已经停止;界面分别显示 settled、inFlight 和 unknown。 + +副作用日志每项最多 **64 条**,超出记录 effectsDropped;派发有独立 ID,异步并行响应不会对错步骤。状态 dispatched/acknowledged/failed/unknown 描述 Host 的派发/响应事实;acknowledged 不证明业务成功,operation/result 仍提供实际业务结论。deadline 或恢复后的不确定性保留 uncertainAt,晚到确认不删除此前的未知事实。没有参数、内存字节、密钥或 shell 命令文本。通用 external 日志和未埋点内部步骤不构成完整副作用审计;日志不是目标状态证明,也不提供回滚。 + +没有新增部署、自启动、真机命令、权限提升或后台自动接管;稳定设备身份、配对/TLS、USB/LAN 统一 RPC 和目标侧撤销仍属后续阶段。 + +## 验证与复现 + +独立 worktree 复用既有依赖(本轮不安装或改动依赖),复制并校验相同的 sandbox ELF;不共享运行数据。测试启动器移除继承的数据根/捕获根/operator 密钥,每个进程使用临时数据。显式提供 `ADH_CLI_SOURCE` 指向相邻 adh-cli 源码,继续实测公共 CLI;缺失外部 CLI 源码时该项打印原因并 skip。 + +```text +cd daemon +npm run typecheck +npm test +node test/fixtures/p2_workbench.ts +``` + +UI fixture 在加载业务模块前禁止真实设备子进程,使用随机 loopback 端口、OS 临时目录、合成 session/socket 和固定合成 operator 密钥。它不启动正式 index,不配置 adb reverse,没有真实 WS/手机连接;用于任务/配置工作流验收,不等于真机采集验收。fixture 的 __fixture 路由仅存在于测试文件,用于模拟并发修改。 + +新增回归 14 项涵盖 task CAS、旧记录、过滤分页、并行日志、日志上限、意图查询、配置差异/rebase、校验、传输未确认、凭据与 HTTP 集成。完整 Host **525 passed / 0 failed / 0 skipped**,类型检查通过。浏览器用 ego-browser 实测任务/结果/下载、人类暂停恢复与 STALE_TASK、unknown/lateResult/显式核对、接管释放、配置 STALE_CONTROL/保留草稿/rebase/确认结果、导入导出、文本安全渲染、独立与现场入口、390px 窄屏。截图实际查看后修复了嵌入页面的 main 全局样式冲突。具体交付状态见 PROGRESS.md。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 60d2082..a33dd81 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4967,3 +4967,20 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 验证:`npm run typecheck` 通过;完整 Host **511 passed / 0 failed / 0 skipped**(P0 基线 489 + P1 新增 22);v71 **92 tools / 0 problems / PASS**。公共 CLI 源码 **14 passed**(新增 6),包括旧版本不刷新、角色凭据显式性与异步提交。Host 合成 TCP agent 夹具先禁设备子进程,实际跑 REST/MCP、Python CLI、开发 CLI、断连和取消;执行器另测恢复、双 Host 共享控制、损坏保护、排队 deadline、局部副作用和晚到失败。只读动作逐工具明确列出,oracle diff/stability、批量 Hook 不会因伪造 status/plan 字段绕过写保护;未知 POST 动作默认受保护。 面板通过独立随机端口、OS 临时数据目录与合成 agent 实测:查看任务,接入合成 operator 凭据,取消未派发任务,接管/释放,以及修改 ui.displayCap 形成 succeeded 操作。浏览器检查用 ego-browser,本轮自建 UI 夹具已停止。原 8088 非 watch 进程保持原 PID/启动时间;没有请求其业务接口、启动正式 index、修改 adb reverse、运行设备门禁、启停目标、发布安装包或重启服务。P1 Host fencing 不提供目标侧撤销、完整设备身份、USB/LAN 新 RPC 或 TLS;这些仍属后续阶段。 + + +## 2026-11-16:P2 人类任务工作台与配置冲突核对 + +按用户授权继续 P2,以 AI 自主分析为主,补齐人类查看、修改、暂停恢复和接管。交付位于独立分支/worktree,原工作目录保留 P1 提交且干净。运行中服务会动态读取 public 静态文件,不能仅靠“不重启 Node”保护现场;因此本轮不把 P2 静态文件放进其工作目录。 + +- 现场“任务工作台”和独立 /workbench 共用一套视图;“设置”打开同一配置编辑器,原数据维护入口保留。支持全库搜索、负责人/状态过滤、任务/操作独立分页、任务版本与状态详情、来源/目标/控制版本、原始/晚到结果及已保存 JSON 下载。默认观察或编辑本地草稿不改变控制权。 +- Task 增加兼容旧记录的 revision、创建来源;面板 pause/resume/cancel/complete 使用 expectedTaskRevision 做 CAS。旧观察被拒绝且保留人类暂停,恢复任务不自动重放失效操作;人类接管与任务暂停分别控制,不把交还 AI 当作自动恢复全部任务。 +- 实际副作用边界保存最多 64 条元数据日志,独立 ID 对应并行派发/响应;超出报告 effectsDropped。只记录 agent 命令名或 Host 动作及派发/确认时间,不记录参数、密钥和 shell 文本。新空日志与旧缺失日志分开显示;acknowledged 不是目标业务成功,unknown/曾经未知/晚到结果持续如实保留。 +- 配置草稿固定编辑版本,提交仅包含变化字段;冲突并列展示编辑时、当前值和草稿意图。显式 rebase 保留本来修改的字段,并采用其他字段的最新值,不自动提交。导入先校验并进入草稿,导出已读 Host 配置。提交等待期间冻结本份草稿,独立跟踪实际结果;传输未确认时保留意图键供只读查询,不重发。 +- 切换控制范围先清空旧快照,读取失败不会误操作旧目标;接管/交还/unknown 核对都使用已显示版本。操作员凭据只在页面内存,连接不自动接管。工作台关闭只停本地轮询,不取消任务、不自动释放控制权。 + +验证:新增回归 14 项;完整 Host **525 passed / 0 failed / 0 skipped**,类型检查通过,v71 **92 tools / 0 problems / PASS**,git diff --check 通过。隔离 worktree 显式 ADH_CLI_SOURCE 继续实测公共 Python CLI 和开发 CLI;复用未改动依赖,复制校验一致的 sandbox ELF,不依赖真实设备或分析产物。回归覆盖任务 CAS、旧记录、分页、并行/有界日志、意图查询、配置差异/rebase/校验、未确认传输和真实 HTTP 入口。 + +浏览器用 ego-browser 对随机 loopback 端口、临时数据目录与合成 agent 实测:任务详情/结果/下载,结果 HTML 作为纯文本,任务暂停恢复及 STALE_TASK,unknown/晚到结果/显式人工核对,接管交还,配置 STALE_CONTROL 后草稿仍保留,再核对提交仅改人类字段且保留 AI 同时改过的其他字段。另测导入只改草稿、导出已读配置、独立/现场入口不叠开旧设置、390px 窄屏。实际查看截图并修复了嵌入页 main 全局样式冲突;关闭了浏览器任务并只停止本轮自建 UI fixture。 + +完整范围、迁移/API 和限制见 [P2_WORKBENCH.md](P2_WORKBENCH.md),同步 REQUIREMENTS、DEVELOPMENT_PLAN、FEATURE_STATUS、MAP 和 MCP 清单。未部署、未推送、未发布安装包;未启动正式 index、修改 adb reverse、运行设备门禁、启停目标或重启当前服务。当前 8088 仍是原非 watch 进程。P2 面板需要配套 P2 Host;副作用日志有界且不等同完整目标审计,设备域服务、USB/LAN 新 RPC、TLS 和目标侧撤销仍属后续阶段。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index f6e4332..43262fd 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 功能需求说明 +> **2026-11-16 P2 人类工作台**:任务搜索/分页、详情/结果/副作用、人类暂停恢复、接管/交还、unknown 核对和配置编辑已接入同一执行层。草稿保留原版本,冲突并列核对,显式 rebase 只保留本来修改的字段,不自动提交;任务状态修改使用 task revision。默认观察不改变 AI 工作。范围、兼容性与验证见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。本轮在独立 worktree 实现,当前服务不升级,原静态目录保留 P1 提交内容。 + > **2026-11-16 P1 操作契约**:MCP、REST、公共/开发 CLI 和人类面板通过同一 Host 执行层;写入必须携带 revision/controlEpoch/hostEpoch,人类接管与修改阻止旧 AI 操作继续写。任务持久保存,不自动重放;取消区分 requested 与确认,派发后超时/断连保留 unknown 和晚到证据。operator 凭据控制接管,不以请求 JSON 的自报角色授权。实现、迁移与边界见 [P1_OPERATIONS.md](P1_OPERATIONS.md)。人类面板可修改/接管的用户决议取代下文历史只读冻结口径;不将 Host 门禁视为真机或新传输验收。 > **2026-11-16 P0 可靠性口径**:作用域包名单更新必须保留完整 Hook policy/未知字段;MCP 与面板设置共用原子保存和逐目标应用结果;模块导入与历史恢复不删除或裁剪磁盘证据。保留策略通过显式维护预览/确认执行,旧文中启动/追加时自动磁盘清理的描述由此更正;内存容量限制保持。实现与升级路径见 [P0 Host 状态说明](P0_HOST_STATE.md)。本轮 Host 验证不等于当前服务已部署或真机验收。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 824175d..b47804f 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -2,7 +2,7 @@ Generated from the source registry (92 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). -P1 writes require `_operation` state/control versions. Task, cancellation and operator contracts: [P1_OPERATIONS.md](P1_OPERATIONS.md). Read queries remain compatible; unversioned writes fail closed. +Writes require `_operation` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. | Tool | Description | Args | |---|---|---| @@ -97,4 +97,4 @@ P1 writes require `_operation` state/control versions. Task, cancellation and op | `analyze_app` | One call from a package name to a bounded report: adds the package to the phone injection allowlist when needed (reported as scopeAdded), cold starts it, waits for the Zygisk-injected agent, then runs triage (caps / maps size / dex files / capture window / module loads / detection surface) plus optional unpack (dump every DEX) and httpCaptureMs (a TLS traffic window). Use it when the caller knows only the app name, not a session id. Every phase reports ok/error and one failed phase does not discard the others. The target must be an installed third-party app: system packages and the ADH manager are refused. | package, autoScope, forceRestart, captureMs, unpack, httpCaptureMs, timeoutMs, settleMs, _operation | | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | _operation | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | -| `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset | +| `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | From 258e69ad21769910a0bcbf690fbf4ff3e401d215 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:42:55 +0800 Subject: [PATCH 15/24] =?UTF-8?q?feat:=20=E5=BB=BA=E7=AB=8B=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=9F=9F=E4=B8=8E=E7=A8=B3=E5=AE=9A=E8=BA=AB=E4=BB=BD?= =?UTF-8?q?=E5=B9=B6=E7=BB=9F=E4=B8=80=20USB=20RPC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 4 + CLAUDE.md | 4 + daemon/src/MAP.md | 4 + daemon/src/device_host.ts | 22 ++ daemon/src/device_protocol.ts | 68 ++++++ daemon/src/devices.ts | 80 ++++++++ daemon/src/execution_context.ts | 4 + daemon/src/http/router.ts | 2 + daemon/src/http/routes_devices.ts | 8 + daemon/src/mcp.ts | 2 + daemon/src/operation_host.ts | 2 +- daemon/src/operation_registry.ts | 9 +- daemon/src/operations.ts | 20 +- daemon/src/transport/adb_device.ts | 60 ++++++ daemon/test/device_controls.test.ts | 30 +++ daemon/test/device_entrypoints.test.ts | 57 +++++ daemon/test/device_fixture.ts | 52 +++++ daemon/test/device_jvm.test.ts | 131 ++++++++++++ daemon/test/device_protocol.test.ts | 48 +++++ device/MAP.md | 6 + .../aidl/com/adh/daemon/IAdhScopeService.aidl | 5 + .../src/main/java/com/adh/core/AdhPaths.kt | 3 + .../src/main/java/com/adh/core/AdhProtocol.kt | 4 +- .../src/main/java/com/adh/core/DeviceRpc.kt | 47 +++++ .../test/java/com/adh/core/ScopeJsonTest.kt | 3 +- device/daemon/build.gradle.kts | 13 ++ .../java/com/adh/daemon/AdhDeviceDaemon.kt | 20 +- .../com/adh/daemon/AndroidDeviceBackend.kt | 140 +++++++++++++ .../java/com/adh/daemon/AppProcessControl.kt | 19 +- .../java/com/adh/daemon/RootScopeBinder.kt | 194 ++++-------------- .../com/adh/daemon/device/DeviceArguments.kt | 39 ++++ .../java/com/adh/daemon/device/DeviceFiles.kt | 24 +++ .../com/adh/daemon/device/DeviceIdentity.kt | 59 ++++++ .../com/adh/daemon/device/DeviceOperations.kt | 104 ++++++++++ .../com/adh/daemon/device/DeviceRpcSession.kt | 55 +++++ .../adh/daemon/device/LocalDeviceRpcServer.kt | 30 +++ .../com/adh/daemon/device/ProcessCatalog.kt | 36 ++++ .../com/adh/daemon/device/ScopeDocuments.kt | 80 ++++++++ .../com/adh/daemon/device/DeviceDomainTest.kt | 125 +++++++++++ .../com/adh/daemon/device/DeviceRpcFixture.kt | 37 ++++ docs/DEVELOPMENT_PLAN.md | 2 + docs/FEATURE_STATUS.md | 2 + docs/P3_DEVICE_DOMAIN.md | 117 +++++++++++ docs/PROGRESS.md | 17 ++ docs/REQUIREMENTS.md | 2 + docs/mcp-tools.md | 5 +- tools/MAP.md | 4 + tools/generate_mcp_docs.mjs | 22 ++ 48 files changed, 1652 insertions(+), 169 deletions(-) create mode 100644 daemon/src/device_host.ts create mode 100644 daemon/src/device_protocol.ts create mode 100644 daemon/src/devices.ts create mode 100644 daemon/src/http/routes_devices.ts create mode 100644 daemon/src/transport/adb_device.ts create mode 100644 daemon/test/device_controls.test.ts create mode 100644 daemon/test/device_entrypoints.test.ts create mode 100644 daemon/test/device_fixture.ts create mode 100644 daemon/test/device_jvm.test.ts create mode 100644 daemon/test/device_protocol.test.ts create mode 100644 device/core/src/main/java/com/adh/core/DeviceRpc.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/AndroidDeviceBackend.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceArguments.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceFiles.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/ProcessCatalog.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt create mode 100644 device/daemon/src/test/java/com/adh/daemon/device/DeviceDomainTest.kt create mode 100644 device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt create mode 100644 docs/P3_DEVICE_DOMAIN.md create mode 100644 tools/generate_mcp_docs.mjs diff --git a/AGENTS.md b/AGENTS.md index 86c5bc6..0523d40 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,3 +166,7 @@ Each layer has a `MAP.md` — read it before editing that layer: ## Boundaries - Never commit captured target data (keys, plaintext, dumps). `.gitignore` excludes `captures/`, `dumps/`, `adhd-data/`. + +## P3 device-domain boundary (2026-11-16 user direction) + +The existing Device Daemon now shares device control between authenticated Binder and adh.device/1 USB RPC. Installation identity, module/app/process discovery, scope, certificates and the Host endpoint remain device coordination, never analysis. The phone exposes only an authenticated abstract UDS in this slice, no HTTP/MCP/database/TCP listener. Host device:UUID controls fence writes; legacy target sessions have no inferred device association. See docs/P3_DEVICE_DOMAIN.md for capability limits and explicit unverified Android/SELinux paths. P4 pairing/TLS and agent local routing are not delivered by the P3 JVM tests. Keep current sessions and their transport mappings untouched during host-only validation. diff --git a/CLAUDE.md b/CLAUDE.md index afeed02..5780726 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -166,3 +166,7 @@ Each layer has a `MAP.md` — read it before editing that layer: ## Boundaries - Never commit captured target data (keys, plaintext, dumps). `.gitignore` excludes `captures/`, `dumps/`, `adhd-data/`. + +## P3 device-domain boundary (2026-11-16 user direction) + +The existing Device Daemon now shares device control between authenticated Binder and adh.device/1 USB RPC. Installation identity, module/app/process discovery, scope, certificates and the Host endpoint remain device coordination, never analysis. The phone exposes only an authenticated abstract UDS in this slice, no HTTP/MCP/database/TCP listener. Host device:UUID controls fence writes; legacy target sessions have no inferred device association. See docs/P3_DEVICE_DOMAIN.md for capability limits and explicit unverified Android/SELinux paths. P4 pairing/TLS and agent local routing are not delivered by the P3 JVM tests. Keep current sessions and their transport mappings untouched during host-only validation. diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index 4b82603..683eee0 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -128,3 +128,7 @@ Shared injection-backend matrix: `backendMatrix()` (sessions by entry + Zygisk p ### root_watch 内存时序 `projectRootSample` 优先使用同条 perf 记录的用户栈解析 `mem`,所有指针跳与目标字节均在快照范围内时才标 `snapshotConsistent:true`。其他窗口保留异步进程读数并标 `false`。不能把 collector 处理记录时读到的堆值当作事件时刻状态。回归测试覆盖已经变化的栈、部分栈、堆指针和带偏移的指针链。 + +### P3 设备域 + +`devices.ts` 持久保存安装身份并管理临时连接,`device_protocol.ts` 提供 adh.device/1 codec/签名与预算,`transport/adb_device.ts` 只负责显式发现、固定 ADB transport、USB bootstrap 和自有 forward。`device_host.ts` 延迟初始化;MCP devices / `http/routes_devices.ts` 共用它与 operation_registry。`operations.ts` 的 device:UUID 范围不等于旧 target session;二者未关联时保守互斥,人类持有与 unknown 都不能跨边界绕过。见 docs/P3_DEVICE_DOMAIN.md。不要把 legacy agent 的 serial 或 Host 上唯一设备当成已验证身份。 diff --git a/daemon/src/device_host.ts b/daemon/src/device_host.ts new file mode 100644 index 0000000..d1a27de --- /dev/null +++ b/daemon/src/device_host.ts @@ -0,0 +1,22 @@ +import {join} from 'node:path'; +import {DATA_DIR} from './state.ts'; +import {Devices} from './devices.ts'; +import {getOperations} from './operation_host.ts'; +import {deviceFail} from './device_protocol.ts'; + +let devices:Devices|undefined; +export function getDevices(){return devices??=new Devices(join(DATA_DIR,'devices.json'),undefined,id=>getOperations().invalidateResource('device:'+id));} +export function setDevicesForTests(value:Devices){if(process.env.ADH_SKIP_ARTIFACT_LOAD!=='1')throw Error('test device adapter is unavailable outside isolated tests');devices=value;} +export async function deviceAction(a:any){ + const service=getDevices(); + switch(a.action||'list'){ + case 'list':return {ok:true,...service.list()}; + case 'discover':return {ok:true,...await service.discover()}; + case 'connect':return service.connect(String(a.serial||''),a.transportId,a.expectedDeviceId); + case 'disconnect':return service.disconnect(a.deviceId,a.connectionId); + case 'info':return service.call({...a,method:'device.info'}); + case 'capabilities':return service.call({...a,method:'device.capabilities'}); + case 'call':return service.call(a); + default:return deviceFail('INVALID_ACTION','unknown device action'); + } +} diff --git a/daemon/src/device_protocol.ts b/daemon/src/device_protocol.ts new file mode 100644 index 0000000..63b9152 --- /dev/null +++ b/daemon/src/device_protocol.ts @@ -0,0 +1,68 @@ +// Shared device-domain wire contract. Mirrors device/core DeviceRpc; conformance tests pin both. +import { createHash, createPublicKey, verify } from 'node:crypto'; +import type { Duplex } from 'node:stream'; +import { randomUUID } from 'node:crypto'; +import { OperationError } from './execution_context.ts'; + +export const DEVICE_PROTOCOL='adh.device/1', DEVICE_SOCKET='adh_device_rpc_v1'; +export const DEVICE_BOOTSTRAP='/data/adb/adh/device-rpc/usb-access.json'; +export const DEVICE_FRAME_MAX=1024*1024; +export const DEVICE_READ_METHODS=new Set(['device.info','device.capabilities','device.state','module.status','scope.get','applications.list','processes.list','certificates.list','host.get','operations.get']); +export const DEVICE_WRITE_METHODS=new Set(['scope.patch','scope.replace','process.control','certificates.put','certificates.delete','host.set','operations.resolve']); +export const uuid=(value:unknown):value is string=>typeof value==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value); +export class DeviceError extends OperationError {} +export function deviceFail(code:string,message:string,uncertain=false):never{throw new DeviceError(code,message,uncertain);} +export function deviceMethodMode(method:string){if(DEVICE_READ_METHODS.has(method))return 'read';if(DEVICE_WRITE_METHODS.has(method))return 'write';return deviceFail('UNSUPPORTED_METHOD','device method is not supported; no shell/ADB fallback was attempted');} +export interface Bootstrap {schemaVersion:1;deviceId:string;identityFingerprint:string;token:string} +export interface DevicePeer {deviceId:string;bootId:string;daemonInstanceId:string;identityFingerprint:string;info:any;capabilities:{methods:Record;[key:string]:any};protocol:string} +export function parseBootstrap(raw:string):Bootstrap { + let value:any;try{if(Buffer.byteLength(raw)>8192)throw Error();value=JSON.parse(raw);}catch{deviceFail('INVALID_BOOTSTRAP','USB bootstrap could not be parsed; credential content is never logged');} + if(!value||value.schemaVersion!==1||!uuid(value.deviceId)||!/^[a-f0-9]{64}$/.test(value.identityFingerprint)||!/^[a-f0-9]{64}$/.test(value.token))deviceFail('INVALID_BOOTSTRAP','invalid USB bootstrap metadata'); + return value; +} +export function verifyHello(reply:any,bootstrap:Bootstrap,id:string,nonce:string):DevicePeer { + try{ + for(const key of ['publicKey','payload','signature'])if(typeof reply[key]!=='string'||reply[key].length>65536||Buffer.from(reply[key],'base64').toString('base64')!==reply[key])throw Error(); + const der=Buffer.from(reply.publicKey,'base64');if(createHash('sha256').update(der).digest('hex')!==bootstrap.identityFingerprint)throw Error(); + const key=createPublicKey({key:der,type:'spki',format:'der'});if(key.asymmetricKeyType!=='rsa')throw Error(); + const payload=Buffer.from(reply.payload,'base64');if(!verify('sha256',payload,key,Buffer.from(reply.signature,'base64')))throw Error(); + const peer=JSON.parse(payload.toString('utf8')); + if(peer.protocol!==DEVICE_PROTOCOL||peer.requestId!==id||peer.clientNonce!==nonce||peer.deviceId!==bootstrap.deviceId||peer.identityFingerprint!==bootstrap.identityFingerprint||!uuid(peer.bootId)||!uuid(peer.daemonInstanceId))throw Error(); + if(!peer.capabilities?.methods||typeof peer.capabilities.methods!=='object')throw Error(); + for(const [method,mode]of Object.entries(peer.capabilities.methods))if(deviceMethodMode(method)!==mode)throw Error(); + return peer; + }catch{deviceFail('IDENTITY_UNVERIFIED','device hello signature, challenge or capability contract did not match the USB bootstrap');} +} +export function deviceFrame(value:unknown):Buffer {const data=Buffer.from(JSON.stringify(value));if(!data.length||data.length>DEVICE_FRAME_MAX)deviceFail('FRAME_LIMIT','device request exceeds frame limit');const header=Buffer.alloc(4);header.writeUInt32BE(data.length);return Buffer.concat([header,data]);} + +/** Stream-only RPC; never reconnects or replays. Authentication is negotiated by the adapter. */ +export class DeviceRpcClient { + readonly stream:Duplex; + private pending=new Mapvoid;reject:(error:Error)=>void;timer:ReturnType;write:boolean}>(); + private buffer=Buffer.alloc(0);private dead=false; + constructor(stream:Duplex,onClose:()=>void=()=>{}) { + this.stream=stream; + stream.on('data',(chunk:Buffer)=>{ + this.buffer=Buffer.concat([this.buffer,chunk]); + while(this.buffer.length>=4){const size=this.buffer.readUInt32BE();if(size<1||size>DEVICE_FRAME_MAX){this.fail('FRAME_LIMIT');return;}if(this.buffer.lengththis.fail('DEVICE_DISCONNECTED'));stream.on('close',()=>{this.fail('DEVICE_DISCONNECTED');onClose();}); + } + request(method:string,params:any,target?:any,meta?:any,budgetMs=15000,id:string=randomUUID()):Promise{ + if(this.dead||this.stream.destroyed)return Promise.reject(new DeviceError('DEVICE_DISCONNECTED','device channel is closed')); + if(!Number.isInteger(budgetMs)||budgetMs<1||budgetMs>60000)return Promise.reject(new DeviceError('INVALID_ARGUMENT','device request budget must be 1..60000 ms')); + if(this.pending.has(id))return Promise.reject(new DeviceError('DUPLICATE_REQUEST','request id is already in flight')); + if(this.pending.size>=32)return Promise.reject(new DeviceError('RPC_BUSY','too many pending device requests')); + const write=DEVICE_WRITE_METHODS.has(method),frame=deviceFrame({protocol:DEVICE_PROTOCOL,id,method,params,...(target?{target}:{}),...(meta?{meta}:{})}); + return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.pending.delete(id);reject(new DeviceError('DEVICE_RPC_TIMEOUT','device reply deadline expired; execution was not stopped or replayed',write));},budgetMs); + this.pending.set(id,{resolve,reject,timer,write});this.stream.write(frame,error=>{if(error)this.fail('DEVICE_DISCONNECTED');}); + }); + } + private fail(code:string){if(this.dead)return;this.dead=true;for(const entry of this.pending.values()){clearTimeout(entry.timer);entry.reject(new DeviceError(code,'device stream closed; no requests were replayed',entry.write));}this.pending.clear();this.stream.destroy();} + close(){this.fail('DEVICE_DISCONNECTED');} +} diff --git a/daemon/src/devices.ts b/daemon/src/devices.ts new file mode 100644 index 0000000..c32fe57 --- /dev/null +++ b/daemon/src/devices.ts @@ -0,0 +1,80 @@ +import {existsSync,readFileSync} from 'node:fs'; +import {atomicWriteJson} from './storage.ts'; +import {AdbDeviceTransport,type AdbConnection} from './transport/adb_device.ts'; +import {DeviceError,deviceFail,deviceMethodMode,uuid,type DevicePeer} from './device_protocol.ts'; +import {checkpoint,executionContext} from './execution_context.ts'; + +interface DeviceRecord {deviceId:string;identityFingerprint:string;lastPeer:DevicePeer;lastSeen:number} +/** Device identity is persistent; transport connections are deliberately ephemeral and replaceable. */ +export class Devices { + private file:string;readonly adapter:AdbDeviceTransport;private generationChanged:(deviceId:string)=>void; + private records:Record={}; + private connections=new Map(); + constructor(file:string,adapter=new AdbDeviceTransport(),generationChanged:(deviceId:string)=>void=()=>{}) { + this.file=file;this.adapter=adapter;this.generationChanged=generationChanged; + if(existsSync(file)){ + const value=JSON.parse(readFileSync(file,'utf8'));if(!value||value.schemaVersion!==1||!value.devices||Array.isArray(value.devices)||typeof value.devices!=='object')deviceFail('DEVICE_REGISTRY_CORRUPT','authoritative device registry cannot be rebuilt automatically'); + for(const [id,record]of Object.entries(value.devices) as [string,DeviceRecord][]){if(!uuid(id)||id!==record.deviceId||!/^[a-f0-9]{64}$/.test(record.identityFingerprint))deviceFail('DEVICE_REGISTRY_CORRUPT','invalid saved device identity');} + this.records=value.devices; + } + } + list(){return {devices:Object.values(this.records).map(record=>({deviceId:record.deviceId,identityFingerprint:record.identityFingerprint,lastSeen:record.lastSeen,lastKnown:record.lastPeer, + online:[...this.connections.values()].some(c=>c.peer.deviceId===record.deviceId&&!c.rpc.stream.destroyed),connections:[...this.connections.values()].filter(c=>c.peer.deviceId===record.deviceId).map(c=>this.connectionView(c))})), + legacyAgentAssociation:'unverified; no session is assigned by ADB serial',discoveryIsExplicit:true};} + private connectionView(c:AdbConnection){return {connectionId:c.id,transport:c.transport,serial:c.serial,transportId:c.transportId,deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId,identityVerified:true,online:!c.rpc.stream.destroyed};} + async discover(){return {transports:await this.adapter.discover(),...this.list()};} + async connect(serial:string,transportId?:string,expectedDeviceId?:string){ + let connection:AdbConnection|undefined; + // Keep closed handles for explicit, verified forward cleanup; never silently reconnect. + connection=await this.adapter.connect(serial,transportId); + try{ + if(expectedDeviceId&&connection.peer.deviceId!==expectedDeviceId)deviceFail('DEVICE_MISMATCH','USB endpoint is another device; no target operations were attempted'); + const id=connection.peer.deviceId,previous=this.records[id]; + if(previous&&previous.identityFingerprint!==connection.peer.identityFingerprint)deviceFail('IDENTITY_COLLISION','saved device id has a different installation key; refusing silent replacement'); + const live=[...this.connections.values()].filter(c=>c.peer.deviceId===id&&!c.rpc.stream.destroyed); + if(live.some(c=>c.peer.bootId!==connection!.peer.bootId||c.peer.daemonInstanceId!==connection!.peer.daemonInstanceId))deviceFail('IDENTITY_COLLISION','same device id claims two live boot/daemon generations'); + checkpoint(); + if(previous&&(previous.lastPeer.bootId!==connection.peer.bootId||previous.lastPeer.daemonInstanceId!==connection.peer.daemonInstanceId))this.generationChanged(id); + const candidate={...this.records,[id]:{deviceId:id,identityFingerprint:connection.peer.identityFingerprint,lastPeer:connection.peer,lastSeen:Date.now()}}; + atomicWriteJson(this.file,{schemaVersion:1,devices:candidate});this.records=candidate;this.connections.set(connection.id,connection); + return {ok:true,...this.connectionView(connection),identity:connection.peer}; + }catch(error){try{if(!(await connection.close()).confirmed)throw Error();}catch{throw new DeviceError('FORWARD_CLEANUP_UNCONFIRMED','device registration failed and owned forward cleanup is unconfirmed',true);}throw error;} + } + private connection(deviceId:string,connectionId?:string,includeClosed=false){ + if(!uuid(deviceId))deviceFail('DEVICE_REQUIRED','select a verified deviceId, not an ADB serial'); + const matches=[...this.connections.values()].filter(c=>c.peer.deviceId===deviceId&&(includeClosed||!c.rpc.stream.destroyed)&&(!connectionId||c.id===connectionId)); + if(!matches.length)deviceFail('DEVICE_OFFLINE','device has no verified active connection; no ADB fallback was attempted'); + if(matches.length!==1)deviceFail('CONNECTION_AMBIGUOUS','select connectionId explicitly; writes never fail over or replay');return matches[0]; + } + async disconnect(deviceId:string,connectionId?:string){ + const c=this.connection(deviceId,connectionId,true),ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'device',action:'connection.close'}); + try{const cleanup=await c.close();if(!cleanup.confirmed)throw Error();this.connections.delete(c.id);ctx?.acknowledged(false,effect);return {ok:true,connectionId:c.id,cleanup};} + catch{ctx?.acknowledged(true,effect,true);throw new DeviceError('FORWARD_CLEANUP_UNCONFIRMED','device connection closed but its owned forward cleanup is unconfirmed',true);} + } + async call(args:{deviceId:string;connectionId?:string;method:string;params?:any;bootId?:string;daemonInstanceId?:string;expectedDeviceRevision?:number;budgetMs?:number}){ + const c=this.connection(args.deviceId,args.connectionId),mode=deviceMethodMode(args.method); + if(args.budgetMs!==undefined&&(!Number.isInteger(args.budgetMs)||args.budgetMs<1||args.budgetMs>60000))deviceFail('INVALID_ARGUMENT','device budget must be an integer in 1..60000 ms'); + if(args.params!==undefined&&(!args.params||Array.isArray(args.params)||typeof args.params!=='object'))deviceFail('INVALID_ARGUMENT','device params must be an object'); + if(c.peer.capabilities.methods[args.method]!==mode)deviceFail('CAPABILITY_UNSUPPORTED','connected device does not advertise this capability'); + const ctx=executionContext.getStore();checkpoint(); + if(mode==='write'){ + if(!ctx?.operationId)deviceFail('OPERATION_REQUIRED','device mutations must enter the shared Host operation coordinator'); + if(ctx.resource!=='device:'+args.deviceId)deviceFail('TARGET_CHANGED','Host operation is bound to another resource; no cross-device dispatch'); + if(args.bootId!==c.peer.bootId||args.daemonInstanceId!==c.peer.daemonInstanceId)deviceFail('TARGET_CHANGED','send the observed device bootId and daemonInstanceId; no automatic rebinding'); + if(!Number.isSafeInteger(args.expectedDeviceRevision)||args.expectedDeviceRevision < 0)deviceFail('DEVICE_VERSION_REQUIRED','send the observed device stateRevision'); + if(args.method==='operations.resolve'&&ctx.principalRole!=='operator')deviceFail('OPERATOR_REQUIRED','only an authenticated operator can reconcile unknown device effects'); + } + const budget=Math.min(60000,Math.max(1,Math.floor(args.budgetMs||15000)),ctx?.remainingMs?.()??60000); + const target={deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId}; + const meta=mode==='write'?{operationId:ctx!.operationId,expectedRevision:args.expectedDeviceRevision,actor:ctx!.principalRole,budgetMs:budget}:undefined; + const effect=mode==='write'?ctx?.dispatched({kind:'device',action:args.method}):undefined; + try{ + const result=await c.rpc.request(args.method,args.params||{},target,meta,budget); + const uncertain=result.state==='unknown'||result.uncertain===true; + if(mode==='write')ctx?.acknowledged(uncertain,effect,result.state==='failed'); + return {ok:!uncertain&&result.state!=='failed'&&result.ok!==false,deviceId:c.peer.deviceId,bootId:c.peer.bootId,connectionId:c.id,result, + ...(uncertain?{code:'UNKNOWN_EXECUTION',uncertain:true}:{}),...(result.state==='failed'?{code:result.code||'DEVICE_OPERATION_FAILED'}:{})}; + }catch(error){if(mode==='write')ctx?.acknowledged((error as any).uncertain===true,effect,true);throw error;} + } + close(){for(const c of this.connections.values())c.rpc.close();this.connections.clear();} +} diff --git a/daemon/src/execution_context.ts b/daemon/src/execution_context.ts index 5d18b3c..4983220 100644 --- a/daemon/src/execution_context.ts +++ b/daemon/src/execution_context.ts @@ -5,6 +5,10 @@ export class OperationError extends Error { constructor(code: string, message: string, uncertain = false) { super(message); this.code=code;this.uncertain=uncertain; } } export interface ExecutionContext { + operationId?: string; + resource?: string; + principalRole?: 'ai' | 'operator'; + remainingMs?(): number; checkpoint(session?: string): void; dispatched(description?: EffectDescription): string | void; acknowledged(uncertain: boolean, id?: string | void, failed?: boolean): void; diff --git a/daemon/src/http/router.ts b/daemon/src/http/router.ts index dc7a7f0..077b5d4 100644 --- a/daemon/src/http/router.ts +++ b/daemon/src/http/router.ts @@ -12,6 +12,7 @@ import { describeHttp } from '../operation_registry.ts'; import { executeManaged, getOperations, operationsRoot, resolveSpec } from '../operation_host.ts'; import { requestPrincipal } from '../access_context.ts'; import { operationFailure } from '../operations.ts'; +import {deviceRoutes} from './routes_devices.ts'; export async function handleHttp(req: http.IncomingMessage, res: http.ServerResponse) { const url = new URL(req.url ?? '/', 'http://localhost'); @@ -26,6 +27,7 @@ export async function handleHttp(req: http.IncomingMessage, res: http.ServerResp const context: RouteContext = { req, res, url, send }; const routes = [ ...operationsRoutes(context), + ...deviceRoutes(context), ...systemRoutes(context), ...runtimeRoutes(context), ...analysisRoutes(context), diff --git a/daemon/src/http/routes_devices.ts b/daemon/src/http/routes_devices.ts new file mode 100644 index 0000000..99025a6 --- /dev/null +++ b/daemon/src/http/routes_devices.ts @@ -0,0 +1,8 @@ +import {deviceAction} from '../device_host.ts'; +import {readBody} from '../state.ts'; +import type {Route,RouteContext} from './types.ts'; +/** Wrapped by the same router/operation registry as MCP; no privileged second execution path. */ +export function deviceRoutes({req,url,send}:RouteContext):Route[]{return [{path:'/api/devices',handler:async()=>{ + const args=req.method==='GET'?Object.fromEntries(url.searchParams):JSON.parse(await readBody(req)||'{}'); + const result=await deviceAction(args);return send(result.ok===false?400:200,result); +}}];} diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 14e7766..6dc1651 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -1,3 +1,4 @@ +import {deviceAction} from './device_host.ts'; import { executeManaged, getOperations, manageOperations } from './operation_host.ts'; import { describeTool } from './operation_registry.ts'; import { operationFailure, type Principal } from './operations.ts'; @@ -404,6 +405,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h ]; // Optional at schema level because reads need no control token; writes enforce it at dispatch. +MCP_TOOLS.push({name:'devices',description:'Device-domain discovery, verified installation identities and USB/ADB RPC. list is cached/offline-safe; discover lists ADB transports without attaching targets; connect requires an explicit serial/transportId and creates only its own ADB forward. info/capabilities query a verified deviceId. call uses advertised device methods; writes require observed bootId, daemonInstanceId, expectedDeviceRevision plus Host _operation versions. Read scope.get before scope.patch and supply params.scopeRevision. Device and connection ids are distinct from legacy agent session ids; no association or ADB fallback is guessed. TLS/LAN, agent routing and arbitrary shell are unsupported in P3. Unknown effects must be inspected, never replayed.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','info','capabilities','call']},serial:S,transportId:S,expectedDeviceId:S,deviceId:S,connectionId:S,method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); for (const tool of MCP_TOOLS) { const metadata=(tool.inputSchema as any).properties._operation ??= { type:'object' }; metadata.properties ??= { expectedRevision:{type:'integer'},controlEpoch:{type:'integer'},hostEpoch:{type:'integer'},taskId:{type:'string'},idempotencyKey:{type:'string'},timeoutMs:{type:'integer'},expectedTaskRevision:{type:'integer'} }; diff --git a/daemon/src/operation_host.ts b/daemon/src/operation_host.ts index 1ca5398..497dd1d 100644 --- a/daemon/src/operation_host.ts +++ b/daemon/src/operation_host.ts @@ -26,7 +26,7 @@ export async function runAutomatic(session: string, name: string, meta: ReturnTy } catch(error) { return operationFailure(error); } } export function resolveSpec(spec: OperationSpec, args: any) { - if(spec.mode==='write' && !spec.global && !spec.session) { + if(spec.mode==='write' && !spec.global && !spec.session && !spec.deviceId) { const online=[...sessions.values()].filter(s=>s.online); if(online.length!==1)throw new OperationError('TARGET_REQUIRED','choose an explicit session; targets are ambiguous or offline'); spec={...spec,session:online[0].sessionId}; diff --git a/daemon/src/operation_registry.ts b/daemon/src/operation_registry.ts index 1e74837..cb64791 100644 --- a/daemon/src/operation_registry.ts +++ b/daemon/src/operation_registry.ts @@ -1,5 +1,6 @@ +import {deviceMethodMode} from './device_protocol.ts'; export type Mode = 'read' | 'analysis' | 'write'; -export interface OperationSpec { name: string; mode: Mode; session?: string; global?: boolean } +export interface OperationSpec { name: string; mode: Mode; session?: string; global?: boolean; deviceId?: string } const readTools = new Set([ 'analysis_guide','process_list','backends','capabilities','dumps_list','runtime_diagnostics','agent_ping', 'memory_maps','maps_query','memory_read','memory_disasm','memory_search','memory_scan_magic','got_enum', @@ -20,6 +21,11 @@ const readActions: Record = { oracle:['list'],stealth:['status'], }; export function describeTool(name: string, args: Record = {}): OperationSpec { + if(name==='devices'){ + const action=args.action||'list'; + const mode:Mode=['list','discover','info','capabilities'].includes(action)?'read':action==='call'?deviceMethodMode(args.method):'write'; + return {name,mode,deviceId:['connect','list','discover'].includes(action)?undefined:args.deviceId,global:action==='connect'||!args.deviceId}; + } let mode: Mode = readTools.has(name) ? 'read' : analysisTools.has(name) ? 'analysis' : 'write'; if (Object.hasOwn(readActions,name) && readActions[name].includes(args.action)) mode = 'read'; if (name === 'settings') mode = args.action === 'get' || args.action === 'maintenance' && args.dryRun !== false ? 'read' : 'write'; @@ -51,6 +57,7 @@ const analysisPaths = new Set(['/api/native/syscall_scan','/api/native/crypto_co '/api/dex/strip','/api/dex/rebuild','/api/dex/repair','/api/art/dump','/api/memory/dump', '/api/unpack/dump-one','/api/unpack/dump-so-one','/api/unpack/pull-so','/api/unpack/dump-all','/api/unpack/dump-so']); export function describeHttp(path: string, method: string, args: Record = {}): OperationSpec { + if(path==='/api/devices')return describeTool('devices',args); const alias = routeTools[path]; if (path === '/api/config') return describeTool('settings', { ...args, action: method === 'POST' ? 'patch' : 'get' }); if (path === '/api/scope') return describeTool(method === 'POST' ? 'scope_set' : 'scope_list', args); diff --git a/daemon/src/operations.ts b/daemon/src/operations.ts index 8195cb4..aa913bb 100644 --- a/daemon/src/operations.ts +++ b/daemon/src/operations.ts @@ -22,8 +22,10 @@ function canonical(value: any): string { const fail = (code: string, message: string): never => { throw new OperationError(code, message); }; function touchTask(task: Task) { task.revision=(task.revision ?? 0)+1;task.updatedAt=Date.now(); } function validResource(resource: string) { - if(resource!=='host' && !/^target:[\w:.-]{1,400}$/.test(resource))fail('INVALID_RESOURCE','invalid control resource'); + if(resource!=='host' && !/^target:[\w:.-]{1,400}$/.test(resource) && !/^device:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(resource))fail('INVALID_RESOURCE','invalid control resource'); } +function resourcesConflict(a:string,b:string){return a==='host'||b==='host'||a===b||a.startsWith('device:')&&b.startsWith('target:')||b.startsWith('device:')&&a.startsWith('target:');} +function crossHeld(data:Ledger,resource:string){return Object.entries(data.controls).some(([key,c])=>(c.owner==='operator'||c.paused)&&(resource.startsWith('device:')&&key.startsWith('target:')||resource.startsWith('target:')&&key.startsWith('device:')));} export function operationFailure(error: unknown) { return { ok: false, code: (error as any)?.code || 'OPERATION_FAILED', error: (error as Error)?.message || String(error) }; } @@ -72,7 +74,12 @@ export class Operations { const data = this.store.read(), control = data.controls[resource] ?? freshControl(); return { resource, ...control, hostEpoch: data.controls.host.epoch }; } - resource(spec: OperationSpec) { return spec.global || !spec.session ? 'host' : this.targetResource(spec.session); } + resource(spec: OperationSpec) {const resource=spec.deviceId?'device:'+spec.deviceId:spec.global || !spec.session ? 'host' : this.targetResource(spec.session);validResource(resource);return resource;} + invalidateResource(resource:string){ + validResource(resource);this.store.update(data=>{const c=data.controls[resource]??=freshControl();c.epoch++;c.revision++; + for(const op of Object.values(data.operations))if(op.resource===resource&&op.state==='queued'){op.state='failed';op.settled=true;op.updatedAt=Date.now();op.error={code:'TARGET_CHANGED',message:'verified device generation changed; old work is not rebound'};data.tasks[op.taskId].state='paused';touchTask(data.tasks[op.taskId]);} + });this.pump(); + } createTask(title: string, principal: Principal, implicit = false): Task { return this.store.update(data => { const task: Task = { id: randomUUID(), title: String(title || 'analysis').slice(0,256), owner: principal.role, @@ -94,6 +101,7 @@ export class Operations { if(resource==='host' && principal.role!=='operator' && Object.values(data.controls).some(c=>c.owner==='operator'||c.paused)) { fail('CONTROL_HELD','a target is operator-held; Host-wide AI mutations are blocked'); } + if(principal.role!=='operator'&&crossHeld(data,resource))fail('CONTROL_HELD','unassociated legacy targets/device control are operator-held; no identity is guessed'); } private take(data: Ledger, resource: string) { const control = data.controls[resource] ??= freshControl(); @@ -296,7 +304,7 @@ export class Operations { if (op.cancelRequested) { this.finish(op.id,'cancelled'); continue; } if (Date.now() >= op.deadline) { this.finish(op.id,'failed',undefined,{code:'DEADLINE_EXCEEDED',message:'deadline expired before dispatch'}); continue; } if (data.tasks[op.taskId].state === 'paused') continue; - const busy = Object.entries(data.controls).some(([key,c]) => c.active && (op.resource === 'host' || key === 'host' || key === op.resource)); + const busy = Object.entries(data.controls).some(([key,c]) => c.active && resourcesConflict(op.resource,key)); if (op.mode === 'write' && (busy || rootWaiting)) { if(op.resource === 'host')rootWaiting=true; continue; } this.queue = this.queue.filter(x => x.id !== item.id); void this.run(item).catch(error => { @@ -315,8 +323,8 @@ export class Operations { if (op.mode === 'write') { this.assertVersion(data,op.resource,{role:op.owner,id:op.actorId,source:op.source},op); const control = data.controls[op.resource] ??= freshControl(); - if(Object.entries(data.controls).some(([key,c])=>c.active && (op.resource==='host'||key==='host'||key===op.resource)))fail('OPERATION_BUSY','resource is in use by another Host operation'); - if (control.uncertain || data.controls.host.uncertain || op.resource === 'host' && Object.values(data.controls).some(c => c.uncertain)) fail('UNKNOWN_EXECUTION','resource has unresolved side effects; inspect and resolve first'); + if(Object.entries(data.controls).some(([key,c])=>c.active && resourcesConflict(op.resource,key)))fail('OPERATION_BUSY','resource is in use by another Host operation'); + if (Object.entries(data.controls).some(([key,c])=>c.uncertain && resourcesConflict(op.resource,key))) fail('UNKNOWN_EXECUTION','resource has unresolved side effects; inspect and resolve first'); control.revision++; control.active=op.id; op.appliedRevision=control.revision; } op.state='running'; op.startedAt=Date.now();op.updatedAt=Date.now(); return op; @@ -325,6 +333,7 @@ export class Operations { const targetEpochs = new Map(); const initial = this.store.read(); const context: ExecutionContext = { + operationId:op.id,resource:op.resource,principalRole:op.owner,remainingMs:()=>Math.max(1,op.deadline-Date.now()), checkpoint: session => { if(this.closed)fail('HOST_CLOSED','coordinator closed'); const data=this.store.read(), current=data.operations[op.id]; @@ -332,6 +341,7 @@ export class Operations { if(current.cancelRequested)fail('CANCEL_REQUESTED','operation cancellation requested; no further effects'); if(Date.now()>=current.deadline || terminal.has(current.state))fail('DEADLINE_EXCEEDED','operation deadline/state no longer permits effects'); if(op.mode==='write') { + if(op.owner!=='operator'&&crossHeld(data,op.resource))fail('STALE_CONTROL','operator changed control across an unverified legacy/device boundary'); const control=data.controls[op.resource] ?? freshControl(); if(control.epoch!==op.controlEpoch || control.revision!==op.appliedRevision || data.controls.host.epoch!==op.hostEpoch)fail('STALE_CONTROL','control changed during operation; later effects blocked'); if(op.resource==='host' && op.owner!=='operator' && Object.values(data.controls).some(c=>c.owner==='operator'||c.paused))fail('STALE_CONTROL','operator took target control; later Host-wide effects blocked'); diff --git a/daemon/src/transport/adb_device.ts b/daemon/src/transport/adb_device.ts new file mode 100644 index 0000000..bf9e5d5 --- /dev/null +++ b/daemon/src/transport/adb_device.ts @@ -0,0 +1,60 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import net from 'node:net'; +import { randomBytes,randomUUID } from 'node:crypto'; +import { DEVICE_BOOTSTRAP,DEVICE_SOCKET,DeviceRpcClient,parseBootstrap,verifyHello,deviceFail,DeviceError,type DevicePeer } from '../device_protocol.ts'; +import { checkpoint,executionContext } from '../execution_context.ts'; + +export interface AdbDevice {serial:string;state:string;transportId?:string;model?:string;link:'usb'|'adb-tcp'|'unknown'} +export type AdbRunner=(args:string[],options?:{timeout?:number;maxBuffer?:number})=>Promise; +const exec=promisify(execFile); +export const realAdbRunner:AdbRunner=async(args,options={})=>{ + if(process.env.ADH_SKIP_ARTIFACT_LOAD==='1')deviceFail('TEST_ADAPTER_REQUIRED','tests must inject an ADB adapter; real devices are forbidden'); + try{return (await exec(process.env.ADH_ADB_PATH||'adb',args,{timeout:options.timeout||10000,maxBuffer:options.maxBuffer||65536,windowsHide:true})).stdout;} + catch(error){throw new DeviceError('ADB_FAILED','ADB request failed; command output and credentials are not logged',(error as any).killed===true);} +}; +export function parseAdbDevices(raw:string):AdbDevice[]{ + const rows:AdbDevice[]=[]; + for(const line of raw.split(/\r?\n/)){const parts=line.trim().split(/\s+/);if(parts.length<2||line.startsWith('List of devices')||line.startsWith('*'))continue; + const [serial,state,...values]=parts;if(!/^[A-Za-z0-9_.:[\]-]{1,200}$/.test(serial))continue; + const props=Object.fromEntries(values.map(p=>{const i=p.indexOf(':');return [p.slice(0,i),p.slice(i+1)];})); + rows.push({serial,state,transportId:/^\d+$/.test(props.transport_id||'')?props.transport_id:undefined,model:props.model,link:props.usb?'usb':serial.includes(':')?'adb-tcp':'unknown'}); + }return rows; +} +export interface AdbConnection {id:string;transport:'adb';serial:string;transportId?:string;port:number;peer:DevicePeer;rpc:DeviceRpcClient;close:()=>Promise<{removed:boolean;confirmed:boolean;reason?:string}>} +export class AdbDeviceTransport { + readonly run:AdbRunner;private dial:(port:number)=>Promise; + constructor(run:AdbRunner=realAdbRunner,dial:(port:number)=>Promise=port=>new Promise((resolve,reject)=>{ + const socket=net.connect({host:'127.0.0.1',port});const timer=setTimeout(()=>socket.destroy(new Error('connect timeout')),5000);socket.once('connect',()=>{clearTimeout(timer);resolve(socket);});socket.once('error',error=>{clearTimeout(timer);reject(error);}); + })){this.run=run;this.dial=dial;} + async discover(){checkpoint();return parseAdbDevices(await this.run(['devices','-l']));} + async connect(serial:string,transportId?:string,onClose:()=>void=()=>{}):Promise{ + const devices=await this.discover(),matches=devices.filter(d=>d.serial===serial&&(!transportId||d.transportId===transportId)); + if(matches.length!==1)deviceFail('DEVICE_AMBIGUOUS','select one exact serial/transportId from discovery');const selected=matches[0]; + if(selected.state!=='device')deviceFail('DEVICE_NOT_READY','ADB transport is '+selected.state+'; no device RPC was attempted'); + const prefix=selected.transportId?['-t',selected.transportId]:['-s',selected.serial]; + checkpoint();const bootstrap=parseBootstrap(await this.run([...prefix,'exec-out','su','-c',`cat ${DEVICE_BOOTSTRAP}`],{maxBuffer:8192})); + const ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'adb',action:'device.forward.create'}); + let port:number; + try{const raw=await this.run([...prefix,'forward','--no-rebind','tcp:0','localabstract:'+DEVICE_SOCKET]);port=Number(raw.trim());if(!Number.isInteger(port)||port<1||port>65535)deviceFail('FORWARD_UNCONFIRMED','ADB did not confirm an owned forward',true);ctx?.acknowledged(false,effect);} + catch(error){ctx?.acknowledged(true,effect,true);throw new DeviceError('FORWARD_UNCONFIRMED','forward creation was not confirmed; no automatic retry',true);} + const remove=async()=>{ + // Verify exactly our mapping and still-current transport. Never remove-all or touch reverse. + const current=(await this.discover()).find(d=>d.serial===selected.serial&&d.transportId===selected.transportId&&d.state==='device'); + if(!current)return {removed:false,confirmed:false,reason:'original ADB transport is no longer present'}; + const rows=(await this.run([...prefix,'forward','--list'])).split(/\r?\n/).map(line=>line.trim().split(/\s+/)); + const mapping=rows.find(([s,l])=>s===selected.serial&&l===`tcp:${port}`); + if(!mapping)return {removed:false,confirmed:true,reason:'owned mapping already absent'}; + if(mapping[2]!=='localabstract:'+DEVICE_SOCKET)return {removed:false,confirmed:false,reason:'mapping was replaced; left untouched'}; + checkpoint();await this.run([...prefix,'forward','--remove',`tcp:${port}`]);return {removed:true,confirmed:true}; + }; + let rpc:DeviceRpcClient|undefined; + try{ + checkpoint();rpc=new DeviceRpcClient(await this.dial(port),onClose); + const id=randomUUID(),nonce=randomBytes(32).toString('hex'); + const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:bootstrap.token}},undefined,undefined,5000,id); + const peer=verifyHello(reply,bootstrap,id,nonce); + return {id:randomUUID(),transport:'adb',serial:selected.serial,transportId:selected.transportId,port,peer,rpc,close:async()=>{rpc!.close();return remove();}}; + }catch(error){rpc?.close();try{if(!(await remove()).confirmed)throw Error();}catch{throw new DeviceError('FORWARD_CLEANUP_UNCONFIRMED','handshake failed and the owned forward cleanup was not confirmed',true);}throw error;} + } +} diff --git a/daemon/test/device_controls.test.ts b/daemon/test/device_controls.test.ts new file mode 100644 index 0000000..6ef9927 --- /dev/null +++ b/daemon/test/device_controls.test.ts @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,rmSync} from 'node:fs'; +import {join} from 'node:path'; +import {tmpdir} from 'node:os'; +import {Operations,type Principal} from '../src/operations.ts'; +import {trackedEffect} from '../src/execution_context.ts'; + +const ai:Principal={role:'ai',id:'fixture',source:'test'},operator:Principal={role:'operator',id:'human',source:'test'}; +const first='00000000-0000-4000-8000-000000000001',second='00000000-0000-4000-8000-000000000002'; +test('verified devices run independently; unassociated legacy targets obey human and unknown-effect fences',async()=>{ + const root=mkdtempSync(join(tmpdir(),'adh-p3-control-')),engine=new Operations(root); + const meta=(r:string)=>{const s=engine.snapshot(r);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; + const a={name:'devices',mode:'write' as const,deviceId:first},b={...a,deviceId:second},legacy={name:'legacy',mode:'write' as const,session:'old'}; + try{ + let release!:()=>void,entered=false,ran=false; + const gate=new Promise(r=>release=r); + const pending=engine.execute(a,{},ai,meta('device:'+first),async()=>trackedEffect(async()=>{entered=true;await gate;return {ok:true};})); + while(!entered)await new Promise(r=>setTimeout(r,2)); + const other=await engine.execute(b,{},ai,meta('device:'+second),async()=>{ran=true;return {ok:true};});assert.equal(other.state,'succeeded');assert.ok(ran); + engine.control('takeover','target:old',operator,meta('target:old')); + assert.throws(()=>engine.submit(b,{},ai,meta('device:'+second),async()=>({ok:true})),/operator-held/); + engine.control('release','target:old',operator,meta('target:old'));release();await pending; + const unknown=await engine.execute(a,{},ai,meta('device:'+first),async()=>trackedEffect(async()=>{throw Error('synthetic lost reply');}));assert.equal(unknown.state,'unknown'); + const blocked=await engine.execute(legacy,{},ai,meta('target:old'),async()=>assert.fail('legacy association unverified'));assert.equal(blocked.error.code,'UNKNOWN_EXECUTION'); + assert.equal((await engine.execute(b,{},ai,meta('device:'+second),async()=>({ok:true}))).state,'succeeded'); + engine.control('resolve','device:'+first,operator,meta('device:'+first),true); + assert.equal((await engine.execute(legacy,{},ai,meta('target:old'),async()=>({ok:true}))).state,'succeeded'); + }finally{engine.close();assert.ok(root.startsWith(join(tmpdir(),'adh-p3-control-')));rmSync(root,{recursive:true,force:true});} +}); diff --git a/daemon/test/device_entrypoints.test.ts b/daemon/test/device_entrypoints.test.ts new file mode 100644 index 0000000..f031614 --- /dev/null +++ b/daemon/test/device_entrypoints.test.ts @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import cp from 'node:child_process'; +import {promisify} from 'node:util'; +import {existsSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {Devices} from '../src/devices.ts'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {setDevicesForTests} from '../src/device_host.ts'; +import {getOperations,operationsRoot} from '../src/operation_host.ts'; +import {initializeOperatorAccess} from '../src/access_context.ts'; +import {handleHttp} from '../src/http/router.ts'; +import {DATA_DIR} from '../src/state.ts'; +import {startDeviceFixture,FakeAdb,jvmManifest,pause} from './device_fixture.ts'; + +test('MCP, REST and published CLI use the same device resource, CAS and operator fence',async t=>{ + if(!existsSync(jvmManifest)){t.skip('offline Kotlin fixture classpath unavailable; no real ADB fallback');return;} + const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('fixture-usb','11',phone); + const engine=getOperations(),key=initializeOperatorAccess(operationsRoot),devices=new Devices(join(DATA_DIR,'devices.json'),new AdbDeviceTransport(adb.run));setDevicesForTests(devices); + const server=http.createServer((req,res)=>{handleHttp(req,res).catch(()=>{res.writeHead(500);res.end('{}');});}); + await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+(server.address() as any).port; + const meta=(resource='host')=>{const s=engine.snapshot(resource);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; + const rpc=async(name:string,args:any,operator=false)=>{ + const response=await fetch(base+'/mcp',{method:'POST',headers:{'Content-Type':'application/json',...(operator?{'X-Adh-Operator-Key':key}:{})},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})}); + const value=await response.json() as any;return JSON.parse(value.result.content[0].text); + }; + try{ + const list=await (await fetch(base+'/api/devices')).json() as any;assert.equal(list.devices.length,0);assert.equal(adb.commands.length,0); + assert.equal((await rpc('devices',{action:'connect',serial:'fixture-usb'})).code,'CONTROL_REQUIRED');assert.equal(adb.commands.length,0); + const connected=await rpc('devices',{action:'connect',serial:'fixture-usb',transportId:'11',_operation:meta()});assert.equal(connected._operation.state,'succeeded'); + const resource='device:'+connected.deviceId; + const read=await rpc('devices',{action:'call',deviceId:connected.deviceId,method:'scope.get'}); + const args={action:'call',deviceId:connected.deviceId,bootId:connected.bootId,daemonInstanceId:connected.daemonInstanceId,expectedDeviceRevision:read.result.stateRevision,method:'scope.patch',params:{scopeRevision:read.result.scopeRevision,add:['com.fixture.one']}}; + const intent={...meta(resource),idempotencyKey:'cross-entry-device-intent'}; + const changed=await fetch(base+'/api/devices',{method:'POST',headers:{'Content-Type':'application/json','X-Adh-Operation':JSON.stringify(intent)},body:JSON.stringify(args)}); + const body=await changed.json() as any;assert.equal(changed.status,200);assert.equal(body._operation.resource,resource); + const again=await rpc('devices',{...args,_operation:intent});assert.equal(again._operation.id,body._operation.id);assert.equal(again.result.stateRevision,1); + const old=meta(resource); + await rpc('operations',{action:'takeover',resource,_operation:meta(resource)},true); + assert.equal((await rpc('devices',{...args,_operation:old})).code,'STALE_CONTROL'); + assert.equal((await rpc('devices',{...args,_operation:meta(resource)})).code,'CONTROL_HELD'); + await rpc('operations',{action:'release',resource,_operation:meta(resource)},true); + const cliSource=process.env.ADH_CLI_SOURCE||resolve('../..','adh-cli','src'); + if(!existsSync(join(cliSource,'adh','__init__.py'))){t.diagnostic('CLI source unavailable; MCP/REST assertions passed, set ADH_CLI_SOURCE for CLI path');return;} + try{await promisify(cp.execFile)('python',['--version'],{windowsHide:true,timeout:5000});}catch(e){if((e as any).code==='ENOENT'){t.diagnostic('Python unavailable; CLI portion not run');return;}throw e;} + const execute=promisify(cp.execFile),env={...process.env,PYTHONPATH:cliSource,ADH_CONFIG_PATH:join(DATA_DIR,'device-cli-fixture.json'),ADH_OPERATOR_TOKEN:key,PYTHONIOENCODING:'utf-8'}; + const state=await rpc('devices',{action:'call',deviceId:connected.deviceId,method:'device.state'}); + const cliArgs={...args,expectedDeviceRevision:state.result.stateRevision,params:{scopeRevision:state.result.scopeRevision}}; + const latest=await rpc('devices',{action:'call',deviceId:connected.deviceId,method:'scope.get'});cliArgs.params={scopeRevision:latest.result.scopeRevision,add:['com.fixture.two']} as any; + const output=await execute('python',['-m','adh','run','devices','--arguments',JSON.stringify(cliArgs),'--endpoint',base,'--json'],{env,timeout:15000,windowsHide:true}); + const submitted=JSON.parse(String(output.stdout)).operation; + for(let n=0;n<100&&!engine.getOperation(submitted.id).settled;n++)await pause(10); + const op=engine.getOperation(submitted.id,true);assert.equal(op.state,'succeeded');assert.equal(op.owner,'ai');assert.equal(op.resource,resource); + assert.deepEqual((await rpc('devices',{action:'call',deviceId:connected.deviceId,method:'scope.get'})).result.document.packages,['com.fixture.one','com.fixture.two']); + }finally{devices.close();await new Promise(r=>server.close(()=>r()));engine.close();await adb.close();await phone.close();} +}); diff --git a/daemon/test/device_fixture.ts b/daemon/test/device_fixture.ts new file mode 100644 index 0000000..968bbed --- /dev/null +++ b/daemon/test/device_fixture.ts @@ -0,0 +1,52 @@ +import {spawn} from 'node:child_process'; +import {mkdtempSync,readFileSync,existsSync,unlinkSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join,delimiter,resolve,dirname,basename} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import net from 'node:net'; +import {DeviceError,DEVICE_BOOTSTRAP,DEVICE_SOCKET} from '../src/device_protocol.ts'; +import type {AdbRunner} from '../src/transport/adb_device.ts'; + +export const jvmManifest=process.env.ADH_DEVICE_JVM_FIXTURE||fileURLToPath(new URL('../../device/daemon/build/device-rpc-fixture-classpath.json',import.meta.url)); +export const pause=(ms:number)=>new Promise(r=>setTimeout(r,ms)); +function checkedRoot(root:string){const path=resolve(root);if(dirname(path)!==resolve(tmpdir())||!basename(path).startsWith('adh-p3-jvm-'))throw Error('unsafe fixture directory');return path;} +export async function startDeviceFixture(existingRoot?:string){ + const root=checkedRoot(existingRoot||mkdtempSync(join(tmpdir(),'adh-p3-jvm-'))); + const ready=join(root,'ready.json');if(existsSync(ready))unlinkSync(ready); + const cp=JSON.parse(readFileSync(jvmManifest,'utf8')) as string[]; + const child=spawn(process.env.JAVA_HOME?join(process.env.JAVA_HOME,'bin','java.exe'):'java',['-cp',cp.join(delimiter),'com.adh.daemon.device.DeviceRpcFixture',root],{windowsHide:true,stdio:['ignore','pipe','pipe']}); + let failure='';child.stderr?.on('data',chunk=>{failure=(failure+chunk).slice(-4000);});child.on('error',e=>{failure=e.message;}); + let metadata:any; + for(let n=0;n<300;n++){if(child.exitCode!==null)throw Error('JVM fixture exited: '+failure);if(existsSync(ready)){try{metadata=JSON.parse(readFileSync(ready,'utf8'));break;}catch{}}await pause(50);} + if(!metadata){child.kill();throw Error('JVM fixture did not become ready: '+failure);} + const stop=async()=>{if(child.exitCode===null){const done=new Promise(r=>child.once('exit',()=>r()));child.kill();await done;}}; + return {root,port:metadata.port as number,deviceId:metadata.deviceId as string,child,stop,async close(){await stop();rmSync(checkedRoot(root),{recursive:true,force:true});}}; +} +type Fixture=Awaited>; +export class FakeAdb { + endpoints=new Map(); + forwards=new Map}>(); + commands:string[][]=[]; + add(serial:string,transportId:string,fixture:Fixture,state='device'){this.endpoints.set(transportId,{serial,transportId,fixture,state});} + run:AdbRunner=async(args)=>{ + this.commands.push([...args]); + if(args.join(' ')==='devices -l')return 'List of devices attached\n'+[...this.endpoints.values()].map(e=>`${e.serial}\t${e.state} usb:1-${e.transportId} model:Fixture transport_id:${e.transportId}`).join('\n'); + const entry=args[0]==='-t'?this.endpoints.get(args[1]):[...this.endpoints.values()].find(e=>e.serial===args[1]); + if(!entry||entry.state!=='device')throw new DeviceError('ADB_FAILED','synthetic stale/offline transport'); + const rest=args.slice(2); + if(rest.join(' ')==='exec-out su -c cat '+DEVICE_BOOTSTRAP)return readFileSync(join(entry.fixture.root,'usb-access.json'),'utf8'); + if(rest.join(' ')==='forward --no-rebind tcp:0 localabstract:'+DEVICE_SOCKET){ + const sockets=new Set(); + const server=net.createServer(local=>{const remote=net.connect(entry.fixture.port,'127.0.0.1');sockets.add(local);sockets.add(remote);local.pipe(remote).pipe(local);local.on('close',()=>{remote.destroy();sockets.delete(local);sockets.delete(remote);});local.on('error',()=>remote.destroy());remote.on('error',()=>local.destroy());}); + await new Promise(r=>server.listen(0,'127.0.0.1',r));const port=(server.address() as net.AddressInfo).port; + this.forwards.set(port,{serial:entry.serial,target:'localabstract:'+DEVICE_SOCKET,server,sockets});return String(port); + } + if(rest.join(' ')==='forward --list')return [...this.forwards.entries()].map(([p,f])=>`${f.serial} tcp:${p} ${f.target}`).join('\n'); + if(rest[0]==='forward'&&rest[1]==='--remove'){ + const port=Number(rest[2].slice(4)),mapping=this.forwards.get(port);if(!mapping||mapping.serial!==entry.serial)throw Error('wrong synthetic forward removal'); + mapping.sockets.forEach(s=>s.destroy());await new Promise(r=>mapping.server.close(()=>r()));this.forwards.delete(port);return ''; + } + throw Error('FORBIDDEN device command in fixture: '+args.join(' ')); + }; + async close(){for(const mapping of this.forwards.values()){mapping.sockets.forEach(s=>s.destroy());await new Promise(r=>mapping.server.close(()=>r()));}this.forwards.clear();} +} diff --git a/daemon/test/device_jvm.test.ts b/daemon/test/device_jvm.test.ts new file mode 100644 index 0000000..8d57c11 --- /dev/null +++ b/daemon/test/device_jvm.test.ts @@ -0,0 +1,131 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {existsSync,mkdtempSync,readFileSync,writeFileSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {randomUUID} from 'node:crypto'; +import {Devices} from '../src/devices.ts'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {Operations,type Principal} from '../src/operations.ts'; +import {describeTool} from '../src/operation_registry.ts'; +import {startDeviceFixture,FakeAdb,jvmManifest,pause} from './device_fixture.ts'; + +const ai:Principal={role:'ai',id:'fixture-ai',source:'test'},human:Principal={role:'operator',id:'fixture-human',source:'test'}; +const reason=existsSync(jvmManifest)?false:'build the offline JVM fixture with :daemon:writeDeviceRpcFixtureClasspath; no real device fallback'; +const metadata=(engine:Operations,resource:string)=>{const s=engine.snapshot(resource);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; +async function fixture(){ + const a=await startDeviceFixture(),b=await startDeviceFixture(),adb=new FakeAdb();adb.add('usb-A','1',a);adb.add('usb-B','2',b); + const root=mkdtempSync(join(tmpdir(),'adh-p3-host-')),engine=new Operations(join(root,'operations')); + const devices=new Devices(join(root,'devices.json'),new AdbDeviceTransport(adb.run),id=>engine.invalidateResource('device:'+id)); + async function execute(args:any,principal=ai,extra:any={}){const spec=describeTool('devices',args);return engine.execute(spec,args,principal,{...metadata(engine,engine.resource(spec)),...extra},async()=>{ + if(args.action==='connect')return devices.connect(args.serial,args.transportId,args.expectedDeviceId); + if(args.action==='disconnect')return devices.disconnect(args.deviceId,args.connectionId); + return devices.call(args); + });} + async function connect(serial='usb-A',transportId='1'){ + const operation=await execute({action:'connect',serial,transportId});assert.equal(operation.state,'succeeded');return engine.getOperation(operation.id,true).result; + } + const read=(deviceId:string,method:string,params:any={},connectionId?:string)=>devices.call({deviceId,method,params,connectionId}); + async function write(peer:any,method:string,params:any={},extra:any={},principal=ai){ + const state=await read(peer.deviceId,'device.state',{},peer.connectionId); + return execute({action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,method,params,...extra},principal); + } + return {a,b,adb,root,engine,devices,execute,connect,read,write,async close(){devices.close();engine.close();await adb.close();await a.close();await b.close();assert.ok(root.startsWith(join(tmpdir(),'adh-p3-host-')));rmSync(root,{recursive:true,force:true});}}; +} + +test('production Kotlin/Node protocol keeps two devices isolated and preserves scope policy', {skip:reason},async()=>{ + const f=await fixture();try{ + assert.equal(f.adb.commands.length,0,'constructors and cached list never discover devices'); + assert.equal(f.devices.list().devices.length,0); + const a=await f.connect(),b=await f.connect('usb-B','2');assert.notEqual(a.deviceId,b.deviceId); + assert.equal(a.identity.capabilities.methods['scope.patch'],'write');assert.equal(f.devices.list().devices.length,2); + writeFileSync(join(f.a.root,'scope.json'),JSON.stringify({version:19,mode:'allowlist',packages:['com.fixture.old'],policy:{'com.fixture.old':{c:{h:true,future:7},future:'kept'}},future:{nested:true}})); + const before=await f.read(a.deviceId,'scope.get'),unchanged=await f.read(b.deviceId,'scope.get'); + const done=await f.write(a,'scope.patch',{scopeRevision:before.result.scopeRevision,add:['com.fixture.new']}); + assert.equal(done.state,'succeeded');assert.equal(done.resource,'device:'+a.deviceId); + const after=await f.read(a.deviceId,'scope.get');assert.deepEqual(after.result.document.packages,['com.fixture.new','com.fixture.old']); + assert.deepEqual(after.result.document.policy,before.result.document.policy);assert.deepEqual(after.result.document.future,{nested:true}); + assert.equal((await f.read(b.deviceId,'scope.get')).result.scopeRevision,unchanged.result.scopeRevision); + const wrongResource=await f.engine.execute(describeTool('devices',{action:'call',deviceId:b.deviceId,method:'scope.patch'}),{},ai,metadata(f.engine,'device:'+b.deviceId),()=>f.devices.call({deviceId:a.deviceId,method:'scope.patch',params:{},bootId:a.bootId,daemonInstanceId:a.daemonInstanceId,expectedDeviceRevision:1})); + assert.equal(wrongResource.state,'failed');assert.equal(wrongResource.error.code,'TARGET_CHANGED'); + const stale=await f.write(a,'scope.patch',{scopeRevision:before.result.scopeRevision,set:[]}); + assert.equal(stale.state,'failed');assert.equal(f.engine.getOperation(stale.id,true).result.result.code,'STALE_SCOPE'); + const args={action:'call',deviceId:a.deviceId,connectionId:a.connectionId,bootId:a.bootId,daemonInstanceId:a.daemonInstanceId,expectedDeviceRevision:0,method:'host.set',params:{endpoint:'fixture:123'}}; + const badVersion=await f.execute(args);assert.equal(badVersion.state,'failed');assert.equal(badVersion.error.code,'STALE_DEVICE_STATE'); + assert.equal((await f.read(a.deviceId,'scope.get')).result.scopeRevision,after.result.scopeRevision); + const cached=readFileSync(join(f.root,'devices.json'),'utf8');assert.ok(!cached.includes('"token"'));assert.ok(!cached.includes('privateKey')); + const commands=f.adb.commands.length,reopened=new Devices(join(f.root,'devices.json'),new AdbDeviceTransport(f.adb.run)); + assert.equal(reopened.list().devices.length,2);assert.ok(reopened.list().devices.every(d=>!d.online));assert.equal(f.adb.commands.length,commands); + }finally{await f.close();} +}); + +test('USB aliases retain installation identity, require explicit connections and remove only owned forwards',{skip:reason},async()=>{ + const f=await fixture();try{ + const a=await f.connect();f.adb.add('usb-replugged','3',f.a); + const alias=await f.connect('usb-replugged','3');assert.equal(alias.deviceId,a.deviceId);assert.equal(f.devices.list().devices.length,1); + await assert.rejects(()=>f.read(a.deviceId,'device.info'),(e:any)=>e.code==='CONNECTION_AMBIGUOUS'); + assert.equal((await f.read(a.deviceId,'device.info',{},alias.connectionId)).result.deviceId,a.deviceId); + const b=await f.connect('usb-B','2');const bPort=[...f.adb.forwards.entries()].find(([,m])=>m.serial==='usb-B')![0]; + assert.equal((await f.execute({action:'disconnect',deviceId:a.deviceId,connectionId:a.connectionId})).state,'succeeded'); + assert.ok(f.adb.forwards.has(bPort));assert.equal(f.adb.forwards.size,2); + // A disconnected channel remains inspectable/cleanable; it never silently fails over. + const aliasPort=[...f.adb.forwards.entries()].find(([,m])=>m.serial==='usb-replugged')![0];f.adb.forwards.get(aliasPort)!.sockets.forEach(s=>s.destroy());await pause(40); + await assert.rejects(()=>f.read(a.deviceId,'scope.get'),(e:any)=>e.code==='DEVICE_OFFLINE'); + assert.equal((await f.execute({action:'disconnect',deviceId:a.deviceId,connectionId:alias.connectionId})).state,'succeeded'); + assert.equal((await f.read(b.deviceId,'module.status')).result.calls,0); + assert.ok(f.adb.commands.every(c=>!c.includes('reverse')&&!c.includes('--remove-all')&&!c.includes('install')&&!c.includes('kill-server'))); + assert.ok(f.adb.commands.filter(c=>c[0]!=='devices').every(c=>c[0]==='-t'),'every selected USB operation pins transport_id'); + }finally{await f.close();} +}); + +test('wrong USB credentials and identity never publish a device and clean only the created mapping',{skip:reason},async()=>{ + const f=await fixture();try{ + const b=await f.connect('usb-B','2'),count=f.adb.forwards.size; + const accessFile=join(f.a.root,'usb-access.json'),access=readFileSync(accessFile,'utf8'); + writeFileSync(accessFile,JSON.stringify({...JSON.parse(access),token:'0'.repeat(64)})); + const rejected=await f.execute({action:'connect',serial:'usb-A',transportId:'1'});assert.equal(rejected.state,'failed');assert.equal(rejected.error.code,'AUTH_FAILED'); + assert.equal(f.devices.list().devices.length,1);assert.equal(f.adb.forwards.size,count);writeFileSync(accessFile,access); + const mismatch=await f.execute({action:'connect',serial:'usb-A',transportId:'1',expectedDeviceId:b.deviceId}); + assert.equal(mismatch.state,'failed');assert.equal(mismatch.error.code,'DEVICE_MISMATCH');assert.equal(f.adb.forwards.size,count); + assert.equal((await f.read(b.deviceId,'device.state')).result.stateRevision,0); + }finally{await f.close();} +}); + +test('replaced forwards are never removed and cleanup uncertainty remains visible',{skip:reason},async()=>{ + const f=await fixture();try{ + const a=await f.connect(),mapping=[...f.adb.forwards.values()][0];mapping.target='localabstract:another-owner'; + const before=f.adb.commands.filter(c=>c.includes('--remove')).length; + const disconnected=await f.execute({action:'disconnect',deviceId:a.deviceId,connectionId:a.connectionId}); + assert.equal(disconnected.state,'unknown');assert.equal(disconnected.error.code,'FORWARD_CLEANUP_UNCONFIRMED'); + assert.equal(f.adb.commands.filter(c=>c.includes('--remove')).length,before);assert.equal(f.adb.forwards.size,1); + assert.equal(f.devices.list().devices[0].connections[0].online,false,'retain the handle and honest closed state for inspection'); + }finally{await f.close();} +}); + +test('deadline after dispatch is unknown, device operation can be queried, and nothing is replayed',{skip:reason},async()=>{ + const f=await fixture();try{ + const a=await f.connect(); + const expired=await f.write(a,'process.control',{delayMs:1600},{budgetMs:300}); + assert.equal(expired.state,'unknown');assert.equal(expired.error.code,'DEVICE_RPC_TIMEOUT'); + const denied=await f.write(a,'process.control',{delayMs:0});assert.equal(denied.state,'failed');assert.equal(denied.error.code,'UNKNOWN_EXECUTION'); + const recorded=await f.read(a.deviceId,'operations.get',{operationId:expired.id});assert.equal(recorded.result.state,'succeeded');assert.equal(recorded.result.result.calls,1); + assert.equal((await f.read(a.deviceId,'module.status')).result.calls,1); + const observed=f.engine.getOperation(expired.id,true);assert.equal(observed.state,'unknown');assert.ok(observed.effects[0].uncertainAt); + f.engine.control('resolve','device:'+a.deviceId,human,metadata(f.engine,'device:'+a.deviceId),true); + assert.equal((await f.write(a,'process.control',{delayMs:0})).state,'succeeded');assert.equal((await f.read(a.deviceId,'module.status')).result.calls,2); + }finally{await f.close();} +}); + +test('boot and daemon changes preserve identity and invalidate Host versions without binding legacy sessions',{skip:reason},async()=>{ + const f=await fixture();try{ + const a=await f.connect(),oldSnapshot=f.engine.snapshot('device:'+a.deviceId),key=a.identity.identityFingerprint; + await f.a.stop();await pause(60);writeFileSync(join(f.a.root,'boot.txt'),randomUUID()); + const restarted=await startDeviceFixture(f.a.root);f.a.port=restarted.port;f.a.child=restarted.child;f.a.stop=restarted.stop;f.a.close=restarted.close; + const current=await f.connect();assert.equal(current.deviceId,a.deviceId);assert.equal(current.identity.identityFingerprint,key);assert.notEqual(current.bootId,a.bootId); + assert.ok(f.engine.snapshot('device:'+a.deviceId).epoch>oldSnapshot.epoch); + const stale=await f.write(current,'process.control',{delayMs:0},{bootId:a.bootId,daemonInstanceId:a.daemonInstanceId});assert.equal(stale.state,'failed');assert.equal(stale.error.code,'TARGET_CHANGED'); + assert.equal((await f.read(current.deviceId,'module.status',{},current.connectionId)).result.calls,0); + assert.match(f.devices.list().legacyAgentAssociation,/unverified/); + await assert.rejects(()=>f.read('usb-A','scope.get'),(e:any)=>e.code==='DEVICE_REQUIRED'); + }finally{await f.close();} +}); diff --git a/daemon/test/device_protocol.test.ts b/daemon/test/device_protocol.test.ts new file mode 100644 index 0000000..e008446 --- /dev/null +++ b/daemon/test/device_protocol.test.ts @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {Duplex} from 'node:stream'; +import {generateKeyPairSync,createHash,sign} from 'node:crypto'; +import {parseAdbDevices} from '../src/transport/adb_device.ts'; +import {DEVICE_PROTOCOL,DeviceRpcClient,deviceFrame,parseBootstrap,verifyHello,deviceMethodMode} from '../src/device_protocol.ts'; +import {describeTool} from '../src/operation_registry.ts'; + +test('discovery retains offline/unauthorized states and transport identity without guessing a device id',()=>{ + const values=parseAdbDevices('List of devices attached\nusb-A device usb:1-1 model:Phone transport_id:9\n192.0.2.1:5555 device model:Phone transport_id:10\nusb-B unauthorized transport_id:11\nusb-C offline transport_id:12'); + assert.equal(values.length,4);assert.equal(values[0].transportId,'9');assert.equal(values[1].link,'adb-tcp');assert.equal(values[2].state,'unauthorized');assert.equal(values[3].state,'offline');assert.ok(values.every(v=>!('deviceId' in v))); +}); + +test('signed hello binds the root bootstrap key, device, nonce and capability effects',()=>{ + const {publicKey,privateKey}=generateKeyPairSync('rsa',{modulusLength:2048}),der=publicKey.export({format:'der',type:'spki'}) as Buffer; + const bootstrap={schemaVersion:1 as const,deviceId:'00000000-0000-4000-8000-000000000001',identityFingerprint:createHash('sha256').update(der).digest('hex'),token:'a'.repeat(64)}; + const peer={protocol:DEVICE_PROTOCOL,requestId:'hello',clientNonce:'b'.repeat(64),deviceId:bootstrap.deviceId,bootId:'00000000-0000-4000-8000-000000000002',daemonInstanceId:'00000000-0000-4000-8000-000000000003',identityFingerprint:bootstrap.identityFingerprint,capabilities:{methods:{'scope.get':'read'}},info:{}}; + const payload=Buffer.from(JSON.stringify(peer)),reply={publicKey:der.toString('base64'),payload:payload.toString('base64'),signature:sign('sha256',payload,privateKey).toString('base64')}; + assert.equal(verifyHello(reply,bootstrap,'hello','b'.repeat(64)).deviceId,bootstrap.deviceId); + assert.throws(()=>verifyHello(reply,bootstrap,'hello','c'.repeat(64)),(e:any)=>e.code==='IDENTITY_UNVERIFIED'); + assert.throws(()=>verifyHello({...reply,payload:Buffer.from('{}').toString('base64')},bootstrap,'hello','b'.repeat(64))); + assert.throws(()=>parseBootstrap('{"token":"synthetic-private-value"}'),e=>!String(e).includes('synthetic-private-value')); + assert.throws(()=>parseBootstrap('null'),(e:any)=>e.code==='INVALID_BOOTSTRAP'); +}); + +test('device methods are exact effect capabilities; arbitrary shell and disguised writes are rejected',()=>{ + assert.equal(deviceMethodMode('scope.get'),'read');assert.equal(deviceMethodMode('scope.patch'),'write'); + assert.equal(describeTool('devices',{action:'call',deviceId:'d',method:'process.control'}).mode,'write'); + assert.throws(()=>deviceMethodMode('shell'),(e:any)=>e.code==='UNSUPPORTED_METHOD'); + assert.throws(()=>describeTool('devices',{action:'call',method:'native_hook_all',status:'read'})); +}); + +function wire(){let stream:Duplex;const frames:any[]=[];stream=new Duplex({read(){},write(data,_,done){frames.push(JSON.parse(data.subarray(4).toString()));done();}});return {stream,frames};} +test('fragmented replies and out-of-order ids are decoded once without replaying writes',async()=>{ + const w=wire(),rpc=new DeviceRpcClient(w.stream); + await assert.rejects(()=>rpc.request('device.info',{},undefined,undefined,NaN),(e:any)=>e.code==='INVALID_ARGUMENT');assert.equal(w.frames.length,0); + const a=rpc.request('device.info',{},undefined,undefined,1000,'one'),b=rpc.request('scope.get',{},undefined,undefined,1000,'two'); + const frame=deviceFrame({protocol:DEVICE_PROTOCOL,id:'two',ok:true,result:{value:2}});w.stream.push(frame.subarray(0,2));w.stream.push(frame.subarray(2)); + w.stream.push(deviceFrame({protocol:DEVICE_PROTOCOL,id:'one',ok:true,result:{value:1}})); + assert.equal((await a).value,1);assert.equal((await b).value,2);assert.equal(w.frames.length,2);rpc.close(); +}); +test('post-dispatch deadline is uncertain; oversized frames close pending calls instead of fabricating cancellation',async()=>{ + const w=wire(),rpc=new DeviceRpcClient(w.stream); + await assert.rejects(()=>rpc.request('process.control',{},undefined,{},30,'write'),(e:any)=>e.uncertain===true&&e.code==='DEVICE_RPC_TIMEOUT'); + assert.equal(w.frames.length,1); + const pending=rpc.request('device.info',{},undefined,undefined,1000,'read');const header=Buffer.alloc(4);header.writeUInt32BE(1024*1024+1);w.stream.push(header); + await assert.rejects(()=>pending,(e:any)=>e.code==='FRAME_LIMIT');rpc.close(); +}); diff --git a/device/MAP.md b/device/MAP.md index 36bf5e3..4bf83a0 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -123,3 +123,9 @@ its own screen, opened from an app row. Home compares `BuildConfig.VERSION_CODE` manifest at the same URL as `module.prop` `updateJson`. Module status distinguishes an unavailable Device Daemon from an absent or unloaded module. Both Home and Scope re-check when returning to the foreground. + +## P3 device domain (2026-11-16) + +`core/DeviceRpc.kt` pins adh.device/1, bounded framing and the method-effect contract. AIDL v19 appends info/capabilities/scope CAS without renumbering previous transactions. `daemon/AndroidDeviceBackend.kt` owns Android business operations; `RootScopeBinder` enforces the existing caller verifier then delegates to the same `device/DeviceOperations` as USB RPC. That package owns installation identity, atomic files, the bounded revision/operation journal, process generations, scope preservation and a stream dispatcher. `LocalDeviceRpcServer` adds only an authenticated abstract UDS; no phone HTTP/MCP/TCP/analysis server. DeviceDaemon holds a process lock for identity/journal ownership. + +JVM `DeviceDomainTest` tests recovery/CAS/storage errors; `DeviceRpcFixture` exposes the production identity/domain/codec over an OS-temp loopback socket with a synthetic backend. `:daemon:writeDeviceRpcFixtureClasspath` explicitly builds its ignored classpath manifest for Host interoperability tests; it never starts a real Android service. See docs/P3_DEVICE_DOMAIN.md for limits and the separate unverified Android/SELinux boundary. diff --git a/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl b/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl index 83778c0..3f14c49 100644 --- a/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl +++ b/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl @@ -32,4 +32,9 @@ interface IAdhScopeService { boolean deleteCaCert(String fileName); /** Reboot. The caller must already have confirmed with the user. Protocol v18. */ boolean rebootDevice(); + /** v19: the same device-domain information and CAS used by USB RPC. */ + String getDeviceInfoJson(); + String getDeviceCapabilitiesJson(); + String getScopeSnapshotJson(); + String setScopeVersionedJson(String json, String scopeRevision, long stateRevision); } diff --git a/device/core/src/main/java/com/adh/core/AdhPaths.kt b/device/core/src/main/java/com/adh/core/AdhPaths.kt index a463669..afa1c07 100644 --- a/device/core/src/main/java/com/adh/core/AdhPaths.kt +++ b/device/core/src/main/java/com/adh/core/AdhPaths.kt @@ -10,6 +10,9 @@ object AdhPaths { /** One line `ipv4:port`. The agent dials this after `127.0.0.1:8761` fails. */ const val HOST_ENDPOINT_PATH = "/data/adb/adh/host.endpoint" const val SCOPE_DIR = "/data/adb/adh" + const val DEVICE_RPC_DIR = "/data/adb/adh/device-rpc" + const val DEVICE_IDENTITY_PATH = "/data/adb/adh/device-rpc/identity.json" + const val DEVICE_USB_ACCESS_PATH = "/data/adb/adh/device-rpc/usb-access.json" /** DER CA files named `.N`. Mounted by post-fs-data, not by magic mount. */ const val CACERTS_DIR = "/data/adb/adh/cacerts" const val LOADER_MARKER = "/data/adb/adh/zygisk_loaded" diff --git a/device/core/src/main/java/com/adh/core/AdhProtocol.kt b/device/core/src/main/java/com/adh/core/AdhProtocol.kt index 38fffaf..09b0082 100644 --- a/device/core/src/main/java/com/adh/core/AdhProtocol.kt +++ b/device/core/src/main/java/com/adh/core/AdhProtocol.kt @@ -7,7 +7,9 @@ object AdhProtocol { * v16 briefly carried an SSL-bypass section; that section was removed and a leftover `b` key * is ignored. v17 stores the host address an injected process dials when adb reverse is absent. * v18 stores user CA certificates that post-fs-data mounts into the system trust store. */ - const val VERSION = 18 + const val VERSION = 19 + /** v19 adds a shared device domain, stable installation identity and USB RPC. */ + const val MIN_DEVICE_DOMAIN_VERSION = 19 const val MIN_SCOPE_VERSION = 1 const val MIN_CATALOG_VERSION = 2 const val MIN_ICON_VERSION = 3 diff --git a/device/core/src/main/java/com/adh/core/DeviceRpc.kt b/device/core/src/main/java/com/adh/core/DeviceRpc.kt new file mode 100644 index 0000000..8251dce --- /dev/null +++ b/device/core/src/main/java/com/adh/core/DeviceRpc.kt @@ -0,0 +1,47 @@ +package com.adh.core + +import org.json.JSONObject +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.EOFException +import java.io.InputStream +import java.io.OutputStream +import java.security.MessageDigest + +/** Transport-independent device RPC; deliberately unrelated to the legacy target agent framing. */ +object DeviceRpc { + const val PROTOCOL = "adh.device/1" + const val SOCKET_NAME = "adh_device_rpc_v1" + const val MAX_FRAME = 1024 * 1024 + const val MAX_BUDGET_MS = 60_000L + val READ_METHODS = setOf("device.info", "device.capabilities", "device.state", "module.status", "scope.get", "applications.list", "processes.list", "certificates.list", "host.get", "operations.get") + val WRITE_METHODS = setOf("scope.patch", "scope.replace", "process.control", "certificates.put", "certificates.delete", "host.set", "operations.resolve") + // Reboot and arbitrary shell/helper execution are NOT remote RPC capabilities in P3. + fun read(input: InputStream): JSONObject? { + val first = input.read() + if (first < 0) return null + val data = DataInputStream(input) + val length = (first shl 24) or (data.readUnsignedByte() shl 16) or (data.readUnsignedByte() shl 8) or data.readUnsignedByte() + require(length in 1..MAX_FRAME) { "invalid device RPC frame length" } + val payload = ByteArray(length) + data.readFully(payload) + return JSONObject(String(payload, Charsets.UTF_8)) + } + fun write(output: OutputStream, value: JSONObject) { + val payload = value.toString().toByteArray(Charsets.UTF_8) + require(payload.size in 1..MAX_FRAME) { "device RPC response exceeds frame limit" } + DataOutputStream(output).apply { writeInt(payload.size); write(payload); flush() } + } + fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + fun canonical(value: Any?): String = when (value) { + null, JSONObject.NULL -> "null" + is JSONObject -> value.keys().asSequence().toList().sorted().joinToString(",", "{", "}") { JSONObject.quote(it) + ":" + canonical(value.get(it)) } + is org.json.JSONArray -> (0 until value.length()).joinToString(",", "[", "]") { canonical(value.get(it)) } + is String -> JSONObject.quote(value) + is Boolean, is Number -> value.toString() + else -> throw IllegalArgumentException("unsupported JSON value") + } + fun response(id: String, result: JSONObject): JSONObject = JSONObject().put("protocol", PROTOCOL).put("id", id).put("ok", true).put("result", result) + fun failure(id: String, code: String, message: String, uncertain: Boolean = false): JSONObject = JSONObject().put("protocol", PROTOCOL).put("id", id).put("ok", false) + .put("error", JSONObject().put("code", code).put("message", message).put("uncertain", uncertain)) +} diff --git a/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt b/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt index 91bf383..725908c 100644 --- a/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt +++ b/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt @@ -137,7 +137,8 @@ class ScopeJsonTest { assertFalse(apps[0].system) assertEquals("com.android.settings", apps[1].packageName) assertTrue(apps[1].system) - assertEquals(AdhProtocol.VERSION, 18) + assertEquals(19, AdhProtocol.VERSION) + assertEquals(19, AdhProtocol.MIN_DEVICE_DOMAIN_VERSION) assertEquals(AdhProtocol.MIN_HOST_ENDPOINT_VERSION, 17) assertEquals(AdhProtocol.MIN_CA_CERT_VERSION, 18) assertEquals(AdhProtocol.MIN_PROCESS_VERSION, 4) diff --git a/device/daemon/build.gradle.kts b/device/daemon/build.gradle.kts index 637e36d..6acc026 100644 --- a/device/daemon/build.gradle.kts +++ b/device/daemon/build.gradle.kts @@ -37,4 +37,17 @@ android { dependencies { implementation(project(":core")) testImplementation(libs.junit) + testImplementation(libs.org.json) +} + +// Explicit host-only interoperability fixture. No APK install, app_process or device command. +tasks.register("writeDeviceRpcFixtureClasspath") { + dependsOn("compileDebugUnitTestKotlin", "processDebugUnitTestJavaRes") + doLast { + val testTask = tasks.named("testDebugUnitTest").get() + val files = (testTask.classpath + testTask.testClassesDirs).files.map { it.absolutePath } + val output = layout.buildDirectory.file("device-rpc-fixture-classpath.json").get().asFile + output.parentFile.mkdirs() + output.writeText(files.joinToString(",", "[", "]") { "\"" + it.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" }) + } } diff --git a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt index 3f8b3fd..f3ad9c4 100644 --- a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt +++ b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt @@ -7,10 +7,17 @@ import android.os.Process import android.util.Log import com.adh.core.AdhPaths import java.io.File +import com.adh.daemon.device.DeviceFiles +import com.adh.daemon.device.DeviceIdentity +import com.adh.daemon.device.DeviceOperations +import com.adh.daemon.device.LocalDeviceRpcServer +import android.system.Os object AdhDeviceDaemon { private const val TAG = "AdhDeviceDaemon" private const val PUBLISH_INTERVAL_MS = 1_000L + private var rpc: LocalDeviceRpcServer? = null + private var domainLock: java.nio.channels.FileLock? = null @JvmStatic fun main(args: Array) { @@ -26,7 +33,18 @@ object AdhDeviceDaemon { Looper.prepareMainLooper() val context = SystemContext.create() - val service = RootScopeBinder(ManagerCallerVerifier(context), context) + val files = DeviceFiles(File(AdhPaths.DEVICE_RPC_DIR), { file, mode -> Os.chmod(file.path, mode) }, { directory -> + val fd = Os.open(directory.path, android.system.OsConstants.O_RDONLY, 0) + try { Os.fsync(fd) } finally { Os.close(fd) } + }) + files.initialize() + val lockChannel = java.io.RandomAccessFile(File(files.directory, "daemon.lock"), "rw").channel + domainLock = checkNotNull(lockChannel.tryLock()) { "another device domain instance owns this installation" } + val identity = DeviceIdentity(files, File("/proc/sys/kernel/random/boot_id").readText().trim()) + val operations = DeviceOperations(identity, files, AndroidDeviceBackend(context, files)) + val service = RootScopeBinder(ManagerCallerVerifier(context), operations) + // RPC availability never tears down the pre-existing authenticated Binder service. + runCatching { rpc = LocalDeviceRpcServer(operations) }.onFailure { Log.e(TAG, "USB RPC unavailable; Binder remains available", it) } File(AdhPaths.SCOPE_DIR).mkdirs() File(AdhPaths.DAEMON_PID_PATH).writeText(Process.myPid().toString()) File(AdhPaths.DAEMON_READY_MARKER).writeText("1\n") diff --git a/device/daemon/src/main/java/com/adh/daemon/AndroidDeviceBackend.kt b/device/daemon/src/main/java/com/adh/daemon/AndroidDeviceBackend.kt new file mode 100644 index 0000000..30d15d9 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/AndroidDeviceBackend.kt @@ -0,0 +1,140 @@ +package com.adh.daemon + +import android.content.Context +import android.system.Os +import com.adh.core.AdhPaths +import com.adh.core.AdhProtocol +import com.adh.core.CaCertStore +import com.adh.core.HostEndpoint +import com.adh.core.PackageControl +import com.adh.daemon.device.DeviceBackend +import com.adh.daemon.device.DeviceFiles +import com.adh.daemon.device.DeviceFault +import com.adh.daemon.device.DeviceArguments +import com.adh.daemon.device.ScopeDocuments +import com.adh.daemon.device.ProcessCatalog +import org.json.JSONObject +import org.json.JSONArray +import android.os.Build +import java.util.Base64 +import java.io.File +import java.io.StringReader +import java.util.Properties + +internal class AndroidDeviceBackend( + private val context: Context, + private val files: DeviceFiles, +) : DeviceBackend { + private val scopes = ScopeDocuments(File(AdhPaths.SCOPE_PATH), files) + private val processes = ProcessCatalog() + override fun validate(method: String, params: JSONObject) { + DeviceArguments.validate(method, params) + if (method == "process.control") { + val pkg = params.getString("package") + val app = try { context.packageManager.getApplicationInfo(pkg, 0) } catch (_: android.content.pm.PackageManager.NameNotFoundException) { throw DeviceFault("TARGET_NOT_FOUND", "package no longer installed") } + if (app.flags and (android.content.pm.ApplicationInfo.FLAG_SYSTEM or android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) throw DeviceFault("TARGET_DENIED", "remote process control is third-party only") + processes.verify(pkg, params.getJSONArray("expectedProcesses")) + } + } + override fun execute(method: String, params: JSONObject): JSONObject = when (method) { + "device.info" -> JSONObject().put("model", Build.MODEL).put("manufacturer", Build.MANUFACTURER).put("android", Build.VERSION.RELEASE).put("sdk", Build.VERSION.SDK_INT).put("abi", Build.SUPPORTED_ABIS.firstOrNull() ?: "unknown").put("binderProtocol", AdhProtocol.VERSION) + "module.status" -> JSONObject().put("present", isModulePresent()).put("loaderActive", isLoaderActive()).put("version", getModuleVersion()) + "scope.get" -> scopes.snapshot() + "scope.patch" -> scopes.patch(params) + "scope.replace" -> scopes.replace(params.getJSONObject("document").toString(), params.optString("scopeRevision").takeIf { it.isNotEmpty() }) + "applications.list" -> { + val all = JSONArray(listApplications()); val offset = params.optInt("offset", 0).coerceIn(0, 100000); val limit = params.optInt("limit", 200).coerceIn(1, 500) + JSONObject().put("applications", JSONArray((offset until minOf(offset + limit, all.length())).map { all.get(it) })).put("total", all.length()).put("nextOffset", if (offset + limit < all.length()) offset + limit else JSONObject.NULL) + } + "processes.list" -> processes.list(params.optString("package"), params.optInt("offset").coerceIn(0, 100000), params.optInt("limit", 200).coerceIn(1, 500)) + "process.control" -> { + val pkg = params.getString("package"); val action = params.getString("action") + if (!PackageControl.mayControl(pkg) || !PackageControl.isAction(action)) throw DeviceFault("TARGET_DENIED", "third-party package and known action required") + val app = context.packageManager.getApplicationInfo(pkg, 0) + if (app.flags and (android.content.pm.ApplicationInfo.FLAG_SYSTEM or android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) throw DeviceFault("TARGET_DENIED", "remote process control is third-party only") + processes.verify(pkg, params.getJSONArray("expectedProcesses")) + val verdict = controlPackage(pkg, action) + JSONObject().put("ok", verdict == "ok").put("verdict", verdict).put("mayHaveExecuted", true) + } + "host.get" -> JSONObject().put("endpoint", getHostEndpoint()) + "host.set" -> { val endpoint = checkNotNull(HostEndpoint.parse(params.getString("endpoint"))); files.write(File(AdhPaths.HOST_ENDPOINT_PATH), checkNotNull(HostEndpoint.format(endpoint.first, endpoint.second)), 420); JSONObject().put("ok", true) } + "certificates.list" -> { val rows = JSONArray(listCaCerts()); JSONObject().put("certificates", rows).put("pendingReboot", (0 until rows.length()).any { !rows.getJSONObject(it).optBoolean("a") }) } + "certificates.put" -> { val count = putCaCert(Base64.getDecoder().decode(params.getString("base64"))); JSONObject().put("ok", count >= 0).put("stored", count).put("pendingReboot", count > 0) } + "certificates.delete" -> JSONObject().put("ok", deleteCaCert(params.getString("fileName"))).put("pendingReboot", true) + "legacy.icon" -> JSONObject().put("base64", Base64.getEncoder().encodeToString(getApplicationIconPng(params.getString("package")))) + "legacy.applications" -> JSONObject().put("applications", JSONArray(listApplications())) + "legacy.process" -> controlPackage(params.getString("package"), params.getString("action")).let { JSONObject().put("verdict", it).put("ok", it == "ok") } + "legacy.reboot" -> JSONObject().put("ok", rebootDevice()) + else -> throw DeviceFault("UNSUPPORTED_METHOD", "device capability is not implemented") + } + + fun isModulePresent(): Boolean { + return File(AdhPaths.MODULE_DIR).isDirectory || File(AdhPaths.MODULE_PROP).isFile + } + + fun isLoaderActive(): Boolean { + return File(AdhPaths.LOADER_MARKER).isFile + } + + fun getModuleVersion(): String { + val raw = runCatching { File(AdhPaths.MODULE_PROP).readText() }.getOrNull() ?: return "" + val properties = Properties() + return runCatching { + properties.load(StringReader(raw)) + properties.getProperty("version").orEmpty() + }.getOrDefault("") + } + + fun listApplications(): String { + return PackageCatalog.listJson(context) + } + + fun getApplicationIconPng(packageName: String?): ByteArray { + return PackageCatalog.iconPng(context, packageName) + } + + fun controlPackage(packageName: String?, action: String?): String { + return AppProcessControl.run(context, packageName, action) + } + + fun getHostEndpoint(): String { + val text = runCatching { File(AdhPaths.HOST_ENDPOINT_PATH).readText() }.getOrNull() ?: return "" + val parsed = HostEndpoint.parse(text) ?: return "" + return "${parsed.first}:${parsed.second}" + } + + fun listCaCerts(): String { + return runCatching { + CaCertStore.encode(CaCertStore.list(File(AdhPaths.CACERTS_DIR), ::caVisible)) + }.getOrDefault("[]") + } + + fun putCaCert(encoded: ByteArray?): Int { + if (encoded == null || encoded.size > CaCertStore.MAX_BUNDLE_BYTES) return -1 + val dir = File(AdhPaths.CACERTS_DIR) + val count = CaCertStore.install(dir, encoded) + if (count > 0) { + Os.chmod(dir.path, 0b111101101) + dir.listFiles()?.forEach { file -> + if (file.isFile) Os.chmod(file.path, 0b110100100) + } + } + return count + } + + fun deleteCaCert(fileName: String?): Boolean { + return CaCertStore.delete(File(AdhPaths.CACERTS_DIR), fileName) + } + + fun rebootDevice(): Boolean { + return runCatching { + Runtime.getRuntime().exec(arrayOf("/system/bin/reboot")) + true + }.getOrDefault(false) + } + + private fun caVisible(name: String): Boolean = + File("/apex/com.android.conscrypt/cacerts", name).isFile || + File("/system/etc/security/cacerts", name).isFile + +} diff --git a/device/daemon/src/main/java/com/adh/daemon/AppProcessControl.kt b/device/daemon/src/main/java/com/adh/daemon/AppProcessControl.kt index fa1107a..c64ae9e 100644 --- a/device/daemon/src/main/java/com/adh/daemon/AppProcessControl.kt +++ b/device/daemon/src/main/java/com/adh/daemon/AppProcessControl.kt @@ -7,6 +7,8 @@ import android.util.Log import com.adh.core.PackageControl import java.io.File import java.util.concurrent.TimeUnit +import java.io.ByteArrayOutputStream +import com.adh.daemon.device.DeviceFault /** * Privileged stop/restart of a target app. Runs as uid 0 via the Device Daemon. @@ -99,15 +101,24 @@ internal object AppProcessControl { Log.w(TAG, "cmd failed to start: ${args.joinToString(" ")}", it) return false } - val output = runCatching { - proc.inputStream.bufferedReader().use { it.readText() } - }.getOrDefault("") + // Drain while waiting: readText() before waitFor() made the timeout ineffective. + val captured = ByteArrayOutputStream() + val collector = Thread { + runCatching { proc.inputStream.use { input -> + val chunk = ByteArray(4096) + while (true) { val count = input.read(chunk); if (count < 0) break + synchronized(captured) { val keep = minOf(count, 4096 - captured.size()); if (keep > 0) captured.write(chunk, 0, keep) } + } + } } + }.apply { isDaemon = true; name = "adh-process-output"; start() } val finished = runCatching { proc.waitFor(8, TimeUnit.SECONDS) }.getOrDefault(false) if (!finished) { proc.destroyForcibly() Log.w(TAG, "cmd timed out: ${args.joinToString(" ")}") - return false + throw DeviceFault("PROCESS_CONTROL_TIMEOUT", "process control timed out after dispatch; effects require inspection", true) } + collector.join(100) + val output = synchronized(captured) { captured.toString("UTF-8") } val code = runCatching { proc.exitValue() }.getOrDefault(-1) if (code != 0) { Log.w(TAG, "cmd exit $code: ${args.joinToString(" ")} ${output.take(200)}") diff --git a/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt b/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt index 453e03e..65a3e2b 100644 --- a/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt +++ b/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt @@ -1,154 +1,40 @@ -package com.adh.daemon - -import android.content.Context -import android.system.Os -import com.adh.core.AdhPaths -import com.adh.core.AdhProtocol -import com.adh.core.CaCertStore -import com.adh.core.HostEndpoint -import com.adh.core.ScopeConfig -import com.adh.core.ScopeJson -import java.io.File -import java.io.FileOutputStream -import java.io.StringReader -import java.nio.file.Files -import java.nio.file.StandardCopyOption -import java.util.Properties - -internal class RootScopeBinder( - private val verifier: ManagerCallerVerifier, - private val context: Context, -) : IAdhScopeService.Stub() { - override fun getProtocolVersion(): Int { - verifier.enforce() - return AdhProtocol.VERSION - } - - override fun getScopeJson(): String { - verifier.enforce() - val file = File(AdhPaths.SCOPE_PATH) - if (!file.exists()) return ScopeJson.encode(ScopeConfig.EMPTY) - return ScopeJson.encode(ScopeJson.decode(file.readText())) - } - - override fun setScopeJson(json: String?): Boolean { - verifier.enforce() - if (json.isNullOrBlank()) return false - val encoded = ScopeJson.encode(ScopeJson.decode(json)) - return runCatching { atomicWrite(File(AdhPaths.SCOPE_PATH), encoded) }.isSuccess - } - - override fun isModulePresent(): Boolean { - verifier.enforce() - return File(AdhPaths.MODULE_DIR).isDirectory || File(AdhPaths.MODULE_PROP).isFile - } - - override fun isLoaderActive(): Boolean { - verifier.enforce() - return File(AdhPaths.LOADER_MARKER).isFile - } - - override fun getModuleVersion(): String { - verifier.enforce() - val raw = runCatching { File(AdhPaths.MODULE_PROP).readText() }.getOrNull() ?: return "" - val properties = Properties() - return runCatching { - properties.load(StringReader(raw)) - properties.getProperty("version").orEmpty() - }.getOrDefault("") - } - - override fun listApplications(): String { - verifier.enforce() - return PackageCatalog.listJson(context) - } - - override fun getApplicationIconPng(packageName: String?): ByteArray { - verifier.enforce() - return PackageCatalog.iconPng(context, packageName) - } - - override fun controlPackage(packageName: String?, action: String?): String { - verifier.enforce() - return AppProcessControl.run(context, packageName, action) - } - - override fun getHostEndpoint(): String { - verifier.enforce() - val text = runCatching { File(AdhPaths.HOST_ENDPOINT_PATH).readText() }.getOrNull() ?: return "" - val parsed = HostEndpoint.parse(text) ?: return "" - return "${parsed.first}:${parsed.second}" - } - - override fun setHostEndpoint(endpoint: String?): Boolean { - verifier.enforce() - val parsed = HostEndpoint.parse(endpoint ?: return false) ?: return false - val body = HostEndpoint.format(parsed.first, parsed.second) ?: return false - return runCatching { atomicWrite(File(AdhPaths.HOST_ENDPOINT_PATH), body) }.isSuccess - } - - override fun listCaCerts(): String { - verifier.enforce() - return runCatching { - CaCertStore.encode(CaCertStore.list(File(AdhPaths.CACERTS_DIR), ::caVisible)) - }.getOrDefault("[]") - } - - override fun putCaCert(encoded: ByteArray?): Int { - verifier.enforce() - if (encoded == null || encoded.size > CaCertStore.MAX_BUNDLE_BYTES) return -1 - val dir = File(AdhPaths.CACERTS_DIR) - val count = runCatching { CaCertStore.install(dir, encoded) }.getOrElse { return -1 } - if (count > 0) { - runCatching { - Os.chmod(dir.path, 0b111101101) - dir.listFiles()?.forEach { file -> - if (file.isFile) Os.chmod(file.path, 0b110100100) - } - } - } - return count - } - - override fun deleteCaCert(fileName: String?): Boolean { - verifier.enforce() - return CaCertStore.delete(File(AdhPaths.CACERTS_DIR), fileName) - } - - override fun rebootDevice(): Boolean { - verifier.enforce() - return runCatching { - Runtime.getRuntime().exec(arrayOf("/system/bin/reboot")) - true - }.getOrDefault(false) - } - - private fun caVisible(name: String): Boolean = - File("/apex/com.android.conscrypt/cacerts", name).isFile || - File("/system/etc/security/cacerts", name).isFile - - private fun atomicWrite(target: File, content: String) { - target.parentFile?.mkdirs() - val temp = File(target.parentFile, ".${target.name}.${android.os.Process.myPid()}.tmp") - try { - FileOutputStream(temp).use { output -> - output.write(content.toByteArray(Charsets.UTF_8)) - output.fd.sync() - } - try { - Files.move( - temp.toPath(), - target.toPath(), - StandardCopyOption.ATOMIC_MOVE, - StandardCopyOption.REPLACE_EXISTING, - ) - } catch (_: Exception) { - check(temp.renameTo(target)) { "rename ${temp.path} -> ${target.path} failed" } - } - Os.chmod(target.path, 0b110100100) - } finally { - temp.delete() - } - } - -} +package com.adh.daemon + +import com.adh.core.AdhProtocol +import com.adh.daemon.device.DeviceOperations +import org.json.JSONObject +import java.util.Base64 + +/** Binder authentication stays here; business operations are shared with device RPC. */ +internal class RootScopeBinder(private val verifier: ManagerCallerVerifier, private val operations: DeviceOperations) : IAdhScopeService.Stub() { + private fun read(method: String, params: JSONObject = JSONObject()): JSONObject { verifier.enforce(); return operations.managerRead(method, params) } + private fun write(method: String, params: JSONObject): JSONObject { + verifier.enforce() + val record = operations.managerWrite(method, params) + check(record.getString("state") == "succeeded") { "device operation ${record.optString("code", "failed")}" } + return record.getJSONObject("result") + } + override fun getProtocolVersion(): Int { verifier.enforce(); return AdhProtocol.VERSION } + override fun getScopeJson(): String = read("scope.get").getJSONObject("document").toString() + override fun setScopeJson(json: String?): Boolean { verifier.enforce(); return runCatching { write("scope.replace", JSONObject().put("document", JSONObject(json ?: ""))).getBoolean("ok") }.getOrDefault(false) } + override fun isModulePresent(): Boolean = read("module.status").getBoolean("present") + override fun isLoaderActive(): Boolean = read("module.status").getBoolean("loaderActive") + override fun getModuleVersion(): String = read("module.status").getString("version") + override fun listApplications(): String = read("legacy.applications").getJSONArray("applications").toString() + override fun getApplicationIconPng(packageName: String?): ByteArray = Base64.getDecoder().decode(read("legacy.icon", JSONObject().put("package", packageName ?: "")).getString("base64")) + override fun controlPackage(packageName: String?, action: String?): String { verifier.enforce(); return runCatching { write("legacy.process", JSONObject().put("package", packageName ?: "").put("action", action ?: "")).getString("verdict") }.getOrDefault("failed") } + override fun getHostEndpoint(): String = read("host.get").getString("endpoint") + override fun setHostEndpoint(endpoint: String?): Boolean { verifier.enforce(); return runCatching { write("host.set", JSONObject().put("endpoint", endpoint ?: "")).getBoolean("ok") }.getOrDefault(false) } + override fun listCaCerts(): String = read("certificates.list").getJSONArray("certificates").toString() + override fun putCaCert(encoded: ByteArray?): Int { verifier.enforce(); return runCatching { write("certificates.put", JSONObject().put("base64", Base64.getEncoder().encodeToString(encoded ?: byteArrayOf()))).getInt("stored") }.getOrDefault(-1) } + override fun deleteCaCert(fileName: String?): Boolean { verifier.enforce(); return runCatching { write("certificates.delete", JSONObject().put("fileName", fileName ?: "")).getBoolean("ok") }.getOrDefault(false) } + override fun rebootDevice(): Boolean { verifier.enforce(); return runCatching { write("legacy.reboot", JSONObject()).getBoolean("ok") }.getOrDefault(false) } + override fun getDeviceInfoJson(): String = read("device.info").toString() + override fun getDeviceCapabilitiesJson(): String = read("device.capabilities").toString() + override fun getScopeSnapshotJson(): String = read("scope.get").toString() + override fun setScopeVersionedJson(json: String?, scopeRevision: String?, stateRevision: Long): String { + verifier.enforce() + return runCatching { operations.write("scope.replace", JSONObject().put("document", JSONObject(json ?: "")).put("scopeRevision", scopeRevision ?: ""), java.util.UUID.randomUUID().toString(), stateRevision, "operator", 60000).toString() } + .getOrElse { JSONObject().put("state", "failed").put("code", (it as? com.adh.daemon.device.DeviceFault)?.code ?: "DEVICE_ERROR").toString() } + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceArguments.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceArguments.kt new file mode 100644 index 0000000..653fc98 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceArguments.kt @@ -0,0 +1,39 @@ +package com.adh.daemon.device + +import com.adh.core.HostEndpoint +import com.adh.core.CaCertStore +import com.adh.core.PackageControl +import org.json.JSONObject +import java.util.Base64 + +/** Pure, effect-free validation used before journal reservation or Android dispatch. */ +internal object DeviceArguments { + fun validate(method: String, params: JSONObject) { + try { + when (method) { + "scope.patch", "scope.replace" -> { + if (method == "scope.replace") packages(params.getJSONObject("document"), "packages") + else for (key in listOf("set", "add", "remove")) if (params.has(key)) packages(params, key) + } + "process.control", "legacy.process" -> { + require(PackageControl.mayControl(params.getString("package")) && PackageControl.isAction(params.getString("action"))) + if (method == "process.control") { + val rows = params.getJSONArray("expectedProcesses"); require(rows.length() <= 128) + for (n in 0 until rows.length()) { val row = rows.getJSONObject(n) + require(row.getInt("pid") > 0 && row.getInt("uid") >= 0 && Regex("[0-9]{1,24}").matches(row.getString("starttimeTicks"))) + } + } + } + "host.set" -> require(HostEndpoint.parse(params.getString("endpoint")) != null) + "certificates.put" -> { val bytes = Base64.getDecoder().decode(params.getString("base64")); require(bytes.size <= CaCertStore.MAX_BUNDLE_BYTES) } + "certificates.delete" -> require(Regex("[0-9a-f]{8}\\.[0-9]{1,2}").matches(params.getString("fileName"))) + } + } catch (_: Exception) { throw DeviceFault("INVALID_ARGUMENT", "invalid device operation parameters; nothing dispatched") } + } + private fun packages(params: JSONObject, key: String) { + val values = params.getJSONArray(key); require(values.length() <= 4096) + for (n in 0 until values.length()) { val pkg = values.getString(n) + require(Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+").matches(pkg) && pkg != "com.adh.manager" && pkg != "com.adh.daemon") + } + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceFiles.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceFiles.kt new file mode 100644 index 0000000..e09f5c4 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceFiles.kt @@ -0,0 +1,24 @@ +package com.adh.daemon.device + +import java.io.File +import java.io.FileOutputStream +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.UUID + +/** Explicit initialization/writes only; callers never rebuild corrupt authoritative files. */ +internal class DeviceFiles(val directory: File, private val secure: (File, Int) -> Unit = { _, _ -> }, private val syncDirectory: (File) -> Unit = {}) { + fun initialize() { check(directory.mkdirs() || directory.isDirectory); secure(directory, 448) /* 0700 */ } + fun write(file: File, text: String, mode: Int = 384) { + val parent = checkNotNull(file.parentFile) + check(parent.mkdirs() || parent.isDirectory) + val temp = File(parent, ".${file.name}.${UUID.randomUUID()}.tmp") + try { + check(temp.createNewFile()); secure(temp, mode) + FileOutputStream(temp).use { it.write(text.toByteArray(Charsets.UTF_8)); it.fd.sync() } + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + secure(file, mode) + syncDirectory(parent) + } finally { temp.delete() } + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt new file mode 100644 index 0000000..12dc81b --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt @@ -0,0 +1,59 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONObject +import java.io.File +import java.security.KeyFactory +import java.security.KeyPairGenerator +import java.security.SecureRandom +import java.security.Signature +import java.security.spec.PKCS8EncodedKeySpec +import java.security.spec.X509EncodedKeySpec +import java.util.Base64 +import java.util.UUID + +/** Installation identity survives daemon restart, USB replug and reboot; never derived from serial. */ +internal class DeviceIdentity(private val files: DeviceFiles, val bootId: String, val instanceId: String = UUID.randomUUID().toString()) { + val deviceId: String + val publicKey: String + val fingerprint: String + val token: String + private val privateKey: java.security.PrivateKey + init { + require(Regex("[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").matches(bootId)) { "a real kernel boot_id is required" } + files.initialize() + val identityFile = File(files.directory, "identity.json") + if (!identityFile.exists()) { + check(!File(files.directory, "usb-access.json").exists()) { "identity missing while credentials exist; refusing identity reset" } + val pair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair() + files.write(identityFile, JSONObject().put("schemaVersion", 1).put("deviceId", UUID.randomUUID().toString()) + .put("publicKey", Base64.getEncoder().encodeToString(pair.public.encoded)).put("privateKey", Base64.getEncoder().encodeToString(pair.private.encoded)).toString()) + } + val identity = JSONObject(identityFile.readText()) + check(identity.getInt("schemaVersion") == 1) + deviceId = identity.getString("deviceId"); UUID.fromString(deviceId) + publicKey = identity.getString("publicKey") + val factory = KeyFactory.getInstance("RSA") + val pub = factory.generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))) + privateKey = factory.generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(identity.getString("privateKey")))) + fingerprint = DeviceRpc.sha256(pub.encoded) + val proof = "identity-key-check".toByteArray() + val signed = Signature.getInstance("SHA256withRSA").run { initSign(privateKey); update(proof); sign() } + check(Signature.getInstance("SHA256withRSA").run { initVerify(pub); update(proof); verify(signed) }) { "identity key mismatch" } + val accessFile = File(files.directory, "usb-access.json") + if (!accessFile.exists()) { + val secret = ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) } + files.write(accessFile, JSONObject().put("schemaVersion", 1).put("deviceId", deviceId).put("identityFingerprint", fingerprint).put("token", secret).toString()) + } + val access = JSONObject(accessFile.readText()) + check(access.getInt("schemaVersion") == 1 && access.getString("deviceId") == deviceId && access.getString("identityFingerprint") == fingerprint) { "USB bootstrap identity mismatch" } + token = access.getString("token"); check(Regex("[a-f0-9]{64}").matches(token)) + } + fun authenticated(candidate: String): Boolean = java.security.MessageDigest.isEqual(token.toByteArray(), candidate.toByteArray()) + fun descriptor(): JSONObject = JSONObject().put("deviceId", deviceId).put("bootId", bootId).put("daemonInstanceId", instanceId).put("identityFingerprint", fingerprint) + fun signHello(requestId: String, nonce: String, info: JSONObject, capabilities: JSONObject): JSONObject { + val payload = descriptor().put("protocol", DeviceRpc.PROTOCOL).put("requestId", requestId).put("clientNonce", nonce).put("info", info).put("capabilities", capabilities).toString().toByteArray(Charsets.UTF_8) + val signature = Signature.getInstance("SHA256withRSA").run { initSign(privateKey); update(payload); sign() } + return JSONObject().put("payload", Base64.getEncoder().encodeToString(payload)).put("signature", Base64.getEncoder().encodeToString(signature)).put("publicKey", publicKey) + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt new file mode 100644 index 0000000..37373b3 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt @@ -0,0 +1,104 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONObject +import java.io.File +import java.util.UUID + +internal class DeviceFault(val code: String, override val message: String, val uncertain: Boolean = false) : RuntimeException(message) +internal fun interface DeviceBackend { + fun execute(method: String, params: JSONObject): JSONObject + fun validate(method: String, params: JSONObject) {} // no effects; reject invalid intent before reservation +} + +/** Single writer shared by authenticated Binder and RPC; device coordination, never analysis. */ +internal class DeviceOperations(val identity: DeviceIdentity, private val files: DeviceFiles, private val backend: DeviceBackend) { + private val stateFile = File(files.directory, "operations.json") + private val lock = Any() + private var state: JSONObject + private var storageUnavailable = false + init { + check(!stateFile.exists() || stateFile.length() <= 2 * 1024 * 1024) { "device operation ledger exceeds limit" } + state = if (stateFile.exists()) JSONObject(stateFile.readText()) else JSONObject().put("schemaVersion", 1).put("revision", 0L).put("operations", JSONObject()) + check(state.getInt("schemaVersion") == 1 && state.getLong("revision") >= 0) + check(records().length() <= 1024) + for (id in records().keys()) { + val record = records().getJSONObject(id) + if (record.getString("state") == "running") record.put("state", "unknown").put("code", "DAEMON_RESTARTED").put("uncertain", true) + } + save() + } + private fun records() = state.getJSONObject("operations") + private fun encoded(value: JSONObject): String { val text = value.toString(); if (text.toByteArray().size > 2 * 1024 * 1024) throw DeviceFault("LEDGER_FULL", "device operation ledger full; no automatic pruning"); return text } + private fun save() { files.write(stateFile, encoded(state)) } + fun revision(): Long = synchronized(lock) { state.getLong("revision") } + fun capabilities(): JSONObject = JSONObject().put("protocol", DeviceRpc.PROTOCOL).put("maxFrameBytes", DeviceRpc.MAX_FRAME).put("maxBudgetMs", DeviceRpc.MAX_BUDGET_MS) + .put("methods", JSONObject().also { methods -> DeviceRpc.READ_METHODS.forEach { methods.put(it, "read") }; DeviceRpc.WRITE_METHODS.forEach { methods.put(it, "write") } }) + .put("unsupported", JSONObject().put("lan.tls", "P4 pairing/TLS not installed").put("agent.route", "legacy target channel retained; not associated by serial").put("shell", "no arbitrary remote root shell").put("reboot", "Manager-only in P3").put("bulk", "not implemented")) + fun read(method: String, params: JSONObject = JSONObject()): JSONObject = synchronized(lock) { + when (method) { + "device.info" -> identity.descriptor().put("info", backend.execute(method, params)).put("stateRevision", revision()) + "device.capabilities" -> capabilities().put("stateRevision", revision()) + "device.state" -> identity.descriptor().put("stateRevision", revision()) + "operations.get" -> { + val id = params.getString("operationId") + val record = records().optJSONObject(id) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no recorded device operation") + JSONObject(record.toString()).put("stateRevision", revision()) + } + else -> backend.execute(method, params).put("stateRevision", revision()) + } + } + fun write(method: String, params: JSONObject, operationId: String, expectedRevision: Long, actor: String, budgetMs: Long, receivedAt: Long = System.nanoTime()): JSONObject = synchronized(lock) { + require(Regex("[A-Za-z0-9_-]{1,128}").matches(operationId)) + if (storageUnavailable) throw DeviceFault("DEVICE_LEDGER_UNAVAILABLE", "ledger persistence failed; writes disabled until inspected restart") + val fingerprint = DeviceRpc.sha256(DeviceRpc.canonical(JSONObject().put("method", method).put("params", params).put("bootId", identity.bootId).put("expectedRevision", expectedRevision)).toByteArray()) + val existing = records().optJSONObject(operationId) + if (existing != null) { + if (existing.getString("fingerprint") != fingerprint) throw DeviceFault("IDEMPOTENCY_CONFLICT", "device operation id identifies another intent") + return JSONObject(existing.toString()).put("stateRevision", revision()) + } + if ((System.nanoTime() - receivedAt) / 1_000_000 >= budgetMs) throw DeviceFault("DEADLINE_EXCEEDED", "expired before device dispatch") + if (expectedRevision != revision()) throw DeviceFault("STALE_DEVICE_STATE", "device was modified; observe again, do not retry old intent") + val unresolved = records().keys().asSequence().map { records().getJSONObject(it) }.filter { it.optString("state") == "unknown" && !it.has("resolvedAt") }.toList() + if (unresolved.isNotEmpty() && method != "operations.resolve") throw DeviceFault("UNKNOWN_EXECUTION", "device has unresolved side effects") + if (method == "operations.resolve" && (actor != "operator" || !params.optBoolean("acknowledge"))) throw DeviceFault("OPERATOR_REQUIRED", "explicit operator inspection required") + if (method == "operations.resolve") { + val old = records().optJSONObject(params.optString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") + if (old.optString("state") != "unknown" || old.has("resolvedAt")) throw DeviceFault("INVALID_STATE", "operation is not unresolved unknown") + } else backend.validate(method, params) + if (records().length() >= 1024) throw DeviceFault("LEDGER_FULL", "device ledger needs explicit archival; nothing dispatched") + val record = JSONObject().put("operationId", operationId).put("method", method).put("bootId", identity.bootId).put("fingerprint", fingerprint) + .put("actor", actor).put("state", "running").put("mayHaveExecuted", true).put("startedAt", System.currentTimeMillis()) + val candidate = JSONObject(state.toString()).put("revision", revision() + 1) + candidate.getJSONObject("operations").put(operationId, record) + val reservation = encoded(candidate) // capacity rejection must not advance in-memory state + try { files.write(stateFile, reservation) } catch (_: Exception) { + storageUnavailable = true // rename/fsync may have reached disk; never retry a reservation + throw DeviceFault("DEVICE_LEDGER_UNAVAILABLE", "reservation persistence failed; no business operation dispatched") + } + state = candidate // durable reservation BEFORE side effects + try { + val result = if (method == "operations.resolve") { + val old = records().optJSONObject(params.getString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") + if (old.optString("state") != "unknown") throw DeviceFault("INVALID_STATE", "operation is not unknown") + old.put("resolvedAt", System.currentTimeMillis()); JSONObject().put("ok", true).put("originalState", "unknown") + } else backend.execute(method, params) + val encoded = result.toString().toByteArray() + record.put("result", if (encoded.size <= 32 * 1024) result else JSONObject().put("omitted", true).put("bytes", encoded.size).put("sha256", DeviceRpc.sha256(encoded))) + record.put("state", if (result.optBoolean("ok", true)) "succeeded" else "failed") + } catch (error: DeviceFault) { + record.put("state", if (error.uncertain) "unknown" else "failed").put("code", error.code).put("uncertain", error.uncertain) + } catch (_: Exception) { + record.put("state", "unknown").put("code", "DEVICE_EFFECT_UNCONFIRMED").put("uncertain", true) + } + record.put("finishedAt", System.currentTimeMillis()) + try { save() } catch (_: Exception) { + storageUnavailable = true + record.put("state", "unknown").put("code", "DEVICE_LEDGER_UNAVAILABLE").put("uncertain", true) + throw DeviceFault("DEVICE_LEDGER_UNAVAILABLE", "effect dispatched but result persistence is unconfirmed", true) + } + JSONObject(record.toString()).put("stateRevision", revision()) + } + fun managerRead(method: String, params: JSONObject = JSONObject()) = read(method, params) + fun managerWrite(method: String, params: JSONObject): JSONObject = synchronized(lock) { write(method, params, UUID.randomUUID().toString(), revision(), "operator", DeviceRpc.MAX_BUDGET_MS) } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt new file mode 100644 index 0000000..b5a93e7 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt @@ -0,0 +1,55 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONObject +import java.io.InputStream +import java.io.OutputStream + +/** Framing/dispatch can be reused by a future authenticated TLS transport unchanged. */ +internal class DeviceRpcSession(private val operations: DeviceOperations) { + fun serve(input: InputStream, output: OutputStream) { + val hello = DeviceRpc.read(input) ?: return + val helloId = validEnvelope(hello) + val params = hello.optJSONObject("params") ?: JSONObject() + val auth = params.optJSONObject("authentication") ?: JSONObject() + if (hello.optString("method") != "device.hello" || auth.optString("type") != "usb-token" || !operations.identity.authenticated(auth.optString("credential"))) { + DeviceRpc.write(output, DeviceRpc.failure(helloId, "AUTH_FAILED", "device authentication failed")); return + } + val nonce = params.optString("clientNonce") + require(Regex("[a-f0-9]{64}").matches(nonce)) + DeviceRpc.write(output, DeviceRpc.response(helloId, operations.identity.signHello(helloId, nonce, operations.read("device.info"), operations.capabilities()))) + while (true) { + val request = DeviceRpc.read(input) ?: return + val received = System.nanoTime() + var id = "invalid" + val reply = try { + id = validEnvelope(request) + val target = request.getJSONObject("target") + val identity = operations.identity + if (target.optString("deviceId") != identity.deviceId || target.optString("bootId") != identity.bootId || target.optString("daemonInstanceId") != identity.instanceId) throw DeviceFault("TARGET_CHANGED", "device/boot/daemon generation differs") + val method = request.getString("method") + val arguments = request.optJSONObject("params") ?: JSONObject() + val result = when (method) { + in DeviceRpc.READ_METHODS -> operations.read(method, arguments) + in DeviceRpc.WRITE_METHODS -> { + val meta = request.getJSONObject("meta") + val budget = meta.getLong("budgetMs"); require(budget in 1..DeviceRpc.MAX_BUDGET_MS) + // A full replacement must carry scope CAS, even on authenticated RPC. + if (method in setOf("scope.patch", "scope.replace")) require(Regex("[a-f0-9]{64}").matches(arguments.optString("scopeRevision"))) + operations.write(method, arguments, meta.getString("operationId"), meta.getLong("expectedRevision"), meta.optString("actor", "ai"), budget, received) + } + else -> throw DeviceFault("UNSUPPORTED_METHOD", "method not advertised by this device protocol") + } + DeviceRpc.response(id, result) + } catch (error: DeviceFault) { DeviceRpc.failure(id, error.code, error.message, error.uncertain) } + catch (_: IllegalArgumentException) { DeviceRpc.failure(id, "INVALID_ARGUMENT", "invalid device RPC arguments") } + catch (_: org.json.JSONException) { DeviceRpc.failure(id, "INVALID_ARGUMENT", "missing or malformed device RPC field") } + catch (_: Exception) { DeviceRpc.failure(id, "DEVICE_UNAVAILABLE", "device request could not be confirmed", true) } + DeviceRpc.write(output, reply) + } + } + private fun validEnvelope(value: JSONObject): String { + require(value.optString("protocol") == DeviceRpc.PROTOCOL) + val id = value.getString("id"); require(Regex("[A-Za-z0-9_-]{1,128}").matches(id)); return id + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt b/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt new file mode 100644 index 0000000..1204775 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt @@ -0,0 +1,30 @@ +package com.adh.daemon.device + +import android.net.LocalServerSocket +import android.net.LocalSocket +import com.adh.core.DeviceRpc +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit + +/** USB ADB forwards to this abstract UDS. No TCP/LAN listener is opened on the phone. */ +internal class LocalDeviceRpcServer(private val operations: DeviceOperations) : AutoCloseable { + private val socket = LocalServerSocket(DeviceRpc.SOCKET_NAME) + private val clients = java.util.concurrent.ConcurrentHashMap.newKeySet() + private val workers = ThreadPoolExecutor(4, 4, 30, TimeUnit.SECONDS, ArrayBlockingQueue(4)) + private val accept = Thread({ + while (!Thread.currentThread().isInterrupted) { + val client = try { socket.accept() } catch (_: Exception) { break } + // adbd may run as root or shell. An app UID cannot use this root RPC endpoint. + val uid = runCatching { client.peerCredentials.uid }.getOrDefault(-1) + if (uid !in setOf(0, 2000)) { client.close(); continue } + clients.add(client) + try { workers.execute { + try { client.soTimeout = 30_000; client.use { DeviceRpcSession(operations).serve(it.inputStream, it.outputStream) } } + catch (_: Exception) { /* close incomplete/authenticated streams; never replay */ } + finally { clients.remove(client); runCatching { client.close() } } + } } catch (_: java.util.concurrent.RejectedExecutionException) { clients.remove(client); client.close() } + } + }, "adh-device-rpc").apply { isDaemon = true; start() } + override fun close() { accept.interrupt(); socket.close(); clients.forEach { runCatching { it.close() } }; workers.shutdownNow() } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/ProcessCatalog.kt b/device/daemon/src/main/java/com/adh/daemon/device/ProcessCatalog.kt new file mode 100644 index 0000000..96f0ed4 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/ProcessCatalog.kt @@ -0,0 +1,36 @@ +package com.adh.daemon.device + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +internal class ProcessCatalog(private val proc: File = File("/proc")) { + fun list(packageName: String, offset: Int = 0, limit: Int = 200): JSONObject { + val rows = mutableListOf() + var inaccessible = 0 + val directories = proc.listFiles() ?: throw DeviceFault("PROC_UNAVAILABLE", "process directory unavailable") + for (dir in directories.filter { it.name.toIntOrNull() != null }.take(8192)) { + val command = try { File(dir, "cmdline").inputStream().use { val bytes = ByteArray(4096); val count = it.read(bytes); if (count < 0) "" else String(bytes, 0, count).substringBefore('\u0000') } } catch (_: Exception) { inaccessible++; continue } + if (command.isBlank() || packageName.isNotEmpty() && command != packageName && !command.startsWith("$packageName:")) continue + val row = try { + val stat = File(dir, "stat").readText() + val fields = stat.substring(stat.lastIndexOf(')') + 2).trim().split(Regex("\\s+")) + val start = fields[19]; require(Regex("[0-9]+").matches(start)) + val uid = File(dir, "status").useLines { lines -> lines.first { it.startsWith("Uid:") }.substringAfter(':').trim().split(Regex("\\s+"))[0].toInt() } + JSONObject().put("pid", dir.name.toInt()).put("uid", uid).put("starttimeTicks", start).put("process", command).put("package", command.substringBefore(':')) + } catch (_: Exception) { inaccessible++; continue } + rows.add(row) + } + rows.sortBy { it.getInt("pid") } + return JSONObject().put("processes", JSONArray(rows.drop(offset).take(limit))).put("total", rows.size).put("nextOffset", if (offset + limit < rows.size) offset + limit else JSONObject.NULL) + .put("complete", inaccessible == 0 && directories.size <= 8192).put("inaccessible", inaccessible) + } + fun verify(packageName: String, expected: JSONArray) { + require(expected.length() <= 128) + val actual = list(packageName, 0, 128) + if (!actual.getBoolean("complete") || actual.getInt("total") > 128) throw DeviceFault("IDENTITY_UNVERIFIED", "cannot verify all current package processes") + fun identities(array: JSONArray): String = (0 until array.length()).map { array.getJSONObject(it) }.map { + "${it.getInt("pid")}:${it.getInt("uid")}:${it.getString("starttimeTicks")}" }.sorted().joinToString(",") + if (identities(actual.getJSONArray("processes")) != identities(expected)) throw DeviceFault("TARGET_CHANGED", "package process generations changed before dispatch") + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt b/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt new file mode 100644 index 0000000..d598ba3 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt @@ -0,0 +1,80 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import com.adh.core.ScopeConfig +import com.adh.core.ScopeJson +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +internal class ScopeDocuments(private val file: File, private val files: DeviceFiles) { + fun snapshot(): JSONObject { + check(!file.exists() || file.length() <= 512 * 1024) { "scope document too large" } + val raw = if (file.exists()) file.readText() else ScopeJson.encode(ScopeConfig.EMPTY) + ScopeJson.decode(raw) // Malformed existing state is never replaced by an empty allowlist. + return JSONObject().put("document", JSONObject(raw)).put("scopeRevision", DeviceRpc.sha256(raw.toByteArray())) + } + fun patch(params: JSONObject): JSONObject { + val before = snapshot() + if (params.optString("scopeRevision") != before.getString("scopeRevision")) throw DeviceFault("STALE_SCOPE", "scope changed outside this request") + val doc = before.getJSONObject("document") + val packages = doc.optJSONArray("packages") ?: JSONArray() + val current = (0 until packages.length()).map { packages.getString(it) }.toMutableSet() + fun values(name: String): List { + if (!params.has(name)) return emptyList() + val array = params.optJSONArray(name) ?: throw DeviceFault("INVALID_ARGUMENT", "scope package values must be arrays") + require(array.length() <= 4096) + return (0 until array.length()).map { array.getString(it) }.onEach { require(Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+").matches(it) && it != "com.adh.manager" && it != "com.adh.daemon") } + } + if (params.has("set")) { current.clear(); current.addAll(values("set")) } + current.removeAll(values("remove").toSet()); current.addAll(values("add")) + doc.put("packages", JSONArray(current.sorted())) // Preserve the COMPLETE policy and unknown fields. + files.write(file, doc.toString(2), 420) + return snapshot().put("ok", true) + } + fun replace(raw: String, expected: String? = null): JSONObject { + val before = snapshot() + if (expected != null && expected != before.getString("scopeRevision")) throw DeviceFault("STALE_SCOPE", "scope changed outside this request") + val input = JSONObject(raw) + val normalized = JSONObject(ScopeJson.encode(ScopeJson.decode(raw))) + val merged = before.getJSONObject("document") + for (key in input.keys()) if (key !in setOf("version", "mode", "packages", "policy")) merged.put(key, input.get(key)) + for (key in listOf("version", "mode", "packages")) merged.put(key, normalized.get(key)) + // Manager edits known policy keys. Preserve future keys while allowing known keys to reset. + val oldPolicy = merged.optJSONObject("policy") ?: JSONObject() + val policy = JSONObject() + for (pkg in oldPolicy.keys()) { + val entry = oldPolicy.optJSONObject(pkg) + if (entry == null) { policy.put(pkg, oldPolicy.get(pkg)); continue } + val kept = JSONObject(entry.toString()).apply { remove("c"); remove("b") } + val c = entry.optJSONObject("c") + val unknown = JSONObject() + if (c != null) for (key in c.keys()) if (key !in setOf("d", "h", "s", "a", "t", "e", "y")) unknown.put(key, c.get(key)) + if (unknown.length() > 0) kept.put("c", unknown) + if (kept.length() > 0) policy.put(pkg, kept) + } + val next = normalized.optJSONObject("policy") ?: JSONObject() + // Preserve/accept future fields in an explicit RPC document too; normalize only known keys. + val requested = input.optJSONObject("policy") ?: JSONObject() + for (pkg in requested.keys()) { + val requestedEntry = requested.optJSONObject(pkg) ?: continue + val entry = policy.optJSONObject(pkg) ?: JSONObject() + for (key in requestedEntry.keys()) if (key !in setOf("c", "b")) entry.put(key, requestedEntry.get(key)) + val c = entry.optJSONObject("c") ?: JSONObject() + val requestedC = requestedEntry.optJSONObject("c") + if (requestedC != null) for (key in requestedC.keys()) if (key !in setOf("d", "h", "s", "a", "t", "e", "y")) c.put(key, requestedC.get(key)) + if (c.length() > 0) entry.put("c", c) + if (entry.length() > 0) policy.put(pkg, entry) + } + for (pkg in next.keys()) { + val entry = policy.optJSONObject(pkg) ?: JSONObject() + val c = entry.optJSONObject("c") ?: JSONObject() + val known = next.getJSONObject(pkg).getJSONObject("c") + for (key in known.keys()) c.put(key, known.get(key)) + policy.put(pkg, entry.put("c", c)) + } + if (policy.length() > 0) merged.put("policy", policy) else merged.remove("policy") + files.write(file, merged.toString(2), 420) + return snapshot().put("ok", true) + } +} diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceDomainTest.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceDomainTest.kt new file mode 100644 index 0000000..6563c80 --- /dev/null +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceDomainTest.kt @@ -0,0 +1,125 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONObject +import org.json.JSONArray +import org.junit.Assert.* +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.nio.file.Files +import java.util.UUID +import java.util.Base64 +import java.security.KeyFactory +import java.security.Signature +import java.security.spec.X509EncodedKeySpec + +class DeviceDomainTest { + private fun root() = Files.createTempDirectory("adh-p3-unit-").toFile() + private fun identity(root: File, boot: String = "00000000-0000-4000-8000-000000000001") = DeviceIdentity(DeviceFiles(root), boot) + private fun frame(value: JSONObject) = ByteArrayOutputStream().apply { DeviceRpc.write(this, value) }.toByteArray() + @Test fun identityPersistsAcrossRestartAndBootWithoutUsingAnAdbSerial() { + val dir = root(); val one = identity(dir); val two = identity(dir); val reboot = identity(dir, "00000000-0000-4000-8000-000000000002") + assertEquals(one.deviceId, two.deviceId); assertEquals(one.deviceId, reboot.deviceId); assertEquals(one.fingerprint, reboot.fingerprint) + assertNotEquals(one.instanceId, two.instanceId); assertNotEquals(one.bootId, reboot.bootId) + val access = File(dir, "usb-access.json").readText(); assertFalse(access.contains("privateKey")); assertFalse(access.contains(one.publicKey)) + File(dir, "identity.json").writeText("corrupt") + assertTrue(runCatching { identity(dir) }.isFailure); assertEquals("corrupt", File(dir, "identity.json").readText()) + } + @Test fun signedHelloBindsNonceIdentityAndCapabilitiesWithoutExposingCredentials() { + val id = identity(root()); val response = id.signHello("hello-1", "a".repeat(64), JSONObject().put("model", "fixture"), JSONObject().put("methods", JSONObject())) + val payload = Base64.getDecoder().decode(response.getString("payload")) + val key = KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(response.getString("publicKey")))) + assertTrue(Signature.getInstance("SHA256withRSA").run { initVerify(key); update(payload); verify(Base64.getDecoder().decode(response.getString("signature"))) }) + val decoded = JSONObject(String(payload)); assertEquals("a".repeat(64), decoded.getString("clientNonce")); assertEquals(id.deviceId, decoded.getString("deviceId")) + assertFalse(String(payload).contains(id.token)); assertFalse(id.authenticated("wrong")); assertTrue(id.authenticated(id.token)) + } + @Test fun managerAndRpcMutationsShareOneRevisionAndDeviceOperationIdsNeverReplay() { + val dir = root(); var calls = 0 + val ops = DeviceOperations(identity(dir), DeviceFiles(dir), DeviceBackend { _, _ -> calls++; JSONObject().put("ok", true) }) + val manager = ops.managerWrite("host.set", JSONObject().put("endpoint", "192.0.2.1:8761")); assertEquals("succeeded", manager.getString("state")) + val stale = runCatching { ops.write("host.set", JSONObject(), "old-intent", 0, "ai", 10000) }.exceptionOrNull() as DeviceFault + assertEquals("STALE_DEVICE_STATE", stale.code); assertEquals(1, calls) + val args = JSONObject().put("privateFixture", "synthetic-secret-payload") + val first = ops.write("host.set", args, "same-intent", 1, "ai", 10000) + val again = ops.write("host.set", args, "same-intent", 1, "ai", 10000) + assertEquals(first.getString("operationId"), again.getString("operationId")); assertEquals(2, calls) + assertEquals("IDEMPOTENCY_CONFLICT", (runCatching { ops.write("host.set", JSONObject(), "same-intent", 2, "ai", 10000) }.exceptionOrNull() as DeviceFault).code) + assertFalse(File(dir, "operations.json").readText().contains("synthetic-secret-payload")) + } + @Test fun crashReservationsBecomeUnknownAndRequireExplicitOperatorReconciliation() { + val dir = root(); val id = identity(dir) + val backend = DeviceBackend { _, _ -> JSONObject().put("ok", true) } + val ops = DeviceOperations(id, DeviceFiles(dir), backend) + ops.write("host.set", JSONObject(), "crashed", 0, "ai", 10000) + val file = File(dir, "operations.json"); val stored = JSONObject(file.readText()); stored.getJSONObject("operations").getJSONObject("crashed").put("state", "running"); file.writeText(stored.toString()) + val restored = DeviceOperations(identity(dir), DeviceFiles(dir), backend) + assertEquals("unknown", restored.read("operations.get", JSONObject().put("operationId", "crashed")).getString("state")) + assertEquals("UNKNOWN_EXECUTION", (runCatching { restored.write("host.set", JSONObject(), "new", 1, "ai", 10000) }.exceptionOrNull() as DeviceFault).code) + assertEquals("OPERATOR_REQUIRED", (runCatching { restored.write("operations.resolve", JSONObject().put("operationId", "crashed").put("acknowledge", true), "ack-ai", 1, "ai", 10000) }.exceptionOrNull() as DeviceFault).code) + restored.write("operations.resolve", JSONObject().put("operationId", "crashed").put("acknowledge", true), "ack-human", 1, "operator", 10000) + val original = restored.read("operations.get", JSONObject().put("operationId", "crashed")); assertEquals("unknown", original.getString("state")); assertTrue(original.has("resolvedAt")) + } + @Test fun scopePatchRetainsFullPolicyAndRejectsAnExternalWriterOrMalformedArray() { + val dir = root(); val file = File(dir, "scope.json") + file.writeText("""{"version":2,"mode":"allowlist","packages":["com.example.old"],"future":{"x":3},"policy":{"com.example.old":{"c":{"h":false,"future":7}}}}""") + val scopes = ScopeDocuments(file, DeviceFiles(dir)); val original = scopes.snapshot() + val after = scopes.patch(JSONObject().put("scopeRevision", original.getString("scopeRevision")).put("set", JSONArray().put("com.example.next"))) + assertEquals(7, after.getJSONObject("document").getJSONObject("policy").getJSONObject("com.example.old").getJSONObject("c").getInt("future")) + assertEquals(3, after.getJSONObject("document").getJSONObject("future").getInt("x")) + assertEquals("STALE_SCOPE", (runCatching { scopes.patch(JSONObject().put("scopeRevision", original.getString("scopeRevision"))) }.exceptionOrNull() as DeviceFault).code) + assertEquals("INVALID_ARGUMENT", (runCatching { scopes.patch(JSONObject().put("scopeRevision", after.getString("scopeRevision")).put("set", "not-an-array")) }.exceptionOrNull() as DeviceFault).code) + } + @Test fun managerResetOfKnownPolicyDoesNotLoseFutureFields() { + val dir = root(); val file = File(dir, "scope.json") + file.writeText("""{"version":2,"packages":["com.example.old"],"future":8,"policy":{"com.example.old":{"c":{"h":false,"future":7}}}}""") + val value = ScopeDocuments(file, DeviceFiles(dir)).replace("""{"version":2,"packages":["com.example.old"]}""").getJSONObject("document") + assertEquals(8, value.getInt("future")); val c = value.getJSONObject("policy").getJSONObject("com.example.old").getJSONObject("c"); assertEquals(7, c.getInt("future")); assertFalse(c.has("h")) + val updated = ScopeDocuments(file, DeviceFiles(dir)).replace("""{"version":2,"packages":["com.example.old"],"future":9,"newField":true,"policy":{"com.example.old":{"newPolicy":4,"c":{"h":false,"another":2}}}}""").getJSONObject("document") + assertEquals(9, updated.getInt("future")); assertTrue(updated.getBoolean("newField")); assertEquals(2, updated.getJSONObject("policy").getJSONObject("com.example.old").getJSONObject("c").getInt("another")) + } + @Test fun framingIsBoundedAndTruncatedFramesDoNotBecomeRequests() { + val stream = ByteArrayInputStream(frame(JSONObject().put("x", 1)) + frame(JSONObject().put("x", 2))) + assertEquals(1, DeviceRpc.read(stream)!!.getInt("x")); assertEquals(2, DeviceRpc.read(stream)!!.getInt("x")); assertNull(DeviceRpc.read(stream)) + assertTrue(runCatching { DeviceRpc.read(ByteArrayInputStream(byteArrayOf(127, 127, 127, 127))) }.isFailure) + assertTrue(runCatching { DeviceRpc.read(ByteArrayInputStream(frame(JSONObject().put("x", 1)).dropLast(1).toByteArray())) }.isFailure) + } + @Test fun sessionRejectsWrongCredentialAndWrongBootBeforeCallingBackend() { + val dir = root(); val id = identity(dir); var hits = 0 + val ops = DeviceOperations(id, DeviceFiles(dir), DeviceBackend { _, _ -> hits++; JSONObject().put("ok", true) }) + fun hello(token: String) = JSONObject().put("protocol", DeviceRpc.PROTOCOL).put("id", "hello").put("method", "device.hello").put("params", JSONObject().put("clientNonce", "a".repeat(64)).put("authentication", JSONObject().put("type", "usb-token").put("credential", token))) + val bad = ByteArrayOutputStream(); DeviceRpcSession(ops).serve(ByteArrayInputStream(frame(hello("wrong"))), bad) + assertEquals("AUTH_FAILED", DeviceRpc.read(ByteArrayInputStream(bad.toByteArray()))!!.getJSONObject("error").getString("code")); assertEquals(0, hits) + val request = JSONObject().put("protocol", DeviceRpc.PROTOCOL).put("id", "read").put("method", "scope.get").put("target", id.descriptor().put("bootId", UUID.randomUUID().toString())) + val out = ByteArrayOutputStream(); DeviceRpcSession(ops).serve(ByteArrayInputStream(frame(hello(id.token)) + frame(request)), out) + val replies = ByteArrayInputStream(out.toByteArray()); assertTrue(DeviceRpc.read(replies)!!.getBoolean("ok")); assertEquals("TARGET_CHANGED", DeviceRpc.read(replies)!!.getJSONObject("error").getString("code")); assertEquals(1, hits) // hello info only + } + @Test fun invalidParametersAreRejectedBeforeRevisionOrEffects() { + val dir = root(); var calls = 0 + val ops = DeviceOperations(identity(dir), DeviceFiles(dir), object : DeviceBackend { + override fun execute(method: String, params: JSONObject): JSONObject { calls++; return JSONObject().put("ok", true) } + override fun validate(method: String, params: JSONObject) { DeviceArguments.validate(method, params) } + }) + for ((method, params) in listOf("scope.patch" to JSONObject().put("set", "bad"), "process.control" to JSONObject().put("package", "com.example.fixture").put("action", "stop"), "host.set" to JSONObject().put("endpoint", "no endpoint"), "certificates.delete" to JSONObject().put("fileName", "../escape"))) { + assertEquals("INVALID_ARGUMENT", (runCatching { ops.write(method, params, UUID.randomUUID().toString(), 0, "ai", 1000) }.exceptionOrNull() as DeviceFault).code) + } + assertEquals(0, calls); assertEquals(0L, ops.revision()) + } + @Test fun reservationFailureDisablesWritesWithoutDispatchingAndResultFailureRemainsUnknown() { + val dir = root(); val id = identity(dir); var fail = false; var calls = 0 + val files = DeviceFiles(dir, { _, _ -> if (fail) throw java.io.IOException("synthetic disk failure") }) + val backend = DeviceBackend { _, _ -> calls++; JSONObject().put("ok", true) } + val ops = DeviceOperations(id, files, backend); fail = true + val error = runCatching { ops.write("host.set", JSONObject(), "no-dispatch", 0, "ai", 10000) }.exceptionOrNull() as DeviceFault + assertEquals("DEVICE_LEDGER_UNAVAILABLE", error.code); assertFalse(error.uncertain); assertEquals(0, calls); assertEquals(0L, ops.revision()) + fail = false + assertEquals("DEVICE_LEDGER_UNAVAILABLE", (runCatching { ops.write("host.set", JSONObject(), "no-retry", 0, "ai", 10000) }.exceptionOrNull() as DeviceFault).code) + val recovered = DeviceOperations(id, files, DeviceBackend { _, _ -> calls++; fail = true; JSONObject().put("ok", true) }) + val after = runCatching { recovered.write("host.set", JSONObject(), "uncertain", 0, "ai", 10000) }.exceptionOrNull() as DeviceFault + assertTrue(after.uncertain); assertEquals(1, calls); assertEquals("unknown", recovered.read("operations.get", JSONObject().put("operationId", "uncertain")).getString("state")) + fail = false + val restarted = DeviceOperations(identity(dir), files, backend) + assertEquals("unknown", restarted.read("operations.get", JSONObject().put("operationId", "uncertain")).getString("state")); assertEquals(1, calls) + } +} diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt new file mode 100644 index 0000000..3133820 --- /dev/null +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt @@ -0,0 +1,37 @@ +package com.adh.daemon.device + +import org.json.JSONObject +import java.io.File +import java.net.InetAddress +import java.net.ServerSocket +import java.util.UUID +import java.util.concurrent.Executors + +/** Runs the production domain/codec on loopback JVM sockets, never Android/ADB or a real app. */ +object DeviceRpcFixture { + @JvmStatic fun main(args: Array) { + require(args.size == 1) + val root = File(args[0]); check(root.isDirectory && root.name.startsWith("adh-p3-jvm-")) + val bootFile = File(root, "boot.txt"); if (!bootFile.exists()) bootFile.writeText(UUID.randomUUID().toString()) + val files = DeviceFiles(root); val identity = DeviceIdentity(files, bootFile.readText().trim()) + val scopes = ScopeDocuments(File(root, "scope.json"), files) + val counter = java.util.concurrent.atomic.AtomicInteger() + val backend = DeviceBackend { method, params -> + when (method) { + "device.info" -> JSONObject().put("model", "JVM fixture").put("synthetic", true) + "scope.get" -> scopes.snapshot() + "scope.patch" -> scopes.patch(params) + "scope.replace" -> scopes.replace(params.getJSONObject("document").toString(), params.getString("scopeRevision")) + "module.status" -> JSONObject().put("synthetic", true).put("calls", counter.get()) + "applications.list" -> JSONObject().put("applications", org.json.JSONArray()).put("total", 0) + "process.control" -> { counter.incrementAndGet(); Thread.sleep(params.optLong("delayMs", 0).coerceIn(0, 5000)); JSONObject().put("ok", true).put("synthetic", true).put("calls", counter.get()) } + else -> throw DeviceFault("UNSUPPORTED_METHOD", "fixture method not implemented") + } + } + val operations = DeviceOperations(identity, files, backend) + val server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); val workers = Executors.newFixedThreadPool(4) + File(root, "ready.json").writeText(JSONObject().put("port", server.localPort).put("deviceId", identity.deviceId).toString()) + Runtime.getRuntime().addShutdownHook(Thread { server.close(); workers.shutdownNow() }) + while (!server.isClosed) { val client = server.accept(); workers.execute { client.use { try { DeviceRpcSession(operations).serve(it.getInputStream(), it.getOutputStream()) } catch (_: Exception) { } } } } + } +} diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md index a577535..b9b88c0 100644 --- a/docs/DEVELOPMENT_PLAN.md +++ b/docs/DEVELOPMENT_PLAN.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 开发计划 +> **2026-11-16 P3 实施**:设备域服务、安装身份、能力查询与 USB/ADB RPC 已在独立 worktree 实现。Binder/RPC 共用业务与 revision;Host 设备范围接入 P1 控制权,MCP/REST/公共 CLI 共用操作。详见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。P4 配对/TLS、旧 ADB-only 能力迁移及 agent 本地路由未实施;原审计 P3 的真机 UDS/fd/SELinux 原型仍待独立设备验证,当前现场不升级。 + > **2026-11-16 P2 实施**:完成同一工作台的独立/现场入口、任务详情/结果/副作用、配置草稿/并发冲突核对、任务 CAS 与暂停恢复、显式接管/交还及 unknown 核对。AI 规划与执行继续由外部 Harness 主导,面板不要求预先接管或固定 recipe。模块/边界见 [P2_WORKBENCH.md](P2_WORKBENCH.md);P3/P4 的设备域与新传输仍未实施,当前分析实例不升级。 > **2026-11-16 P1 实施**:共享执行器、持久任务、状态版本/控制 epoch、人类接管、真实超时/取消反馈与最小面板控制入口已落地,见 [P1_OPERATIONS.md](P1_OPERATIONS.md)。P2 仍需完整任务工作台/编辑体验;P3/P4 的稳定设备身份和 USB/LAN 新 RPC、配对/TLS 尚未实现。本轮不替换当前运行实例。 diff --git a/docs/FEATURE_STATUS.md b/docs/FEATURE_STATUS.md index a9f44f2..8b74e3d 100644 --- a/docs/FEATURE_STATUS.md +++ b/docs/FEATURE_STATUS.md @@ -1,5 +1,7 @@ # ADH 功能状态(2026-10-24 更新:通用原生分析与证据核验;各轮实测范围见 §2) +> **2026-11-16 P3**:设备域、稳定安装身份、能力查询及 USB/ADB RPC 已实现,Binder/RPC 共享业务与状态版本,MCP 增至 **93**。隔离生产 Kotlin/Node 协议、双设备、超时/结果追踪、人类控制与公共 CLI 路径均已测;Android JVM **61 passed**,Device Daemon 构建及 Manager 编译通过。完整 Host 结果见 PROGRESS.md。**真机 Android UDS/SELinux、真实应用/证书效果尚未验证**;LAN/TLS/配对、agent 本地路由、bulk 与 ADB-only 能力迁移未实施,不能宣称 USB/LAN 全能力对等。见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。源码仅在独立 worktree,不替换当前实例。 + > **2026-11-16 P2**:人类任务工作台已在隔离 Host/浏览器验收,含任务搜索分页、详情/结果/下载、有限副作用日志、配置草稿与显式冲突核对、暂停恢复、接管/交还与 unknown。完整 Host **525 passed / 0 failed / 0 skipped**;模块与限制见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。交付在独立 worktree;原工作目录保留 P1,当前服务与真实设备未部署或升级。 > **2026-11-16 P1**:统一操作执行层、SQLite 持久任务、revision/epoch 控制权、人类修改防旧写、超时 unknown/晚到证据、真实取消状态与最小面板已在隔离 Host 验证。公共 adh-cli 同步提供 run/tasks/control,尚未发布或替换本机安装包。接口/限制见 [P1_OPERATIONS.md](P1_OPERATIONS.md);完整计数见 PROGRESS.md。源码未加载到当前分析服务,USB/LAN 新协议与真机效果不在本轮验收范围。 diff --git a/docs/P3_DEVICE_DOMAIN.md b/docs/P3_DEVICE_DOMAIN.md new file mode 100644 index 0000000..e1a64a9 --- /dev/null +++ b/docs/P3_DEVICE_DOMAIN.md @@ -0,0 +1,117 @@ +# P3:设备域、稳定身份与 USB RPC(2026-11-16) + +设备控制从传输中拆出:手机现有 Device Daemon 的 `DeviceOperations` 由签名校验后的 Binder 与 USB RPC 共用,Host 的 `Devices` 管理经过验证的安装身份、能力和连接。AI 默认拥有规划和执行权;不需要固定 recipe 或每次人工确认。人类的修改、暂停与接管继续由 P1/P2 的操作协调器约束。 + +本轮在 `feat/adh-p3-device-domain-20261116` 独立 worktree 开发并验证,不发布、不部署、不替换当前进程或静态资源,不执行任何真实 ADB 命令,不调整现有 reverse/forward,不关联或迁移正在运行的 target session。 + +## 模块与边界 + +| 模块 | 职责 | +|---|---| +| `device/:core` 的 `DeviceRpc` | `adh.device/1`、方法效果表、帧编解码;AIDL v19 在末尾追加身份/能力/作用域快照及 CAS 方法,保留旧 transaction 顺序 | +| `device/:daemon` 的 `AndroidDeviceBackend` | 模块、应用、作用域、进程、证书与 Host 地址业务;Binder 不再复制这些实现 | +| `device/…/device/DeviceOperations` | 单写入锁、持久 revision、操作意图去重、预先落盘、未知隔离;Manager 旧写入也推进同一 revision | +| `DeviceIdentity` / `DeviceFiles` | 明确初始化、持久 UUID/身份密钥、USB 凭据;原子替换、文件/目录 fsync;损坏不重建 | +| `DeviceRpcSession` / `LocalDeviceRpcServer` | 与传输无关的 dispatcher;当前适配 Android abstract UDS,限制 peer UID、帧和工作线程 | +| `daemon/src/device_protocol.ts` | 同一协议的 Node codec、签名校验、有界 pending、超时与断线,不重连或重放 | +| `daemon/src/transport/adb_device.ts` | 显式发现、固定 transport、可信 USB bootstrap、创建与清理自己拥有的 forward | +| `daemon/src/devices.ts` / `device_host.ts` | 持久设备清单、临时连接、身份去重、代际失效与显式能力调用 | +| MCP `devices` / REST `/api/devices` | 同一操作分类和执行器;公共 Python CLI 的 `call` / `run` 无需增加第二套业务逻辑 | + +手机不增加 HTTP、MCP、数据库或逆向分析。设备操作日志是有界 JSON 协调记录;采集、索引、反汇编、任务工作流仍在 Host/Harness。进程 RPC 仅提供现有第三方应用控制,不恢复已退役的 UI 自动化。 + +## 身份与可信建立 + +- `deviceId` 是首次初始化时生成的安装 UUID,与 RSA-2048 身份密钥共同保存在 `/data/adb/adh/device-rpc/identity.json`。目录 0700、文件 0600;不使用 ADB serial、Android ID、型号、目标 PID 或 session ID 代替设备身份。 +- `/data/adb/adh/device-rpc/usb-access.json` 只含 schema、deviceId、公钥 SHA-256 指纹与随机 USB token,不含私钥。Host 通过明确选择的已授权 root ADB transport 读取;token 只在本次内存握手使用,不写入 Host 设备缓存、任务或输出。 +- `bootId` 来自内核 boot_id;每次 Device Daemon 启动另生成 `daemonInstanceId`。主机要求每次写入带上已观察的两种代际;重启不会把旧指令重新绑定到新实例。 +- hello 的 RSA/SHA-256 签名覆盖客户端 nonce、请求 ID、协议、设备/代际、信息与能力。Host 验证签名和 bootstrap 指纹,再对照已保存的 deviceId→指纹,不静默覆盖身份。 +- 多条 USB/ADB 连接可以合并为一个设备;有多条活连接时必须给 connectionId,不自动选路或故障切换。相同身份同时声明不同活 boot/daemon 代际会被拒绝。断线后保留清理句柄,便于显式断开并核对 forward。 + +这是安装身份,不是硬件证明。离线复制整份身份目录的两个系统不能仅凭公钥区分;在线代际冲突可检测。删除安装身份会成为新设备,Host 不通过 serial 自动合并。身份或日志损坏必须人工核对备份,不能自动删除后继续执行。 + +## 传输与协议 + +设备端只监听 `localabstract:adh_device_rpc_v1`,检查 peer UID 为 root/shell,并验证 USB token。手机不开放 TCP/LAN 监听。Android 的 [LocalSocket](https://developer.android.com/reference/android/net/LocalSocket) 提供 peer credentials 和读超时接口;本机只完成编译与 JVM 协议测试,未把 Android socket/SELinux 行为当作已通过的真机结论。 + +Host 显式执行 `adb devices -l`,保留 device/offline/unauthorized 状态。连接会重新核对发现结果,用 `-t transport_id` 固定设备;旧 adb 不返回 transport_id 时才使用发现到的精确 `-s serial`。创建方式是 `forward --no-rebind tcp:0 localabstract:adh_device_rpc_v1`,符合 [AOSP adb 命令约定](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/client/commandline.cpp)。不会调用 reverse、remove-all、kill-server、安装或重启。 + +清理时重新检查原 transport,以及 serial/本地端口/远端 socket 三者完全匹配的映射;只移除自己创建的映射。原 transport 消失或映射已被替换时,留下不属于自己的映射并报告清理未确认。Host 正常缓存恢复不会发现、连接设备或自动清理任何映射;Host 进程异常退出可能留下自己的 forward,需要之后明确核对。 + +帧为 `[4 字节大端长度][UTF-8 JSON]`,上限 1 MiB。它与原 target agent 协议不同。请求示意: + +```json +{ + "protocol": "adh.device/1", + "id": "unique-request-id", + "method": "scope.patch", + "target": { + "deviceId": "observed-installation-uuid", + "bootId": "observed-kernel-uuid", + "daemonInstanceId": "observed-daemon-uuid" + }, + "params": {"scopeRevision": "observed-sha256", "add": ["com.example.fixture"]}, + "meta": {"operationId": "host-operation-uuid", "expectedRevision": 7, "actor": "ai", "budgetMs": 10000} +} +``` + +实际 UUID/哈希必须来自观察,示例字符串不能直接执行。响应以相同 id 返回 `{protocol,id,ok,result}` 或 `{protocol,id,ok:false,error:{code,message,uncertain}}`。方法效果由静态表与签名能力共同决定,不能用调用者的 `status` 或 `read` 字段把写入伪装成读取。新传输只需提供经过认证的流,复用 codec、dispatcher、身份及业务方法;P4 还必须实现配对、TLS、撤销和连接权限,不能把 USB token 直接当成公网认证方案。 + +## 能力、状态与副作用 + +| 方法 | 效果 | 前提/返回 | +|---|---|---| +| `device.info` / `device.capabilities` / `device.state` | 读取 | 身份、代际、设备信息、方法表、stateRevision;无目标进程也可查询 | +| `module.status` | 读取 | 模块存在/加载标记/版本 | +| `scope.get` | 读取 | 完整 document、原文 SHA-256 scopeRevision、stateRevision | +| `applications.list` / `processes.list` | 读取 | 分页与 nextOffset;进程返回 PID/UID/starttimeTicks、不完整状态 | +| `certificates.list` / `host.get` | 读取 | 当前证书及 pendingReboot、Host endpoint | +| `operations.get` | 读取 | 设备端按 Host operationId 查询持久实际结果;不重发执行 | +| `scope.patch` | 写入 | scopeRevision CAS,只改 packages,保留完整策略/未知字段,不重启目标 | +| `scope.replace` | 写入 | scopeRevision CAS;规范化已知策略键,保留并合并扩展字段;不自动注入/重启 | +| `process.control` | 写入 | 明确第三方包、open/stop/restart、expectedProcesses 的 PID/UID/starttimeTicks 集合;调用前复查,不声称有内核原子 CAS | +| `certificates.put` / `certificates.delete` | 写入 | 有界 CA 字节/受限文件名;标记需重启,不远程重启 | +| `host.set` | 写入 | 合法 endpoint,原子保存;现有目标不会因此自动重连 | +| `operations.resolve` | 写入 | 已认证人类、明确未知操作 ID 与 acknowledge;保留原 unknown 历史 | + +每个 RPC 写入同时要求:Host `_operation.expectedRevision/controlEpoch/hostEpoch`、`device:` 资源、已观察 boot/daemon 代际,以及 `expectedDeviceRevision`。作用域另要求 scopeRevision。结构非法在设备业务派发前拒绝;磁盘 reservation 未持久化不派发。已派发后结果持久化失败返回未知并关闭后续写入,重启从预留记录恢复 unknown,绝不重放。 + +Device Daemon 的全局单写入锁协调 Binder/RPC。旧 Manager 不强制升级 UI,每次旧写也推进设备 revision,因而旧 AI 指令会失效;新增 AIDL CAS 供后续 Manager 编辑器采用。外部旧 Host/直接 ADB 文件写入不经过该锁,scopeRevision 可发现检查前的变化,不能承诺与任意外部文件写入之间有原子事务。 + +设备日志限 1024 条/2 MiB,不自动删除历史;单结果超过 32 KiB 保存省略摘要、大小和哈希。达到限制拒绝新写入,本轮没有在线归档 API。人工维护需要先安排隔离/停止对应新实例并核对备份,不能在当前分析现场删除日志。只读查询仍可使用。 + +Host 以 `device:` 作为独立控制范围;两个已验证设备可并行。原 agent session 仍没有可验证设备归属,因此旧 target 与新设备写入保守互斥;其中一边被人类持有或有未知副作用时,AI 不能从另一边绕过。不会根据“当前只有一台 ADB 设备”推断归属。工作台可从该设备操作的任务详情选择“查看此范围控制权”,继续查看副作用、接管或交还 AI。 + +## 公共入口与 AI 工作流 + +1. `devices action=list` 读取 Host 缓存,明确 lastKnown/online;不会进行 ADB 操作。`discover` 才显式发现传输。 +2. `operations action=snapshot tool=devices arguments={action:connect,serial,transportId}` 得到 Host 版本,然后提交 connect。现有公共 CLI 可使用 `adh run devices --arguments ''` 自动走相同 snapshot/submit;连接不是注入或重启。 +3. 用返回的 deviceId 查询 `info`、`capabilities`、`device.state` 和 `scope.get`。读取失效/缺能力时先诊断,不能偷偷回退 ADB 或切换另一连接。 +4. 给 `adh run devices --arguments ''` 的 arguments 填 action=call、deviceId、method、params、bootId、daemonInstanceId、expectedDeviceRevision。Host `run` 只负责 Host 状态版本,不替调用者刷新设备版本或重写意图。 +5. 用任务/操作 ID 读取结果,超时或断线后用设备 `operations.get` 查询实际执行,不重发原命令。设备预算最多 60 秒,预算在设备等待锁后也会检查;执行中的 Android 调用不能保证被取消。 + +REST 的 GET/POST `/api/devices` 接收同一 action/参数,写入携带 `X-Adh-Operation`;MCP/CLI 参数使用 `_operation`。operator 身份只来自 Host 凭据,RPC meta 从执行上下文产生,调用参数不能伪造 actor。相同幂等意图键跨 REST/MCP 取回同一 Host 操作,不再执行。 + +未知处理:先观察设备 `operations.get`、scope/进程事实及 Host 副作用,再由人类显式核对 Host unknown;设备日志若也有 unresolved unknown,继续由人类在设备资源持有状态下调用 `operations.resolve`。两层历史均保留;核对不等于宣布原调用成功。已派发请求超时后不故障切换、不自动重试,也不声称目标已取消。 + +## 验证与未验证项 + +```powershell +cd device +.\gradlew.bat --offline :core:testDebugUnitTest :daemon:testDebugUnitTest :manager:testDebugUnitTest :daemon:assembleDebug :manager:compileDebugKotlin :daemon:writeDeviceRpcFixtureClasspath -PadhManagerCertSha256=<64-hex-test-pin> +cd ../daemon +$env:ADH_CLI_SOURCE='/src' +npm run typecheck +npm test +cd .. +node tools/generate_mcp_docs.mjs --check +``` + +本轮用全零测试 pin,仅生成隔离构建产物,不可发布/安装。JVM classpath 清单是忽略的 build 产物;测试探测不到它时明确 skip,绝不转用真机。完整验收前先构建清单;本轮跨语言用例确实执行,未 skip。 + +- Host 完整回归 **538 passed / 0 failed / 0 skipped**,含生产 Kotlin/Node codec、签名握手、双设备隔离、USB 别名去重、旧 boot 拒绝、Host 代际失效、凭据错误清理、超时后设备结果查询、MCP/REST/公共 Python CLI 同资源与 CAS、人类接管。 +- Android JVM **61 passed / 0 failed / 0 skipped**:core 22、daemon 11(含设备域 10)、Manager 28;Device Daemon debug APK 构建、Manager Kotlin 编译通过。包含共享 Binder/RPC 服务的 revision/去重、磁盘失败、崩溃 unknown、作用域策略与帧限制。 +- ADB 适配器由本机 loopback 代理模拟,设备域/编解码/持久化运行生产 Kotlin 实现;未测试 Android UDS 的真机 SELinux 可达性、真实证书挂载、真实第三方应用启停、旧 Manager Binder 的实机调用。 +- LAN/TLS/配对撤销、bulk、agent 本地路由和旧 ADB-only 诊断/helper/fs 迁移均明确未实施。原审计附录 P3 的 agent 本地 UDS/fd/SELinux 原型仍待专用设备验证,不能把本轮构建和 JVM 信号当成该原型通过。 + +当前在线服务与原工作目录保持原状;交付的是已验证并提交的源码,不是当前分析实例升级。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index a33dd81..678dddd 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -4984,3 +4984,20 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 浏览器用 ego-browser 对随机 loopback 端口、临时数据目录与合成 agent 实测:任务详情/结果/下载,结果 HTML 作为纯文本,任务暂停恢复及 STALE_TASK,unknown/晚到结果/显式人工核对,接管交还,配置 STALE_CONTROL 后草稿仍保留,再核对提交仅改人类字段且保留 AI 同时改过的其他字段。另测导入只改草稿、导出已读配置、独立/现场入口不叠开旧设置、390px 窄屏。实际查看截图并修复了嵌入页 main 全局样式冲突;关闭了浏览器任务并只停止本轮自建 UI fixture。 完整范围、迁移/API 和限制见 [P2_WORKBENCH.md](P2_WORKBENCH.md),同步 REQUIREMENTS、DEVELOPMENT_PLAN、FEATURE_STATUS、MAP 和 MCP 清单。未部署、未推送、未发布安装包;未启动正式 index、修改 adb reverse、运行设备门禁、启停目标或重启当前服务。当前 8088 仍是原非 watch 进程。P2 面板需要配套 P2 Host;副作用日志有界且不等同完整目标审计,设备域服务、USB/LAN 新 RPC、TLS 和目标侧撤销仍属后续阶段。 + + +## 2026-11-16:P3 设备域、稳定安装身份与 USB/ADB RPC + +在 P2 提交 91be0f5 上建立独立 worktree/分支 feat/adh-p3-device-domain-20261116。原 Android 工作目录继续保留 P1 且干净,P2 worktree 不改;没有加载本轮源码到当前分析服务或其 public 目录。 + +- Device Daemon 提取 AndroidDeviceBackend 与 DeviceOperations,签名校验后的 Binder 与 adh.device/1 RPC 共用业务、持久 revision 和写入锁;AIDL v19 末尾追加身份/能力/作用域 CAS,旧 Manager 写入也推进同一版本。手机不增加 HTTP/MCP/数据库/分析。 +- 安装 UUID + RSA 身份密钥持久保存,bootstrap 不含私钥。Host 验证 nonce/能力/身份签名与指纹,分开 deviceId、bootId、daemonInstanceId、connectionId、ADB transport 和旧 session。多连接去重,代际变化失效旧 Host 指令;不靠 serial 推断目标归属。 +- Host Devices 统一缓存/显式发现/信息/能力/调用。USB 固定 transport_id、只创建 tcp:0 自有 forward,清理重新核对映射;断线保留清理句柄,映射被替换返回未知且不删除。没有 reverse、remove-all、安装、启停真实 App 或隐式故障切换。 +- MCP devices 与 REST /api/devices 共用执行器,公共 Python CLI 现有 call/run 直接复用。写入要求 Host 控制版本 + device:UUID 资源 + 设备代际/revision,scope 另带内容哈希。人类持有与 unknown 在旧 target/新设备未关联时保守互锁;两个已验证设备仍可并行。 +- 设备日志先落盘再派发,意图去重,不存请求凭据/参数原文,不重放;预留失败不执行,结果保存失败与重启恢复为 unknown。容量/结果有界,不自动清理历史。修复进程命令在 waitFor 前 readText 导致的无效超时,输出有界,派发后超时明确未知。 + +验证:Host 类型检查通过,完整 **538 passed / 0 failed / 0 skipped**(P2 525 + 新增 13),其中跨语言测试运行生产 Kotlin 身份/域/持久化/codec 与 Node ADB loopback 模拟;包含双设备、USB 别名、版本冲突、代际、超时后实际结果、清理归属、人类接管及 MCP/REST/真实 Python CLI。Android 离线 core/daemon/Manager JVM **61 passed / 0 failed / 0 skipped**,Device Daemon debug 构建和 Manager Kotlin 编译通过,构建只用隔离全零测试 pin。v71 **93 tools / 0 problems / PASS**。新增可复现 MCP 文档生成器,--check 通过;git whitespace 检查按既有 CRLF 使用 cr-at-eol。 + +局限如实保留:Android abstract UDS/peer UID/SELinux 可达性及真实 Binder、证书挂载、第三方进程效果没有真机验证;旧审计 P3 的 agent 本地 UDS/fd 原型尚未交付。LAN/TLS/配对/撤销、bulk、agent 路由和旧 ADB-only 诊断/helper/fs 迁移仍待 P4;现有 agent 通道明确 legacy/unverified,不宣称全能力 LAN 对等。完整 API、身份语义、未知核对顺序与迁移见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。 + +未部署、未推送、未发布或安装产物,未启动正式 index、未请求当前 8088 业务接口、未操作真机/当前会话或重启服务;只启动并清理 OS 临时目录里的 JVM/HTTP 测试夹具。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index 43262fd..81a82fe 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 功能需求说明 +> **2026-11-16 P3 设备契约**:稳定安装 UUID/密钥与 boot/daemon 代际,设备发现、信息/能力、作用域/进程/证书/Host 地址由同一设备域服务提供,Binder 与 USB RPC 共用持久 revision。所有远程写经过 Host 设备资源控制及设备 CAS,派发后未知不重试。新协议与现有 agent session 显式区分,未验证的归属不猜测;局域网 TLS、配对和旧 ADB 能力迁移留待后续。范围和验证边界见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。本轮不部署、不改变当前分析现场。 + > **2026-11-16 P2 人类工作台**:任务搜索/分页、详情/结果/副作用、人类暂停恢复、接管/交还、unknown 核对和配置编辑已接入同一执行层。草稿保留原版本,冲突并列核对,显式 rebase 只保留本来修改的字段,不自动提交;任务状态修改使用 task revision。默认观察不改变 AI 工作。范围、兼容性与验证见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。本轮在独立 worktree 实现,当前服务不升级,原静态目录保留 P1 提交内容。 > **2026-11-16 P1 操作契约**:MCP、REST、公共/开发 CLI 和人类面板通过同一 Host 执行层;写入必须携带 revision/controlEpoch/hostEpoch,人类接管与修改阻止旧 AI 操作继续写。任务持久保存,不自动重放;取消区分 requested 与确认,派发后超时/断连保留 unknown 和晚到证据。operator 凭据控制接管,不以请求 JSON 的自报角色授权。实现、迁移与边界见 [P1_OPERATIONS.md](P1_OPERATIONS.md)。人类面板可修改/接管的用户决议取代下文历史只读冻结口径;不将 Host 门禁视为真机或新传输验收。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index b47804f..0bcab6c 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -1,9 +1,11 @@ # ADH MCP Tools -Generated from the source registry (92 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). +Generated from the source registry (93 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). Writes require `_operation` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. +Verified installation identities, device capabilities and USB/ADB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Legacy target sessions remain unassociated; LAN/TLS are not implemented. + | Tool | Description | Args | |---|---|---| | `analysis_guide` | START HERE when context or reversing experience is limited. action=guide (default) returns Host-only workflows without device operations: topic start/writer/crypto/trace/stuck, ordered templates, prerequisites, checks and failure branches. action=assess interprets CURRENT evidence for an explicit session: stage, facts, missingEvidence, doNotConclude, one proposed next call with purpose/effect/expected result, and a checkpoint for another agent. It reads retained Host records and may query native_hook status once with a 3-second budget; no hooks, trigger, replay, restart, capture drain or root upload is performed. No session returns target-selection advice, never an invented target. Optional hookId narrows to that hook; buffer/tid are caller-supplied writer candidates and never automatically trusted. Read-only assessment is not an algorithm proof or complete case history. Template $variables need actual correctly typed values. | action, topic, session, hookId, buffer, tid, _operation | @@ -98,3 +100,4 @@ Writes require `_operation` state/control versions: [P1_OPERATIONS.md](P1_OPERAT | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | _operation | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | | `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | +| `devices` | Device-domain discovery, verified installation identities and USB/ADB RPC. list is cached/offline-safe; discover lists ADB transports without attaching targets; connect requires an explicit serial/transportId and creates only its own ADB forward. info/capabilities query a verified deviceId. call uses advertised device methods; writes require observed bootId, daemonInstanceId, expectedDeviceRevision plus Host _operation versions. Read scope.get before scope.patch and supply params.scopeRevision. Device and connection ids are distinct from legacy agent session ids; no association or ADB fallback is guessed. TLS/LAN, agent routing and arbitrary shell are unsupported in P3. Unknown effects must be inspected, never replayed. | action, serial, transportId, expectedDeviceId, deviceId, connectionId, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | diff --git a/tools/MAP.md b/tools/MAP.md index 74704b4..107d3ab 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -197,3 +197,7 @@ event-limit accounting, explicit stop and wrong-TID refusal. It does not run the ### root_watch 内存窗口时序补充(2026-11-16) `native/root_watch.c` 的 `emit_mem` 在收到 perf 事件后读取目标进程,不是内核事件时刻的堆快照;原始窗口明确标为 `source=process-memory-after-sample`、`snapshotConsistent:false`。同事件内核栈可用时,由 Host `projectRootSample` 恢复确定的栈窗口。自测的固定内存值通过不能证明动态目标的异步窗口同步正确。 + +## MCP registry documentation + +`node tools/generate_mcp_docs.mjs` regenerates docs/mcp-tools.md from the source registry; `--check` validates it. It uses isolated, pure imports and performs no Host initialization, discovery or ADB operation. The generator is tracked so fresh clones do not depend on an ignored adhd-data script. diff --git a/tools/generate_mcp_docs.mjs b/tools/generate_mcp_docs.mjs new file mode 100644 index 0000000..d00798c --- /dev/null +++ b/tools/generate_mcp_docs.mjs @@ -0,0 +1,22 @@ +// Source-registry documentation. Pure imports; never initialize a Host or discover devices. +import {readFileSync,writeFileSync} from 'node:fs'; +process.env.ADH_SKIP_ARTIFACT_LOAD='1'; +delete process.env.ADH_DATA_DIR;delete process.env.ADH_CAPTURES_DIR; +const {MCP_TOOLS}=await import('../daemon/src/mcp.ts'); +const clean=value=>String(value).replace(/\|/g,'\\|').replace(/\r?\n/g,' '); +const header=`# ADH MCP Tools + +Generated from the source registry (${MCP_TOOLS.length} tools). Endpoint: \`POST /mcp\` (JSON-RPC 2.0). + +Writes require \`_operation\` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. + +Verified installation identities, device capabilities and USB/ADB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Legacy target sessions remain unassociated; LAN/TLS are not implemented. + +| Tool | Description | Args | +|---|---|---| +`; +const doc=header+MCP_TOOLS.map(t=>`| \`${t.name}\` | ${clean(t.description)} | ${Object.keys(t.inputSchema.properties).join(', ')} |`).join('\n')+'\n'; +const destination=new URL('../docs/mcp-tools.md',import.meta.url); +if(process.argv.includes('--check')){if(readFileSync(destination,'utf8')!==doc)throw Error('MCP docs out of date: node tools/generate_mcp_docs.mjs');} +else writeFileSync(destination,doc); +console.log(`MCP documentation: ${MCP_TOOLS.length} tools; ${process.argv.includes('--check')?'PASS':'generated'}`); From fa98813b1aa5ab361e07b55f653af90181a3ab66 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:52:44 +0800 Subject: [PATCH 16/24] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=B1=80?= =?UTF-8?q?=E5=9F=9F=E7=BD=91=20TLS=20=E9=85=8D=E5=AF=B9=E6=92=A4=E9=94=80?= =?UTF-8?q?=E4=B8=8E=E6=8C=81=E4=B9=85=E5=AF=B9=E8=B4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 4 + CLAUDE.md | 4 + daemon/public/workbench.js | 15 +- daemon/src/MAP.md | 4 + daemon/src/device_client_identity.ts | 32 ++++ daemon/src/device_host.ts | 22 ++- daemon/src/device_protocol.ts | 4 +- daemon/src/devices.ts | 71 +++++++-- daemon/src/execution_context.ts | 2 + daemon/src/mcp.ts | 2 +- daemon/src/operation_registry.ts | 9 +- daemon/src/operations.ts | 26 ++-- daemon/src/task_store.ts | 3 + daemon/src/transport/adb_device.ts | 3 +- daemon/src/transport/device_transport.ts | 8 + daemon/src/transport/lan_device.ts | 43 ++++++ daemon/test/device_client_identity.test.ts | 27 ++++ daemon/test/device_fixture.ts | 4 +- daemon/test/device_lan.test.ts | 145 ++++++++++++++++++ daemon/test/device_lan_entrypoints.test.ts | 54 +++++++ daemon/test/fixtures/p4_workbench.ts | 26 ++++ device/MAP.md | 4 + .../src/main/java/com/adh/core/DeviceRpc.kt | 4 +- .../java/com/adh/daemon/AdhDeviceDaemon.kt | 3 + .../com/adh/daemon/device/DeviceIdentity.kt | 2 + .../com/adh/daemon/device/DeviceNetwork.kt | 93 +++++++++++ .../com/adh/daemon/device/DeviceOperations.kt | 31 +++- .../com/adh/daemon/device/DevicePairings.kt | 80 ++++++++++ .../com/adh/daemon/device/DeviceRpcSession.kt | 41 ++++- .../java/com/adh/daemon/device/DeviceTls.kt | 56 +++++++ .../adh/daemon/device/DeviceNetworkTest.kt | 66 ++++++++ .../com/adh/daemon/device/DeviceRpcFixture.kt | 18 ++- docs/DEVELOPMENT_PLAN.md | 2 + docs/FEATURE_STATUS.md | 2 + docs/P4_LAN_AUTH.md | 122 +++++++++++++++ docs/PROGRESS.md | 19 +++ docs/REQUIREMENTS.md | 2 + docs/mcp-tools.md | 4 +- tools/generate_mcp_docs.mjs | 2 +- 39 files changed, 998 insertions(+), 61 deletions(-) create mode 100644 daemon/src/device_client_identity.ts create mode 100644 daemon/src/transport/device_transport.ts create mode 100644 daemon/src/transport/lan_device.ts create mode 100644 daemon/test/device_client_identity.test.ts create mode 100644 daemon/test/device_lan.test.ts create mode 100644 daemon/test/device_lan_entrypoints.test.ts create mode 100644 daemon/test/fixtures/p4_workbench.ts create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceNetwork.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceTls.kt create mode 100644 device/daemon/src/test/java/com/adh/daemon/device/DeviceNetworkTest.kt create mode 100644 docs/P4_LAN_AUTH.md diff --git a/AGENTS.md b/AGENTS.md index 0523d40..badf7df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,3 +170,7 @@ Each layer has a `MAP.md` — read it before editing that layer: ## P3 device-domain boundary (2026-11-16 user direction) The existing Device Daemon now shares device control between authenticated Binder and adh.device/1 USB RPC. Installation identity, module/app/process discovery, scope, certificates and the Host endpoint remain device coordination, never analysis. The phone exposes only an authenticated abstract UDS in this slice, no HTTP/MCP/database/TCP listener. Host device:UUID controls fence writes; legacy target sessions have no inferred device association. See docs/P3_DEVICE_DOMAIN.md for capability limits and explicit unverified Android/SELinux paths. P4 pairing/TLS and agent local routing are not delivered by the P3 JVM tests. Keep current sessions and their transport mappings untouched during host-only validation. + +## P4 opt-in LAN boundary (2026-11-16 user direction) + +The P4 user request extends the P3 UDS-only transport boundary with an explicitly enabled TLS listener in the existing Device Daemon. Trusted USB enrolls Host public keys; every LAN capability dispatch checks its durable grant. Never accept the USB token over LAN, weaken the installation-key pin, reconnect/replay writes automatically, or silently route an unmigrated device/LAN request through legacy ADB. Device analysis/HTTP/MCP/database red lines remain unchanged. Connection recovery and authorization reductions are narrowly classified exceptions to unknown quarantine; they cannot dispatch ordinary device modifications. Preserve original unknown history and require observed versions for human resolution. See docs/P4_LAN_AUTH.md for the tested matrix and unverified Android hardware boundary. diff --git a/CLAUDE.md b/CLAUDE.md index 5780726..f2b31ef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -170,3 +170,7 @@ Each layer has a `MAP.md` — read it before editing that layer: ## P3 device-domain boundary (2026-11-16 user direction) The existing Device Daemon now shares device control between authenticated Binder and adh.device/1 USB RPC. Installation identity, module/app/process discovery, scope, certificates and the Host endpoint remain device coordination, never analysis. The phone exposes only an authenticated abstract UDS in this slice, no HTTP/MCP/database/TCP listener. Host device:UUID controls fence writes; legacy target sessions have no inferred device association. See docs/P3_DEVICE_DOMAIN.md for capability limits and explicit unverified Android/SELinux paths. P4 pairing/TLS and agent local routing are not delivered by the P3 JVM tests. Keep current sessions and their transport mappings untouched during host-only validation. + +## P4 opt-in LAN boundary (2026-11-16 user direction) + +The P4 user request extends the P3 UDS-only transport boundary with an explicitly enabled TLS listener in the existing Device Daemon. Trusted USB enrolls Host public keys; every LAN capability dispatch checks its durable grant. Never accept the USB token over LAN, weaken the installation-key pin, reconnect/replay writes automatically, or silently route an unmigrated device/LAN request through legacy ADB. Device analysis/HTTP/MCP/database red lines remain unchanged. Connection recovery and authorization reductions are narrowly classified exceptions to unknown quarantine; they cannot dispatch ordinary device modifications. Preserve original unknown history and require observed versions for human resolution. See docs/P4_LAN_AUTH.md for the tested matrix and unverified Android hardware boundary. diff --git a/daemon/public/workbench.js b/daemon/public/workbench.js index 1a11e1a..297e642 100644 --- a/daemon/public/workbench.js +++ b/daemon/public/workbench.js @@ -51,14 +51,19 @@ $('awRefresh').onclick=()=>work(refresh);$('awScope').onchange=()=>work(async()=>{$('awAck').checked=false;await refreshControl();});$('awAck').onchange=permissions; async function refreshControl(){const resource=$('awScope').value,generation=++controlGeneration; if(s.control?.resource!==resource){s.control=null;$('awControlText').textContent='正在读取所选范围的控制状态…';$('awUncertain').hidden=true;permissions();} - const value=await client.management({action:'snapshot',resource});if(resource!==$('awScope').value||generation!==controlGeneration)return;s.control=value; + const value=await client.management({action:'snapshot',resource});if(resource!==$('awScope').value||generation!==controlGeneration)return; + if(s.control&&(s.control.revision!==value.revision||s.control.epoch!==value.epoch||s.control.hostEpoch!==value.hostEpoch))$('awAck').checked=false;s.control=value; $('awControlText').textContent=`${value.owner==='operator'?'人类持有控制':'AI 拥有控制'}${value.uncertain?' · 写入已隔离':''} · 状态版本 ${value.revision} · 控制代次 ${value.epoch} · Host 代次 ${value.hostEpoch}`; + let unknowns=$('awUnknownOperations');if(!unknowns){unknowns=element('div',undefined,'aw-row aw-spaced');unknowns.id='awUnknownOperations';$('awUncertain').append(unknowns);} + unknowns.replaceChildren(...(value.uncertainOperations||[]).map((id,n)=>button(`查看未知操作 ${n+1} · ${id.slice(0,8)}`,()=>work(()=>goOperation(id))))); + $('awAck').parentElement.lastChild.textContent='我已核对本范围全部未知操作的实际状态'; $('awUncertain').hidden=!value.uncertain;permissions();} async function control(action){const observed=s.control;if(!observed)throw Error('请先读取控制状态');await client.controlAction(observed,action,$('awAck').checked);$('awAck').checked=false;notice(action==='release'?'已交还 AI':action==='resolve'?'已记录人工核对':'已接管所选范围',action==='release'?'已失效的旧指令不会自动重放。被人工暂停的任务仍需单独恢复。':action==='resolve'?'原 unknown 记录仍保留;这不证明目标命令已停止。':'旧 AI 写入已受版本约束;查询仍可继续。','','success');await refresh();} $('awTake').onclick=()=>work(()=>control('takeover'));$('awRelease').onclick=()=>work(()=>control('release'));$('awResolve').onclick=()=>work(()=>control('resolve')); $('awUnknownDetail').onclick=()=>work(()=>goOperation(s.control.uncertain)); function addScope(resource,label){if(![...$('awScope').options].some(o=>o.value===resource))$('awScope').add(new Option(label||resource,resource));} - async function refreshAgents(){const {value}=await client.request('/api/agents');for(const a of value.filter(a=>a.online))addScope(`target:${a.sessionId}:${a.pid}:${a.uid}:${a.starttimeTicks||'legacy'}`,`${a.process||a.package} · PID ${a.pid}`);} + async function refreshAgents(){const {value}=await client.request('/api/agents');for(const a of value.filter(a=>a.online))addScope(`target:${a.sessionId}:${a.pid}:${a.uid}:${a.starttimeTicks||'legacy'}`,`${a.process||a.package} · PID ${a.pid}`); + const devices=await client.request('/api/devices');for(const d of devices.value.devices)addScope('device:'+d.deviceId,`设备 · ${d.deviceId.slice(0,8)} · ${d.online?'已连接':'离线缓存'}`);} async function refreshList(){const generation=++s.listGeneration;const value=await client.management({action:'list',limit:25,offset:s.listOffset,...filters()});if(generation!==s.listGeneration)return; $('awTaskCount').textContent=`${value.totalTasks} 项任务 · 第 ${Math.floor(s.listOffset/25)+1} 页`;$('awTaskPrev').disabled=s.listOffset===0;$('awTaskNext').disabled=value.nextTaskOffset===null; const signature=json(value.tasks)+'|'+s.taskId;if(signature===lastListRender)return;lastListRender=signature; @@ -90,9 +95,9 @@ async function goOperation(id){const {operation}=await client.management({action:'get',id});view('tasks');if(s.taskId!==operation.taskId)await selectTask(operation.taskId);await selectOperation(id);} async function selectOperation(id){s.opId=id;for(const row of $('awOperationRows').querySelectorAll('[data-operation]'))row.setAttribute('aria-selected',String(row.dataset.operation===id));s.op=null;s.resultLoaded=false;s.resultSignature='';lastOpRender='';await refreshOperation();} async function refreshOperation(force=false){if(!s.opId)return;const id=s.opId,generation=++s.operationGeneration;let {operation}=await client.management({action:'get',id});if(id!==s.opId||generation!==s.operationGeneration)return; - const signature=(operation.resultFile||'')+'|'+(operation.lateResultFile||''); + const signature=(operation.resultFile||'')+'|'+(operation.lateResultFile||'')+'|'+(operation.reconciliations||[]).map(r=>r.file).join('|'); if(s.resultLoaded&&(force||signature!==s.resultSignature)){({operation}=await client.management({action:'get',id,includeResult:true}));if(id!==s.opId||generation!==s.operationGeneration)return;s.resultSignature=signature;} - else if(s.resultLoaded){operation.result=s.op?.result;operation.lateResult=s.op?.lateResult;} + else if(s.resultLoaded){operation.result=s.op?.result;operation.lateResult=s.op?.lateResult;operation.reconciliations=s.op?.reconciliations;} s.op=operation;const renderSignature=json(operation)+'|'+s.resultLoaded;if(renderSignature!==lastOpRender){lastOpRender=renderSignature;renderOperation();} } function facts(parent,pairs){const list=element('dl',undefined,'aw-facts');for(const [label,value]of pairs){const item=element('div');item.append(element('dt',label),element('dd',value));list.append(item);}parent.append(list);} @@ -110,6 +115,8 @@ if(op.effectsDropped)effects.append(element('p',`日志达到 64 条上限;另有 ${op.effectsDropped} 条派发步骤未逐条保存,不能把当前列表当成全部证据。`,'aw-muted aw-spaced'));area.append(effects); const results=element('section',undefined,'aw-detail-section');results.append(element('h3','已保存结果与晚到证据'));if(!s.resultLoaded)results.append(button('加载已保存结果',()=>work(async()=>{s.resultLoaded=true;await refreshOperation(true);}),'aw-spaced')); else {for(const [key,label]of [['result','原始结果'],['lateResult','晚到结果(不改变原终态)']]){const box=element('div',undefined,'aw-result-block');box.append(element('h3',label));if(op[key]===undefined)box.append(element('p','尚无已保存内容;不代表目标没有执行。'));else {const raw=json(op[key]);box.append(element('pre',raw.length>120000?raw.slice(0,120000)+'\n…界面预览已截断':raw));if(raw.length>120000)box.append(element('p','界面预览限制 120000 字符,下载可查看全部已保存内容。'));if(op[key]?.omitted)box.append(element('p','Host 只保存了结果摘要,下载文件也不包含被省略的原始数据。'));box.append(button('下载'+label,()=>download(op[key],`${op.id}-${key}.json`)));}results.append(box);}} + if(op.reconciliations?.length){results.append(element('p',`已保存 ${op.reconciliations.length} 次设备对账;查询没有重放指令,也不改变 Host 原终态。`,'aw-muted aw-spaced')); + if(s.resultLoaded)for(const [index,record]of op.reconciliations.entries()){const box=element('div',undefined,'aw-result-block');box.append(element('h3',`设备对账证据 ${index+1}(保留原终态)`));const raw=json(record.evidence);box.append(element('pre',raw.length>120000?raw.slice(0,120000)+'\n…界面预览已截断':raw));box.append(button('下载设备对账证据',()=>download(record,`${op.id}-reconciliation-${index+1}.json`)));results.append(box);}} area.append(results);permissions(); } function buildFields(){const groups=new Map();for(const field of M.fields){if(!groups.has(field.group)){const fieldset=element('fieldset');fieldset.append(element('legend',field.group));const content=element('div',undefined,'aw-fields');fieldset.append(content);groups.set(field.group,{fieldset,content});} diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index 683eee0..40f54ec 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -132,3 +132,7 @@ Shared injection-backend matrix: `backendMatrix()` (sessions by entry + Zygisk p ### P3 设备域 `devices.ts` 持久保存安装身份并管理临时连接,`device_protocol.ts` 提供 adh.device/1 codec/签名与预算,`transport/adb_device.ts` 只负责显式发现、固定 ADB transport、USB bootstrap 和自有 forward。`device_host.ts` 延迟初始化;MCP devices / `http/routes_devices.ts` 共用它与 operation_registry。`operations.ts` 的 device:UUID 范围不等于旧 target session;二者未关联时保守互斥,人类持有与 unknown 都不能跨边界绕过。见 docs/P3_DEVICE_DOMAIN.md。不要把 legacy agent 的 serial 或 Host 上唯一设备当成已验证身份。 + +### P4 LAN 与对账 + +`transport/device_transport.ts` 抽象认证流,`lan_device.ts` 强制 TLS/SPKI 固定与客户端挑战证明,不导入 ADB。`device_client_identity.ts` 在显式 pair 时排他发布持久密钥,禁止自动轮换;私钥不进入任务或设备缓存。`device_host.ts` 的 reconcile 校验操作归属/完整结果集合,再由 operations 保存独立证据文件,原终态和控制隔离保留。operation_registry 静态区分 connectionOnly/securityOnly,恢复与安全收缩不能变成普通设备写入;给旧工具/路由添加设备/LAN 选择会明确 unsupported。工作台显示最近对账及多个 unknown,元数据版本变化清除人工确认。详见 docs/P4_LAN_AUTH.md;LAN 发现仅列已知端点,不扫描。 diff --git a/daemon/src/device_client_identity.ts b/daemon/src/device_client_identity.ts new file mode 100644 index 0000000..cda1a05 --- /dev/null +++ b/daemon/src/device_client_identity.ts @@ -0,0 +1,32 @@ +import {existsSync,readFileSync,linkSync,unlinkSync} from 'node:fs'; +import {randomUUID} from 'node:crypto'; +import {createHash,createPublicKey,createPrivateKey,generateKeyPairSync,sign,verify} from 'node:crypto'; +import {atomicWriteJson} from './storage.ts'; +import {deviceFail} from './device_protocol.ts'; + +export interface ClientIdentity {schemaVersion:1;clientId:string;publicKey:string;privateKey:string} +/** One explicit Host client key. Never stored in a task, device cache, response or tool arguments. */ +export class DeviceClientIdentity { + readonly file:string; + constructor(file:string){this.file=file;} + read():ClientIdentity { + try{ + const raw=readFileSync(this.file);if(raw.length>16384)throw Error();const value=JSON.parse(raw.toString()) as ClientIdentity; + const key=createPrivateKey(value.privateKey),publicKey=createPublicKey(key).export({type:'spki',format:'der'}) as Buffer; + if(value.schemaVersion!==1||publicKey.toString('base64')!==value.publicKey||createHash('sha256').update(publicKey).digest('hex')!==value.clientId)throw Error(); + const parsed=createPublicKey({key:Buffer.from(value.publicKey,'base64'),format:'der',type:'spki'}); + if(parsed.asymmetricKeyType!=='rsa'||(parsed.asymmetricKeyDetails?.modulusLength||0)<2048||!verify('sha256',Buffer.from('client-key-check'),parsed,sign('sha256',Buffer.from('client-key-check'),key)))throw Error();return value; + }catch{deviceFail('CLIENT_IDENTITY_UNAVAILABLE','Host client key is absent or invalid; pair through trusted USB, never regenerate an existing identity automatically');} + } + ensure():ClientIdentity { + if(!existsSync(this.file)){ + const {publicKey,privateKey}=generateKeyPairSync('rsa',{modulusLength:2048});const der=publicKey.export({type:'spki',format:'der'}) as Buffer; + const temporary=this.file+'.'+randomUUID()+'.new'; + try{ + atomicWriteJson(temporary,{schemaVersion:1,clientId:createHash('sha256').update(der).digest('hex'),publicKey:der.toString('base64'),privateKey:privateKey.export({type:'pkcs8',format:'pem'})}); + try{linkSync(temporary,this.file);}catch(error){if((error as any).code!=='EEXIST')throw error;} + }finally{try{unlinkSync(temporary);}catch{}} + } + return this.read(); + } +} diff --git a/daemon/src/device_host.ts b/daemon/src/device_host.ts index d1a27de..d3e914d 100644 --- a/daemon/src/device_host.ts +++ b/daemon/src/device_host.ts @@ -11,8 +11,26 @@ export async function deviceAction(a:any){ const service=getDevices(); switch(a.action||'list'){ case 'list':return {ok:true,...service.list()}; - case 'discover':return {ok:true,...await service.discover()}; - case 'connect':return service.connect(String(a.serial||''),a.transportId,a.expectedDeviceId); + case 'discover':return {ok:true,...await service.discover(a.transport)}; + case 'connect':{ + if(a.transport==='lan')return service.connectLan(a.deviceId,a.address,a.port); + if(a.transport&&a.transport!=='adb')return deviceFail('UNSUPPORTED_TRANSPORT','only adb and paired LAN are implemented'); + return service.connect(String(a.serial||''),a.transportId,a.expectedDeviceId); + } + case 'pair':return service.pair(a); + case 'reconcile':{ + const engine=getOperations(),ids=a.operationIds; + if(!Array.isArray(ids)||ids.length<1||ids.length>100)return deviceFail('INVALID_ARGUMENT','select 1..100 Host device mutation ids'); + for(const id of ids){const op=engine.getOperation(id);if(op.resource!=='device:'+a.deviceId||op.name!=='devices'||op.mode!=='write'||op.connectionOnly)return deviceFail('TARGET_CHANGED','operation belongs to another device or is not a device mutation');} + const result=await service.reconcile(a.deviceId,ids,a.connectionId); + const rows=result.result?.operations; + if(!Array.isArray(rows)||rows.length!==ids.length||new Set(rows.map((r:any)=>r.operationId)).size!==ids.length||rows.some((r:any)=>!ids.includes(r.operationId)))return deviceFail('RECONCILIATION_INVALID','device did not return the exact requested operation set; no evidence attached'); + const reconciled=rows.map((evidence:any)=>{ + const op=engine.recordDeviceReconciliation(evidence.operationId,a.deviceId,{...evidence,observedOn:{bootId:result.bootId,connectionId:result.connectionId},notFoundDoesNotProveUnsent:true,replayed:false}); + return {operationId:op.id,hostState:op.state,deviceEvidence:evidence}; + }); + return {ok:true,deviceId:a.deviceId,reconciled,replayed:false,hostStateUnchanged:true}; + } case 'disconnect':return service.disconnect(a.deviceId,a.connectionId); case 'info':return service.call({...a,method:'device.info'}); case 'capabilities':return service.call({...a,method:'device.capabilities'}); diff --git a/daemon/src/device_protocol.ts b/daemon/src/device_protocol.ts index 63b9152..04d0da1 100644 --- a/daemon/src/device_protocol.ts +++ b/daemon/src/device_protocol.ts @@ -7,8 +7,8 @@ import { OperationError } from './execution_context.ts'; export const DEVICE_PROTOCOL='adh.device/1', DEVICE_SOCKET='adh_device_rpc_v1'; export const DEVICE_BOOTSTRAP='/data/adb/adh/device-rpc/usb-access.json'; export const DEVICE_FRAME_MAX=1024*1024; -export const DEVICE_READ_METHODS=new Set(['device.info','device.capabilities','device.state','module.status','scope.get','applications.list','processes.list','certificates.list','host.get','operations.get']); -export const DEVICE_WRITE_METHODS=new Set(['scope.patch','scope.replace','process.control','certificates.put','certificates.delete','host.set','operations.resolve']); +export const DEVICE_READ_METHODS=new Set(['device.info','device.capabilities','device.state','module.status','scope.get','applications.list','processes.list','certificates.list','host.get','operations.get','operations.reconcile','lan.status','pairings.list']); +export const DEVICE_WRITE_METHODS=new Set(['scope.patch','scope.replace','process.control','certificates.put','certificates.delete','host.set','operations.resolve','lan.configure','pairings.grant','pairings.revoke']); export const uuid=(value:unknown):value is string=>typeof value==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value); export class DeviceError extends OperationError {} export function deviceFail(code:string,message:string,uncertain=false):never{throw new DeviceError(code,message,uncertain);} diff --git a/daemon/src/devices.ts b/daemon/src/devices.ts index c32fe57..ccff6a9 100644 --- a/daemon/src/devices.ts +++ b/daemon/src/devices.ts @@ -1,32 +1,50 @@ import {existsSync,readFileSync} from 'node:fs'; import {atomicWriteJson} from './storage.ts'; -import {AdbDeviceTransport,type AdbConnection} from './transport/adb_device.ts'; +import {dirname,join} from 'node:path'; +import {AdbDeviceTransport} from './transport/adb_device.ts'; +import {LanDeviceTransport,type LanEnrollment} from './transport/lan_device.ts'; +import type {DeviceConnection} from './transport/device_transport.ts'; +import {DeviceClientIdentity} from './device_client_identity.ts'; import {DeviceError,deviceFail,deviceMethodMode,uuid,type DevicePeer} from './device_protocol.ts'; import {checkpoint,executionContext} from './execution_context.ts'; -interface DeviceRecord {deviceId:string;identityFingerprint:string;lastPeer:DevicePeer;lastSeen:number} +interface DeviceRecord {deviceId:string;identityFingerprint:string;lastPeer:DevicePeer;lastSeen:number;pairing?:LanEnrollment;lanEndpoint?:{address:string;port:number}} /** Device identity is persistent; transport connections are deliberately ephemeral and replaceable. */ export class Devices { private file:string;readonly adapter:AdbDeviceTransport;private generationChanged:(deviceId:string)=>void; + readonly clientIdentity:DeviceClientIdentity;readonly lan:LanDeviceTransport; private records:Record={}; - private connections=new Map(); - constructor(file:string,adapter=new AdbDeviceTransport(),generationChanged:(deviceId:string)=>void=()=>{}) { + private connections=new Map(); + constructor(file:string,adapter=new AdbDeviceTransport(),generationChanged:(deviceId:string)=>void=()=>{},lan=new LanDeviceTransport()) { this.file=file;this.adapter=adapter;this.generationChanged=generationChanged; + this.clientIdentity=new DeviceClientIdentity(join(dirname(file),'device-client.json'));this.lan=lan; if(existsSync(file)){ const value=JSON.parse(readFileSync(file,'utf8'));if(!value||value.schemaVersion!==1||!value.devices||Array.isArray(value.devices)||typeof value.devices!=='object')deviceFail('DEVICE_REGISTRY_CORRUPT','authoritative device registry cannot be rebuilt automatically'); for(const [id,record]of Object.entries(value.devices) as [string,DeviceRecord][]){if(!uuid(id)||id!==record.deviceId||!/^[a-f0-9]{64}$/.test(record.identityFingerprint))deviceFail('DEVICE_REGISTRY_CORRUPT','invalid saved device identity');} this.records=value.devices; } } - list(){return {devices:Object.values(this.records).map(record=>({deviceId:record.deviceId,identityFingerprint:record.identityFingerprint,lastSeen:record.lastSeen,lastKnown:record.lastPeer, + list(){return {devices:Object.values(this.records).map(record=>({deviceId:record.deviceId,identityFingerprint:record.identityFingerprint,lastSeen:record.lastSeen,lastKnown:record.lastPeer,pairing:record.pairing?{...record.pairing,authorization:'cached enrollment; device rechecks every LAN request'}:undefined,lanEndpoint:record.lanEndpoint, online:[...this.connections.values()].some(c=>c.peer.deviceId===record.deviceId&&!c.rpc.stream.destroyed),connections:[...this.connections.values()].filter(c=>c.peer.deviceId===record.deviceId).map(c=>this.connectionView(c))})), legacyAgentAssociation:'unverified; no session is assigned by ADB serial',discoveryIsExplicit:true};} - private connectionView(c:AdbConnection){return {connectionId:c.id,transport:c.transport,serial:c.serial,transportId:c.transportId,deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId,identityVerified:true,online:!c.rpc.stream.destroyed};} - async discover(){return {transports:await this.adapter.discover(),...this.list()};} + private connectionView(c:DeviceConnection){return {connectionId:c.id,transport:c.transport,serial:c.serial,transportId:c.transportId,address:c.address,port:c.transport==='lan'?c.port:undefined,grantId:c.grantId,tlsVersion:c.tlsVersion,deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId,identityVerified:true,online:!c.rpc.stream.destroyed};} + async discover(transport='adb'){ + if(transport==='lan')return {transports:Object.values(this.records).filter(r=>r.lanEndpoint).map(r=>({transport:'lan',deviceId:r.deviceId,...r.lanEndpoint,state:'last-known; not probed'})),...this.list()}; + if(transport!=='adb')deviceFail('UNSUPPORTED_TRANSPORT','only adb and paired LAN are implemented');return {transports:await this.adapter.discover(),...this.list()}; + } async connect(serial:string,transportId?:string,expectedDeviceId?:string){ - let connection:AdbConnection|undefined; + const connection=await this.adapter.connect(serial,transportId); + return this.register(connection,expectedDeviceId); + } + async connectLan(deviceId:string,address?:string,port?:number){ + const record=this.records[deviceId];if(!record?.pairing)deviceFail('DEVICE_NOT_PAIRED','enroll this Host key over trusted USB before LAN; no ADB fallback'); + const endpoint={address:address??record.lanEndpoint?.address,port:port??record.lanEndpoint?.port}; + const identity=this.clientIdentity.read(),ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'lan',action:'TLS connection.authenticate'}); + try{const result=await this.register(await this.lan.connect(record.lastPeer,record.pairing,identity,endpoint.address!,endpoint.port!),deviceId);ctx?.acknowledged(false,effect);return result;} + catch(error){ctx?.acknowledged((error as any).uncertain===true,effect,true);throw error;} + } + private async register(connection:DeviceConnection,expectedDeviceId?:string){ // Keep closed handles for explicit, verified forward cleanup; never silently reconnect. - connection=await this.adapter.connect(serial,transportId); try{ if(expectedDeviceId&&connection.peer.deviceId!==expectedDeviceId)deviceFail('DEVICE_MISMATCH','USB endpoint is another device; no target operations were attempted'); const id=connection.peer.deviceId,previous=this.records[id]; @@ -35,11 +53,39 @@ export class Devices { if(live.some(c=>c.peer.bootId!==connection!.peer.bootId||c.peer.daemonInstanceId!==connection!.peer.daemonInstanceId))deviceFail('IDENTITY_COLLISION','same device id claims two live boot/daemon generations'); checkpoint(); if(previous&&(previous.lastPeer.bootId!==connection.peer.bootId||previous.lastPeer.daemonInstanceId!==connection.peer.daemonInstanceId))this.generationChanged(id); - const candidate={...this.records,[id]:{deviceId:id,identityFingerprint:connection.peer.identityFingerprint,lastPeer:connection.peer,lastSeen:Date.now()}}; + const candidate={...this.records,[id]:{...previous,deviceId:id,identityFingerprint:connection.peer.identityFingerprint,lastPeer:connection.peer,lastSeen:Date.now(),...(connection.transport==='lan'?{lanEndpoint:{address:connection.address!,port:connection.port}}:{})}}; atomicWriteJson(this.file,{schemaVersion:1,devices:candidate});this.records=candidate;this.connections.set(connection.id,connection); return {ok:true,...this.connectionView(connection),identity:connection.peer}; }catch(error){try{if(!(await connection.close()).confirmed)throw Error();}catch{throw new DeviceError('FORWARD_CLEANUP_UNCONFIRMED','device registration failed and owned forward cleanup is unconfirmed',true);}throw error;} } + async pair(args:any){ + const c=this.connection(args.deviceId,args.connectionId); + if(c.transport!=='adb')deviceFail('TRUSTED_USB_REQUIRED','Host key enrollment requires a verified USB bootstrap'); + const ctx=executionContext.getStore();checkpoint(); + if(!ctx?.operationId||ctx.resource!=='device:'+args.deviceId||ctx.connectionOnly)deviceFail('OPERATION_REQUIRED','pairing must use a device mutation operation'); + const effect=ctx.dispatched({kind:'host',action:'device.client.identity'}); + let identity;try{identity=this.clientIdentity.ensure();ctx.acknowledged(false,effect);}catch(error){ctx.acknowledged(false,effect,true);throw error;} + let result:any; + if(args.grantId){ + const observed=await this.call({...args,method:'pairings.list'}); + const grant=observed.result.grants.find((g:any)=>g.grantId===args.grantId&&g.clientId===identity.clientId&&!g.revokedAt); + if(!grant)deviceFail('PAIRING_NOT_FOUND','USB did not confirm this Host key and active grant'); + result={ok:true,deviceId:args.deviceId,result:{result:grant},adopted:true}; + }else result=await this.call({...args,method:'pairings.grant',params:{publicKey:identity.publicKey,label:args.label||'ADH Host',permissions:args.permissions||['read','write']}}); + if(result.ok){ + const effect=ctx.dispatched({kind:'host',action:'device.enrollment.persist'}); + try{ + const grant=result.result.result;if(!grant?.grantId||grant.clientId!==identity.clientId)throw Error(); + const candidate={...this.records,[args.deviceId]:{...this.records[args.deviceId],pairing:{grantId:grant.grantId,clientId:grant.clientId,permissions:grant.permissions}}}; + atomicWriteJson(this.file,{schemaVersion:1,devices:candidate});this.records=candidate;ctx.acknowledged(false,effect); + }catch{ctx.acknowledged(true,effect,true);deviceFail('PAIRING_UNCONFIRMED','device granted access but Host enrollment persistence is unconfirmed; inspect pairings.list over USB',true);} + } + return result; + } + async reconcile(deviceId:string,operationIds:string[],connectionId?:string){ + if(!Array.isArray(operationIds)||operationIds.length<1||operationIds.length>100||operationIds.some(id=>typeof id!=='string'||!/^[\w-]{1,128}$/.test(id)))deviceFail('INVALID_ARGUMENT','select 1..100 recorded Host operation ids'); + return this.call({deviceId,connectionId,method:'operations.reconcile',params:{operationIds}}); + } private connection(deviceId:string,connectionId?:string,includeClosed=false){ if(!uuid(deviceId))deviceFail('DEVICE_REQUIRED','select a verified deviceId, not an ADB serial'); const matches=[...this.connections.values()].filter(c=>c.peer.deviceId===deviceId&&(includeClosed||!c.rpc.stream.destroyed)&&(!connectionId||c.id===connectionId)); @@ -55,10 +101,13 @@ export class Devices { const c=this.connection(args.deviceId,args.connectionId),mode=deviceMethodMode(args.method); if(args.budgetMs!==undefined&&(!Number.isInteger(args.budgetMs)||args.budgetMs<1||args.budgetMs>60000))deviceFail('INVALID_ARGUMENT','device budget must be an integer in 1..60000 ms'); if(args.params!==undefined&&(!args.params||Array.isArray(args.params)||typeof args.params!=='object'))deviceFail('INVALID_ARGUMENT','device params must be an object'); - if(c.peer.capabilities.methods[args.method]!==mode)deviceFail('CAPABILITY_UNSUPPORTED','connected device does not advertise this capability'); + if(c.peer.capabilities.deniedMethods?.includes(args.method))deviceFail('PERMISSION_DENIED','paired client is not authorized for this capability'); + if(c.peer.capabilities.methods[args.method]!==mode)deviceFail('CAPABILITY_UNSUPPORTED','connected device does not advertise this capability; no fallback'); const ctx=executionContext.getStore();checkpoint(); if(mode==='write'){ if(!ctx?.operationId)deviceFail('OPERATION_REQUIRED','device mutations must enter the shared Host operation coordinator'); + if(ctx.connectionOnly)deviceFail('OPERATION_REQUIRED','connection recovery cannot dispatch device mutations'); + if(ctx.securityOnly&&!(args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false))deviceFail('OPERATION_REQUIRED','quarantined security control can only revoke grants or disable LAN'); if(ctx.resource!=='device:'+args.deviceId)deviceFail('TARGET_CHANGED','Host operation is bound to another resource; no cross-device dispatch'); if(args.bootId!==c.peer.bootId||args.daemonInstanceId!==c.peer.daemonInstanceId)deviceFail('TARGET_CHANGED','send the observed device bootId and daemonInstanceId; no automatic rebinding'); if(!Number.isSafeInteger(args.expectedDeviceRevision)||args.expectedDeviceRevision < 0)deviceFail('DEVICE_VERSION_REQUIRED','send the observed device stateRevision'); diff --git a/daemon/src/execution_context.ts b/daemon/src/execution_context.ts index 4983220..f0a285b 100644 --- a/daemon/src/execution_context.ts +++ b/daemon/src/execution_context.ts @@ -7,6 +7,8 @@ export class OperationError extends Error { export interface ExecutionContext { operationId?: string; resource?: string; + connectionOnly?: boolean; + securityOnly?: boolean; principalRole?: 'ai' | 'operator'; remainingMs?(): number; checkpoint(session?: string): void; diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 6dc1651..48d7f7d 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -405,7 +405,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h ]; // Optional at schema level because reads need no control token; writes enforce it at dispatch. -MCP_TOOLS.push({name:'devices',description:'Device-domain discovery, verified installation identities and USB/ADB RPC. list is cached/offline-safe; discover lists ADB transports without attaching targets; connect requires an explicit serial/transportId and creates only its own ADB forward. info/capabilities query a verified deviceId. call uses advertised device methods; writes require observed bootId, daemonInstanceId, expectedDeviceRevision plus Host _operation versions. Read scope.get before scope.patch and supply params.scopeRevision. Device and connection ids are distinct from legacy agent session ids; no association or ADB fallback is guessed. TLS/LAN, agent routing and arbitrary shell are unsupported in P3. Unknown effects must be inspected, never replayed.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','info','capabilities','call']},serial:S,transportId:S,expectedDeviceId:S,deviceId:S,connectionId:S,method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); +MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); for (const tool of MCP_TOOLS) { const metadata=(tool.inputSchema as any).properties._operation ??= { type:'object' }; metadata.properties ??= { expectedRevision:{type:'integer'},controlEpoch:{type:'integer'},hostEpoch:{type:'integer'},taskId:{type:'string'},idempotencyKey:{type:'string'},timeoutMs:{type:'integer'},expectedTaskRevision:{type:'integer'} }; diff --git a/daemon/src/operation_registry.ts b/daemon/src/operation_registry.ts index cb64791..5f44158 100644 --- a/daemon/src/operation_registry.ts +++ b/daemon/src/operation_registry.ts @@ -1,6 +1,7 @@ import {deviceMethodMode} from './device_protocol.ts'; +import {OperationError} from './execution_context.ts'; export type Mode = 'read' | 'analysis' | 'write'; -export interface OperationSpec { name: string; mode: Mode; session?: string; global?: boolean; deviceId?: string } +export interface OperationSpec { name: string; mode: Mode; session?: string; global?: boolean; deviceId?: string; connectionOnly?:boolean; securityOnly?:boolean } const readTools = new Set([ 'analysis_guide','process_list','backends','capabilities','dumps_list','runtime_diagnostics','agent_ping', 'memory_maps','maps_query','memory_read','memory_disasm','memory_search','memory_scan_magic','got_enum', @@ -23,9 +24,10 @@ const readActions: Record = { export function describeTool(name: string, args: Record = {}): OperationSpec { if(name==='devices'){ const action=args.action||'list'; - const mode:Mode=['list','discover','info','capabilities'].includes(action)?'read':action==='call'?deviceMethodMode(args.method):'write'; - return {name,mode,deviceId:['connect','list','discover'].includes(action)?undefined:args.deviceId,global:action==='connect'||!args.deviceId}; + const mode:Mode=['list','discover','info','capabilities'].includes(action)?'read':action==='reconcile'?'analysis':action==='call'?deviceMethodMode(args.method):'write'; + return {name,mode,deviceId:['list','discover'].includes(action)||action==='connect'&&args.transport!=='lan'?undefined:args.deviceId,global:action==='connect'&&args.transport!=='lan'||!args.deviceId,connectionOnly:['connect','disconnect'].includes(action),securityOnly:action==='call'&&(args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false)}; } + if(name!=='operations'&&(Object.hasOwn(args,'deviceId')||Object.hasOwn(args,'connectionId')||args.transport==='lan'))throw new OperationError('UNSUPPORTED_DEVICE_ROUTING','this legacy tool has no verified device/LAN route; use devices capabilities, never fall back to ADB'); let mode: Mode = readTools.has(name) ? 'read' : analysisTools.has(name) ? 'analysis' : 'write'; if (Object.hasOwn(readActions,name) && readActions[name].includes(args.action)) mode = 'read'; if (name === 'settings') mode = args.action === 'get' || args.action === 'maintenance' && args.dryRun !== false ? 'read' : 'write'; @@ -58,6 +60,7 @@ const analysisPaths = new Set(['/api/native/syscall_scan','/api/native/crypto_co '/api/unpack/dump-one','/api/unpack/dump-so-one','/api/unpack/pull-so','/api/unpack/dump-all','/api/unpack/dump-so']); export function describeHttp(path: string, method: string, args: Record = {}): OperationSpec { if(path==='/api/devices')return describeTool('devices',args); + if(Object.hasOwn(args,'deviceId')||Object.hasOwn(args,'connectionId')||args.transport==='lan')throw new OperationError('UNSUPPORTED_DEVICE_ROUTING','this legacy route has no verified device/LAN route; no ADB fallback'); const alias = routeTools[path]; if (path === '/api/config') return describeTool('settings', { ...args, action: method === 'POST' ? 'patch' : 'get' }); if (path === '/api/scope') return describeTool(method === 'POST' ? 'scope_set' : 'scope_list', args); diff --git a/daemon/src/operations.ts b/daemon/src/operations.ts index aa913bb..c1a0a27 100644 --- a/daemon/src/operations.ts +++ b/daemon/src/operations.ts @@ -63,7 +63,7 @@ export class Operations { for(const effect of op.effects || [])if(effect.state==='dispatched'){effect.state='unknown';effect.uncertainAt=Date.now();} let control = data.controls[op.resource]; if (control?.active === op.id) delete control.active; - if (op.mode === 'write' && op.state === 'unknown') (control ??= data.controls[op.resource] = freshControl()).uncertain = op.id; + if (op.mode === 'write' && op.state === 'unknown') {control ??= data.controls[op.resource]=freshControl();control.uncertain ||= op.id;control.revision++;} if (data.tasks[op.taskId]) {data.tasks[op.taskId].state = op.state === 'unknown' ? 'unknown' : 'paused';touchTask(data.tasks[op.taskId]);} } data.hosts[this.host] = { pid: process.pid, hostname: hostname(), active: true }; @@ -72,7 +72,7 @@ export class Operations { snapshot(resource = 'host') { validResource(resource); const data = this.store.read(), control = data.controls[resource] ?? freshControl(); - return { resource, ...control, hostEpoch: data.controls.host.epoch }; + return { resource, ...control, hostEpoch: data.controls.host.epoch,uncertainOperations:Object.values(data.operations).filter(op=>op.resource===resource&&op.mode==='write'&&op.state==='unknown'&&!op.resolvedAt).map(op=>op.id) }; } resource(spec: OperationSpec) {const resource=spec.deviceId?'device:'+spec.deviceId:spec.global || !spec.session ? 'host' : this.targetResource(spec.session);validResource(resource);return resource;} invalidateResource(resource:string){ @@ -125,11 +125,10 @@ export class Operations { else if (action === 'resolve') { if (!acknowledge) fail('ACKNOWLEDGEMENT_REQUIRED', 'inspect actual state and acknowledge unknown side effects explicitly'); if (control.active) fail('OPERATION_RUNNING', 'a Host handler is still running; its later effects cannot be released'); - const uncertain = control.uncertain && data.operations[control.uncertain]; - if (uncertain && !uncertain.settled && data.hosts[uncertain.host]?.active) fail('OPERATION_RUNNING','a timed-out handler is still awaiting target completion'); + const unknowns = Object.values(data.operations).filter(op=>op.resource===resource&&op.mode==='write'&&op.state==='unknown'&&!op.resolvedAt); + if (unknowns.some(op=>!op.settled&&data.hosts[op.host]?.active)) fail('OPERATION_RUNNING','a timed-out handler is still awaiting target completion'); delete control.uncertain; control.epoch++; control.revision++; - if(uncertain)uncertain.resolvedAt=Date.now(); - if(uncertain && data.tasks[uncertain.taskId]?.state==='unknown'){data.tasks[uncertain.taskId].state='paused';touchTask(data.tasks[uncertain.taskId]);} + for(const uncertain of unknowns){uncertain.resolvedAt=Date.now();if(data.tasks[uncertain.taskId]?.state==='unknown'){data.tasks[uncertain.taskId].state='paused';touchTask(data.tasks[uncertain.taskId]);}} } else fail('INVALID_ACTION', 'control action must be takeover|pause|release|resolve'); return { resource, ...control, hostEpoch: data.controls.host.epoch }; }); @@ -171,7 +170,7 @@ export class Operations { const op: Operation = { id: randomUUID(), taskId: task.id, name: spec.name, resource, mode: spec.mode, owner: principal.role, actorId: principal.id, source: principal.source, host: this.host, state: 'queued', createdAt: Date.now(), updatedAt: Date.now(), deadline: Date.now() + timeout, ...expected, key, fingerprint, mayHaveExecuted: false, inFlight: 0, - uncertainEffect: false, cancelRequested: false, settled: false,effects:[],effectsDropped:0 }; + uncertainEffect: false, cancelRequested: false, settled: false,effects:[],effectsDropped:0,connectionOnly:spec.connectionOnly===true,securityOnly:spec.securityOnly===true }; data.operations[op.id] = op; return op; }); if (operation.host === this.host && operation.state === 'queued' && !this.completions.has(operation.id)) { @@ -193,8 +192,15 @@ export class Operations { const out: any = structuredClone(op); if (includeResult && op.resultFile) out.result = JSON.parse(readFileSync(op.resultFile, 'utf8')); if (includeResult && op.lateResultFile) out.lateResult = JSON.parse(readFileSync(op.lateResultFile, 'utf8')); + if (includeResult && op.reconciliations) out.reconciliations=op.reconciliations.map(r=>({...r,evidence:JSON.parse(readFileSync(r.file,'utf8'))})); return out; } + recordDeviceReconciliation(id:string,deviceId:string,evidence:any){ + const op=this.getOperation(id);if(op.resource!=='device:'+deviceId||op.name!=='devices'||op.mode!=='write'||op.connectionOnly)fail('TARGET_CHANGED','reconciliation must name a device mutation on this device'); + const file=this.saveResult(`${id}.reconcile.${randomUUID()}`,evidence); + this.store.update(data=>{const current=data.operations[id];(current.reconciliations??=[]).push({at:Date.now(),deviceId,file});if(current.reconciliations.length>8)current.reconciliations.shift();current.updatedAt=Date.now();touchTask(data.tasks[current.taskId]);}); + return this.getOperation(id,true); // preserve unknown/error/control history + } findOperation(key: string, principal: Principal, includeResult = false) { const op=Object.values(this.store.read().operations).find(op=>op.key===key && op.owner===principal.role); if(!op)fail('OPERATION_NOT_FOUND','no operation is recorded for this intent key; pending transport is not proof of non-execution'); @@ -284,7 +290,7 @@ export class Operations { if(state==='unknown')for(const effect of op.effects || [])if(effect.state==='dispatched'){effect.state='unknown';effect.uncertainAt=Date.now();} const control = data.controls[op.resource]; if (control?.active === id) delete control.active; - if (op.mode === 'write' && state === 'unknown') (data.controls[op.resource] ??= freshControl()).uncertain = id; + if (op.mode === 'write' && state === 'unknown') {const c=data.controls[op.resource]??=freshControl();c.uncertain ||= id;c.revision++;} const task = data.tasks[op.taskId]; if (state === 'unknown') task.state = 'unknown'; else if (task.state === 'cancel_requested' && !Object.values(data.operations).some(x => x.taskId === task.id && !terminal.has(x.state))) { @@ -324,7 +330,7 @@ export class Operations { this.assertVersion(data,op.resource,{role:op.owner,id:op.actorId,source:op.source},op); const control = data.controls[op.resource] ??= freshControl(); if(Object.entries(data.controls).some(([key,c])=>c.active && resourcesConflict(op.resource,key)))fail('OPERATION_BUSY','resource is in use by another Host operation'); - if (Object.entries(data.controls).some(([key,c])=>c.uncertain && resourcesConflict(op.resource,key))) fail('UNKNOWN_EXECUTION','resource has unresolved side effects; inspect and resolve first'); + if (!op.connectionOnly && !op.securityOnly && Object.entries(data.controls).some(([key,c])=>c.uncertain && resourcesConflict(op.resource,key))) fail('UNKNOWN_EXECUTION','resource has unresolved side effects; inspect and resolve first'); control.revision++; control.active=op.id; op.appliedRevision=control.revision; } op.state='running'; op.startedAt=Date.now();op.updatedAt=Date.now(); return op; @@ -333,7 +339,7 @@ export class Operations { const targetEpochs = new Map(); const initial = this.store.read(); const context: ExecutionContext = { - operationId:op.id,resource:op.resource,principalRole:op.owner,remainingMs:()=>Math.max(1,op.deadline-Date.now()), + operationId:op.id,resource:op.resource,connectionOnly:op.connectionOnly,securityOnly:op.securityOnly,principalRole:op.owner,remainingMs:()=>Math.max(1,op.deadline-Date.now()), checkpoint: session => { if(this.closed)fail('HOST_CLOSED','coordinator closed'); const data=this.store.read(), current=data.operations[op.id]; diff --git a/daemon/src/task_store.ts b/daemon/src/task_store.ts index 6677733..11f0e0f 100644 --- a/daemon/src/task_store.ts +++ b/daemon/src/task_store.ts @@ -25,6 +25,9 @@ export interface Operation { key: string; fingerprint: string; mayHaveExecuted: boolean; inFlight: number; uncertainEffect: boolean; cancelRequested: boolean; settled: boolean; error?: { code: string; message: string }; resultFile?: string; lateResultFile?: string; partialEffects?: boolean; + connectionOnly?: boolean; + securityOnly?: boolean; + reconciliations?: {at:number;deviceId:string;file:string}[]; appliedRevision?: number; resolvedAt?: number; startedAt?: number; finishedAt?: number; effects?: Effect[]; effectsDropped?: number; diff --git a/daemon/src/transport/adb_device.ts b/daemon/src/transport/adb_device.ts index bf9e5d5..d1587ec 100644 --- a/daemon/src/transport/adb_device.ts +++ b/daemon/src/transport/adb_device.ts @@ -4,6 +4,7 @@ import net from 'node:net'; import { randomBytes,randomUUID } from 'node:crypto'; import { DEVICE_BOOTSTRAP,DEVICE_SOCKET,DeviceRpcClient,parseBootstrap,verifyHello,deviceFail,DeviceError,type DevicePeer } from '../device_protocol.ts'; import { checkpoint,executionContext } from '../execution_context.ts'; +import type {DeviceConnection} from './device_transport.ts'; export interface AdbDevice {serial:string;state:string;transportId?:string;model?:string;link:'usb'|'adb-tcp'|'unknown'} export type AdbRunner=(args:string[],options?:{timeout?:number;maxBuffer?:number})=>Promise; @@ -21,7 +22,7 @@ export function parseAdbDevices(raw:string):AdbDevice[]{ rows.push({serial,state,transportId:/^\d+$/.test(props.transport_id||'')?props.transport_id:undefined,model:props.model,link:props.usb?'usb':serial.includes(':')?'adb-tcp':'unknown'}); }return rows; } -export interface AdbConnection {id:string;transport:'adb';serial:string;transportId?:string;port:number;peer:DevicePeer;rpc:DeviceRpcClient;close:()=>Promise<{removed:boolean;confirmed:boolean;reason?:string}>} +export interface AdbConnection extends DeviceConnection {transport:'adb';serial:string} export class AdbDeviceTransport { readonly run:AdbRunner;private dial:(port:number)=>Promise; constructor(run:AdbRunner=realAdbRunner,dial:(port:number)=>Promise=port=>new Promise((resolve,reject)=>{ diff --git a/daemon/src/transport/device_transport.ts b/daemon/src/transport/device_transport.ts new file mode 100644 index 0000000..315696c --- /dev/null +++ b/daemon/src/transport/device_transport.ts @@ -0,0 +1,8 @@ +import type {DevicePeer,DeviceRpcClient} from '../device_protocol.ts'; +/** Business logic consumes an authenticated stream, not ADB or TLS implementation details. */ +export interface DeviceConnection { + id:string;transport:'adb'|'lan';serial?:string;transportId?:string;address?:string;port:number; + peer:DevicePeer;rpc:DeviceRpcClient;clientId?:string;grantId?:string; + tlsVersion?:string; + close():Promise<{removed:boolean;confirmed:boolean;reason?:string}>; +} diff --git a/daemon/src/transport/lan_device.ts b/daemon/src/transport/lan_device.ts new file mode 100644 index 0000000..cfee6e0 --- /dev/null +++ b/daemon/src/transport/lan_device.ts @@ -0,0 +1,43 @@ +import tls from 'node:tls'; +import {isIP} from 'node:net'; +import {randomBytes,randomUUID,createHash,sign,X509Certificate} from 'node:crypto'; +import {DEVICE_PROTOCOL,DeviceRpcClient,verifyHello,deviceFail,DeviceError,type DevicePeer} from '../device_protocol.ts'; +import type {ClientIdentity} from '../device_client_identity.ts'; +import type {DeviceConnection} from './device_transport.ts'; +import {checkpoint} from '../execution_context.ts'; + +export interface LanEnrollment {grantId:string;clientId:string;permissions:string[]} +export class LanDeviceTransport { + async connect(peer:DevicePeer,enrollment:LanEnrollment,identity:ClientIdentity,address:string,port:number):Promise{ + if(!isIP(address)||!Number.isInteger(port)||port<1||port>65535)deviceFail('INVALID_ARGUMENT','select an explicit numeric LAN address and port'); + if(enrollment.clientId!==identity.clientId)deviceFail('CLIENT_IDENTITY_MISMATCH','pairing belongs to another Host key'); + checkpoint(); + const stream=await new Promise((resolve,reject)=>{ + // Private self-signed installation PKI: TLS proof + mandatory SPKI pin replace public CA/hostname trust. + // Absolutely no RPC/client proof is sent until this pin check has succeeded. + const socket=tls.connect({host:address,port,minVersion:'TLSv1.2',rejectUnauthorized:false}); + const timer=setTimeout(()=>{socket.destroy();reject(new DeviceError('TLS_TIMEOUT','TLS connection deadline expired'));},5000); + socket.once('error',()=>{clearTimeout(timer);reject(new DeviceError('TLS_FAILED','TLS transport could not be established'));}); + socket.once('secureConnect',()=>{ + clearTimeout(timer); + try{ + const raw=socket.getPeerCertificate().raw;if(!raw||raw.length>16384)throw Error();const cert=new X509Certificate(raw); + const der=cert.publicKey.export({type:'spki',format:'der'}) as Buffer; + if(createHash('sha256').update(der).digest('hex')!==peer.identityFingerprint||!cert.verify(cert.publicKey)||Date.now()Date.parse(cert.validTo))throw Error(); + resolve(socket); + }catch{socket.destroy();reject(new DeviceError('TLS_IDENTITY_MISMATCH','TLS certificate does not match the paired installation key or validity'));} + }); + }); + const rpc=new DeviceRpcClient(stream); + try{ + checkpoint();const challenge=await rpc.request('device.challenge',{},undefined,undefined,5000); + if(challenge.deviceId!==peer.deviceId||!/^[a-f0-9]{64}$/.test(challenge.challenge))deviceFail('IDENTITY_UNVERIFIED','TLS challenge does not match selected device'); + const id=randomUUID(),nonce=randomBytes(32).toString('hex'); + const message=JSON.stringify([DEVICE_PROTOCOL,'lan-auth/1',challenge.deviceId,challenge.bootId,challenge.daemonInstanceId,challenge.challenge,nonce,id,identity.clientId,enrollment.grantId]); + const signature=sign('sha256',Buffer.from(message),identity.privateKey).toString('base64'); + const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'client-signature',clientId:identity.clientId,grantId:enrollment.grantId,signature}},undefined,undefined,5000,id); + const verified=verifyHello(reply,{schemaVersion:1,deviceId:peer.deviceId,identityFingerprint:peer.identityFingerprint,token:''},id,nonce); + return {id:randomUUID(),transport:'lan',address,port,peer:verified,rpc,tlsVersion:stream.getProtocol()||undefined,clientId:identity.clientId,grantId:enrollment.grantId,close:async()=>{rpc.close();return {removed:false,confirmed:true};}}; + }catch(error){rpc.close();throw error;} + } +} diff --git a/daemon/test/device_client_identity.test.ts b/daemon/test/device_client_identity.test.ts new file mode 100644 index 0000000..a8259a9 --- /dev/null +++ b/daemon/test/device_client_identity.test.ts @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,rmSync,readFileSync,writeFileSync,existsSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {execFile} from 'node:child_process'; +import {promisify} from 'node:util'; +import {DeviceClientIdentity} from '../src/device_client_identity.ts'; + +test('Host key reads never enroll implicitly; corruption is preserved and never resets identity',()=>{ + const root=mkdtempSync(join(tmpdir(),'adh-p4-client-')),file=join(root,'client.json'),identity=new DeviceClientIdentity(file); + try{ + assert.throws(()=>identity.read(),(e:any)=>e.code==='CLIENT_IDENTITY_UNAVAILABLE');assert.equal(existsSync(file),false); + const first=identity.ensure();assert.equal(identity.ensure().clientId,first.clientId); + writeFileSync(file,'corrupt');assert.throws(()=>identity.ensure(),(e:any)=>e.code==='CLIENT_IDENTITY_UNAVAILABLE');assert.equal(readFileSync(file,'utf8'),'corrupt'); + }finally{assert.ok(root.startsWith(join(tmpdir(),'adh-p4-client-')));rmSync(root,{recursive:true,force:true});} +}); + +test('two independent Hosts creating the same client identity cannot replace each other\'s key',async()=>{ + const root=mkdtempSync(join(tmpdir(),'adh-p4-client-')),file=join(root,'client.json'); + try{ + const source=new URL('../src/device_client_identity.ts',import.meta.url).href; + const script=`const {DeviceClientIdentity}=await import(${JSON.stringify(source)});process.stdout.write(new DeviceClientIdentity(process.argv[1]).ensure().clientId);`; + const run=()=>promisify(execFile)(process.execPath,['--input-type=module','-e',script,file],{windowsHide:true,timeout:15000}); + const [one,two]=await Promise.all([run(),run()]);assert.equal(String(one.stdout),String(two.stdout));assert.equal(new DeviceClientIdentity(file).read().clientId,String(one.stdout)); + }finally{assert.ok(root.startsWith(join(tmpdir(),'adh-p4-client-')));rmSync(root,{recursive:true,force:true});} +}); diff --git a/daemon/test/device_fixture.ts b/daemon/test/device_fixture.ts index 968bbed..97c4e11 100644 --- a/daemon/test/device_fixture.ts +++ b/daemon/test/device_fixture.ts @@ -19,8 +19,8 @@ export async function startDeviceFixture(existingRoot?:string){ let metadata:any; for(let n=0;n<300;n++){if(child.exitCode!==null)throw Error('JVM fixture exited: '+failure);if(existsSync(ready)){try{metadata=JSON.parse(readFileSync(ready,'utf8'));break;}catch{}}await pause(50);} if(!metadata){child.kill();throw Error('JVM fixture did not become ready: '+failure);} - const stop=async()=>{if(child.exitCode===null){const done=new Promise(r=>child.once('exit',()=>r()));child.kill();await done;}}; - return {root,port:metadata.port as number,deviceId:metadata.deviceId as string,child,stop,async close(){await stop();rmSync(checkedRoot(root),{recursive:true,force:true});}}; + const stop=async()=>{if(child.exitCode===null&&child.signalCode===null){const done=new Promise(r=>child.once('exit',()=>r()));child.kill();await done;}}; + return {root,port:metadata.port as number,lanPort:metadata.lanPort as number|undefined,deviceId:metadata.deviceId as string,child,stop,async close(){await stop();rmSync(checkedRoot(root),{recursive:true,force:true});}}; } type Fixture=Awaited>; export class FakeAdb { diff --git a/daemon/test/device_lan.test.ts b/daemon/test/device_lan.test.ts new file mode 100644 index 0000000..32a9069 --- /dev/null +++ b/daemon/test/device_lan.test.ts @@ -0,0 +1,145 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {existsSync,mkdtempSync,rmSync,readFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {randomUUID,randomBytes,sign} from 'node:crypto'; +import tls from 'node:tls'; +import {Devices} from '../src/devices.ts'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {Operations,type Principal} from '../src/operations.ts'; +import {describeTool} from '../src/operation_registry.ts'; +import {DeviceRpcClient,DEVICE_PROTOCOL} from '../src/device_protocol.ts'; +import {startDeviceFixture,FakeAdb,jvmManifest,pause} from './device_fixture.ts'; + +const ai:Principal={role:'ai',id:'lan-fixture',source:'test'},human:Principal={role:'operator',id:'human',source:'test'}; +const skip=existsSync(jvmManifest)?false:'offline Kotlin fixture unavailable; never use a real device'; +const meta=(engine:Operations,resource:string)=>{const s=engine.snapshot(resource);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; +async function fixture(){ + const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('usb-TLS','1',phone); + const root=mkdtempSync(join(tmpdir(),'adh-p4-lan-'));let adbEnabled=true,forbiddenAdb=0; + const hosts:{devices:Devices;engine:Operations}[]=[]; + function host(name='one'){ + const engine=new Operations(join(root,name,'operations')); + const devices=new Devices(join(root,name,'devices.json'),new AdbDeviceTransport(async(args,o)=>{if(!adbEnabled){forbiddenAdb++;throw Error('ADB REMOVED');}return adb.run(args,o);}),id=>engine.invalidateResource('device:'+id)); + hosts.push({devices,engine}); + const read=(peer:any,method:string,params:any={})=>devices.call({deviceId:peer.deviceId,connectionId:peer.connectionId,method,params}); + async function execute(args:any,principal=ai,extra:any={}){const spec=describeTool('devices',args);return engine.execute(spec,args,principal,{...meta(engine,engine.resource(spec)),...extra},async()=>{ + if(args.action==='connect')return args.transport==='lan'?devices.connectLan(args.deviceId,args.address,args.port):devices.connect('usb-TLS','1'); + if(args.action==='disconnect')return devices.disconnect(args.deviceId,args.connectionId); + if(args.action==='pair')return devices.pair(args);return devices.call(args); + });} + async function connect(deviceId?:string,port?:number){const op=await execute(deviceId?{action:'connect',transport:'lan',deviceId,address:'127.0.0.1',port}:{action:'connect',transport:'adb',serial:'usb-TLS',transportId:'1'});assert.equal(op.state,'succeeded',JSON.stringify(op.error));return op.result;} + async function write(peer:any,method:string,params:any={},options:any={},principal=ai){const state=await read(peer,'device.state');return execute({action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,method,params,...options},principal);} + async function pair(peer:any,permissions=['read','write','manage']){const state=await read(peer,'device.state');const op=await execute({action:'pair',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,permissions});assert.equal(op.state,'succeeded',JSON.stringify(op));return op.result.result.result;} + return {devices,engine,read,write,connect,execute,pair}; + } + const one=host(); + async function setup(){const usb=await one.connect();const configured=await one.write(usb,'lan.configure',{enabled:true,address:'127.0.0.1',port:0});assert.equal(configured.state,'succeeded',JSON.stringify(configured));const port=configured.result.result.result.port;const grant=await one.pair(usb);const lan=await one.connect(usb.deviceId,port);return {usb,lan,port,grant};} + async function restart(){await phone.stop();await pause(50);const next=await startDeviceFixture(phone.root);Object.assign(phone,next);return next;} + return {root,phone,adb,one,host,setup,restart,disableAdb(){adbEnabled=false;},get forbiddenAdb(){return forbiddenAdb;},async close(){for(const h of hosts){h.devices.close();h.engine.close();}await adb.close();await phone.close();assert.ok(root.startsWith(join(tmpdir(),'adh-p4-lan-')));rmSync(root,{recursive:true,force:true});}}; +} + +test('real Kotlin TLS and USB share identity, capabilities, scope/process/certificate/host methods without ADB fallback',{skip},async()=>{ + const f=await fixture();try{ + const {usb,lan}=await f.setup();assert.equal(lan.deviceId,usb.deviceId);assert.equal(lan.bootId,usb.bootId);assert.match(lan.tlsVersion,/^TLSv1\.[23]$/); + assert.deepEqual(lan.identity.capabilities.methods,usb.identity.capabilities.methods);assert.equal(f.one.devices.list().devices.length,1); + await assert.rejects(()=>f.one.devices.call({deviceId:usb.deviceId,method:'scope.get'}),(e:any)=>e.code==='CONNECTION_AMBIGUOUS'); + assert.equal((await f.one.execute({action:'disconnect',deviceId:usb.deviceId,connectionId:usb.connectionId})).state,'succeeded'); + f.disableAdb(); + for(const method of ['device.info','device.capabilities','module.status','applications.list','processes.list','certificates.list','host.get','lan.status'])assert.equal((await f.one.read(lan,method)).ok,true); + const scope=await f.one.read(lan,'scope.get');assert.equal((await f.one.write(lan,'scope.patch',{scopeRevision:scope.result.scopeRevision,add:['com.fixture.lan']})).state,'succeeded'); + assert.equal((await f.one.write(lan,'host.set',{endpoint:'192.0.2.1:8761'})).state,'succeeded');assert.equal((await f.one.read(lan,'host.get')).result.endpoint,'192.0.2.1:8761'); + assert.equal((await f.one.write(lan,'certificates.put',{base64:'fixture'})).state,'succeeded');assert.equal((await f.one.read(lan,'certificates.list')).result.certificates.length,1); + assert.equal((await f.one.write(lan,'certificates.delete',{fileName:'00000000.0'})).state,'succeeded'); + assert.equal((await f.one.write(lan,'process.control',{delayMs:0})).state,'succeeded');assert.equal((await f.one.read(lan,'module.status')).result.calls,1); + for(const method of ['agent.hook','fs.read','diagnostics','root.helper','bulk.read'])await assert.rejects(()=>f.one.devices.call({deviceId:lan.deviceId,connectionId:lan.connectionId,method}),(e:any)=>e.code==='UNSUPPORTED_METHOD'); + assert.equal(f.forbiddenAdb,0);assert.ok(!JSON.stringify(f.one.devices.list()).includes('privateKey')); + const credentials=JSON.parse(readFileSync(f.one.devices.clientIdentity.file,'utf8'));assert.ok(!JSON.stringify(f.one.engine.list()).includes(credentials.privateKey)); + const restored=f.host('one');assert.equal(restored.devices.list().devices[0].online,false);assert.ok(restored.devices.list().devices[0].lanEndpoint);assert.equal(restored.devices.clientIdentity.read().clientId,credentials.clientId); + assert.equal((await restored.connect(lan.deviceId)).deviceId,lan.deviceId);assert.equal(f.forbiddenAdb,0); + }finally{await f.close();} +}); + +test('lost TLS response is reconciled on a new channel, remains unknown and never executes twice',{skip},async()=>{ + const f=await fixture();try{ + const {usb,lan,port}=await f.setup();await f.one.execute({action:'disconnect',deviceId:usb.deviceId,connectionId:usb.connectionId});f.disableAdb(); + const state=await f.one.read(lan,'device.state'); + const running=f.one.execute({action:'call',deviceId:lan.deviceId,connectionId:lan.connectionId,bootId:lan.bootId,daemonInstanceId:lan.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,method:'process.control',params:{delayMs:900}}); + for(let n=0;n<200&&!existsSync(join(f.phone.root,'dispatch-count.txt'));n++)await pause(5);assert.ok(existsSync(join(f.phone.root,'dispatch-count.txt'))); + (f.one.devices as any).connections.get(lan.connectionId).rpc.stream.destroy();const unknown=await running;assert.equal(unknown.state,'unknown'); + const next=await f.one.connect(lan.deviceId,port); // recovery is allowed while this device is quarantined + const observed=await f.one.devices.reconcile(next.deviceId,[unknown.id,'not-recorded'],next.connectionId); + assert.equal(observed.result.operations[0].state,'succeeded');assert.equal(observed.result.operations[0].result.calls,1);assert.equal(observed.result.operations[1].found,false);assert.equal(observed.result.notFoundDoesNotProveUnsent,true); + const updated=f.one.engine.recordDeviceReconciliation(unknown.id,next.deviceId,observed.result.operations[0]);assert.equal(updated.state,'unknown');assert.equal(updated.reconciliations.length,1);assert.ok(f.one.engine.snapshot('device:'+next.deviceId).uncertain); + const blocked=await f.one.write(next,'process.control',{delayMs:0});assert.equal(blocked.error.code,'UNKNOWN_EXECUTION');assert.equal(readFileSync(join(f.phone.root,'dispatch-count.txt'),'utf8'),'1'); + assert.equal(f.forbiddenAdb,0); + }finally{await f.close();} +}); + +test('read-only grants deny writes; revocation closes established streams and survives daemon restart',{skip},async()=>{ + const f=await fixture();try{ + const {usb,port}=await f.setup(),two=f.host('two'),usb2=await two.connect(),grant2=await two.pair(usb2,['read']),lan2=await two.connect(usb2.deviceId,port); + assert.equal((await two.read(lan2,'scope.get')).ok,true);const denied=await two.write(lan2,'process.control',{delayMs:0});assert.equal(denied.error.code,'PERMISSION_DENIED'); + const revoked=await f.one.write(usb,'pairings.revoke',{grantId:grant2.grantId});assert.equal(revoked.state,'succeeded');await pause(50); + await assert.rejects(()=>two.read(lan2,'scope.get'),(e:any)=>e.code==='DEVICE_OFFLINE'); + const reconnect=await two.execute({action:'connect',transport:'lan',deviceId:usb2.deviceId,address:'127.0.0.1',port});assert.equal(reconnect.state,'failed');assert.equal(reconnect.error.code,'AUTH_FAILED'); + const next=await f.restart();const after=await two.execute({action:'connect',transport:'lan',deviceId:usb2.deviceId,address:'127.0.0.1',port:next.lanPort});assert.equal(after.state,'failed');assert.equal(after.error.code,'AUTH_FAILED'); + }finally{await f.close();} +}); + +test('TLS pins reject another device and plaintext; a client proof cannot be replayed on a fresh TLS challenge',{skip},async()=>{ + const f=await fixture(),other=await fixture();try{ + const {usb,port,grant}=await f.setup(),second=await other.setup(); + const wrong=await f.one.execute({action:'connect',transport:'lan',deviceId:usb.deviceId,address:'127.0.0.1',port:second.port});assert.equal(wrong.error.code,'TLS_IDENTITY_MISMATCH'); + const plain=await f.one.execute({action:'connect',transport:'lan',deviceId:usb.deviceId,address:'127.0.0.1',port:f.phone.port});assert.equal(plain.error.code,'TLS_FAILED'); + const identity=f.one.devices.clientIdentity.read(); + async function raw(){const socket=await new Promise((resolve,reject)=>{const s=tls.connect({host:'127.0.0.1',port,rejectUnauthorized:false,minVersion:'TLSv1.2',maxVersion:'TLSv1.2'},()=>resolve(s));s.once('error',reject);});return new DeviceRpcClient(socket);} + const first=await raw(),challenge=await first.request('device.challenge',{}),id=randomUUID(),nonce=randomBytes(32).toString('hex'); + const payload=JSON.stringify([DEVICE_PROTOCOL,'lan-auth/1',challenge.deviceId,challenge.bootId,challenge.daemonInstanceId,challenge.challenge,nonce,id,identity.clientId,grant.grantId]); + const authentication={type:'client-signature',clientId:identity.clientId,grantId:grant.grantId,signature:sign('sha256',Buffer.from(payload),identity.privateKey).toString('base64')}; + await first.request('device.hello',{clientNonce:nonce,authentication},undefined,undefined,5000,id);first.close(); + const replay=await raw();await replay.request('device.challenge',{}); + await assert.rejects(()=>replay.request('device.hello',{clientNonce:nonce,authentication},undefined,undefined,5000,id),(e:any)=>e.code==='AUTH_FAILED');replay.close(); + const usbToken=JSON.parse(readFileSync(join(f.phone.root,'usb-access.json'),'utf8')).token; + const wrongAuth=await raw();await wrongAuth.request('device.challenge',{}); + await assert.rejects(()=>wrongAuth.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:usbToken}}),(e:any)=>e.code==='AUTH_FAILED');wrongAuth.close(); + }finally{await f.close();await other.close();} +}); + +test('device crash leaves a durable unknown reservation; LAN restart and repeated reads do not replay effects',{skip},async()=>{ + const f=await fixture();try{ + const {usb,lan}=await f.setup();await f.one.execute({action:'disconnect',deviceId:usb.deviceId,connectionId:usb.connectionId});f.disableAdb(); + const state=await f.one.read(lan,'device.state');const work=f.one.execute({action:'call',deviceId:lan.deviceId,connectionId:lan.connectionId,bootId:lan.bootId,daemonInstanceId:lan.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,method:'process.control',params:{delayMs:5000}}); + for(let n=0;n<200&&!existsSync(join(f.phone.root,'dispatch-count.txt'));n++)await pause(5);assert.ok(existsSync(join(f.phone.root,'dispatch-count.txt'))); + await f.phone.stop();const unknown=await work;assert.equal(unknown.state,'unknown');const next=await f.restart();const restored=await f.one.connect(lan.deviceId,next.lanPort); + for(let n=0;n<2;n++){const facts=await f.one.devices.reconcile(restored.deviceId,[unknown.id],restored.connectionId);assert.equal(facts.result.operations[0].state,'unknown');assert.equal(facts.result.operations[0].code,'DAEMON_RESTARTED');} + assert.equal(readFileSync(join(f.phone.root,'dispatch-count.txt'),'utf8'),'1');assert.equal(f.forbiddenAdb,0); + // Revocation is a security reduction, so it is still possible under both quarantines. + const grant=f.one.devices.list().devices[0].pairing!; + const old=meta(f.one.engine,'device:'+restored.deviceId); + const revoked=await f.one.write(restored,'pairings.revoke',{grantId:grant.grantId});assert.equal(revoked.state,'unknown','self-revocation closes the response stream; never fabricate an ack'); + const controls=f.one.engine.snapshot('device:'+restored.deviceId);assert.equal(controls.uncertainOperations.length,2); + assert.throws(()=>f.one.engine.control('resolve','device:'+restored.deviceId,human,old,true),/changed/); + f.one.engine.control('resolve','device:'+restored.deviceId,human,meta(f.one.engine,'device:'+restored.deviceId),true); + assert.ok(f.one.engine.getOperation(unknown.id).resolvedAt);assert.ok(f.one.engine.getOperation(revoked.id).resolvedAt);assert.equal(f.one.engine.getOperation(unknown.id).state,'unknown'); + }finally{await f.close();} +}); + +test('explicit human resolution on LAN preserves both unknown histories and permits only a fresh later intent',{skip},async()=>{ + const f=await fixture();try{ + const {usb,lan}=await f.setup();await f.one.execute({action:'disconnect',deviceId:usb.deviceId,connectionId:usb.connectionId});f.disableAdb(); + const state=await f.one.read(lan,'device.state');const work=f.one.execute({action:'call',deviceId:lan.deviceId,connectionId:lan.connectionId,bootId:lan.bootId,daemonInstanceId:lan.daemonInstanceId,expectedDeviceRevision:state.result.stateRevision,method:'process.control',params:{delayMs:5000}}); + for(let n=0;n<200&&!existsSync(join(f.phone.root,'dispatch-count.txt'));n++)await pause(5);assert.ok(existsSync(join(f.phone.root,'dispatch-count.txt'))); + await f.phone.stop();const unknown=await work,next=await f.restart(),restored=await f.one.connect(lan.deviceId,next.lanPort),resource='device:'+lan.deviceId; + const evidence=await f.one.devices.reconcile(restored.deviceId,[unknown.id],restored.connectionId);assert.equal(evidence.result.operations[0].state,'unknown'); + f.one.engine.control('resolve',resource,human,meta(f.one.engine,resource),true); + const aiResolve=await f.one.write(restored,'operations.resolve',{operationId:unknown.id,acknowledge:true});assert.equal(aiResolve.error.code,'OPERATOR_REQUIRED'); + const manual=await f.one.write(restored,'operations.resolve',{operationId:unknown.id,acknowledge:true},{},human);assert.equal(manual.state,'succeeded'); + const held=await f.one.write(restored,'process.control',{delayMs:0}).catch((error:any)=>({error}));assert.equal(held.error.code,'CONTROL_HELD'); + f.one.engine.control('release',resource,human,meta(f.one.engine,resource)); + assert.equal((await f.one.write(restored,'process.control',{delayMs:0})).state,'succeeded');assert.equal(readFileSync(join(f.phone.root,'dispatch-count.txt'),'utf8'),'2'); + const original=await f.one.read(restored,'operations.get',{operationId:unknown.id});assert.equal(original.result.state,'unknown');assert.ok(original.result.resolvedAt); + assert.equal(f.one.engine.getOperation(unknown.id).state,'unknown');assert.ok(f.one.engine.getOperation(unknown.id).resolvedAt);assert.equal(f.forbiddenAdb,0); + }finally{await f.close();} +}); diff --git a/daemon/test/device_lan_entrypoints.test.ts b/daemon/test/device_lan_entrypoints.test.ts new file mode 100644 index 0000000..4c3d569 --- /dev/null +++ b/daemon/test/device_lan_entrypoints.test.ts @@ -0,0 +1,54 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import cp from 'node:child_process'; +import {promisify} from 'node:util'; +import {existsSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {Devices} from '../src/devices.ts'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {setDevicesForTests} from '../src/device_host.ts'; +import {getOperations,operationsRoot} from '../src/operation_host.ts'; +import {initializeOperatorAccess} from '../src/access_context.ts'; +import {handleHttp} from '../src/http/router.ts'; +import {DATA_DIR} from '../src/state.ts'; +import {startDeviceFixture,FakeAdb,jvmManifest,pause} from './device_fixture.ts'; + +test('public CLI pairing, MCP LAN recovery and REST revocation share durable reconciliation and control fences',async t=>{ + if(!existsSync(jvmManifest)){t.skip('build the offline Kotlin fixture; no real ADB fallback');return;} + const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('p4-fixture','1',phone);let available=true,forbidden=0; + const engine=getOperations(),key=initializeOperatorAccess(operationsRoot); + const devices=new Devices(join(DATA_DIR,'devices.json'),new AdbDeviceTransport(async(args,o)=>{if(!available){forbidden++;throw Error('ADB removed');}return adb.run(args,o);}),id=>engine.invalidateResource('device:'+id));setDevicesForTests(devices); + const server=http.createServer((req,res)=>{handleHttp(req,res).catch(()=>{res.writeHead(500);res.end('{}');});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+(server.address() as any).port; + const meta=(resource='host')=>{const s=engine.snapshot(resource);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; + async function rpc(name:string,args:any,operator=false){const response=await fetch(base+'/mcp',{method:'POST',headers:{'Content-Type':'application/json',...(operator?{'X-Adh-Operator-Key':key}:{})},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})});const json=await response.json() as any;return JSON.parse(json.result.content[0].text);} + async function rest(args:any,resource:string){const response=await fetch(base+'/api/devices',{method:'POST',headers:{'Content-Type':'application/json','X-Adh-Operation':JSON.stringify(meta(resource))},body:JSON.stringify(args)});return {status:response.status,body:await response.json() as any};} + async function state(peer:any){return (await rpc('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,method:'device.state'})).result;} + async function intent(peer:any,method:string,params:any={}){const observed=await state(peer);return {action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:observed.stateRevision,method,params};} + try{ + const usb=await rpc('devices',{action:'connect',serial:'p4-fixture',transportId:'1',_operation:meta()}),resource='device:'+usb.deviceId;assert.equal(usb._operation.state,'succeeded'); + const configured=await rest(await intent(usb,'lan.configure',{enabled:true,address:'127.0.0.1',port:0}),resource);assert.equal(configured.status,200);const port=configured.body.result.result.port; + const observed=await state(usb);const pairing={action:'pair',deviceId:usb.deviceId,connectionId:usb.connectionId,bootId:usb.bootId,daemonInstanceId:usb.daemonInstanceId,expectedDeviceRevision:observed.stateRevision,permissions:['read','write','manage']}; + assert.equal((await rpc('devices',pairing)).code,'CONTROL_REQUIRED'); + const cliSource=process.env.ADH_CLI_SOURCE||resolve('../..','adh-cli','src'); + if(existsSync(join(cliSource,'adh','__init__.py'))){ + const output=await promisify(cp.execFile)('python',['-m','adh','run','devices','--arguments',JSON.stringify(pairing),'--endpoint',base,'--json'],{env:{...process.env,PYTHONPATH:cliSource,ADH_CONFIG_PATH:join(DATA_DIR,'p4-cli.json'),ADH_OPERATOR_TOKEN:key,PYTHONIOENCODING:'utf-8'},timeout:15000,windowsHide:true}); + const op=JSON.parse(String(output.stdout)).operation;for(let n=0;n<200&&!engine.getOperation(op.id).settled;n++)await pause(5);assert.equal(engine.getOperation(op.id).state,'succeeded');assert.equal(engine.getOperation(op.id).owner,'ai'); + }else{t.diagnostic('CLI source unavailable; set ADH_CLI_SOURCE for full path');assert.equal((await rpc('devices',{...pairing,_operation:meta(resource)}))._operation.state,'succeeded');} + const lan=await rpc('devices',{action:'connect',transport:'lan',deviceId:usb.deviceId,address:'127.0.0.1',port,_operation:meta(resource)});assert.equal(lan._operation.state,'succeeded'); + assert.equal((await rest({action:'disconnect',deviceId:usb.deviceId,connectionId:usb.connectionId},resource)).status,200);available=false; + const work=await rpc('devices',{...await intent(lan,'process.control',{delayMs:500}),budgetMs:50,_operation:meta(resource)});assert.equal(work._operation.state,'unknown'); + const recovered=await rpc('devices',{action:'connect',transport:'lan',deviceId:usb.deviceId,address:'127.0.0.1',port,_operation:meta(resource)});assert.equal(recovered._operation.state,'succeeded'); + const audit=await rpc('devices',{action:'reconcile',deviceId:usb.deviceId,connectionId:recovered.connectionId,operationIds:[work._operation.id]});assert.equal(audit.replayed,false);assert.equal(audit.reconciled[0].deviceEvidence.state,'succeeded');assert.equal(audit.reconciled[0].hostState,'unknown'); + const record=await rpc('operations',{action:'get',id:work._operation.id,includeResult:true});assert.equal(record.operation.reconciliations.length,1);assert.equal(record.operation.reconciliations[0].evidence.result.calls,1); + assert.equal((await rpc('runtime_diagnostics',{deviceId:usb.deviceId,transport:'lan',session:'unverified-legacy'})).code,'UNSUPPORTED_DEVICE_ROUTING'); + assert.equal((await (await fetch(base+'/api/agents?deviceId='+usb.deviceId)).json() as any).code,'UNSUPPORTED_DEVICE_ROUTING'); + const mismatch=await rpc('devices',{action:'reconcile',deviceId:'00000000-0000-4000-8000-000000000009',operationIds:[work._operation.id]});assert.equal(mismatch.code,'TARGET_CHANGED'); + await rpc('operations',{action:'resolve',resource,acknowledge:true,_operation:meta(resource)},true); + await rpc('operations',{action:'takeover',resource,_operation:meta(resource)},true); + const blocked=await rpc('devices',{...await intent(recovered,'host.set',{endpoint:'192.0.2.2:8761'}),_operation:meta(resource)});assert.equal(blocked.code,'CONTROL_HELD'); + await rpc('operations',{action:'release',resource,_operation:meta(resource)},true); + const grant=devices.list().devices[0].pairing!;const revoked=await rest(await intent(recovered,'pairings.revoke',{grantId:grant.grantId}),resource);assert.equal(revoked.status,504);assert.equal(revoked.body._operation.state,'unknown'); + const denied=await rpc('devices',{action:'connect',transport:'lan',deviceId:usb.deviceId,address:'127.0.0.1',port,_operation:meta(resource)});assert.equal(denied.code,'AUTH_FAILED');assert.equal(forbidden,0); + }finally{devices.close();await new Promise(r=>server.close(()=>r()));engine.close();await adb.close();await phone.close();} +}); diff --git a/daemon/test/fixtures/p4_workbench.ts b/daemon/test/fixtures/p4_workbench.ts new file mode 100644 index 0000000..b7ac152 --- /dev/null +++ b/daemon/test/fixtures/p4_workbench.ts @@ -0,0 +1,26 @@ +// Browser-only synthetic device evidence. No index.ts, devices, ADB or target process. +import cp from 'node:child_process'; +import {syncBuiltinESMExports} from 'node:module'; +import {mkdtempSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import http from 'node:http'; +process.env.ADH_DATA_DIR=mkdtempSync(join(tmpdir(),'adh-p4-panel-'));process.env.ADH_SKIP_ARTIFACT_LOAD='1';delete process.env.ADH_CAPTURES_DIR; +process.env.ADH_OPERATOR_TOKEN='synthetic-p4-operator-key'; +cp.execFile=(()=>{throw Error('ADB forbidden in P4 panel fixture');}) as unknown as typeof cp.execFile; +cp.spawn=(()=>{throw Error('device process forbidden in P4 panel fixture');}) as unknown as typeof cp.spawn;syncBuiltinESMExports(); +const {getOperations}=await import('../../src/operation_host.ts'); +const {handleHttp}=await import('../../src/http/router.ts'); +const {trackedEffect}=await import('../../src/execution_context.ts'); +const engine=getOperations(),deviceId='00000000-0000-4000-8000-000000000004',resource='device:'+deviceId; +const ai={role:'ai' as const,id:'fixture',source:'mcp'},task=engine.createTask('LAN 断线对账 · 合成设备',ai); +const meta=()=>{const c=engine.snapshot(resource);return {expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch,taskId:task.id};}; +const lost=await engine.execute({name:'devices',mode:'write',deviceId},{},ai,meta(),()=>trackedEffect(async()=>{throw Error('synthetic response lost');},undefined,{kind:'device',action:'process.control'})); +engine.recordDeviceReconciliation(lost.id,deviceId,{operationId:lost.id,found:true,state:'succeeded',result:{synthetic:true,calls:1,note:''},replayed:false}); +// A second implicit task demonstrates multiple unknown controls without resuming the held task. +const spec={name:'devices',mode:'write' as const,deviceId,securityOnly:true};const m=meta();delete (m as any).taskId; +const revoked=await engine.execute(spec,{},ai,m,()=>trackedEffect(async()=>{throw Error('synthetic self-revocation closed stream');},undefined,{kind:'device',action:'pairings.revoke'})); +const server=http.createServer((req,res)=>handleHttp(req,res).catch(()=>{res.writeHead(500);res.end('{}');})); +server.listen(0,'127.0.0.1',()=>console.log('P4_WORKBENCH='+JSON.stringify({url:'http://127.0.0.1:'+(server.address() as any).port,taskId:task.id,unknownId:lost.id,revocationId:revoked.id,root:process.env.ADH_DATA_DIR}))); +const stop=()=>{server.closeAllConnections();server.close();engine.close();process.exit(0);}; +process.stdin.resume();process.stdin.on('data',line=>{if(String(line).trim()==='stop')stop();});process.on('SIGINT',stop); diff --git a/device/MAP.md b/device/MAP.md index 4bf83a0..61af43d 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -129,3 +129,7 @@ module. Both Home and Scope re-check when returning to the foreground. `core/DeviceRpc.kt` pins adh.device/1, bounded framing and the method-effect contract. AIDL v19 appends info/capabilities/scope CAS without renumbering previous transactions. `daemon/AndroidDeviceBackend.kt` owns Android business operations; `RootScopeBinder` enforces the existing caller verifier then delegates to the same `device/DeviceOperations` as USB RPC. That package owns installation identity, atomic files, the bounded revision/operation journal, process generations, scope preservation and a stream dispatcher. `LocalDeviceRpcServer` adds only an authenticated abstract UDS; no phone HTTP/MCP/TCP/analysis server. DeviceDaemon holds a process lock for identity/journal ownership. JVM `DeviceDomainTest` tests recovery/CAS/storage errors; `DeviceRpcFixture` exposes the production identity/domain/codec over an OS-temp loopback socket with a synthetic backend. `:daemon:writeDeviceRpcFixtureClasspath` explicitly builds its ignored classpath manifest for Host interoperability tests; it never starts a real Android service. See docs/P3_DEVICE_DOMAIN.md for limits and the separate unverified Android/SELinux boundary. + +## P4 authenticated LAN (2026-11-16) + +`DeviceTls` builds a self-signed installation certificate using public JCA/JSSE, independent of imported system CAs. `DeviceNetwork` restores only explicitly enabled TLS configuration; its default is disabled. `DevicePairings` persists bounded public grants and revocations, closes revoked streams and fails closed on storage errors. The same DeviceRpcSession negotiates USB-token or LAN client-signature authentication, then dispatches through DeviceOperations with a per-request authorization guard inside the domain lock. Capabilities are filtered by grant; no TCP plaintext, remote root shell, HTTP/MCP, database or analysis is introduced. Existing Binder numbering stays v19; its API was not changed this slice. See docs/P4_LAN_AUTH.md for USB-first enrollment, permissions, recovery and unsupported legacy capabilities. Real Android TLS/SELinux and device effects remain a separate hardware gate. diff --git a/device/core/src/main/java/com/adh/core/DeviceRpc.kt b/device/core/src/main/java/com/adh/core/DeviceRpc.kt index 8251dce..ad63e2b 100644 --- a/device/core/src/main/java/com/adh/core/DeviceRpc.kt +++ b/device/core/src/main/java/com/adh/core/DeviceRpc.kt @@ -14,8 +14,8 @@ object DeviceRpc { const val SOCKET_NAME = "adh_device_rpc_v1" const val MAX_FRAME = 1024 * 1024 const val MAX_BUDGET_MS = 60_000L - val READ_METHODS = setOf("device.info", "device.capabilities", "device.state", "module.status", "scope.get", "applications.list", "processes.list", "certificates.list", "host.get", "operations.get") - val WRITE_METHODS = setOf("scope.patch", "scope.replace", "process.control", "certificates.put", "certificates.delete", "host.set", "operations.resolve") + val READ_METHODS = setOf("device.info", "device.capabilities", "device.state", "module.status", "scope.get", "applications.list", "processes.list", "certificates.list", "host.get", "operations.get", "operations.reconcile", "lan.status", "pairings.list") + val WRITE_METHODS = setOf("scope.patch", "scope.replace", "process.control", "certificates.put", "certificates.delete", "host.set", "operations.resolve", "lan.configure", "pairings.grant", "pairings.revoke") // Reboot and arbitrary shell/helper execution are NOT remote RPC capabilities in P3. fun read(input: InputStream): JSONObject? { val first = input.read() diff --git a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt index f3ad9c4..1fa4b47 100644 --- a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt +++ b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt @@ -11,12 +11,14 @@ import com.adh.daemon.device.DeviceFiles import com.adh.daemon.device.DeviceIdentity import com.adh.daemon.device.DeviceOperations import com.adh.daemon.device.LocalDeviceRpcServer +import com.adh.daemon.device.DeviceNetwork import android.system.Os object AdhDeviceDaemon { private const val TAG = "AdhDeviceDaemon" private const val PUBLISH_INTERVAL_MS = 1_000L private var rpc: LocalDeviceRpcServer? = null + private var network: DeviceNetwork? = null private var domainLock: java.nio.channels.FileLock? = null @JvmStatic @@ -42,6 +44,7 @@ object AdhDeviceDaemon { domainLock = checkNotNull(lockChannel.tryLock()) { "another device domain instance owns this installation" } val identity = DeviceIdentity(files, File("/proc/sys/kernel/random/boot_id").readText().trim()) val operations = DeviceOperations(identity, files, AndroidDeviceBackend(context, files)) + network = DeviceNetwork(operations, files) // default disabled; restore only explicitly saved TLS configuration val service = RootScopeBinder(ManagerCallerVerifier(context), operations) // RPC availability never tears down the pre-existing authenticated Binder service. runCatching { rpc = LocalDeviceRpcServer(operations) }.onFailure { Log.e(TAG, "USB RPC unavailable; Binder remains available", it) } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt index 12dc81b..6b35e20 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt @@ -50,6 +50,8 @@ internal class DeviceIdentity(private val files: DeviceFiles, val bootId: String token = access.getString("token"); check(Regex("[a-f0-9]{64}").matches(token)) } fun authenticated(candidate: String): Boolean = java.security.MessageDigest.isEqual(token.toByteArray(), candidate.toByteArray()) + fun sign(bytes: ByteArray): ByteArray = Signature.getInstance("SHA256withRSA").run { initSign(privateKey); update(bytes); sign() } + fun tlsKey(): java.security.PrivateKey = privateKey // internal TLS key manager only; never an RPC field fun descriptor(): JSONObject = JSONObject().put("deviceId", deviceId).put("bootId", bootId).put("daemonInstanceId", instanceId).put("identityFingerprint", fingerprint) fun signHello(requestId: String, nonce: String, info: JSONObject, capabilities: JSONObject): JSONObject { val payload = descriptor().put("protocol", DeviceRpc.PROTOCOL).put("requestId", requestId).put("clientNonce", nonce).put("info", info).put("capabilities", capabilities).toString().toByteArray(Charsets.UTF_8) diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceNetwork.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceNetwork.kt new file mode 100644 index 0000000..6ad66d5 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceNetwork.kt @@ -0,0 +1,93 @@ +package com.adh.daemon.device + +import org.json.JSONObject +import java.io.File +import java.net.InetAddress +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLServerSocket +import javax.net.ssl.SSLSocket + +/** Opt-in TLS transport. All device methods still dispatch through the same DeviceOperations. */ +internal class DeviceNetwork(private val operations: DeviceOperations, private val files: DeviceFiles, private val allowEphemeral: Boolean = false) : AutoCloseable { + val pairings = DevicePairings(files) + private val configFile = File(files.directory, "lan.json") + private var config = JSONObject().put("schemaVersion", 1).put("enabled", false).put("address", "0.0.0.0").put("port", 8762) + private val tls by lazy { DeviceTls.context(operations.identity, files) } + private class Listener(val socket: SSLServerSocket, val clients: java.util.concurrent.ConcurrentHashMap) + private var listener: Listener? = null + private var startupError: String? = null + private val workers = ThreadPoolExecutor(4, 4, 30, TimeUnit.SECONDS, ArrayBlockingQueue(4)) + private val allClients = java.util.concurrent.ConcurrentHashMap() + val methods = setOf("lan.status", "lan.configure", "pairings.list", "pairings.grant", "pairings.revoke") + init { + operations.network = this + if (configFile.exists()) { check(configFile.length() <= 4096); config = JSONObject(configFile.readText()); check(config.getInt("schemaVersion") == 1); validateConfig(config) } + pairings.revoked = { grant -> allClients.entries.filter { it.value == grant }.forEach { runCatching { it.key.close() } } } + if (config.getBoolean("enabled")) try { listener = open(config); accept(checkNotNull(listener)) } catch (_: Exception) { startupError = "LAN_START_FAILED" } + } + private fun validateConfig(value: JSONObject) { + require(value.get("enabled") is Boolean) + val address = value.getString("address") + val ipv4 = Regex("(0|[1-9][0-9]{0,2})(\\.(0|[1-9][0-9]{0,2})){3}").matches(address) && address.split('.').all { it.toInt() <= 255 } + require(ipv4 || address.contains(':') && Regex("[0-9a-fA-F:]{2,64}").matches(address)); InetAddress.getByName(address) + val port = value.get("port"); require(port is Number && port !is Double && port !is Float && port.toLong() in (if (allowEphemeral) 0L else 1L)..65535L) + } + fun validate(method: String, params: JSONObject) { + when (method) { + "lan.configure" -> try { validateConfig(params) } catch (_: Exception) { throw DeviceFault("INVALID_ARGUMENT", "explicit enabled, numeric bind address and port required") } + "pairings.grant" -> pairings.validateGrant(params) + "pairings.revoke" -> if (!Regex("[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").matches(params.optString("grantId"))) throw DeviceFault("INVALID_ARGUMENT", "explicit grantId required") + } + } + @Synchronized fun execute(method: String, params: JSONObject): JSONObject = when (method) { + "lan.status" -> JSONObject().put("configured", JSONObject(config.toString())).put("listening", listener != null) + .put("port", listener?.socket?.localPort ?: JSONObject.NULL).put("startupError", startupError ?: JSONObject.NULL) + .put("tls", "TLSv1.2+").put("identityFingerprint", operations.identity.fingerprint).put("pairing", "trusted USB enrollment; client RSA challenge proof") + "lan.configure" -> configure(params) + "pairings.list" -> pairings.list() + "pairings.grant" -> pairings.grant(params) + "pairings.revoke" -> pairings.revoke(params) + else -> throw DeviceFault("UNSUPPORTED_METHOD", "network capability unsupported") + } + private fun configure(params: JSONObject): JSONObject { + validate("lan.configure", params) + val candidate = JSONObject().put("schemaVersion", 1).put("enabled", params.getBoolean("enabled")).put("address", params.getString("address")).put("port", params.getInt("port")) + if (candidate.getBoolean("enabled") == config.getBoolean("enabled") && candidate.getString("address") == config.getString("address") && candidate.getInt("port") == config.getInt("port") && (!candidate.getBoolean("enabled") || listener != null)) return execute("lan.status", JSONObject()).put("ok", true) + val prepared = if (candidate.getBoolean("enabled")) try { open(candidate) } catch (_: Exception) { throw DeviceFault("LAN_START_FAILED", "TLS listener could not start; previous configuration retained") } else null + try { files.write(configFile, candidate.toString()) } catch (error: Exception) { prepared?.socket?.close(); throw error } + val previous = listener; listener = prepared; config = candidate; startupError = null + previous?.let { stop(it) }; prepared?.let { accept(it) } + return execute("lan.status", JSONObject()).put("ok", true) + } + private fun open(value: JSONObject): Listener { + val socket = tls.serverSocketFactory.createServerSocket() as SSLServerSocket + try { + socket.enabledProtocols = socket.supportedProtocols.filter { it in setOf("TLSv1.3", "TLSv1.2") }.toTypedArray() + socket.enabledCipherSuites = socket.supportedCipherSuites.filter { it.startsWith("TLS_AES_") || it.startsWith("TLS_CHACHA20_") || it.contains("ECDHE_RSA") && (it.contains("GCM") || it.contains("CHACHA20")) }.toTypedArray() + check(socket.enabledProtocols.isNotEmpty() && socket.enabledCipherSuites.isNotEmpty()) + socket.reuseAddress = true; socket.bind(java.net.InetSocketAddress(InetAddress.getByName(value.getString("address")), value.getInt("port")), 8) + return Listener(socket, java.util.concurrent.ConcurrentHashMap()) + } catch (error: Exception) { socket.close(); throw error } + } + private fun accept(current: Listener) { + Thread({ + while (!current.socket.isClosed) { + val client = try { current.socket.accept() as SSLSocket } catch (_: Exception) { break } + current.clients[client] = ""; allClients[client] = "" + try { workers.execute { + try { + client.soTimeout = 5000; client.startHandshake() + DeviceRpcSession(operations).serve(client.inputStream, client.outputStream, pairings, { grant -> + current.clients[client] = grant; allClients[client] = grant; client.soTimeout = 30_000 + }) + } catch (_: Exception) { /* broken/TLS/auth streams close; no replay */ } + finally { current.clients.remove(client); allClients.remove(client); runCatching { client.close() } } + } } catch (_: java.util.concurrent.RejectedExecutionException) { current.clients.remove(client); allClients.remove(client); client.close() } + } + }, "adh-device-tls").apply { isDaemon = true; start() } + } + private fun stop(current: Listener) { current.socket.close(); current.clients.keys.forEach { runCatching { it.close() } } } + @Synchronized override fun close() { listener?.let { stop(it) }; listener = null; workers.shutdownNow() } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt index 37373b3..18310b1 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt @@ -17,6 +17,7 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: private val lock = Any() private var state: JSONObject private var storageUnavailable = false + var network: DeviceNetwork? = null init { check(!stateFile.exists() || stateFile.length() <= 2 * 1024 * 1024) { "device operation ledger exceeds limit" } state = if (stateFile.exists()) JSONObject(stateFile.readText()) else JSONObject().put("schemaVersion", 1).put("revision", 0L).put("operations", JSONObject()) @@ -33,9 +34,13 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: private fun save() { files.write(stateFile, encoded(state)) } fun revision(): Long = synchronized(lock) { state.getLong("revision") } fun capabilities(): JSONObject = JSONObject().put("protocol", DeviceRpc.PROTOCOL).put("maxFrameBytes", DeviceRpc.MAX_FRAME).put("maxBudgetMs", DeviceRpc.MAX_BUDGET_MS) - .put("methods", JSONObject().also { methods -> DeviceRpc.READ_METHODS.forEach { methods.put(it, "read") }; DeviceRpc.WRITE_METHODS.forEach { methods.put(it, "write") } }) - .put("unsupported", JSONObject().put("lan.tls", "P4 pairing/TLS not installed").put("agent.route", "legacy target channel retained; not associated by serial").put("shell", "no arbitrary remote root shell").put("reboot", "Manager-only in P3").put("bulk", "not implemented")) - fun read(method: String, params: JSONObject = JSONObject()): JSONObject = synchronized(lock) { + .put("methods", JSONObject().also { methods -> DeviceRpc.READ_METHODS.filter { available(it) }.forEach { methods.put(it, "read") }; DeviceRpc.WRITE_METHODS.filter { available(it) }.forEach { methods.put(it, "write") } }) + .put("transports", JSONObject().put("usb", true).put("lanTls", network != null)) + .put("unsupported", JSONObject().put("agent.route", "legacy target channel retained; not associated by serial").put("agent.hook", "target agent routing not migrated").put("agent.memory", "target agent routing not migrated").put("agent.trace", "target agent routing not migrated").put("diagnostics", "legacy ADB-only; no LAN fallback").put("fs", "not migrated").put("root.helper", "not migrated").put("shell", "no arbitrary remote root shell").put("reboot", "Manager-only").put("bulk", "not implemented")) + private fun available(method: String) = method !in setOf("lan.status", "lan.configure", "pairings.list", "pairings.grant", "pairings.revoke") || network != null + private fun execute(method: String, params: JSONObject): JSONObject = if (method in (network?.methods ?: emptySet())) network!!.execute(method, params) else backend.execute(method, params) + fun read(method: String, params: JSONObject = JSONObject(), authorize: () -> Unit = {}): JSONObject = synchronized(lock) { + authorize() when (method) { "device.info" -> identity.descriptor().put("info", backend.execute(method, params)).put("stateRevision", revision()) "device.capabilities" -> capabilities().put("stateRevision", revision()) @@ -45,10 +50,19 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: val record = records().optJSONObject(id) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no recorded device operation") JSONObject(record.toString()).put("stateRevision", revision()) } - else -> backend.execute(method, params).put("stateRevision", revision()) + "operations.reconcile" -> { + val ids = params.getJSONArray("operationIds"); require(ids.length() in 1..100) + val rows = org.json.JSONArray() + for (n in 0 until ids.length()) { val id = ids.getString(n); require(Regex("[A-Za-z0-9_-]{1,128}").matches(id)) + rows.put(records().optJSONObject(id)?.let { JSONObject(it.toString()).put("found", true) } ?: JSONObject().put("operationId", id).put("found", false)) + } + JSONObject().put("operations", rows).put("notFoundDoesNotProveUnsent", true).put("replayed", false).put("stateRevision", revision()) + } + else -> execute(method, params).put("stateRevision", revision()) } } - fun write(method: String, params: JSONObject, operationId: String, expectedRevision: Long, actor: String, budgetMs: Long, receivedAt: Long = System.nanoTime()): JSONObject = synchronized(lock) { + fun write(method: String, params: JSONObject, operationId: String, expectedRevision: Long, actor: String, budgetMs: Long, receivedAt: Long = System.nanoTime(), authorize: () -> Unit = {}): JSONObject = synchronized(lock) { + authorize() require(Regex("[A-Za-z0-9_-]{1,128}").matches(operationId)) if (storageUnavailable) throw DeviceFault("DEVICE_LEDGER_UNAVAILABLE", "ledger persistence failed; writes disabled until inspected restart") val fingerprint = DeviceRpc.sha256(DeviceRpc.canonical(JSONObject().put("method", method).put("params", params).put("bootId", identity.bootId).put("expectedRevision", expectedRevision)).toByteArray()) @@ -60,12 +74,13 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: if ((System.nanoTime() - receivedAt) / 1_000_000 >= budgetMs) throw DeviceFault("DEADLINE_EXCEEDED", "expired before device dispatch") if (expectedRevision != revision()) throw DeviceFault("STALE_DEVICE_STATE", "device was modified; observe again, do not retry old intent") val unresolved = records().keys().asSequence().map { records().getJSONObject(it) }.filter { it.optString("state") == "unknown" && !it.has("resolvedAt") }.toList() - if (unresolved.isNotEmpty() && method != "operations.resolve") throw DeviceFault("UNKNOWN_EXECUTION", "device has unresolved side effects") + val securityOnly = method == "pairings.revoke" || method == "lan.configure" && params.opt("enabled") == false + if (unresolved.isNotEmpty() && method != "operations.resolve" && !securityOnly) throw DeviceFault("UNKNOWN_EXECUTION", "device has unresolved side effects") if (method == "operations.resolve" && (actor != "operator" || !params.optBoolean("acknowledge"))) throw DeviceFault("OPERATOR_REQUIRED", "explicit operator inspection required") if (method == "operations.resolve") { val old = records().optJSONObject(params.optString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") if (old.optString("state") != "unknown" || old.has("resolvedAt")) throw DeviceFault("INVALID_STATE", "operation is not unresolved unknown") - } else backend.validate(method, params) + } else if (method in (network?.methods ?: emptySet())) network!!.validate(method, params) else backend.validate(method, params) if (records().length() >= 1024) throw DeviceFault("LEDGER_FULL", "device ledger needs explicit archival; nothing dispatched") val record = JSONObject().put("operationId", operationId).put("method", method).put("bootId", identity.bootId).put("fingerprint", fingerprint) .put("actor", actor).put("state", "running").put("mayHaveExecuted", true).put("startedAt", System.currentTimeMillis()) @@ -82,7 +97,7 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: val old = records().optJSONObject(params.getString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") if (old.optString("state") != "unknown") throw DeviceFault("INVALID_STATE", "operation is not unknown") old.put("resolvedAt", System.currentTimeMillis()); JSONObject().put("ok", true).put("originalState", "unknown") - } else backend.execute(method, params) + } else execute(method, params) val encoded = result.toString().toByteArray() record.put("result", if (encoded.size <= 32 * 1024) result else JSONObject().put("omitted", true).put("bytes", encoded.size).put("sha256", DeviceRpc.sha256(encoded))) record.put("state", if (result.optBoolean("ok", true)) "succeeded" else "failed") diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt b/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt new file mode 100644 index 0000000..3b1a360 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt @@ -0,0 +1,80 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.security.KeyFactory +import java.security.Signature +import java.security.spec.X509EncodedKeySpec +import java.util.Base64 +import java.util.UUID + +internal class DevicePairings(private val files: DeviceFiles) { + private val file = File(files.directory, "pairings.json") + private var state: JSONObject + var revoked: (String) -> Unit = {} + private var unavailable = false + init { + check(!file.exists() || file.length() <= 512 * 1024) + state = if (file.exists()) JSONObject(file.readText()) else JSONObject().put("schemaVersion", 1).put("grants", JSONObject()) + check(state.getInt("schemaVersion") == 1 && state.getJSONObject("grants").length() <= 256) + for (id in grants().keys()) { val grant = grants().getJSONObject(id); check(id == grant.getString("grantId") && UUID.fromString(id).toString() == id) + check(DeviceRpc.sha256(key(grant.getString("publicKey")).encoded) == grant.getString("clientId")); permissions(grant.getJSONArray("permissions")) } + } + private fun grants() = state.getJSONObject("grants") + private fun key(encoded: String): java.security.PublicKey { + require(encoded.length <= 2048) + val key = KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(encoded))) + require((key as java.security.interfaces.RSAPublicKey).modulus.bitLength() in 2048..4096); return key + } + private fun permissions(values: JSONArray): Set { + require(values.length() in 1..3) + val result = (0 until values.length()).map { values.getString(it) }.toSet() + require(result.all { it in setOf("read", "write", "manage") } && "read" in result); return result + } + private fun persist(candidate: JSONObject) { + if (unavailable) throw DeviceFault("AUTH_STORAGE_UNAVAILABLE", "authorization storage requires inspection") + try { files.write(file, candidate.toString()); state = candidate } catch (_: Exception) { unavailable = true; throw DeviceFault("AUTH_STORAGE_UNAVAILABLE", "authorization persistence unconfirmed", true) } + } + @Synchronized fun list(): JSONObject = JSONObject().put("grants", JSONArray(grants().keys().asSequence().map { id -> + JSONObject(grants().getJSONObject(id).toString()).apply { remove("publicKey") } + }.toList())) + @Synchronized fun validateGrant(params: JSONObject) { + try { key(params.getString("publicKey")); permissions(params.getJSONArray("permissions")); require(params.optString("label").length <= 128) } + catch (_: Exception) { throw DeviceFault("INVALID_ARGUMENT", "RSA public key, label and explicit read/write/manage permissions required") } + } + @Synchronized fun grant(params: JSONObject): JSONObject { + validateGrant(params) + if (grants().length() >= 256) throw DeviceFault("PAIRING_LIMIT", "explicit pairing archival required") + val publicKey = key(params.getString("publicKey")); val clientId = DeviceRpc.sha256(publicKey.encoded) + if (grants().keys().asSequence().any { val g = grants().getJSONObject(it); g.getString("clientId") == clientId && !g.has("revokedAt") }) throw DeviceFault("PAIRING_EXISTS", "client already paired; inspect existing grant, do not create a duplicate") + val id = UUID.randomUUID().toString() + val grant = JSONObject().put("grantId", id).put("clientId", clientId).put("publicKey", Base64.getEncoder().encodeToString(publicKey.encoded)) + .put("permissions", JSONArray(permissions(params.getJSONArray("permissions")).sorted())).put("label", params.optString("label")).put("createdAt", System.currentTimeMillis()) + val candidate = JSONObject(state.toString()); candidate.getJSONObject("grants").put(id, grant); persist(candidate) + return JSONObject(grant.toString()).apply { remove("publicKey"); put("ok", true) } + } + @Synchronized fun revoke(params: JSONObject): JSONObject { + val id = params.getString("grantId") + val existing = grants().optJSONObject(id) ?: throw DeviceFault("PAIRING_NOT_FOUND", "grant not found") + if (!existing.has("revokedAt")) { val candidate = JSONObject(state.toString()); candidate.getJSONObject("grants").getJSONObject(id).put("revokedAt", System.currentTimeMillis()); persist(candidate) } + revoked(id) // close existing authenticated streams after durable revocation + return JSONObject().put("ok", true).put("grantId", id).put("revoked", true).put("alreadyDispatchedMayComplete", true) + } + @Synchronized fun authorize(grantId: String, method: String) { + if (unavailable) throw DeviceFault("AUTH_STORAGE_UNAVAILABLE", "authorization storage requires inspection") + val grant = grants().optJSONObject(grantId) ?: throw DeviceFault("AUTH_REVOKED", "grant unavailable") + if (grant.has("revokedAt")) throw DeviceFault("AUTH_REVOKED", "grant revoked") + val needed = if (method in setOf("lan.configure", "pairings.list", "pairings.grant", "pairings.revoke", "operations.resolve")) "manage" else if (method in DeviceRpc.WRITE_METHODS) "write" else "read" + if (needed !in permissions(grant.getJSONArray("permissions"))) throw DeviceFault("PERMISSION_DENIED", "grant does not permit this capability") + } + @Synchronized fun authenticate(auth: JSONObject, message: ByteArray): String { + try { + val id = auth.getString("grantId"); authorize(id, "device.info") + val grant = grants().getJSONObject(id); require(grant.getString("clientId") == auth.getString("clientId")) + val proof = Base64.getDecoder().decode(auth.getString("signature")); require(proof.size <= 512) + require(Signature.getInstance("SHA256withRSA").run { initVerify(key(grant.getString("publicKey"))); update(message); verify(proof) }); return id + } catch (_: Exception) { throw DeviceFault("AUTH_FAILED", "LAN client authentication failed") } + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt index b5a93e7..9d201d8 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt @@ -7,17 +7,42 @@ import java.io.OutputStream /** Framing/dispatch can be reused by a future authenticated TLS transport unchanged. */ internal class DeviceRpcSession(private val operations: DeviceOperations) { - fun serve(input: InputStream, output: OutputStream) { - val hello = DeviceRpc.read(input) ?: return + fun serve(input: InputStream, output: OutputStream, pairings: DevicePairings? = null, authenticated: (String) -> Unit = {}) { + var hello = DeviceRpc.read(input) ?: return + var challenge = "" + if (pairings != null) { + val challengeId = validEnvelope(hello) + if (hello.optString("method") != "device.challenge") { DeviceRpc.write(output, DeviceRpc.failure(challengeId, "AUTH_FAILED", "LAN challenge required")); return } + challenge = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) } + DeviceRpc.write(output, DeviceRpc.response(challengeId, operations.identity.descriptor().put("challenge", challenge))) + hello = DeviceRpc.read(input) ?: return // one challenge per TLS stream, 5 second socket deadline + } val helloId = validEnvelope(hello) val params = hello.optJSONObject("params") ?: JSONObject() val auth = params.optJSONObject("authentication") ?: JSONObject() - if (hello.optString("method") != "device.hello" || auth.optString("type") != "usb-token" || !operations.identity.authenticated(auth.optString("credential"))) { + val nonce = params.optString("clientNonce") + var grantId: String? = null + val authorized = try { + require(hello.optString("method") == "device.hello" && Regex("[a-f0-9]{64}").matches(nonce)) + if (pairings == null) { require(auth.optString("type") == "usb-token" && operations.identity.authenticated(auth.optString("credential"))) } + else { + require(auth.optString("type") == "client-signature") + val identity = operations.identity + val proof = org.json.JSONArray(listOf(DeviceRpc.PROTOCOL, "lan-auth/1", identity.deviceId, identity.bootId, identity.instanceId, challenge, nonce, helloId, auth.getString("clientId"), auth.getString("grantId"))).toString().toByteArray(Charsets.UTF_8) + grantId = pairings.authenticate(auth, proof); authenticated(checkNotNull(grantId)) + } + true + } catch (_: Exception) { false } + if (!authorized) { DeviceRpc.write(output, DeviceRpc.failure(helloId, "AUTH_FAILED", "device authentication failed")); return } - val nonce = params.optString("clientNonce") - require(Regex("[a-f0-9]{64}").matches(nonce)) - DeviceRpc.write(output, DeviceRpc.response(helloId, operations.identity.signHello(helloId, nonce, operations.read("device.info"), operations.capabilities()))) + fun check(method: String) { if (grantId != null) pairings!!.authorize(grantId!!, method) } + fun capabilities(): JSONObject { + val value = operations.capabilities(); val methods = value.getJSONObject("methods"); val denied = org.json.JSONArray() + for (method in methods.keys().asSequence().toList()) if (runCatching { check(method) }.isFailure) { methods.remove(method); denied.put(method) } + return value.put("deniedMethods", denied).put("connection", JSONObject().put("transport", if (pairings == null) "adb" else "lan").put("grantId", grantId ?: JSONObject.NULL)) + } + DeviceRpc.write(output, DeviceRpc.response(helloId, operations.identity.signHello(helloId, nonce, operations.read("device.info", authorize = { check("device.info") }), capabilities()))) while (true) { val request = DeviceRpc.read(input) ?: return val received = System.nanoTime() @@ -30,13 +55,13 @@ internal class DeviceRpcSession(private val operations: DeviceOperations) { val method = request.getString("method") val arguments = request.optJSONObject("params") ?: JSONObject() val result = when (method) { - in DeviceRpc.READ_METHODS -> operations.read(method, arguments) + in DeviceRpc.READ_METHODS -> operations.read(method, arguments, authorize = { check(method) }).let { if (method == "device.capabilities") capabilities().put("stateRevision", it.getLong("stateRevision")) else it } in DeviceRpc.WRITE_METHODS -> { val meta = request.getJSONObject("meta") val budget = meta.getLong("budgetMs"); require(budget in 1..DeviceRpc.MAX_BUDGET_MS) // A full replacement must carry scope CAS, even on authenticated RPC. if (method in setOf("scope.patch", "scope.replace")) require(Regex("[a-f0-9]{64}").matches(arguments.optString("scopeRevision"))) - operations.write(method, arguments, meta.getString("operationId"), meta.getLong("expectedRevision"), meta.optString("actor", "ai"), budget, received) + operations.write(method, arguments, meta.getString("operationId"), meta.getLong("expectedRevision"), meta.optString("actor", "ai"), budget, received, authorize = { check(method) }) } else -> throw DeviceFault("UNSUPPORTED_METHOD", "method not advertised by this device protocol") } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceTls.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceTls.kt new file mode 100644 index 0000000..6fc3d1d --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceTls.kt @@ -0,0 +1,56 @@ +package com.adh.daemon.device + +import java.io.ByteArrayInputStream +import java.io.File +import java.math.BigInteger +import java.security.KeyStore +import java.security.SecureRandom +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.text.SimpleDateFormat +import java.util.Base64 +import java.util.Date +import java.util.TimeZone +import javax.net.ssl.KeyManagerFactory +import javax.net.ssl.SSLContext + +/** Public JCA/JSSE only: Android has no supported sun.security.x509 API. Pin the installation SPKI. */ +internal object DeviceTls { + private fun der(tag: Int, data: ByteArray): ByteArray { + val length = if (data.size < 128) byteArrayOf(data.size.toByte()) else { + val bytes = BigInteger.valueOf(data.size.toLong()).toByteArray().dropWhile { it == 0.toByte() }.toByteArray() + byteArrayOf((128 + bytes.size).toByte()) + bytes + } + return byteArrayOf(tag.toByte()) + length + data + } + private fun seq(vararg data: ByteArray) = der(48, data.fold(byteArrayOf()) { a, b -> a + b }) + private fun oid(hex: String) = der(6, hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()) + fun context(identity: DeviceIdentity, files: DeviceFiles): SSLContext { + val file = File(files.directory, "tls-certificate.der.b64") + val factory = CertificateFactory.getInstance("X.509") + if (!file.exists()) { + val algorithm = seq(oid("2a864886f70d01010b"), der(5, byteArrayOf())) // sha256WithRSAEncryption + val name = seq(der(49, seq(oid("550403"), der(12, ("ADH-" + identity.deviceId).toByteArray())))) + val format = SimpleDateFormat("yyyyMMddHHmmss'Z'", java.util.Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") } + val now = System.currentTimeMillis() + val serial = BigInteger(128, SecureRandom()).abs().add(BigInteger.ONE).toByteArray() + val extensions = der(163, seq( + seq(oid("551d13"), der(1, byteArrayOf(-1)), der(4, seq())), // critical basicConstraints CA=false + seq(oid("551d25"), der(4, seq(oid("2b06010505070301")))), // serverAuth + )) + val body = seq(der(160, der(2, byteArrayOf(2))), der(2, serial), algorithm, name, + seq(der(24, format.format(Date(now - 86_400_000)).toByteArray()), der(24, format.format(Date(now + 315_360_000_000L)).toByteArray())), + name, Base64.getDecoder().decode(identity.publicKey), extensions) + val certificate = seq(body, algorithm, der(3, byteArrayOf(0) + identity.sign(body))) + files.write(file, Base64.getEncoder().encodeToString(certificate)) + } + check(file.length() <= 16384) + val certificate = factory.generateCertificate(ByteArrayInputStream(Base64.getDecoder().decode(file.readText()))) as X509Certificate + certificate.verify(certificate.publicKey); certificate.checkValidity() + check(com.adh.core.DeviceRpc.sha256(certificate.publicKey.encoded) == identity.fingerprint) { "TLS identity mismatch" } + val password = CharArray(32) { 'x' } + val store = KeyStore.getInstance("PKCS12").apply { load(null, null); setKeyEntry("device", identity.tlsKey(), password, arrayOf(certificate)) } + val manager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, password) } + return SSLContext.getInstance("TLS").apply { init(manager.keyManagers, null, SecureRandom()) } + } +} diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceNetworkTest.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceNetworkTest.kt new file mode 100644 index 0000000..efc326e --- /dev/null +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceNetworkTest.kt @@ -0,0 +1,66 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import org.json.JSONObject +import org.json.JSONArray +import org.junit.Assert.* +import org.junit.Test +import java.nio.file.Files +import java.io.File +import java.security.KeyPairGenerator +import java.security.Signature +import java.util.Base64 + +class DeviceNetworkTest { + private fun root() = Files.createTempDirectory("adh-p4-unit-").toFile() + private fun key() = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair() + private fun request(publicKey: java.security.PublicKey, vararg permissions: String) = JSONObject().put("publicKey", Base64.getEncoder().encodeToString(publicKey.encoded)).put("permissions", JSONArray(permissions.toList())).put("label", "fixture") + @Test fun grantsArePersistentScopedAndRevokedWithoutErasingHistory() { + val dir=root();val pairings=DevicePairings(DeviceFiles(dir));val key=key();val grant=pairings.grant(request(key.public,"read"));val id=grant.getString("grantId") + pairings.authorize(id,"scope.get") + assertEquals("PERMISSION_DENIED",(runCatching { pairings.authorize(id,"scope.patch") }.exceptionOrNull() as DeviceFault).code) + assertEquals("PERMISSION_DENIED",(runCatching { pairings.authorize(id,"pairings.list") }.exceptionOrNull() as DeviceFault).code) + assertEquals("PAIRING_EXISTS",(runCatching { pairings.grant(request(key.public,"read")) }.exceptionOrNull() as DeviceFault).code) + var closed="";pairings.revoked={closed=it};pairings.revoke(JSONObject().put("grantId",id));assertEquals(id,closed) + val restored=DevicePairings(DeviceFiles(dir));assertEquals("AUTH_REVOKED",(runCatching { restored.authorize(id,"scope.get") }.exceptionOrNull() as DeviceFault).code) + assertTrue(restored.list().getJSONArray("grants").getJSONObject(0).has("revokedAt"));assertFalse(restored.list().toString().contains("publicKey")) + } + @Test fun proofIsBoundToTheWholeChallengeAndGrant() { + val pairings=DevicePairings(DeviceFiles(root()));val key=key();val grant=pairings.grant(request(key.public,"read","write"));val message="fixture-challenge".toByteArray() + val proof=Signature.getInstance("SHA256withRSA").run { initSign(key.private);update(message);sign() } + val auth=JSONObject().put("grantId",grant.getString("grantId")).put("clientId",grant.getString("clientId")).put("signature",Base64.getEncoder().encodeToString(proof)) + assertEquals(grant.getString("grantId"),pairings.authenticate(auth,message)) + assertEquals("AUTH_FAILED",(runCatching { pairings.authenticate(auth,"other-challenge".toByteArray()) }.exceptionOrNull() as DeviceFault).code) + pairings.revoke(JSONObject().put("grantId",grant.getString("grantId"))) + assertEquals("AUTH_FAILED",(runCatching { pairings.authenticate(auth,message) }.exceptionOrNull() as DeviceFault).code) + } + @Test fun storageFailureClosesAuthorizationAndCorruptionIsNeverRebuilt() { + val dir=root();var fail=false;val files=DeviceFiles(dir,{_,_->if(fail)throw java.io.IOException("fixture")});val pairings=DevicePairings(files);val key=key();val grant=pairings.grant(request(key.public,"read"));fail=true + assertEquals("AUTH_STORAGE_UNAVAILABLE",(runCatching { pairings.revoke(JSONObject().put("grantId",grant.getString("grantId"))) }.exceptionOrNull() as DeviceFault).code) + assertEquals("AUTH_STORAGE_UNAVAILABLE",(runCatching { pairings.authorize(grant.getString("grantId"),"scope.get") }.exceptionOrNull() as DeviceFault).code) + File(dir,"pairings.json").writeText("corrupt");assertTrue(runCatching { DevicePairings(DeviceFiles(dir)) }.isFailure);assertEquals("corrupt",File(dir,"pairings.json").readText()) + } + @Test fun tlsIdentityPersistsAndListenerIsDisabledUntilAnExplicitConfiguration() { + val dir=root();val files=DeviceFiles(dir);val identity=DeviceIdentity(files,"00000000-0000-4000-8000-000000000001") + val ops=DeviceOperations(identity,files,DeviceBackend{_,_->JSONObject()});val network=DeviceNetwork(ops,files,true) + try { + assertFalse(network.execute("lan.status",JSONObject()).getBoolean("listening"));assertFalse(File(dir,"tls-certificate.der.b64").exists()) + val configured=network.execute("lan.configure",JSONObject().put("enabled",true).put("address","127.0.0.1").put("port",0));assertTrue(configured.getInt("port")>0) + val cert=File(dir,"tls-certificate.der.b64").readText();DeviceTls.context(identity,files);assertEquals(cert,File(dir,"tls-certificate.der.b64").readText()) + val before=File(dir,"lan.json").readText() + assertEquals("INVALID_ARGUMENT",(runCatching { network.execute("lan.configure",JSONObject().put("enabled",true).put("address","invalid.invalid").put("port",0)) }.exceptionOrNull() as DeviceFault).code) + assertEquals(before,File(dir,"lan.json").readText()) + for (params in listOf(JSONObject().put("enabled",true).put("address","deadbeef").put("port",8762),JSONObject().put("enabled",true).put("address","127.0.0.1").put("port",1.5))) { + assertEquals("INVALID_ARGUMENT",(runCatching { network.execute("lan.configure",params) }.exceptionOrNull() as DeviceFault).code) + } + } finally { network.close() } + } + @Test fun requestAuthorizationRunsInsideTheDomainBeforeIdempotencyOrEffects() { + val dir=root();val files=DeviceFiles(dir);var hits=0;val ops=DeviceOperations(DeviceIdentity(files,"00000000-0000-4000-8000-000000000001"),files,DeviceBackend{_,_->hits++;JSONObject().put("ok",true)}) + val first=ops.write("host.set",JSONObject(),"same-id",0,"ai",1000);assertEquals("succeeded",first.getString("state")) + val denied=runCatching { ops.write("host.set",JSONObject(),"same-id",0,"ai",1000,authorize={throw DeviceFault("AUTH_REVOKED","fixture")}) }.exceptionOrNull() as DeviceFault + assertEquals("AUTH_REVOKED",denied.code);assertEquals(1,hits) + val facts=ops.read("operations.reconcile",JSONObject().put("operationIds",JSONArray(listOf("same-id","not-present")))) + assertFalse(facts.getBoolean("replayed"));assertTrue(facts.getBoolean("notFoundDoesNotProveUnsent"));assertFalse(facts.getJSONArray("operations").getJSONObject(1).getBoolean("found")) + } +} diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt index 3133820..9a5bf58 100644 --- a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt @@ -15,7 +15,10 @@ object DeviceRpcFixture { val bootFile = File(root, "boot.txt"); if (!bootFile.exists()) bootFile.writeText(UUID.randomUUID().toString()) val files = DeviceFiles(root); val identity = DeviceIdentity(files, bootFile.readText().trim()) val scopes = ScopeDocuments(File(root, "scope.json"), files) - val counter = java.util.concurrent.atomic.AtomicInteger() + val countFile = File(root, "dispatch-count.txt") + val counter = java.util.concurrent.atomic.AtomicInteger(if (countFile.exists()) countFile.readText().toInt() else 0) + var endpoint = "" + val certificates = org.json.JSONArray() val backend = DeviceBackend { method, params -> when (method) { "device.info" -> JSONObject().put("model", "JVM fixture").put("synthetic", true) @@ -24,14 +27,21 @@ object DeviceRpcFixture { "scope.replace" -> scopes.replace(params.getJSONObject("document").toString(), params.getString("scopeRevision")) "module.status" -> JSONObject().put("synthetic", true).put("calls", counter.get()) "applications.list" -> JSONObject().put("applications", org.json.JSONArray()).put("total", 0) - "process.control" -> { counter.incrementAndGet(); Thread.sleep(params.optLong("delayMs", 0).coerceIn(0, 5000)); JSONObject().put("ok", true).put("synthetic", true).put("calls", counter.get()) } + "processes.list" -> JSONObject().put("processes", org.json.JSONArray()).put("complete", true).put("total", 0) + "host.get" -> JSONObject().put("endpoint", endpoint) + "host.set" -> { endpoint = params.getString("endpoint"); JSONObject().put("ok", true) } + "certificates.list" -> JSONObject().put("certificates", org.json.JSONArray(certificates.toString())) + "certificates.put" -> { certificates.put("fixture-ca"); JSONObject().put("ok", true).put("stored", 1).put("pendingReboot", true) } + "certificates.delete" -> { if (certificates.length() > 0) certificates.remove(0); JSONObject().put("ok", true).put("pendingReboot", true) } + "process.control" -> { countFile.writeText(counter.incrementAndGet().toString()); Thread.sleep(params.optLong("delayMs", 0).coerceIn(0, 5000)); JSONObject().put("ok", true).put("synthetic", true).put("calls", counter.get()) } else -> throw DeviceFault("UNSUPPORTED_METHOD", "fixture method not implemented") } } val operations = DeviceOperations(identity, files, backend) + val network = DeviceNetwork(operations, files, allowEphemeral = true) val server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); val workers = Executors.newFixedThreadPool(4) - File(root, "ready.json").writeText(JSONObject().put("port", server.localPort).put("deviceId", identity.deviceId).toString()) - Runtime.getRuntime().addShutdownHook(Thread { server.close(); workers.shutdownNow() }) + File(root, "ready.json").writeText(JSONObject().put("port", server.localPort).put("deviceId", identity.deviceId).put("lanPort", network.execute("lan.status", JSONObject()).opt("port")).toString()) + Runtime.getRuntime().addShutdownHook(Thread { server.close(); network.close(); workers.shutdownNow() }) while (!server.isClosed) { val client = server.accept(); workers.execute { client.use { try { DeviceRpcSession(operations).serve(it.getInputStream(), it.getOutputStream()) } catch (_: Exception) { } } } } } } diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md index b9b88c0..c4abb6e 100644 --- a/docs/DEVELOPMENT_PLAN.md +++ b/docs/DEVELOPMENT_PLAN.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 开发计划 +> **2026-11-16 P4 实施**:P3 设备 RPC 已增加 opt-in LAN TLS、可信 USB 配对、持久 read/write/manage 授权与撤销,USB/LAN 共用设备业务。断线后显式恢复连接并持久对账,不重放、不自动解除 unknown;工作台展示证据及多个未知操作。迁移矩阵、初次配对、密钥与实机限制见 [P4_LAN_AUTH.md](P4_LAN_AUTH.md)。agent 本地路由、bulk 与旧 ADB-only 诊断/fs/helper 未迁移,明确 unsupported;当前分析实例不升级。 + > **2026-11-16 P3 实施**:设备域服务、安装身份、能力查询与 USB/ADB RPC 已在独立 worktree 实现。Binder/RPC 共用业务与 revision;Host 设备范围接入 P1 控制权,MCP/REST/公共 CLI 共用操作。详见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。P4 配对/TLS、旧 ADB-only 能力迁移及 agent 本地路由未实施;原审计 P3 的真机 UDS/fd/SELinux 原型仍待独立设备验证,当前现场不升级。 > **2026-11-16 P2 实施**:完成同一工作台的独立/现场入口、任务详情/结果/副作用、配置草稿/并发冲突核对、任务 CAS 与暂停恢复、显式接管/交还及 unknown 核对。AI 规划与执行继续由外部 Harness 主导,面板不要求预先接管或固定 recipe。模块/边界见 [P2_WORKBENCH.md](P2_WORKBENCH.md);P3/P4 的设备域与新传输仍未实施,当前分析实例不升级。 diff --git a/docs/FEATURE_STATUS.md b/docs/FEATURE_STATUS.md index 8b74e3d..4d41b87 100644 --- a/docs/FEATURE_STATUS.md +++ b/docs/FEATURE_STATUS.md @@ -1,5 +1,7 @@ # ADH 功能状态(2026-10-24 更新:通用原生分析与证据核验;各轮实测范围见 §2) +> **2026-11-16 P4**:LAN TLS、可信 USB 配对、客户端公钥证明、权限/撤销和持久对账已在隔离真实 Node↔Kotlin TLS 流验证。Host **547 passed / 0 failed / 0 skipped**,Android JVM **66 passed**,构建/类型检查通过;MCP 仍 **93**。禁模拟 ADB 后设备域查询、scope/进程/证书/地址 RPC 可独立走 LAN;设备实际效果由合成 backend 验证传输,**真实 Android JSSE/UDS/SELinux/无线链路及真实应用/CA 效果未验证**。agent/diagnostics/fs/helper/bulk 明确未迁移,无隐式 ADB fallback。工作台对账、下载和多 unknown 已浏览器实测。详见 [P4_LAN_AUTH.md](P4_LAN_AUTH.md)。独立 worktree 交付,不部署当前现场。 + > **2026-11-16 P3**:设备域、稳定安装身份、能力查询及 USB/ADB RPC 已实现,Binder/RPC 共享业务与状态版本,MCP 增至 **93**。隔离生产 Kotlin/Node 协议、双设备、超时/结果追踪、人类控制与公共 CLI 路径均已测;Android JVM **61 passed**,Device Daemon 构建及 Manager 编译通过。完整 Host 结果见 PROGRESS.md。**真机 Android UDS/SELinux、真实应用/证书效果尚未验证**;LAN/TLS/配对、agent 本地路由、bulk 与 ADB-only 能力迁移未实施,不能宣称 USB/LAN 全能力对等。见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。源码仅在独立 worktree,不替换当前实例。 > **2026-11-16 P2**:人类任务工作台已在隔离 Host/浏览器验收,含任务搜索分页、详情/结果/下载、有限副作用日志、配置草稿与显式冲突核对、暂停恢复、接管/交还与 unknown。完整 Host **525 passed / 0 failed / 0 skipped**;模块与限制见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。交付在独立 worktree;原工作目录保留 P1,当前服务与真实设备未部署或升级。 diff --git a/docs/P4_LAN_AUTH.md b/docs/P4_LAN_AUTH.md new file mode 100644 index 0000000..92dc227 --- /dev/null +++ b/docs/P4_LAN_AUTH.md @@ -0,0 +1,122 @@ +# P4:LAN、配对、TLS、授权撤销与断线对账(2026-11-16) + +P4 在 P3 的安装身份和 `adh.device/1` 上增加 TLS 流。USB 和 LAN 进入同一个 dispatcher、设备业务服务、持久 revision 与操作日志,不建立第二套分析流程。AI 继续默认自主执行;人类凭据、接管、暂停和版本冲突仍由同一 Host 协调器处理。 + +源码在 `feat/adh-p4-lan-20261116` 独立 worktree,基于 P3 `258e69a`。本轮没有部署到当前实例,没有启动正式 index、执行真实 ADB、重设 reverse/forward、安装 APK、启停目标或重启当前分析服务。 + +LAN 需要配套 P4 Host/Device,不能只替换一端或静态页面。P4 Host 可以查询旧设备已广告的子集;P3 Host 的严格能力校验可能拒绝 P4 新能力,需要明确升级。现有 Binder transaction 顺序/v19 与 target agent 协议不变;本轮不安排现场升级。 + +## 模块与信任边界 + +| 模块 | 实现 | +|---|---| +| Device `DeviceTls` | 用安装 RSA 密钥签发独立 TLS 证书,公共 JCA/JSSE API;不使用 Android 不支持的 sun.security.x509,不安装系统 CA | +| Device `DeviceNetwork` | 默认关闭、显式配置的 TLS listener,持久配置恢复、实际 listening/port/startupError、有限连接/线程、撤销后关闭流 | +| Device `DevicePairings` | 有界持久 grant、公钥/权限、撤销 tombstone;授权存储失败关闭后续认证,不丢弃损坏文件 | +| `DeviceRpcSession` / `DeviceOperations` | USB token 和 LAN 客户端证明分别认证,复用帧、业务、代际/CAS、去重与日志;权限在域锁内、每次派发前检查 | +| Host `device_client_identity.ts` | 显式配对时生成本机 RSA 客户端密钥;完整写入后排他发布,多个 Host 不能相互覆盖;损坏不自动重建 | +| Host `transport/device_transport.ts` / `lan_device.ts` | 统一认证连接接口、TLS 身份固定、挑战证明;无 ADB 调用或自动重连/重放 | +| Host `Devices` / `device_host` | USB/LAN 合并同一 deviceId,显式连接选择、配对/采用已观察 grant、对账证据落盘;公共 MCP/REST/CLI 入口共用 | +| Host `operations` / `task_store` / 工作台 | 窄范围连接恢复/安全收缩、多个 unknown、对账历史、版本确认失效与结果下载 | + +手机仍只有设备控制和有界协调记录,没有 HTTP/MCP、数据库、反汇编、索引或 AI 工作流。设备 TLS 证书、Host 客户端证明、Manager APK 签名和用户导入的系统 CA 是四种不同用途,不互相替代。 + +## 配对与 TLS + +采用 **可信 USB 首次登记**,不是未认证网络上的自动信任: + +1. 通过 P3 的已验证 USB 连接,Host 获得稳定 deviceId/身份公钥指纹。USB bootstrap token 只用于本地 UDS,LAN 拒绝 usb-token 认证。 +2. `devices action=pair` 生成/读取 Host 私钥,并将公钥和明确权限提交到设备的 `pairings.grant`。返回 grantId、clientId、公有权限;私钥不进入工具参数、任务、设备缓存或响应。默认 `read,write`,需要远程管理时显式加入 `manage`。 +3. 设备 `lan.configure` 显式开启数字地址和端口,生产默认端口 8762;出厂配置 enabled=false。测试只在 127.0.0.1 随机端口运行。保存 enabled=true 后,新 Device Daemon 启动会恢复它;失败报告 LAN_START_FAILED/listening=false,USB 仍可查询。 +4. Host `connect transport=lan` 指定已配对 deviceId 和数字 address/port。首次成功后保存“已验证过的端点”;以后可以省略地址/端口,仍然需要明确 connect,不在启动时自动拨号。 + +TLS 只允许 1.2/1.3,使用 TLS 1.3 AEAD 或 ECDHE-RSA 的 GCM/ChaCha20 套件。Host 对自签安装证书不使用公网 CA/主机名信任,必须在发送任何 RPC 或客户端证明前检查 **SPKI SHA-256 固定值、自签验证及证书有效期**。错误设备、明文或身份变化都会失败,不退回无 TLS。原理依据见 [JSSE 参考](https://docs.oracle.com/en/java/javase/17/security/java-secure-socket-extension-jsse-reference-guide.html) 与 [Node TLS API](https://nodejs.org/api/tls.html);TLS 证书不会因为用户在系统证书页导入了别的 CA 而被信任。 + +TLS 建立后先执行 `device.challenge`,设备每条流只发一个 256-bit 随机挑战。Host 用自己的 RSA 私钥签署以下 JSON 数组的 UTF-8 字节,作为 device.hello 的 client-signature: + +```text +["adh.device/1", "lan-auth/1", deviceId, bootId, daemonInstanceId, + serverChallenge, clientNonce, helloRequestId, clientId, grantId] +``` + +设备检查 grant 有效性、clientId、公钥签名及整条挑战。原 P3 的设备签名 hello 仍绑定 nonce、代际与能力。旧挑战或另一个 grant 的证明不能重放;初始认证限时,空闲连接也有读超时。它是服务端 TLS 身份认证加应用层公钥认证,不声称采用 mTLS 客户端证书。 + +设备身份仍是安装身份,不是硬件证明。复制整个安装私钥目录无法凭本协议证明属于另一件硬件;P3 的双活代际冲突拒绝继续保留。 + +## 权限与撤销 + +| 权限 | 能力 | +|---|---| +| `read` | 身份/信息/状态、普通能力、模块、作用域、应用/进程/证书/Host 地址、操作结果与对账 | +| `write` | scope patch/replace、第三方进程控制、CA 保存/删除、Host 地址修改;仍需 Host 和设备状态版本 | +| `manage` | 配对清单/授权/撤销、LAN 配置及设备 unknown 人工核对;不自动获得 write | + +每个 grant 至少需要 read。USB 是经 root bootstrap 验证的管理通道;LAN 的签名能力表按 grant 过滤,未授权方法列入 deniedMethods。Host 返回 PERMISSION_DENIED,设备在同一个域锁内再次检查,不能靠旧 hello、旧 connectionId 或重放操作 ID 绕过授权。 + +`pairings.revoke` 必须给明确 grantId。先持久保存 revokedAt,再关闭该 grant 的既有流;之后的认证和派发均拒绝。撤销记录保留,重启不会恢复授权。再次登记同一个客户端需要新 grantId;不把旧撤销记录改回有效。不承诺撤回已经派发的方法或中途取消 Android 系统调用。 + +从当前 LAN 流撤销自己,或关闭当前 LAN listener,会先切断响应:Host 保持 unknown,不能伪造“已收到成功确认”。可以从另一条仍获授权的连接/USB 查询设备操作记录。配对响应或 Host 保存未确认时,同样先查询;`devices pair grantId=<已观察 ID>` 会经已验证 USB 检查该 grant 确实属于本机密钥且未撤销,再保存 Host 登记,不重复授权。 + +权限以设备为准。Host 清单里的 pairing 是**缓存登记**,不证明当前仍获授权;每次 LAN 请求都会重新检查。遗失或损坏 Host 私钥不会自动换一把密钥继续连接,必须通过可信路径重新登记。设备 pairings 上限 256 条/512 KiB,包含撤销历史,无自动清理或在线归档。 + +## USB/LAN 能力对等矩阵 + +下表针对新设备 RPC,权限足够时两条传输调用同一实现。 + +| 能力 | USB | LAN | 证据/限制 | +|---|---|---|---| +| 设备/模块/应用/进程查询 | 支持 | 支持 | 无目标 agent 也可查询;进程完整性按实际返回 | +| scope get/patch/replace | 支持 | 支持 | 相同 scopeRevision、设备 revision、完整策略保留;不自动重启 | +| 第三方进程 open/stop/restart | 支持 | 支持 | 相同 PID/UID/starttimeTicks 检查;实机 Android 效果本轮未测 | +| 用户 CA 列表/保存/删除 | 支持 | 支持 | 同一业务、pendingReboot;不远程重启;实机挂载未测 | +| Host endpoint | 支持 | 支持 | 原子保存,不强制现有目标重连 | +| operations get/reconcile/resolve | 支持 | 支持 | resolve 仍需人类身份;LAN 还需 manage | +| LAN 配置、grant 管理/撤销 | 支持 | 支持 | LAN 需 manage;Host pair 简化入口要求可信 USB | +| agent Hook/内存/主动调用/trace/dump | unsupported | unsupported | 旧 agent 通道未迁入设备身份域 | +| runtime diagnostics/fs/root helper | unsupported | unsupported | 旧 ADB-only 路径未迁移,不伪装 LAN 能力 | +| bulk、自动路由/重试、广播发现、无 USB 首次配对 | unsupported | unsupported | 不制造部分成功或隐式替代 | + +同一 deviceId 的 USB/LAN 只占一个设备条目,连接各有 connectionId。多条活连接必须显式选择;任何写入都不因某条连接断开而自动换路。新 Device Daemon 不改变旧 target agent 的归属,旧 session 仍是 legacy/unverified。 + +`devices call` 未知方法返回 UNSUPPORTED_METHOD,未安装的已知能力返回 CAPABILITY_UNSUPPORTED。给旧 MCP/REST 能力附 deviceId、connectionId 或 transport=lan 会返回 UNSUPPORTED_DEVICE_ROUTING,避免旧工具忽略设备选择后继续走 ADB。调用旧 session 的既有工具仍是明确的 legacy 路径,不能据此宣称设备域 LAN 对等。 + +`discover transport=lan` 只列已经验证过的端点,明确标记 last-known/not-probed,不扫描网络、不宣称在线。list 也是缓存视图;connect 和 live info 才建立/查询认证连接。 + +## 断线、超时与对账 + +P3 的持久 operationId reservation、内容指纹、代际和 revision 保留:同一设备操作 ID 不能重新派发另一份意图;重启将 running 恢复为 unknown。LAN 不增加自动重试、写入重放或 exactly-once 的虚假保证。reservation 后、业务前崩溃也可能留下 unknown;这不证明一定执行过。 + +- `devices action=reconcile operationIds=[...]` 先核对 Host 操作确实属于所选设备,再以设备只读 `operations.reconcile` 查询,最多 100 个 ID。结果集合必须精确对应请求;错误设备或不合规结果不附加证据。 +- 对账作为 Host analysis 操作保存结果,并把每条设备证据附到原操作。最近 8 次索引持久保存,旧文件不自动删除;遵循原结果 8 MiB 省略策略。更新任务元数据版本,**不修改原终态、不解除隔离、不恢复任务**。 +- 设备返回 succeeded/failed/unknown 或 found=false。found=false 明确不是“证明未发送”,更不是自动重试许可。新 boot 上仍可读取旧 boot 的持久记录。 +- 网络中断后的 connect/disconnect 使用静态 connectionOnly 分类:仍受 Host CAS、人类控制和串行协调约束,但允许在 unknown 下恢复查询通道;该上下文禁止派发设备修改。 +- 撤销授权、明确 enabled=false 的 LAN 关闭属于 securityOnly 收缩,可在 unknown 下执行;上下文拒绝把它换成启用 LAN 或其他写入,设备也单独执行相同限制。普通写入仍被隔离,不允许通过伪造请求标记绕过。 +- 同一范围可能因原操作和自身撤销出现多个 unknown。Host 保留全部 ID,新的 unknown 推进控制版本;人工核对必须基于当前版本、覆盖已显示的全部未知操作,仍在等待的 Host handler 不能解除隔离。核对保留每条原 unknown,任务只变为暂停,不自动重放或恢复。 + +工作台增加缓存设备范围选择、多未知记录入口、对账证据预览/下载;版本变化清除已勾选的人工确认。证据作为纯文本显示,目标字符串不解释为 HTML。 + +## 公共调用顺序 + +所有写入继续用 Host `_operation.expectedRevision/controlEpoch/hostEpoch`,由现有 `adh run` 获取 Host snapshot/submit;设备 bootId、daemonInstanceId、expectedDeviceRevision 必须来自本次观察,不在提交时偷偷刷新旧意图。 + +1. `devices discover transport=adb`,再 `connect transport=adb serial=... transportId=...`。 +2. 查询 device.state,`call method=lan.configure params={enabled:true,address:"0.0.0.0",port:8762}`。 +3. 查询新 stateRevision,`pair deviceId=... connectionId= permissions=["read","write","manage"]`。需要最小权限时仅给所需项。 +4. `connect transport=lan deviceId=... address=<手机局域网 IP> port=8762`。如 USB 仍在线,后续调用明确 LAN connectionId;准备好后可断开自己的 USB RPC 连接,再拔 USB。不会改变原分析通道的 reverse。 +5. 断线后明确恢复连接,`reconcile deviceId=... connectionId=... operationIds=[]`;核对实际设备结果与工作台证据后,由人类决定解除隔离和下一步。 + +可以用 `adh run devices --arguments ''` 提交 connect/pair/call;list/info/capabilities 用现有 call。对账同样可用 run(Host analysis)或 MCP/REST。REST `/api/devices` 使用相同 action/参数及 X-Adh-Operation;没有新 CLI 业务实现或客户端包发布。 + +Host 新增私有 `ADH_DATA_DIR/device-client.json`,设备新增 `device-rpc/pairings.json`、`lan.json`、`tls-certificate.der.b64`,沿用 P3 root 目录及原子文件策略。POSIX 私有文件为 0600;Windows 依赖现有数据目录 ACL。备份/迁移时保留客户端与安装密钥,不将私钥复制进日志、工单或源码。 + +## 隔离验收与剩余限制 + +构建/验收命令沿用 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md) 的离线 Gradle 任务、classpath 清单和 npm launcher,必须**先完成构建再启动 JVM Host 测试**,Windows 正在使用的 classpath JAR 不能同时替换。测试只用合成 backend、临时数据目录和 loopback TLS,完全禁用真实设备操作。 + +- Host 类型检查通过;完整 **547 passed / 0 failed / 0 skipped**,P3 基线 538 + P4 新增 9。真实 Node↔生产 Kotlin TLS 流验证配对、通道能力/身份一致、禁 ADB 后独立运行、只读权限、既有连接撤销及重启持久化、错误证书/明文/重放拒绝、响应丢失和设备中途退出后的对账与派发计数为 1,以及 MCP/REST/真实公共 Python CLI 路径、旧路由拒绝、Host 并发密钥创建。 +- Android JVM **66 passed / 0 failed / 0 skipped**:core 22、daemon 16、Manager 28;Device Daemon debug 构建、Manager Kotlin 编译通过。只使用全零隔离测试 pin,产物不发布/安装。 +- ego-browser 随机端口验收并查看截图:对账保持原 unknown,HTML 作为纯文本,下载完整已保存证据,多未知分别展示,控制版本改变清除确认,人工核对及交还不自动恢复任务。浏览器和本轮 fixture 已关闭。 + +**未验证**:Android JSSE/provider、UDS/SELinux/防火墙的真机可达性、真实无线链路、真实 Binder/应用启停/系统 CA 效果。本轮不能替代专用测试设备的发布前验收。Android/API 差异导致 TLS 无法启动时明确返回实际未监听状态,不放宽身份校验或退到明文。无网络配对 UI/广播发现、证书在线轮换、grant/日志在线归档、bulk 与 agent/ADB-only 能力迁移;以上保持明确 unsupported,后续按单项证据推进。 + +未更改当前分析服务或真机;交付的是隔离验证过的源码提交。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 678dddd..104b7b5 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -5001,3 +5001,22 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 局限如实保留:Android abstract UDS/peer UID/SELinux 可达性及真实 Binder、证书挂载、第三方进程效果没有真机验证;旧审计 P3 的 agent 本地 UDS/fd 原型尚未交付。LAN/TLS/配对/撤销、bulk、agent 路由和旧 ADB-only 诊断/helper/fs 迁移仍待 P4;现有 agent 通道明确 legacy/unverified,不宣称全能力 LAN 对等。完整 API、身份语义、未知核对顺序与迁移见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。 未部署、未推送、未发布或安装产物,未启动正式 index、未请求当前 8088 业务接口、未操作真机/当前会话或重启服务;只启动并清理 OS 临时目录里的 JVM/HTTP 测试夹具。 + + +## 2026-11-16:P4 LAN TLS、配对授权、撤销与持久对账 + +从 P3 258e69a 新建独立 worktree/分支 feat/adh-p4-lan-20261116,不把源码或静态页面放进原分析实例工作目录。当前 Android 主工作区仍为 P1、P2/P3 worktree 均保留干净,公共 adh-cli 源码未修改或发布。 + +- 设备新增默认关闭的 TLS listener;公共 JCA/JSSE 签发与安装身份密钥一致的自签证书,限定 TLS1.2/1.3 与 AEAD/ECDHE 套件。可信 USB 登记 Host 公钥,LAN 只接受挑战签名,拒绝 USB token;Host 在发送证明前检查 SPKI 固定值/证书签名/有效期。仍复用 adh.device/1 dispatcher、业务、代际与持久日志,没有新增分析/HTTP/MCP/数据库。 +- grant 持久保存 read/write/manage 权限和撤销历史;每次派发在域锁内检查权限,撤销持久化后关闭既有流,重启不恢复授权。密钥/授权损坏不自动重建;并发 Host 初次创建同一客户端密钥不能互相覆盖。配对不明确时可经 USB 采用已观察的有效 grant,避免再授权。 +- Host 认证连接抽象分开 ADB 与 LAN adapter,同一 deviceId 去重、多连接明确选择。缓存登记不等于实时授权。LAN list/discover 仅返回已知缓存端点,不扫描。未迁的 agent Hook/内存/trace/dump、diagnostics/fs/root helper/bulk 明确 unsupported;旧 MCP/REST 接口收到设备/LAN 选择也明确拒绝,不默默忽略后走 ADB。 +- 新设备 operations.reconcile 有界查询实际结果,not-found 不当成未发送;Host 验证归属和结果集合后持久附加证据,更新任务元数据但不改变原 unknown/控制权,不重放。连接恢复与撤销/关闭 LAN 属于静态、受限的 connectionOnly/securityOnly,允许在 unknown 下恢复查询或收缩权限,禁止伪装成普通设备写入。 +- 多个 unknown 保留全部 ID,新增未知推进版本,人工核对要求当前快照且所有 Host handler 已结束。工作台列出设备范围、多个未知及对账预览/下载,版本变化清除人工确认;解除隔离只保留原记录并暂停任务,不自动恢复或重试。 + +验证:完整 Host **547 passed / 0 failed / 0 skipped**,类型检查通过(P3 538 + P4 9);真实 Node↔生产 Kotlin TLS 流、TLS1.2/1.3、USB/LAN 身份和能力一致,撤去模拟 ADB 后仍可查询/修改已迁能力。包含撤销旧连接及重启持久化、只读授权、错误证书/明文/重放/USB-token 拒绝、响应丢失和设备退出后的只读对账、派发计数为 1、Host 密钥并发创建,以及实际公共 Python CLI 配对、REST/MCP 控制/对账/撤销与旧路由拒绝。Android 离线 JVM **66 passed / 0 failed / 0 skipped**(core22/daemon16/Manager28);Device Daemon debug 构建与 Manager 编译通过,只用全零测试 pin。v71 **93 tools / 0 problems / PASS**,MCP 文档生成器 --check 通过,whitespace 按既有 CRLF 用 cr-at-eol 检查。 + +浏览器使用 ego-browser 对独立随机 loopback Host 与合成证据实测:保留 unknown、HTML 文本无执行、完整下载、多未知入口、版本改变清除确认、人工核对与交还 AI 不自动恢复任务。实际看过截图;浏览器空间关闭,只停止本轮自建 fixture,未触及当前 8088。 + +边界:只完成隔离 JVM TLS/模拟 ADB 路径与构建;真实 Android JSSE/provider、UDS/SELinux/防火墙/无线网络、真实 Binder/进程和系统 CA 效果未验证。没有 agent 本地路由、bulk、广播发现、无 USB 首次配对/手机配对 UI、在线证书轮换/归档;未迁能力继续如实 unsupported。完整协议/权限、能力矩阵、配对/恢复顺序和数据文件见 [P4_LAN_AUTH.md](P4_LAN_AUTH.md)。 + +未部署、未推送、未发布安装包、未执行真实 ADB、未启停目标、未改 reverse/forward、未重启当前分析服务;交付本轮源码提交。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index 81a82fe..0e7e207 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -1,5 +1,7 @@ # ADH (Android DecryptHub) — 功能需求说明 +> **2026-11-16 P4 传输/授权契约**:手机经显式配置才能监听 LAN TLS;首次 Host 配对经可信 USB,TLS 固定安装公钥,客户端挑战证明绑定设备/代际/流/grant。每次派发检查持久权限,撤销关闭既有流且重启不恢复。设备域已迁能力 USB/LAN 共用同一实现,未迁能力和旧路由选择明确拒绝。断线对账只读取实际结果并保存证据,保留 unknown、人工控制和无重放原则。范围与验收见 [P4_LAN_AUTH.md](P4_LAN_AUTH.md),无当前服务或真机升级。 + > **2026-11-16 P3 设备契约**:稳定安装 UUID/密钥与 boot/daemon 代际,设备发现、信息/能力、作用域/进程/证书/Host 地址由同一设备域服务提供,Binder 与 USB RPC 共用持久 revision。所有远程写经过 Host 设备资源控制及设备 CAS,派发后未知不重试。新协议与现有 agent session 显式区分,未验证的归属不猜测;局域网 TLS、配对和旧 ADB 能力迁移留待后续。范围和验证边界见 [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md)。本轮不部署、不改变当前分析现场。 > **2026-11-16 P2 人类工作台**:任务搜索/分页、详情/结果/副作用、人类暂停恢复、接管/交还、unknown 核对和配置编辑已接入同一执行层。草稿保留原版本,冲突并列核对,显式 rebase 只保留本来修改的字段,不自动提交;任务状态修改使用 task revision。默认观察不改变 AI 工作。范围、兼容性与验证见 [P2_WORKBENCH.md](P2_WORKBENCH.md)。本轮在独立 worktree 实现,当前服务不升级,原静态目录保留 P1 提交内容。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 0bcab6c..cbabfd6 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -4,7 +4,7 @@ Generated from the source registry (93 tools). Endpoint: `POST /mcp` (JSON-RPC 2 Writes require `_operation` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. -Verified installation identities, device capabilities and USB/ADB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Legacy target sessions remain unassociated; LAN/TLS are not implemented. +Verified installation identities and USB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Paired LAN/TLS, permissions, revocation, the capability parity matrix and durable reconciliation: [P4_LAN_AUTH.md](P4_LAN_AUTH.md). Legacy target sessions remain unassociated; unmigrated device/LAN routes fail explicitly. | Tool | Description | Args | |---|---|---| @@ -100,4 +100,4 @@ Verified installation identities, device capabilities and USB/ADB RPC: [P3_DEVIC | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | _operation | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | | `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | -| `devices` | Device-domain discovery, verified installation identities and USB/ADB RPC. list is cached/offline-safe; discover lists ADB transports without attaching targets; connect requires an explicit serial/transportId and creates only its own ADB forward. info/capabilities query a verified deviceId. call uses advertised device methods; writes require observed bootId, daemonInstanceId, expectedDeviceRevision plus Host _operation versions. Read scope.get before scope.patch and supply params.scopeRevision. Device and connection ids are distinct from legacy agent session ids; no association or ADB fallback is guessed. TLS/LAN, agent routing and arbitrary shell are unsupported in P3. Unknown effects must be inspected, never replayed. | action, serial, transportId, expectedDeviceId, deviceId, connectionId, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | +| `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | diff --git a/tools/generate_mcp_docs.mjs b/tools/generate_mcp_docs.mjs index d00798c..08859eb 100644 --- a/tools/generate_mcp_docs.mjs +++ b/tools/generate_mcp_docs.mjs @@ -10,7 +10,7 @@ Generated from the source registry (${MCP_TOOLS.length} tools). Endpoint: \`POST Writes require \`_operation\` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. -Verified installation identities, device capabilities and USB/ADB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Legacy target sessions remain unassociated; LAN/TLS are not implemented. +Verified installation identities and USB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Paired LAN/TLS, permissions, revocation, the capability parity matrix and durable reconciliation: [P4_LAN_AUTH.md](P4_LAN_AUTH.md). Legacy target sessions remain unassociated; unmigrated device/LAN routes fail explicitly. | Tool | Description | Args | |---|---|---| From de9d134cba02069790a8b0045135417f3707aed6 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:20:44 +0800 Subject: [PATCH 17/24] =?UTF-8?q?feat:=20=E5=BB=BA=E7=AB=8B=20Host=20Hook?= =?UTF-8?q?=20=E6=96=B9=E6=A1=88=E5=BA=93=E4=B8=8E=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E5=B9=B6=E8=BF=81=E7=A7=BB=E6=89=8B=E6=9C=BA?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 +- agent/CMakeLists.txt | 3 +- agent/exports.map | 1 + agent/src/MAP.md | 3 + agent/src/bootstrap/agent_main.c | 16 +- agent/src/bootstrap/early_plan.cpp | 31 ++ agent/src/bootstrap/early_wire.h | 50 ++++ daemon/public/hook-plans-panel.js | 29 ++ daemon/public/index.html | 2 +- daemon/public/workbench-model.js | 16 +- daemon/public/workbench.html | 2 +- daemon/public/workbench.js | 11 +- daemon/src/MAP.md | 8 + daemon/src/device_host.ts | 2 +- daemon/src/device_protocol.ts | 4 +- daemon/src/devices.ts | 2 +- daemon/src/hook_plan_host.ts | 35 +++ daemon/src/hook_plans.ts | 97 ++++++ daemon/src/http/router.ts | 2 + daemon/src/http/routes_hook_plans.ts | 8 + daemon/src/http/routes_system.ts | 1 + daemon/src/index.ts | 15 +- daemon/src/mcp.ts | 3 + daemon/src/operation_host.ts | 1 + daemon/src/operation_registry.ts | 8 +- daemon/src/operations.ts | 2 +- daemon/src/service.ts | 36 +-- daemon/src/settings_service.ts | 11 +- daemon/src/state.ts | 7 +- daemon/test/device_lan.test.ts | 15 + daemon/test/fixtures/early_wire.cpp | 12 + daemon/test/fixtures/p5_workbench.ts | 16 + daemon/test/hook_early.test.ts | 58 ++++ daemon/test/hook_entrypoints.test.ts | 32 ++ daemon/test/hook_plans.test.ts | 71 +++++ daemon/test/settings_service.test.ts | 7 +- device/MAP.md | 6 + .../aidl/com/adh/daemon/IAdhScopeService.aidl | 4 + .../src/main/java/com/adh/core/AdhProtocol.kt | 3 +- .../src/main/java/com/adh/core/DeviceRpc.kt | 4 +- .../main/java/com/adh/core/EarlyPlanWire.kt | 42 +++ .../test/java/com/adh/core/ScopeJsonTest.kt | 2 +- .../java/com/adh/daemon/AdhDeviceDaemon.kt | 6 + .../main/java/com/adh/daemon/AgentEarlyAbi.kt | 24 ++ .../java/com/adh/daemon/AndroidHookBinding.kt | 36 +++ .../java/com/adh/daemon/RootScopeBinder.kt | 7 + .../com/adh/daemon/device/DeviceOperations.kt | 13 +- .../com/adh/daemon/device/DevicePairings.kt | 2 +- .../com/adh/daemon/device/DeviceRpcSession.kt | 2 +- .../com/adh/daemon/device/EarlyPlanBroker.kt | 24 ++ .../com/adh/daemon/device/HookPlanCache.kt | 75 +++++ .../com/adh/daemon/device/ScopeDocuments.kt | 10 + .../java/com/adh/daemon/AgentEarlyAbiTest.kt | 21 ++ .../com/adh/daemon/device/DeviceRpcFixture.kt | 7 +- .../main/java/com/adh/manager/MainActivity.kt | 2 +- .../adh/manager/data/DaemonScopeRepository.kt | 17 ++ .../com/adh/manager/data/ScopeRepository.kt | 2 + .../adh/manager/ipc/DaemonBinderProvider.kt | 4 + .../adh/manager/ui/scope/HookConfigScreen.kt | 280 +++--------------- .../src/main/res/values-en/strings.xml | 13 +- .../manager/src/main/res/values/strings.xml | 13 +- .../manager/data/DaemonScopeRepositoryTest.kt | 26 +- docs/P5_HOOK_PLANS.md | 106 +++++++ docs/mcp-tools.md | 5 +- injector/zygisk/jni/main.cpp | 57 ++-- tools/generate_mcp_docs.mjs | 2 + 66 files changed, 1090 insertions(+), 350 deletions(-) create mode 100644 agent/src/bootstrap/early_plan.cpp create mode 100644 agent/src/bootstrap/early_wire.h create mode 100644 daemon/public/hook-plans-panel.js create mode 100644 daemon/src/hook_plan_host.ts create mode 100644 daemon/src/hook_plans.ts create mode 100644 daemon/src/http/routes_hook_plans.ts create mode 100644 daemon/test/fixtures/early_wire.cpp create mode 100644 daemon/test/fixtures/p5_workbench.ts create mode 100644 daemon/test/hook_early.test.ts create mode 100644 daemon/test/hook_entrypoints.test.ts create mode 100644 daemon/test/hook_plans.test.ts create mode 100644 device/core/src/main/java/com/adh/core/EarlyPlanWire.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/AgentEarlyAbi.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/HookPlanCache.kt create mode 100644 device/daemon/src/test/java/com/adh/daemon/AgentEarlyAbiTest.kt create mode 100644 docs/P5_HOOK_PLANS.md diff --git a/README.md b/README.md index 6608fbf..047a1de 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,15 @@ Android DecryptHub(ADH)是一套 Android 运行时分析工具。它把一个轻量程序注入到你勾选的应用里,观察这个应用在运行时做了什么:网络、加密、Java 方法、native 函数、内存和 DEX。重的分析放在电脑上,不放进目标应用。 +P5 分支将 Hook 方案和编辑器迁到 Host。MCP `hook_plans`、Python CLI `adh call/run hook_plans` 和任务工作台共用执行层。保存、暂存和实际安装分别报告,连接不自动套用旧捕获/启动默认值。迁移与兼容边界见 [P5_HOOK_PLANS.md](docs/P5_HOOK_PLANS.md)。此分支尚未部署到现有分析现场。 + ## 能做什么 **只影响勾选的应用。** 在手机上的 ADH Manager 里勾选注入范围并保存,然后重新打开该应用。主进程和 `:core` 这类子进程都会注入。没勾选的应用不会注入。 -**用代理看 HTTPS。** 应用被注入之后,Java 侧的证书校验会放行。配合你自己的抓包代理(系统代理或 VPN),可以看到这个应用发出的 HTTPS。native 的 `SSL_read` / `SSL_write` 明文是另一项,要在电脑上开始采集才会装,Manager 里的「TLS 明文」开关管的是这一项。 +**用代理看 HTTPS。** 手机负责系统 CA 管理;Java trust-manager bypass 由 Host 显式执行 `java_hook action=bypass`。native 的 `SSL_read` / `SSL_write` 明文由显式捕获方案控制。注入与连接本身不会自动安装这些 Hook。 -**记录 Java 加密。** 注入后自动观察这些接口,原来的方法照常执行: +**记录 Java 加密。** Host 可显式执行 `java_hook action=crypto`,或用方案中的 Java 方法步骤观察这些接口;原来的方法照常执行: | 接口 | 记下什么 | | --- | --- | @@ -17,7 +19,7 @@ Android DecryptHub(ADH)是一套 Android 运行时分析工具。它把一 | `java.security.MessageDigest` | `digest`。例如 MD5、SHA-256 | | `java.security.Signature` | `initSign`、`initVerify`、`sign`、`verify`。例如 SHA256withRSA | -每条记录包含算法名、操作(加密、解密、摘要、签名等)、密钥、IV、输入和输出。Manager 里可以按应用关掉某一族(摘要、HMAC、对称、非对称、AEAD);关掉的族不会安装钩子。保存后要重启该应用。RSA 加解密跟着「对称」或 AEAD,RSA 签名跟着「非对称」。 +每条记录按接口能力包含算法名、操作、密钥、IV、输入和输出。方案中的 family 控制后续 native 捕获安装资格;Manager 保留旧配置快照和缓存撤销入口,编辑方案在 Host 完成。Java 原语的覆盖边界以工具返回和实际事件为准。 这些情况记不到,或只能记到一部分: diff --git a/agent/CMakeLists.txt b/agent/CMakeLists.txt index a03d4fe..4bf0a86 100644 --- a/agent/CMakeLists.txt +++ b/agent/CMakeLists.txt @@ -9,6 +9,7 @@ set(CMAKE_C_VISIBILITY_PRESET hidden) set(AGENT_SOURCES src/capture/capture.c src/bootstrap/agent_main.c + src/bootstrap/early_plan.cpp src/bootstrap/util.c src/bootstrap/io.c src/bootstrap/mem.c @@ -139,4 +140,4 @@ target_link_libraries(adh_agent ${log-lib} dl ${HOOK_LIBS} ${LSPLANT_LIBS}) # Keep our own code small + hidden; -Wall/-Wextra apply to C agent sources only # (third-party hook sources get -Wno-everything above). target_compile_options(adh_agent PRIVATE -O2 -fvisibility=hidden) -target_compile_options(adh_agent PRIVATE $<$:-Wall -Wextra>) \ No newline at end of file +target_compile_options(adh_agent PRIVATE $<$:-Wall -Wextra>) diff --git a/agent/exports.map b/agent/exports.map index dfc53b7..6cf8b0a 100644 --- a/agent/exports.map +++ b/agent/exports.map @@ -7,6 +7,7 @@ adh_agent_set_qbdi_fd; adh_agent_set_vm; adh_agent_start; + adh_agent_apply_early_v1; local: *; }; diff --git a/agent/src/MAP.md b/agent/src/MAP.md index 9cc6d11..29e5018 100644 --- a/agent/src/MAP.md +++ b/agent/src/MAP.md @@ -65,3 +65,6 @@ the build you think you flashed. Both the module zip and the agent must be rebui - `tools/build_agent.sh` keeps `libadh_agent.so.debug` locally and stages only a stripped `.so`. - `exports.map` restricts `.dynsym` to `JNI_OnLoad`, `adh_agent_set_package`, `adh_agent_set_policy`, and `adh_agent_start`. - `compat_probe` reports bootstrap vs current exec/anon-exec/RWX counters; base injection and GOT hooks must not add true anonymous executable pages. +# P5 early-plan/1 addition + +`bootstrap/early_wire.h` is the shared bounded native validator and SHA implementation; `bootstrap/early_plan.cpp` consumes only verified named capture/GOT observation steps before `adh_agent_start`, stops on an unconfirmed installation and adds agent-reported receipts to hello. `capture_policy` explicitly sets/reads family eligibility. No .init_array timing guarantee. Full contract: [P5_HOOK_PLANS.md](../../docs/P5_HOOK_PLANS.md). diff --git a/agent/src/bootstrap/agent_main.c b/agent/src/bootstrap/agent_main.c index 7949e50..b0d96ca 100644 --- a/agent/src/bootstrap/agent_main.c +++ b/agent/src/bootstrap/agent_main.c @@ -55,6 +55,7 @@ static char g_package[512] = ""; // Per-package hook policy line from the Zygisk companion ("d=1,h=0,…,y=0"); empty = no policy → // crypto families on, system detection off. static char g_policy[64] = ""; +extern const char *adh_early_status_json(void); // ---- report + command loop ------------------------------------------------ @@ -69,7 +70,7 @@ static const char *ADH_AGENT_OPS[] = { "native_call", "got_enum", "stealth", "javahook_probe", "gothook_selftest", "capture_start", "capture_drain", "capture_stop", "trigger", "load_so", "file_probe", "qbdi_trace", "qbdi_read", "compat_probe", "object_inspect", "object_set", "object_invoke", "art_dexfiles", "list_dir", - "read_file", "scan_magic", "mem_backend", "search", "frame_echo", "ping", "module_watch", + "read_file", "scan_magic", "mem_backend", "search", "frame_echo", "ping", "module_watch", "capture_policy", }; static void send_caps(int fd) { @@ -129,15 +130,15 @@ static void report(int fd) { if (adh_self_starttime_ticks(ticks, sizeof(ticks))) snprintf(generation, sizeof(generation), "\"starttimeTicks\":\"%s\",", ticks); - char hello[2048]; + char hello[4096]; snprintf(hello, sizeof(hello), "{\"t\":\"hello\",\"agentVer\":\"%s\",\"pid\":%d,\"uid\":%d," "%s\"package\":\"%s\",\"process\":\"%s\",\"abi\":\"%s\",\"android\":\"%s\",\"sdk\":%s," "\"entry\":\"%s\",\"selfModule\":\"%s\",\"selfBase\":\"0x%llx\"," - "\"policy\":\"%s\"}\n", + "\"policy\":\"%s\",\"earlyPlan\":%s}\n", AGENT_VER, getpid(), getuid(), generation, pkgj, pkg, abi[0] ? abi : "?", rel[0] ? rel : "?", sdk[0] ? sdk : "0", g_entry, - selfj, self_start, g_policy[0] ? g_policy : "default"); + selfj, self_start, g_policy[0] ? g_policy : "default",adh_early_status_json()); if (send_line(fd, hello) != 0) { LOGE("send hello failed"); return; } // The manifest goes immediately after the hello so a client can plan from what this build // can actually do before it issues any command. @@ -828,6 +829,12 @@ static void command_loop(int fd) { char waction[16] = ""; json_get_str(line, "action", waction, sizeof(waction)); adh_cmd_module_watch(fd, id, waction); + } else if (strcmp(op, "capture_policy") == 0) { + char flags[64]="",action[16]="",idj[128];json_get_str(line,"families",flags,sizeof(flags));json_get_str(line,"action",action,sizeof(action));json_escape(id,idj,sizeof(idj)); + int valid=strlen(flags)==27; + const char *keys="dhsatey";for(int i=0;i<7&&valid;i++)if(flags[i*4]!=keys[i]||flags[i*4+1]!='='||(flags[i*4+2]!='0'&&flags[i*4+2]!='1')||(i<6&&flags[i*4+3]!=','))valid=0; + if(strcmp(action,"status")==0)valid=1;else if(valid){extern void adh_agent_set_policy(const char*);adh_agent_set_policy(flags);} + char reply[256];snprintf(reply,sizeof(reply),"{\"t\":\"cmdResult\",\"id\":\"%s\",\"op\":\"capture_policy\",\"ok\":%s,\"policy\":\"%s\"}",idj,valid?"true":"false",g_policy[0]?g_policy:"d=1,h=1,s=1,a=1,t=1,e=1,y=0");send_line(fd,reply); } else if (strcmp(op, "capture_start") == 0) { char cmod[64] = "", fmod[64] = "", smod[512] = ""; json_get_str(line, "cryptoModule", cmod, sizeof(cmod)); @@ -1104,6 +1111,7 @@ static int current_agent_copy_is_owner(void) { } static void start_reporter_watch(void); // defined below +int adh_agent_copy_owner(void) { return current_agent_copy_is_owner(); } __attribute__((visibility("default"))) void adh_agent_start(void) { diff --git a/agent/src/bootstrap/early_plan.cpp b/agent/src/bootstrap/early_plan.cpp new file mode 100644 index 0000000..860c8ab --- /dev/null +++ b/agent/src/bootstrap/early_plan.cpp @@ -0,0 +1,31 @@ +#include "early_wire.h" +#include "../hook/native_hooks.h" +#include "../capture/capture.h" +#include +#include +#include +#include +extern "C" void adh_agent_set_policy(const char*); +extern "C" int adh_agent_copy_owner(void); +static char status[2048]="null"; +static bool attempted=false; +static int apply(const AdhEarlyStep& step,int* hookId,void*){ + if(step.type==2){char error[512]{};int ok=adh_native_hook_install("got",step.a,step.b,"",0,0,0,-1,0,0,"",0,0,0,step.c,-1,0,"",-1,"","",0,"","",0,1,0,"",hookId,error,sizeof(error));return ok&&*hookId>0?1:0;} + int fd=int(syscall(SYS_memfd_create,"adh-early-result",1));if(fd<0)return -1; + adh_cmd_capture_start(fd,"early-cache",step.a,step.b,step.c); + auto size=lseek(fd,0,SEEK_END);if(size<5||size>8192||lseek(fd,0,SEEK_SET)<0){close(fd);return -1;}char data[8193]{};auto n=read(fd,data,size_t(size));close(fd);if(n!=size)return -1; + const auto* h=reinterpret_cast(data);size_t len=(size_t(h[0])<<24)|(size_t(h[1])<<16)|(size_t(h[2])<<8)|h[3];if(len+5!=size_t(size)||h[4]!=1)return -1; + // This response contains install counters only, except sysModules. Count positive counters, + // never the agent's unconditional ok:true or the number of requested system modules. + int installed=0;const char* p=data+5;while((p=strstr(p,"\":"))){const char* end=p;const char* begin=end;while(begin>data+5&&begin[-1]!='"')begin--;bool modules=size_t(end-begin)==10&&!memcmp(begin,"sysModules",10);p+=2;while(*p==' ')p++;if(*p>='0'&&*p<='9'){char* next=nullptr;long v=strtol(p,&next,10);if(!modules&&v>0&&v<100000)installed+=int(v);p=next;}} + return installed; +} +extern "C" const char* adh_early_status_json(){return status;} +extern "C" __attribute__((visibility("default"))) int adh_agent_apply_early_v1(const void* wire,size_t size,const char* package,const char* actualAgentSha){ + if(!adh_agent_copy_owner()||attempted)return 0;attempted=true;AdhEarlyPlan plan; + if(!adh_early_parse(wire,size,package,uint32_t(getuid()),actualAgentSha,uint64_t(time(nullptr)),plan)){snprintf(status,sizeof(status),"{\"state\":\"rejected\",\"phase\":\"post-specialize-before-agent-start\"}");return 0;} + char flags[64];snprintf(flags,sizeof(flags),"d=%d,h=%d,s=%d,a=%d,t=%d,e=%d,y=%d",!!(plan.families&1),!!(plan.families&2),!!(plan.families&4),!!(plan.families&8),!!(plan.families&16),!!(plan.families&32),!!(plan.families&64));adh_agent_set_policy(flags); + auto result=adh_early_run(plan,apply,nullptr);std::string steps;for(unsigned n=0;n +#include +#include +#include +#include + +// SHA-256 for integrity/binary identity only; authorization belongs to the root broker. +struct AdhSha256 { + uint32_t h[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; + uint8_t buffer[64]{};size_t used=0;uint64_t length=0; + static uint32_t r(uint32_t x,unsigned n){return(x>>n)|(x<<(32-n));} + void block(const uint8_t* p){ + static const uint32_t k[64]={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; + uint32_t w[64];for(int i=0;i<16;i++)w[i]=(uint32_t(p[i*4])<<24)|(uint32_t(p[i*4+1])<<16)|(uint32_t(p[i*4+2])<<8)|p[i*4+3]; + for(int i=16;i<64;i++)w[i]=w[i-16]+(r(w[i-15],7)^r(w[i-15],18)^(w[i-15]>>3))+w[i-7]+(r(w[i-2],17)^r(w[i-2],19)^(w[i-2]>>10)); + uint32_t a=h[0],b=h[1],c=h[2],d=h[3],e=h[4],f=h[5],g=h[6],v=h[7]; + for(int i=0;i<64;i++){uint32_t t=v+(r(e,6)^r(e,11)^r(e,25))+((e&f)^(~e&g))+k[i]+w[i];uint32_t u=(r(a,2)^r(a,13)^r(a,22))+((a&b)^(a&c)^(b&c));v=g;g=f;f=e;e=d+t;d=c;c=b;b=a;a=t+u;} + h[0]+=a;h[1]+=b;h[2]+=c;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g;h[7]+=v; + } + void update(const void* data,size_t size){const auto* p=static_cast(data);length+=size;while(size){size_t n=64-used;if(n>size)n=size;memcpy(buffer+used,p,n);used+=n;p+=n;size-=n;if(used==64){block(buffer);used=0;}}} + void final(uint8_t out[32]){uint64_t bits=length*8;buffer[used++]=0x80;if(used>56){while(used<64)buffer[used++]=0;block(buffer);used=0;}while(used<56)buffer[used++]=0;for(int i=7;i>=0;i--)buffer[used++]=uint8_t(bits>>(i*8));block(buffer);for(int i=0;i<32;i++)out[i]=uint8_t(h[i/4]>>(24-8*(i%4)));} +}; +inline std::string adh_hex(const uint8_t* data,size_t n){static const char d[]="0123456789abcdef";std::string s;for(size_t i=0;i>4];s+=d[data[i]&15];}return s;} +inline std::string adh_sha_fd(int fd){auto old=lseek(fd,0,SEEK_CUR);if(lseek(fd,0,SEEK_SET)<0)return{};AdhSha256 hash;uint8_t data[8192];size_t total=0;bool ok=true;for(;;){auto n=read(fd,data,sizeof(data));if(n<0){ok=false;break;}if(!n)break;total+=size_t(n);if(total>128*1024*1024){ok=false;break;}hash.update(data,size_t(n));}if(old>=0)lseek(fd,old,SEEK_SET);if(!ok)return{};uint8_t out[32];hash.final(out);return adh_hex(out,32);} +constexpr size_t ADH_EARLY_MAX=32768; +struct AdhEarlyStep {uint8_t type=0;char a[160]{},b[160]{},c[160]{};}; +struct AdhEarlyPlan {char deployment[40]{},digest[65]{},package[256]{},agentSha[65]{};uint32_t uid=0;uint64_t expires=0;uint8_t families=0,count=0;AdhEarlyStep steps[16]{};}; +struct AdhEarlyReader {const uint8_t* data;size_t size,pos=0;bool ok=true; + uint64_t num(size_t n){if(n>8||pos+n>size){ok=false;return 0;}uint64_t v=0;while(n--)v=(v<<8)|data[pos++];return v;} + bool text(char* out,size_t cap){size_t n=size_t(num(2));if(!ok||n>=cap||pos+n>size){ok=false;return false;}for(size_t i=0;i126){ok=false;return false;}memcpy(out,data+pos,n);out[n]=0;pos+=n;return true;} +}; +inline bool adh_hash_string(const char* s){if(strlen(s)!=64)return false;for(int i=0;i<64;i++)if(!((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')))return false;return true;} +inline bool adh_module_string(const char* s,bool empty){if(!s[0])return empty;if(strlen(s)>63)return false;unsigned commas=0;for(const char* p=s;*p;p++){char c=*p;if(c==',')commas++;if(!((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||strchr("_./+,-",c)))return false;}return commas<8;} +inline bool adh_early_parse(const void* value,size_t size,const char* package,uint32_t uid,const char* agentSha,uint64_t now,AdhEarlyPlan& plan){ + if(!value||size<40||size>ADH_EARLY_MAX)return false;const auto* bytes=static_cast(value);AdhSha256 hash;uint8_t actual[32];hash.update(bytes+32,size-32);hash.final(actual);if(memcmp(actual,bytes,32)||memcmp(bytes+32,"ADHEP1\r\n",8))return false; + AdhEarlyReader r{bytes+40,size-40};if(!r.text(plan.deployment,sizeof(plan.deployment))||strlen(plan.deployment)!=36||!r.text(plan.digest,sizeof(plan.digest))||!adh_hash_string(plan.digest)||!r.text(plan.package,sizeof(plan.package)))return false; + plan.uid=uint32_t(r.num(4));if(!r.text(plan.agentSha,sizeof(plan.agentSha))||!adh_hash_string(plan.agentSha))return false;plan.expires=r.num(8);plan.families=uint8_t(r.num(1));plan.count=uint8_t(r.num(1)); + if(!r.ok||strcmp(plan.package,package)||plan.uid!=uid||strcmp(plan.agentSha,agentSha)||plan.expires<=now||plan.expires-now>86400||plan.families>127||plan.count<1||plan.count>16)return false; + for(unsigned i=0;i='a'&&*p<='z')||(*p>='A'&&*p<='Z')||(*p>='0'&&*p<='9')||strchr("_.$@",*p)))return false;} + else return false; + }return r.ok&&r.pos==r.size; +} +struct AdhEarlyReceipt {int attempted=0,confirmed=0;int counts[16]{},hookIds[16]{};bool applied=false;}; +using AdhEarlyApply=int(*)(const AdhEarlyStep&,int*,void*); +inline AdhEarlyReceipt adh_early_run(const AdhEarlyPlan& plan,AdhEarlyApply apply,void* context){AdhEarlyReceipt result;for(unsigned n=0;n{ + const json=value=>JSON.stringify(value,null,2); + function mount(root,client,goOperation){ + root.innerHTML=`

Host Hook 方案库

方案保存在 Host。保存版本不会装 Hook;应用只作用于明确选择的进程。AI 默认继续自主分析,人类写入遵循相同的控制版本。

尚未读取方案库

执行、早期缓存与可逆迁移

早期缓存只支持具名模块捕获和只观测的 GOT Hook,阶段为进程 specialize 后、Agent 启动前。先查询设备和绑定,再显式迁移、暂存;无法提前执行的步骤返回 unsupported。撤销只阻止未来进程使用缓存,已安装 Hook 需单独核对。

参数示例:实时操作填写 digest、session;观察/撤销填写 runId;缓存和迁移填写 deviceId、connectionId、bootId、daemonInstanceId、expectedDeviceRevision,以及 prepare/preview 返回的绑定和版本。每次改变意图后重新读取提交版本。

草稿尚未提交

{}
`; + const $=id=>root.querySelector('#'+id),reads=['list','get','validate','preflight','run','observe','early-prepare','early-status','migration-preview'],writes=['put','import-legacy','apply','undo','early-stage','early-revoke','migration-apply','migration-rollback']; + let libraryRevision,prepared,pending,waiting=false,busy=false; + for(const action of [...reads,...writes]){const option=document.createElement('option');option.value=action;option.textContent=action+(reads.includes(action)?' · 查询':' · 写入');$('hpAction').append(option);} + $('hpPlan').value=json({schemaVersion:1,id:'my-plan',title:'我的 Hook 方案',package:'com.example.app',families:{digest:true,hmac:true,symmetric:false,asymmetric:false,tls:false,aead:false,system:false},steps:[{id:'capture',tool:'capture_start',arguments:{cryptoModule:'libexample.so',fileModule:'',sysModule:''}}]}); + function args(){return {...JSON.parse($('hpArgs').value),action:$('hpAction').value};} + function permissions(){for(const id of ['hpQuery','hpRead','hpPrepare','hpValidate','hpSaveDraft'])$(id).disabled=busy||!!pending||waiting;$('hpSubmit').disabled=busy||!!pending||waiting||!client.operator||!prepared;$('hpFind').hidden=!pending;for(const id of ['hpPlan','hpArgs','hpAction'])$(id).disabled=busy||!!pending||waiting;} + client.subscribe(permissions); + function invalidate() {prepared=undefined;$('hpStatus').textContent='草稿已修改,请重新读取版本';permissions();} + $('hpArgs').oninput=invalidate;$('hpAction').onchange=invalidate;$('hpPlan').oninput=invalidate; + async function work(fn){if(busy)return;busy=true;permissions();try{await fn();}catch(error){$('hpStatus').textContent=(error.transport?'请求结果未确认;保留意图键,请查询任务。':`未完成 · ${error.code||'ERROR'} · ${error.message}`);$('hpResult').textContent=json(error.value||{code:error.code,error:error.message});}finally{busy=false;permissions();}} + const show=value=>{$('hpResult').textContent=json(value);}; + async function readLibrary(){const value=(await client.request('/api/hook-plans?action=list')).value;libraryRevision=value.revision;$('hpVersion').textContent=`方案库版本 ${value.revision} · ${value.plans.length} 个方案 · 不自动应用`;$('hpLibrary').replaceChildren();for(const item of value.plans){const button=document.createElement('button');button.textContent=item.title+' · '+item.package;button.title=item.digest;button.onclick=()=>work(async()=>{const v=(await client.request('/api/hook-plans?action=get&digest='+item.digest)).value;$('hpPlan').value=json(v.plan);$('hpArgs').value=json({digest:item.digest});invalidate();show(v);});$('hpLibrary').append(button);}} + $('hpRead').onclick=()=>work(readLibrary); + $('hpValidate').onclick=()=>work(async()=>{show((await client.request('/api/hook-plans',{action:'validate',plan:JSON.parse($('hpPlan').value)})).value);$('hpStatus').textContent='方案草稿验证完成;尚未保存或应用';}); + $('hpSaveDraft').onclick=()=>work(async()=>{if(libraryRevision===undefined)await readLibrary();$('hpAction').value='put';$('hpArgs').value=json({plan:JSON.parse($('hpPlan').value),expectedLibraryRevision:libraryRevision});invalidate();$('hpStatus').textContent='已准备保存参数;读取提交版本后显式提交';}); + $('hpQuery').onclick=()=>work(async()=>{if(!reads.includes($('hpAction').value))throw Error('此操作会写入,请先读取提交版本');show((await client.request('/api/hook-plans',args())).value);$('hpStatus').textContent='查询已完成;没有安装或重发写入';}); + $('hpPrepare').onclick=()=>work(async()=>{const intent=args();if(!writes.includes(intent.action))throw Error('选择写入操作后再读取提交版本');const snapshot=await client.managementPrepare('/api/hook-plans','POST',intent);prepared={intent:json(intent),snapshot,key:client.intent()};$('hpStatus').textContent=`已读取 ${snapshot.resource} · v${snapshot.revision} · 控制代次 ${snapshot.epoch}。接管/交还控制后需重新读取。`;show(snapshot);}); + async function find(){const value=await client.management({action:'get',idempotencyKey:pending,includeResult:true});const op=value.operation;show(op);$('hpLink').replaceChildren();const link=document.createElement('button');link.textContent='查看任务、结果与副作用';link.onclick=()=>goOperation(op.id);$('hpLink').append(link);$('hpStatus').textContent=`${op.state} · ${op.id} · 不自动重发`;if(['succeeded','failed','unknown','cancelled'].includes(op.state)){pending=undefined;prepared=undefined;}permissions();} + $('hpSubmit').onclick=()=>work(async()=>{client.requireOperator();if(!prepared||prepared.intent!==json(args()))throw Error('参数已变更,请重新读取提交版本');const current=prepared;pending=current.key;waiting=true;try{const value=await client.management({action:'submit',tool:'hook_plans',arguments:JSON.parse(current.intent),_operation:client.metadata(current.snapshot,current.key)});show(value);prepared=undefined;await find();}catch(error){if(!error.transport)pending=undefined;throw error;}finally{waiting=false;}}); + $('hpFind').onclick=()=>work(find);permissions(); + return {read:()=>work(readLibrary)}; + } + scope.AdhHookPlansPanel={mount}; +})(globalThis); diff --git a/daemon/public/index.html b/daemon/public/index.html index 337b070..3cbdca0 100644 --- a/daemon/public/index.html +++ b/daemon/public/index.html @@ -751,7 +751,7 @@

注入后端

- + + diff --git a/daemon/public/workbench.js b/daemon/public/workbench.js index 297e642..33361e1 100644 --- a/daemon/public/workbench.js +++ b/daemon/public/workbench.js @@ -9,12 +9,12 @@ root.classList.add('adh-workbench'); root.innerHTML=`
ADH / HUMAN CONSOLE

任务工作台

AI 自主分析 · 人类观察、修改与接管

操作员连接 · 凭据仅保留在当前页面内存

查看任务无需接管。只有明确修改、暂停或切换控制权时才使用操作员权限。

- +

正在读取控制状态…

选择一项任务AI 提交的任务会显示在左侧。查看任务不会暂停分析,也不会改变控制权。
- `; + `; const $=id=>root.querySelector('#'+id),s={view:'tasks',visible:true,busy:false,listOffset:0,opOffset:0,taskId:null,task:null,opId:null,op:null,resultLoaded:false,resultSignature:'',draft:null,conflict:null,pending:null,intent:null,control:null,listGeneration:0,detailGeneration:0,operationGeneration:0}; let timer,pendingTimer,searchTimer,controlGeneration=0,lastOpRender='',lastTaskRender='',lastListRender='',lastRowsRender=''; const notice=(title,text,code='',tone='error',actions=[])=>{$('awNotice').hidden=false;$('awNotice').dataset.tone=tone;$('awNoticeTitle').textContent=title;$('awNoticeText').textContent=text;$('awNoticeCode').textContent=code;$('awNoticeCode').hidden=!code;$('awNoticeActions').replaceChildren(...actions);}; @@ -24,7 +24,7 @@ $('awRole').textContent=client.operator?'操作员已连接':'观察模式';$('awRole').dataset.state=client.operator?'paused':'active'; for(const node of root.querySelectorAll('[data-mutate]'))node.disabled=s.busy||!client.operator; for(const node of root.querySelectorAll('[data-navigate]'))node.disabled=s.busy; - for(const id of ['awTasksTab','awConfigTab','awRefresh'])$(id).disabled=s.busy; + for(const id of ['awTasksTab','awConfigTab','awPlansTab','awRefresh'])$(id).disabled=s.busy; $('awScope').disabled=s.busy; const editingBlocked=s.busy||!!s.pending||!!s.intent||!!s.checkingPending; for(const node of $('awConfigForm').querySelectorAll('input,textarea'))node.disabled=editingBlocked; @@ -41,8 +41,9 @@ $('awDisconnect').onclick=()=>{client.disconnect();notice('已断开操作员','页面已清除凭据。既有控制权不会自动释放,请在离开前按需交还 AI。','','success');}; $('awNoticeDismiss').onclick=()=>{$('awNotice').hidden=true;}; $('awClose').onclick=()=>options.close?options.close():location.assign('/'); - function view(name){s.view=name;$('awTasksView').hidden=name!=='tasks';$('awConfigView').hidden=name!=='configuration';$('awTasksTab').setAttribute('aria-pressed',String(name==='tasks'));$('awConfigTab').setAttribute('aria-pressed',String(name==='configuration'));if(name==='configuration'&&!s.draft)work(loadConfiguration);} - $('awTasksTab').onclick=()=>view('tasks');$('awConfigTab').onclick=()=>view('configuration'); + const plansPanel=scope.AdhHookPlansPanel.mount($('awPlansView'),client,id=>{view('tasks');work(()=>goOperation(id));}); + function view(name){s.view=name;$('awPlansView').hidden=name!=='plans';$('awPlansTab').setAttribute('aria-pressed',String(name==='plans'));$('awTasksView').hidden=name!=='tasks';$('awConfigView').hidden=name!=='configuration';$('awTasksTab').setAttribute('aria-pressed',String(name==='tasks'));$('awConfigTab').setAttribute('aria-pressed',String(name==='configuration'));if(name==='configuration'&&!s.draft)work(loadConfiguration);} + $('awPlansTab').onclick=()=>{view('plans');plansPanel.read();};$('awTasksTab').onclick=()=>view('tasks');$('awConfigTab').onclick=()=>view('configuration'); const filters=()=>({q:$('awSearch').value,state:$('awState').value,owner:$('awOwner').value}); function filter(){s.listOffset=0;refreshList().catch(report);} $('awSearch').oninput=()=>{clearTimeout(searchTimer);searchTimer=setTimeout(filter,250);};$('awState').onchange=filter;$('awOwner').onchange=filter; diff --git a/daemon/src/MAP.md b/daemon/src/MAP.md index 40f54ec..0628306 100644 --- a/daemon/src/MAP.md +++ b/daemon/src/MAP.md @@ -4,6 +4,14 @@ ADH Daemon / `adhd` (Node 24 + TypeScript, runs `.ts` directly, no build step). ## P2 human workbench (2026-11-16) +## P5 Host Hook plans (2026-11-16) + +- `hook_plans.ts` owns immutable JSON plan versions, library CAS, explicit target preflight, coordinated steps/receipts and ownership-checked undo. `hook_plan_host.ts` dispatches the same actions for MCP, REST and published Python CLI. No hello/settings auto-install. +- `public/hook-plans-panel.js` mounts inside the shared workbench; drafts, frozen submit versions, persistent tasks and intent-key recovery use `operation-client.js`. +- Device early cache and reversible scope migration use the P3/P4 verified device RPC, never legacy target identity inference or ADB fallback. See [P5_HOOK_PLANS.md](../../docs/P5_HOOK_PLANS.md). + +## P2 human workbench details + - `public/workbench.js`, `workbench.css`, `workbench.html`: the SAME task/configuration UI embedded in the live viewer and served at `/workbench`. `public/operations.js` is the thin live-view adapter; `operation-client.js` owns the shared credential/transport and legacy fetch guard. `workbench-model.js` isolates draft diff/validation/explicit rebase without DOM/I/O. - Task get includes revision, resources and operation counts; panel task changes use `_operation.expectedTaskRevision`. Filtered lists expose independent task/operation pagination. Intent-key get is read-only recovery, never replay. - `execution_context.ts` assigns bounded effect IDs so concurrent dispatch/acknowledgement pairs remain correct; `operations.ts` persists up to 64 metadata-only effect rows and omission counts. New operation timestamps are factual; missing legacy data stays missing. Do not include payloads/keys or turn an acknowledgement into proof of target success. diff --git a/daemon/src/device_host.ts b/daemon/src/device_host.ts index d3e914d..09afd22 100644 --- a/daemon/src/device_host.ts +++ b/daemon/src/device_host.ts @@ -21,7 +21,7 @@ export async function deviceAction(a:any){ case 'reconcile':{ const engine=getOperations(),ids=a.operationIds; if(!Array.isArray(ids)||ids.length<1||ids.length>100)return deviceFail('INVALID_ARGUMENT','select 1..100 Host device mutation ids'); - for(const id of ids){const op=engine.getOperation(id);if(op.resource!=='device:'+a.deviceId||op.name!=='devices'||op.mode!=='write'||op.connectionOnly)return deviceFail('TARGET_CHANGED','operation belongs to another device or is not a device mutation');} + for(const id of ids){const op=engine.getOperation(id);if(op.resource!=='device:'+a.deviceId||!['devices','hook_plans'].includes(op.name)||op.mode!=='write'||op.connectionOnly)return deviceFail('TARGET_CHANGED','operation belongs to another device or is not a device mutation');} const result=await service.reconcile(a.deviceId,ids,a.connectionId); const rows=result.result?.operations; if(!Array.isArray(rows)||rows.length!==ids.length||new Set(rows.map((r:any)=>r.operationId)).size!==ids.length||rows.some((r:any)=>!ids.includes(r.operationId)))return deviceFail('RECONCILIATION_INVALID','device did not return the exact requested operation set; no evidence attached'); diff --git a/daemon/src/device_protocol.ts b/daemon/src/device_protocol.ts index 04d0da1..cfd02d7 100644 --- a/daemon/src/device_protocol.ts +++ b/daemon/src/device_protocol.ts @@ -7,8 +7,8 @@ import { OperationError } from './execution_context.ts'; export const DEVICE_PROTOCOL='adh.device/1', DEVICE_SOCKET='adh_device_rpc_v1'; export const DEVICE_BOOTSTRAP='/data/adb/adh/device-rpc/usb-access.json'; export const DEVICE_FRAME_MAX=1024*1024; -export const DEVICE_READ_METHODS=new Set(['device.info','device.capabilities','device.state','module.status','scope.get','applications.list','processes.list','certificates.list','host.get','operations.get','operations.reconcile','lan.status','pairings.list']); -export const DEVICE_WRITE_METHODS=new Set(['scope.patch','scope.replace','process.control','certificates.put','certificates.delete','host.set','operations.resolve','lan.configure','pairings.grant','pairings.revoke']); +export const DEVICE_READ_METHODS=new Set(['device.info','device.capabilities','device.state','module.status','scope.get','applications.list','processes.list','certificates.list','host.get','operations.get','operations.reconcile','lan.status','pairings.list','early.prepare','early.status','hooks.migration.preview']); +export const DEVICE_WRITE_METHODS=new Set(['scope.patch','scope.replace','process.control','certificates.put','certificates.delete','host.set','operations.resolve','lan.configure','pairings.grant','pairings.revoke','early.stage','early.revoke','hooks.migration.apply','hooks.migration.rollback']); export const uuid=(value:unknown):value is string=>typeof value==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value); export class DeviceError extends OperationError {} export function deviceFail(code:string,message:string,uncertain=false):never{throw new DeviceError(code,message,uncertain);} diff --git a/daemon/src/devices.ts b/daemon/src/devices.ts index ccff6a9..b2e3be6 100644 --- a/daemon/src/devices.ts +++ b/daemon/src/devices.ts @@ -107,7 +107,7 @@ export class Devices { if(mode==='write'){ if(!ctx?.operationId)deviceFail('OPERATION_REQUIRED','device mutations must enter the shared Host operation coordinator'); if(ctx.connectionOnly)deviceFail('OPERATION_REQUIRED','connection recovery cannot dispatch device mutations'); - if(ctx.securityOnly&&!(args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false))deviceFail('OPERATION_REQUIRED','quarantined security control can only revoke grants or disable LAN'); + if(ctx.securityOnly&&!(args.method==='early.revoke'||args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false))deviceFail('OPERATION_REQUIRED','quarantined security control can only revoke grants/cache or disable LAN'); if(ctx.resource!=='device:'+args.deviceId)deviceFail('TARGET_CHANGED','Host operation is bound to another resource; no cross-device dispatch'); if(args.bootId!==c.peer.bootId||args.daemonInstanceId!==c.peer.daemonInstanceId)deviceFail('TARGET_CHANGED','send the observed device bootId and daemonInstanceId; no automatic rebinding'); if(!Number.isSafeInteger(args.expectedDeviceRevision)||args.expectedDeviceRevision < 0)deviceFail('DEVICE_VERSION_REQUIRED','send the observed device stateRevision'); diff --git a/daemon/src/hook_plan_host.ts b/daemon/src/hook_plan_host.ts new file mode 100644 index 0000000..8e199b6 --- /dev/null +++ b/daemon/src/hook_plan_host.ts @@ -0,0 +1,35 @@ +import {join} from 'node:path'; +import {DATA_DIR,settings} from './state.ts'; +import {HookPlans,validatePlan,legacyPlan,canonical,type PlanTool} from './hook_plans.ts'; +import {getDevices} from './device_host.ts'; +import {OperationError} from './execution_context.ts'; +import {getOperations} from './operation_host.ts'; +let library:HookPlans|undefined; +export const getHookPlans=()=>library??=new HookPlans(join(DATA_DIR,'hook-plans')); +type Lookup=(name:string)=>PlanTool|undefined; +export async function hookPlanAction(a:any,lookup:Lookup){ + const plans=getHookPlans(); + switch(a.action||'list'){ + case 'list':return plans.list(); + case 'get':return plans.get(a.digest); + case 'validate':return {ok:true,plan:validatePlan(a.plan,lookup),applied:false}; + case 'put':return plans.put(a.plan,a.expectedLibraryRevision,lookup); + case 'import-legacy':return plans.put(legacyPlan(a.scope,a.settings||structuredClone(settings),a.package,a.id),a.expectedLibraryRevision,lookup); + case 'preflight':return plans.preflight(a.digest,a.session,lookup); + case 'apply':return plans.apply(a.digest,a.session,lookup); + case 'run':return {ok:true,run:plans.run(a.runId),operation:getOperations().getOperation(a.runId),recordedStateIsHistorical:true}; + case 'observe':return {...await plans.observe(a.runId,lookup),operation:getOperations().getOperation(a.runId)}; + case 'undo':if(plans.run(a.runId).session!==a.session)throw new OperationError('PLAN_TARGET_MISMATCH','undo must name the original session');return plans.undo(a.runId,lookup); + case 'early-prepare':return getDevices().call({...a,method:'early.prepare',params:{package:a.package}}); + case 'early-status':return getDevices().call({...a,method:'early.status',params:{package:a.package}}); + case 'early-stage':{ + const {plan}=plans.get(a.digest);validatePlan(plan,lookup); + return getDevices().call({...a,method:'early.stage',params:{plan,canonicalPlan:canonical(plan),digest:a.digest,binding:a.binding,expiresAt:a.expiresAt,offline:a.offline,expectedCacheRevision:a.expectedCacheRevision}}); + } + case 'early-revoke':return getDevices().call({...a,method:'early.revoke',params:{package:a.package,deploymentId:a.deploymentId,expectedCacheRevision:a.expectedCacheRevision}}); + case 'migration-preview':return getDevices().call({...a,method:'hooks.migration.preview',params:{package:a.package}}); + case 'migration-apply':return getDevices().call({...a,method:'hooks.migration.apply',params:{package:a.package,scopeRevision:a.scopeRevision,planDigest:a.digest}}); + case 'migration-rollback':return getDevices().call({...a,method:'hooks.migration.rollback',params:{migrationId:a.migrationId,scopeRevision:a.scopeRevision}}); + default:throw new OperationError('INVALID_ACTION','unknown hook plan action'); + } +} diff --git a/daemon/src/hook_plans.ts b/daemon/src/hook_plans.ts new file mode 100644 index 0000000..14b38f2 --- /dev/null +++ b/daemon/src/hook_plans.ts @@ -0,0 +1,97 @@ +import {existsSync,readFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {createHash,randomUUID} from 'node:crypto'; +import {atomicWriteJson} from './storage.ts'; +import {checkpoint,executionContext,localEffect,OperationError} from './execution_context.ts'; +import {sessions} from './state.ts'; +import {agentCmd} from './service.ts'; + +export const FAMILY_KEYS=['digest','hmac','symmetric','asymmetric','tls','aead','system'] as const; +const SHORT=['d','h','s','a','t','e','y']; +const TOOLS=new Set(['native_hook','java_hook','jni_onload','module_watch','capture_start']); +export const canonical=(value:any):string=>Array.isArray(value)?'['+value.map(canonical).join(',')+']':value&&typeof value==='object'?'{'+Object.keys(value).sort().map(k=>JSON.stringify(k)+':'+canonical(value[k])).join(',')+'}':JSON.stringify(value); +export const digest=(value:any)=>createHash('sha256').update(canonical(value)).digest('hex'); +const fail=(code:string,message:string):never=>{throw new OperationError(code,message);}; +function object(value:any,keys:string[]){if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(k=>!keys.includes(k)))fail('INVALID_PLAN','invalid or unknown plan fields');} +export interface HookPlan {schemaVersion:1;id:string;title:string;package:string;families:Record;steps:{id:string;tool:string;arguments:any;waitMs?:number}[];metadata?:any} +export interface PlanTool {inputSchema:any;handler:(args:any)=>Promise} +type Lookup=(name:string)=>PlanTool|undefined; +export function validatePlan(value:any,lookup?:Lookup):HookPlan { + object(value,['schemaVersion','id','title','package','families','steps','metadata']); + if(value.schemaVersion!==1||!/^[a-z][a-z0-9_-]{0,63}$/.test(value.id)||typeof value.title!=='string'||value.title.length>160||!/^[A-Za-z][\w]*(\.[\w]+)+$/.test(value.package)||['com.adh.manager','com.adh.daemon'].includes(value.package))fail('INVALID_PLAN','schema/id/title/package invalid'); + object(value.families,[...FAMILY_KEYS]);if(!FAMILY_KEYS.every(k=>typeof value.families[k]==='boolean'))fail('INVALID_PLAN','all seven family decisions must be explicit'); + if(!Array.isArray(value.steps)||!value.steps.length||value.steps.length>32||Buffer.byteLength(canonical(value))>128*1024)fail('INVALID_PLAN','plan must have 1..32 steps and fit 128 KiB'); + const ids=new Set();for(const step of value.steps){ + object(step,['id','tool','arguments','waitMs']);if(!/^[a-z][\w-]{0,63}$/.test(step.id)||ids.has(step.id)||!TOOLS.has(step.tool))fail('INVALID_PLAN','step id/tool invalid');ids.add(step.id); + if(step.waitMs!==undefined&&(!Number.isInteger(step.waitMs)||step.waitMs<0||step.waitMs>600000))fail('INVALID_PLAN','step wait must be 0..600000 ms'); + if(!step.arguments||Array.isArray(step.arguments)||typeof step.arguments!=='object'||['session','deviceId','connectionId','_operation','transport','__proto__','constructor','prototype'].some(k=>Object.hasOwn(step.arguments,k)))fail('INVALID_PLAN','step arguments cannot replace scope or authorization'); + if(step.tool==='capture_start'&&!['cryptoModule','fileModule','sysModule'].every(k=>typeof step.arguments[k]==='string'))fail('INVALID_PLAN','capture modules must all be explicit; empty cryptoModule deliberately scans all'); + if(step.tool!=='capture_start'&&!['hook','hookAll','start'].includes(step.arguments.action))fail('INVALID_PLAN','plan steps install only; observe and undo are separate actions'); + if(step.tool==='native_hook'&&step.arguments.action!=='hook'||step.tool==='java_hook'&&!['hook','hookAll'].includes(step.arguments.action)||step.tool==='jni_onload'&&step.arguments.action!=='hook'||step.tool==='module_watch'&&step.arguments.action!=='start')fail('INVALID_PLAN','tool action not supported by this plan version'); + const schema=lookup?.(step.tool)?.inputSchema;if(lookup&&!schema)fail('UNSUPPORTED_PLAN_TOOL','plan tool is unavailable'); + if(schema){for(const [key,arg]of Object.entries(step.arguments)){const spec=schema.properties[key];if(!spec)fail('INVALID_PLAN','unknown argument '+key+' for '+step.tool); + if(spec.type==='string'&&typeof arg!=='string'||spec.type==='boolean'&&typeof arg!=='boolean'||spec.type==='number'&&typeof arg!=='number'||spec.type==='integer'&&!Number.isInteger(arg)||spec.enum&&!spec.enum.includes(arg))fail('INVALID_PLAN','argument type/enum invalid: '+key);} + for(const key of schema.required||[])if(key!=='session'&&!Object.hasOwn(step.arguments,key))fail('INVALID_PLAN','missing argument '+key); + } + }return structuredClone(value); +} +export function familyFlags(families:Record){return SHORT.map((key,n)=>key+'='+(families[FAMILY_KEYS[n]]?'1':'0')).join(',');} + +/** Immutable bodies + CAS heads; no import/startup I/O or automatic application. */ +export class HookPlans { + readonly root:string; + constructor(root:string){this.root=root;} + private index(){const file=join(this.root,'library.json');if(!existsSync(file))return {schemaVersion:1,revision:0,heads:{}} as any;const data=JSON.parse(readFileSync(file,'utf8'));if(data.schemaVersion!==1||!Number.isSafeInteger(data.revision)||!data.heads||Array.isArray(data.heads))fail('PLAN_LIBRARY_CORRUPT','plan index cannot be rebuilt automatically');return data;} + list(){const index=this.index();return {ok:true,revision:index.revision,plans:Object.entries(index.heads).map(([id,entry]:any)=>({id,...entry})),automaticApply:false};} + get(hash:string){if(!/^[a-f0-9]{64}$/.test(hash||''))fail('PLAN_VERSION_REQUIRED','select an immutable plan digest');const value=JSON.parse(readFileSync(join(this.root,'versions',hash+'.json'),'utf8'));if(digest(value)!==hash)fail('PLAN_LIBRARY_CORRUPT','plan body digest differs');return {ok:true,digest:hash,plan:validatePlan(value)};} + put(value:any,expectedRevision:number,lookup?:Lookup){const plan=validatePlan(value,lookup),index=this.index();if(expectedRevision!==index.revision)fail('STALE_PLAN_LIBRARY','library changed; preserve draft and re-plan'); + const hash=digest(plan),file=join(this.root,'versions',hash+'.json'); + localEffect(()=>{if(existsSync(file)){if(digest(JSON.parse(readFileSync(file,'utf8')))!==hash)fail('PLAN_LIBRARY_CORRUPT','immutable body differs');}else atomicWriteJson(file,plan); + index.heads[plan.id]={digest:hash,title:plan.title,package:plan.package,updatedAt:Date.now()};index.revision++;atomicWriteJson(join(this.root,'library.json'),index);},{kind:'host',action:'hook-plan.version.save'}); + return {ok:true,digest:hash,revision:index.revision,applied:false}; + } + preflight(hash:string,sid:string,lookup:Lookup){const {plan}=this.get(hash);validatePlan(plan,lookup);const s=sessions.get(sid);if(!s?.online||s.package!==plan.package)fail('PLAN_TARGET_MISMATCH','select an explicit online generation of the plan package'); + const required=['capture_policy',...plan.steps.map(x=>x.tool)];const absent=[...new Set(required)].filter(op=>!s.caps?.ops?.includes(op));return {ok:!absent.length,digest:hash,session:sid,package:s.package,process:s.process,pid:s.pid,uid:s.uid,starttimeTicks:s.starttimeTicks,missingCapabilities:absent,willApply:false,steps:plan.steps.map(x=>({id:x.id,tool:x.tool,waitMs:x.waitMs||0})),sideEffects:['changes future capture-family eligibility',...plan.steps.filter(x=>x.tool==='capture_start').map(()=>'replaces the session persistent capture set')]};} + async apply(hash:string,sid:string,lookup:Lookup){const preflight=this.preflight(hash,sid,lookup);if(!preflight.ok)fail('UNSUPPORTED_AGENT','required agent operations missing: '+preflight.missingCapabilities.join(',')); + const {plan}=this.get(hash),ctx=executionContext.getStore();if(!ctx?.operationId)fail('OPERATION_REQUIRED','plan execution needs the shared coordinator');checkpoint(sid); + const run:any={id:ctx.operationId,digest:hash,session:sid,generation:preflight,state:'running',receipts:[],createdAt:Date.now(),previousPolicy:sessions.get(sid)?.policy};const file=join(this.root,'runs',run.id+'.json'); + const persist=()=>atomicWriteJson(file,run);localEffect(persist,{kind:'host',action:'hook-plan.run.reserve'}); + try{ + const before=await agentCmd(sid,'capture_policy',{action:'status'});if(before.ok!==true||!/^d=[01],h=[01],s=[01],a=[01],t=[01],e=[01],y=[01]$/.test(before.policy))fail('UNSUPPORTED_AGENT','agent did not confirm the previous family policy');run.previousPolicy=before.policy;persist(); + const flags=familyFlags(plan.families),reply=await agentCmd(sid,'capture_policy',{families:flags});run.receipts.push({id:'families',tool:'capture_policy',reply});persist();if(reply.ok!==true)fail('PLAN_STEP_FAILED','agent refused explicit family policy');sessions.get(sid)!.policy=flags; + for(const step of plan.steps){checkpoint(sid);if(step.waitMs){if(step.waitMs>=(ctx.remainingMs?.()||0))fail('PLAN_BUDGET','wait exceeds remaining operation budget');await new Promise(r=>setTimeout(r,step.waitMs));checkpoint(sid);} + const reply=await lookup(step.tool)!.handler({...step.arguments,session:sid});run.receipts.push({id:step.id,tool:step.tool,arguments:step.arguments,reply});if(step.tool==='capture_start')run.captureFingerprint=digest(sessions.get(sid)?.captureHooks||{});persist();if(reply.ok!==true||reply.partial===true&&step.tool!=='capture_start')fail('PLAN_STEP_FAILED','step '+step.id+' did not confirm the requested installation'); + } + run.captureFingerprint=digest(sessions.get(sid)?.captureHooks||{});run.state='applied';run.finishedAt=Date.now();persist();return {ok:true,run,applied:true}; + }catch(error){run.state=(error as any).uncertain?'unknown':'partial-or-failed';run.error={code:(error as any).code||'PLAN_FAILED',message:(error as Error).message};persist();throw error;} + } + run(id:string){if(!/^[\w-]{1,128}$/.test(id||''))fail('INVALID_ARGUMENT','invalid run id');return JSON.parse(readFileSync(join(this.root,'runs',id+'.json'),'utf8'));} + async observe(id:string,lookup:Lookup){const run=this.run(id),s=sessions.get(run.session);if(!s?.online||s.pid!==run.generation.pid||s.uid!==run.generation.uid||s.starttimeTicks!==run.generation.starttimeTicks)fail('PLAN_TARGET_MISMATCH','run belongs to another or offline process generation'); + const observed:any={};for(const tool of new Set(run.receipts.map((r:any)=>r.tool))){if(tool==='native_hook'||tool==='java_hook')observed[String(tool)]=await lookup(String(tool))!.handler({action:'status',session:run.session});} + const policy=await agentCmd(run.session,'capture_policy',{action:'status'}); + return {ok:true,run,observed,policy,appliedIsHistorical:true,earlyReport:s.earlyPlan||null}; + } + async undo(id:string,lookup:Lookup){const recorded=this.run(id);if(!['applied','undone'].includes(recorded.state))fail('UNSUPPORTED_UNDO','partial/unknown run can contain unacknowledged effects; inspect and remove explicitly');if(recorded.state!=='undone'&&recorded.receipts.some((r:any)=>r.tool==='capture_start'))fail('UNSUPPORTED_UNDO','persistent capture ownership cannot be verified from a historical Host reply; inspect and explicitly capture_stop');const {run,observed,policy}=await this.observe(id,lookup);checkpoint(run.session);if(run.state==='undone')return {ok:true,alreadyUndone:true,run}; + if(policy.policy!==familyFlags(this.get(run.digest).plan.families))fail('STALE_RUNTIME','agent family policy changed; re-plan undo explicitly'); + // Only owned, verifiable single hooks can be removed; never remove all hooks after an ambiguous batch. + for(const r of run.receipts){if(r.tool==='capture_policy')continue; + if(!['native_hook','java_hook'].includes(r.tool)||!Number.isInteger(r.reply.hookId))fail('UNSUPPORTED_UNDO','step lacks an individually owned hook id; inspect and remove explicitly'); + const reply=observed[r.tool],rows=reply?.status?.hooks||reply?.hooks||reply?.status; + if(!Array.isArray(rows)||!rows.some((h:any)=>Number(h.id??h.hookId)===r.reply.hookId&&(r.tool!=='native_hook'||h.module===r.arguments.module&&h.symbol===r.arguments.symbol)))fail('STALE_RUNTIME','hook ownership is not verified'); + } + run.undoReceipts=[];for(const r of [...run.receipts].reverse()){checkpoint(run.session);if(r.tool==='capture_policy')continue;const reply=await lookup(r.tool)!.handler({action:'unhook',hookId:r.reply.hookId,session:run.session});run.undoReceipts.push({id:r.id,reply});atomicWriteJson(join(this.root,'runs',id+'.json'),run);if(reply.ok!==true)fail('PLAN_UNDO_UNCONFIRMED','undo step did not confirm');} + // Do not silently overwrite a family policy changed after this plan. + if(sessions.get(run.session)?.policy!==familyFlags(this.get(run.digest).plan.families))fail('STALE_RUNTIME','family policy changed; old policy not restored'); + const previous=run.previousPolicy&&run.previousPolicy!=='default'?run.previousPolicy:'d=1,h=1,s=1,a=1,t=1,e=1,y=0';const reply=await agentCmd(run.session,'capture_policy',{families:previous});if(reply.ok!==true)fail('PLAN_UNDO_UNCONFIRMED','family restore unconfirmed');sessions.get(run.session)!.policy=previous; + run.state='undone';atomicWriteJson(join(this.root,'runs',id+'.json'),run);return {ok:true,run}; + } +} + +export function legacyPlan(scope:any,settings:any,pkg:string,id:string):HookPlan { + if(!scope?.packages?.includes(pkg))fail('INVALID_PLAN','legacy package is not in scope');const c=scope.policy?.[pkg]?.c||{},families=Object.fromEntries(FAMILY_KEYS.map((k,n)=>[k,typeof c[SHORT[n]]==='boolean'?c[SHORT[n]]:k!=='system'])); + const capture=settings?.capture||{},steps:any[]=[];const startup=settings?.startup||{}; + if(startup.antiDebug&&(!startup.packages?.length||startup.packages.includes(pkg)))for(const symbol of ['ptrace',...(startup.extraTargets||[])])steps.push({id:'startup-'+steps.length,tool:'native_hook',arguments:{action:'hook',mode:'inline',module:startup.module||'libc.so',symbol,skipOriginal:true,returnValue:'-1',errno:13}}); + steps.push({id:'capture',tool:'capture_start',arguments:{cryptoModule:capture.cryptoModule??'',fileModule:capture.fileModule??'',sysModule:capture.sysModule??''}}); + if(startup.antiDebug&&startup.widenAfterMs>0&&(!startup.packages?.length||startup.packages.includes(pkg)))for(const symbol of startup.widenTargets||[])steps.push({id:'widen-'+steps.length,tool:'native_hook',waitMs:steps.some(x=>x.id.startsWith('widen'))?0:startup.widenAfterMs,arguments:{action:'hook',mode:'inline',module:startup.module||'libc.so',symbol,skipOriginal:true,returnValue:'-1',errno:13}}); + return validatePlan({schemaVersion:1,id,title:'Migrated '+pkg,package:pkg,families,steps,metadata:{legacy:{scope:structuredClone(scope),settings:structuredClone(settings),scopeDigest:digest(scope)},automaticApply:false,warning:'Snapshot preserves unknown/retired fields; capture output filters and retired bypass are not installed by this plan.'}}); +} diff --git a/daemon/src/http/router.ts b/daemon/src/http/router.ts index 077b5d4..46d043b 100644 --- a/daemon/src/http/router.ts +++ b/daemon/src/http/router.ts @@ -13,6 +13,7 @@ import { executeManaged, getOperations, operationsRoot, resolveSpec } from '../o import { requestPrincipal } from '../access_context.ts'; import { operationFailure } from '../operations.ts'; import {deviceRoutes} from './routes_devices.ts'; +import {hookPlanRoutes} from './routes_hook_plans.ts'; export async function handleHttp(req: http.IncomingMessage, res: http.ServerResponse) { const url = new URL(req.url ?? '/', 'http://localhost'); @@ -28,6 +29,7 @@ export async function handleHttp(req: http.IncomingMessage, res: http.ServerResp const routes = [ ...operationsRoutes(context), ...deviceRoutes(context), + ...hookPlanRoutes(context), ...systemRoutes(context), ...runtimeRoutes(context), ...analysisRoutes(context), diff --git a/daemon/src/http/routes_hook_plans.ts b/daemon/src/http/routes_hook_plans.ts new file mode 100644 index 0000000..8358488 --- /dev/null +++ b/daemon/src/http/routes_hook_plans.ts @@ -0,0 +1,8 @@ +import {hookPlanAction} from '../hook_plan_host.ts'; +import {MCP_MAP} from '../mcp.ts'; +import {readBody} from '../state.ts'; +import type {Route,RouteContext} from './types.ts'; +export function hookPlanRoutes({req,url,send}:RouteContext):Route[]{return [{path:'/api/hook-plans',handler:async()=>{ + const args=req.method==='GET'?Object.fromEntries(url.searchParams):JSON.parse(await readBody(req)||'{}'); + const result:any=await hookPlanAction(args,name=>MCP_MAP.get(name));return send(result.ok===false?400:200,result); +}}];} diff --git a/daemon/src/http/routes_system.ts b/daemon/src/http/routes_system.ts index f118a24..80c74ea 100644 --- a/daemon/src/http/routes_system.ts +++ b/daemon/src/http/routes_system.ts @@ -43,6 +43,7 @@ export function systemRoutes({ req, res, url, send }: RouteContext): Route[] { { path:'/operation-client.js',handler:servePublic('operation-client.js','text/javascript; charset=utf-8') }, { path:'/workbench-model.js',handler:servePublic('workbench-model.js','text/javascript; charset=utf-8') }, { path:'/workbench.js',handler:servePublic('workbench.js','text/javascript; charset=utf-8') }, + { path:'/hook-plans-panel.js',handler:servePublic('hook-plans-panel.js','text/javascript; charset=utf-8') }, { path:'/operations.js',handler:servePublic('operations.js','text/javascript; charset=utf-8') }, { path: '/api/apps', handler: async () => { const scope = await scopedApps(); diff --git a/daemon/src/index.ts b/daemon/src/index.ts index 703c9ce..e2aefca 100644 --- a/daemon/src/index.ts +++ b/daemon/src/index.ts @@ -5,9 +5,9 @@ import net from 'node:net'; import { AGENT_PORT, HTTP_PORT, webUrls } from './config.ts'; import { handleHttp } from './http/router.ts'; import { ensureAdbReverse } from './scope_list.ts'; -import { startCaptureLoop, forgetCaptureSession, clearCaptureArmProtect, applyStartupHooks } from './service.ts'; +import { startCaptureLoop, forgetCaptureSession, clearCaptureArmProtect } from './service.ts'; import { initializeHost } from './host_lifecycle.ts'; -import { automaticSnapshot, initializeOperations, runAutomatic } from './operation_host.ts'; +import { initializeOperations } from './operation_host.ts'; import { agentSockets, broadcast, captureTimers, failPendingFor, frameJson, FRAME_JSON, FRAME_MAX, log, nextId, pending, pruneSessions, sessions, wss, @@ -58,6 +58,7 @@ const agentServer = net.createServer((sock) => { selfModule: msg.selfModule ?? '', selfBase: msg.selfBase ?? '', policy: msg.policy ?? '', + earlyPlan: msg.earlyPlan ?? null, connectedAt: Date.now(), lastSeen: Date.now(), online: true, @@ -72,13 +73,9 @@ const agentServer = net.createServer((sock) => { // Fresh process after unpack: allow auto-arm again (protect only blocks the live post-unpack session). clearCaptureArmProtect(session.package); broadcast('agent.hello', session); - // Startup policy BEFORE the capture loop: on a target that checks for a debugger early, the - // difference between "hooks installed now" and "installed after the first command round - // trip" is often the difference between a live process and an exit. Fire-and-forget with - // `finally` so a slow or failing install can never stop capture from starting. - runAutomatic(id,'automatic-startup',automaticSnapshot(id),()=>applyStartupHooks(id)) - .catch((e) => log(`[startup] anti-debug 布防失败 ${id}:`, (e as Error).message)) - .finally(() => startCaptureLoop(id)); // install persistent hooks + stream captures + // Connection/reconnection observes only. Installs require an explicit plan/primitive; + // an authorized early cache already ran before this hello and reports its own receipts. + startCaptureLoop(id,{skipArm:true}); } else if (msg.t === 'caps' && session) { // Arrives right after the hello (before the maps sample). Stored on the session, never // merged from another session: two processes of the same app can run different builds. diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 48d7f7d..68ea0cc 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -1,3 +1,4 @@ +import {hookPlanAction} from './hook_plan_host.ts'; import {deviceAction} from './device_host.ts'; import { executeManaged, getOperations, manageOperations } from './operation_host.ts'; import { describeTool } from './operation_registry.ts'; @@ -406,6 +407,8 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h // Optional at schema level because reads need no control token; writes enforce it at dispatch. MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); +MCP_TOOLS.push({name:'hook_plans',description:'Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','get','validate','put','import-legacy','preflight','apply','run','observe','undo','early-prepare','early-status','early-stage','early-revoke','migration-preview','migration-apply','migration-rollback']},plan:{type:'object'},digest:S,expectedLibraryRevision:{type:'integer'},session:S,runId:S,id:S,package:S,scope:{type:'object'},settings:{type:'object'},deviceId:S,connectionId:S,bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},binding:{type:'object'},expiresAt:{type:'integer'},offline:{type:'string',enum:['keep-until-expiry']},expectedCacheRevision:{type:'integer'},deploymentId:S,scopeRevision:S,migrationId:S}},handler:a=>hookPlanAction(a,name=>MCP_MAP.get(name))}); + for (const tool of MCP_TOOLS) { const metadata=(tool.inputSchema as any).properties._operation ??= { type:'object' }; metadata.properties ??= { expectedRevision:{type:'integer'},controlEpoch:{type:'integer'},hostEpoch:{type:'integer'},taskId:{type:'string'},idempotencyKey:{type:'string'},timeoutMs:{type:'integer'},expectedTaskRevision:{type:'integer'} }; diff --git a/daemon/src/operation_host.ts b/daemon/src/operation_host.ts index 497dd1d..b132d17 100644 --- a/daemon/src/operation_host.ts +++ b/daemon/src/operation_host.ts @@ -26,6 +26,7 @@ export async function runAutomatic(session: string, name: string, meta: ReturnTy } catch(error) { return operationFailure(error); } } export function resolveSpec(spec: OperationSpec, args: any) { + if(spec.name==='hook_plans'&&spec.mode==='write'&&!spec.global&&!spec.deviceId&&!spec.session)throw new OperationError('TARGET_REQUIRED','hook plan apply/undo needs an explicit session or device'); if(spec.mode==='write' && !spec.global && !spec.session && !spec.deviceId) { const online=[...sessions.values()].filter(s=>s.online); if(online.length!==1)throw new OperationError('TARGET_REQUIRED','choose an explicit session; targets are ambiguous or offline'); diff --git a/daemon/src/operation_registry.ts b/daemon/src/operation_registry.ts index 5f44158..d8acc4f 100644 --- a/daemon/src/operation_registry.ts +++ b/daemon/src/operation_registry.ts @@ -22,10 +22,15 @@ const readActions: Record = { oracle:['list'],stealth:['status'], }; export function describeTool(name: string, args: Record = {}): OperationSpec { + if(name==='hook_plans'){ + const action=args.action||'list',device=action.startsWith('early-')||action.startsWith('migration-'); + const read=['list','get','validate','preflight','run','observe','early-prepare','early-status','migration-preview'].includes(action); + return {name,mode:read?'read':'write',deviceId:device?args.deviceId:undefined,session:device?undefined:args.session,global:!device&&!['apply','undo'].includes(action),securityOnly:action==='early-revoke'}; + } if(name==='devices'){ const action=args.action||'list'; const mode:Mode=['list','discover','info','capabilities'].includes(action)?'read':action==='reconcile'?'analysis':action==='call'?deviceMethodMode(args.method):'write'; - return {name,mode,deviceId:['list','discover'].includes(action)||action==='connect'&&args.transport!=='lan'?undefined:args.deviceId,global:action==='connect'&&args.transport!=='lan'||!args.deviceId,connectionOnly:['connect','disconnect'].includes(action),securityOnly:action==='call'&&(args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false)}; + return {name,mode,deviceId:['list','discover'].includes(action)||action==='connect'&&args.transport!=='lan'?undefined:args.deviceId,global:action==='connect'&&args.transport!=='lan'||!args.deviceId,connectionOnly:['connect','disconnect'].includes(action),securityOnly:action==='call'&&(args.method==='early.revoke'||args.method==='pairings.revoke'||args.method==='lan.configure'&&args.params?.enabled===false)}; } if(name!=='operations'&&(Object.hasOwn(args,'deviceId')||Object.hasOwn(args,'connectionId')||args.transport==='lan'))throw new OperationError('UNSUPPORTED_DEVICE_ROUTING','this legacy tool has no verified device/LAN route; use devices capabilities, never fall back to ADB'); let mode: Mode = readTools.has(name) ? 'read' : analysisTools.has(name) ? 'analysis' : 'write'; @@ -60,6 +65,7 @@ const analysisPaths = new Set(['/api/native/syscall_scan','/api/native/crypto_co '/api/unpack/dump-one','/api/unpack/dump-so-one','/api/unpack/pull-so','/api/unpack/dump-all','/api/unpack/dump-so']); export function describeHttp(path: string, method: string, args: Record = {}): OperationSpec { if(path==='/api/devices')return describeTool('devices',args); + if(path==='/api/hook-plans')return describeTool('hook_plans',args); if(Object.hasOwn(args,'deviceId')||Object.hasOwn(args,'connectionId')||args.transport==='lan')throw new OperationError('UNSUPPORTED_DEVICE_ROUTING','this legacy route has no verified device/LAN route; no ADB fallback'); const alias = routeTools[path]; if (path === '/api/config') return describeTool('settings', { ...args, action: method === 'POST' ? 'patch' : 'get' }); diff --git a/daemon/src/operations.ts b/daemon/src/operations.ts index c1a0a27..d4dbfca 100644 --- a/daemon/src/operations.ts +++ b/daemon/src/operations.ts @@ -196,7 +196,7 @@ export class Operations { return out; } recordDeviceReconciliation(id:string,deviceId:string,evidence:any){ - const op=this.getOperation(id);if(op.resource!=='device:'+deviceId||op.name!=='devices'||op.mode!=='write'||op.connectionOnly)fail('TARGET_CHANGED','reconciliation must name a device mutation on this device'); + const op=this.getOperation(id);if(op.resource!=='device:'+deviceId||!['devices','hook_plans'].includes(op.name)||op.mode!=='write'||op.connectionOnly)fail('TARGET_CHANGED','reconciliation must name a device mutation on this device'); const file=this.saveResult(`${id}.reconcile.${randomUUID()}`,evidence); this.store.update(data=>{const current=data.operations[id];(current.reconciliations??=[]).push({at:Date.now(),deviceId,file});if(current.reconciliations.length>8)current.reconciliations.shift();current.updatedAt=Date.now();touchTask(data.tasks[current.taskId]);}); return this.getOperation(id,true); // preserve unknown/error/control history diff --git a/daemon/src/service.ts b/daemon/src/service.ts index 2dae5b1..288388e 100644 --- a/daemon/src/service.ts +++ b/daemon/src/service.ts @@ -825,9 +825,8 @@ export async function applyCaptureEnabled(): Promise<{ ok: boolean; targets: { session: string; ok: boolean; skipped?: string; error?: string }[]; error?: string; }> { const on = settings.capture.enabled; - if (on) { try { await scopedApps(); } catch { /* cache may still help */ } } const targets = await Promise.all([...sessions.values()].filter(s => s.online).map(async s => { - if (on && !shouldAutoArmPackage(s.package, s.entry)) return { session: s.sessionId, ok: true, skipped: 'outside scope' }; + if (on) { startCaptureLoop(s.sessionId,{skipArm:true});return {session:s.sessionId,ok:true,skipped:'drain-only; explicit hook plan required'}; } const blocked = on ? captureArmBlockedReason(s.package) : null; if (blocked) return { session: s.sessionId, ok: true, skipped: blocked }; try { @@ -915,11 +914,11 @@ export async function setCapture( modules?: { cryptoModule?: string; fileModule?: string; sysModule?: string; force?: boolean }, ): Promise { const mods = { ...captureModules() }; - // Only keys the caller actually passed override the settings defaults (an explicit undefined - // must not blank a module out - that would silently turn "hook this module" into "scan all"). + // Omitted keys use the legacy template. An explicit empty string is an intentional + // all-module scan (crypto) or disabled module family (file/system), as in plan JSON. for (const k of ['cryptoModule', 'fileModule', 'sysModule'] as const) { const v = modules?.[k]; - if (typeof v === 'string' && v.length) mods[k] = v; + if (typeof v === 'string') mods[k] = v; } if (on) { const pkg = sessions.get(sid)?.package ?? ''; @@ -934,7 +933,7 @@ export async function setCapture( } as CaptureToggle; } if (modules?.force === true && pkg) clearCaptureArmProtect(pkg); - const verdict = await armCaptureHooks(sid, mods); + const verdict = await armCaptureHooks(sid, mods, typeof modules?.sysModule === 'string'); // Start the drain loop without a second arm (hello path arms itself after a short delay). startCaptureLoop(sid, { skipArm: true }); return verdict; @@ -999,7 +998,7 @@ export async function resolveSysModuleForArm( * Drain → stop → start so GOT install counters are honest. Does not start the drain loop * (callers that need streaming must already have called startCaptureLoop / setCapture). */ -async function armCaptureHooks(sid: string, mods: { cryptoModule: string; fileModule: string; sysModule: string }): Promise { +async function armCaptureHooks(sid: string, mods: { cryptoModule: string; fileModule: string; sysModule: string }, exactSystemModule=false): Promise { // RE-ARM FROM A CLEAN SLATE. adh_got_replace matches a GOT slot by VALUE, so an install that // runs while our own wrapper already sits in the slot reports 0 for it - indistinguishable // from "this symbol is not imported". Measured on the sandbox: a repeat capture_start said @@ -1008,7 +1007,7 @@ async function armCaptureHooks(sid: string, mods: { cryptoModule: string; fileMo // original pointers: drain (never lose what the ring holds), stop, then install. const drained = await drainSession(sid); try { await sendCmd(sid, 'capture_stop', {}, 8_000); } catch { /* not armed: nothing to restore */ } - const sysModule = await resolveSysModuleForArm(sid, mods.sysModule); + const sysModule = exactSystemModule ? (policySystemOn(sessions.get(sid)?.policy)?mods.sysModule:'') : await resolveSysModuleForArm(sid, mods.sysModule); const armedMods = { ...mods, sysModule }; const reply = await sendCmd(sid, 'capture_start', armedMods, 15_000); recordCaptureHooks(sid, reply); @@ -1028,9 +1027,7 @@ async function armCaptureHooks(sid: string, mods: { cryptoModule: string; fileMo }; } -// Install persistent hooks on connect, then poll capture_drain and stream each new record -// into the store + over WS. Also auto-dump the app's DEX files so the panel can download -// them. Mirrors the ios-decrypt-helper flow (hooks stay live, events fill the panel). +// Connect only starts draining. Installation/dumps require explicit Host operations. // Seed from durable captures so ids stay unique across daemon restarts. let capSeq = captures.reduce((m, c) => Math.max(m, Number(c.id) || 0), 0); @@ -1115,21 +1112,8 @@ export function startCaptureLoop(sid: string, opts?: { skipArm?: boolean }) { log(`capture_start skip ${sid} (unpack in progress for ${pkg})`); return; } - // Refresh scope cache (best-effort) then auto-arm when capture is not force-stopped. - if (!opts?.skipArm && settings.capture.enabled) { - try { await scopedApps(); } catch { /* keep prior cache */ } - if (shouldAutoArmPackage(pkg, entry)) { - try { - const verdict = await armCaptureHooks(sid, { ...captureModules() }); - log(`capture_start ${sid} ok=${verdict.ok}`); - } catch (e) { log('capture_start failed', (e as Error).message); } - } else { - log(`capture_start skip ${sid} (package not in scope)`); - } - } - if (!opts?.skipArm && settings.capture.autoDumpDex) { - autoDumpDex(sid).catch((e) => log(`[capture] autoDumpDex ${sid} 失败:`, (e as Error).message)); - } + // P5: draining existing observations never installs hooks or dumps dex. Legacy settings + // remain exportable migration input, not authorization for a new process generation. if (captureTimers.has(sid)) return; let busy = false; let drainErrLogged = false; // fail-loud once per wedged-drain episode, not every 1.5s tick diff --git a/daemon/src/settings_service.ts b/daemon/src/settings_service.ts index 2af0dc2..b388ec5 100644 --- a/daemon/src/settings_service.ts +++ b/daemon/src/settings_service.ts @@ -25,10 +25,9 @@ export function patchSettings(patch: unknown, applyCapture = applyCaptureEnabled checkpoint(); Object.assign(settings, candidate); const capture = (patch as Record).capture; - // Output filters apply on ingestion; startup/auto-dump changes apply at the next - // explicit start/hello. A UI-only or retention patch must not re-install hooks. - const needsCaptureApply = typeof capture?.enabled === 'boolean' - || ['cryptoModule', 'fileModule', 'sysModule'].some(key => typeof capture?.[key] === 'string'); + // Output filters apply on ingestion; legacy startup/auto-dump fields are migration + // templates. Neither hello nor a settings patch installs hooks or dumps DEX. + const needsCaptureApply = typeof capture?.enabled === 'boolean'; let runtime: Awaited> = { ok: true, targets: [] }; if (needsCaptureApply) { try { runtime = await applyCapture(); } @@ -37,8 +36,8 @@ export function patchSettings(patch: unknown, applyCapture = applyCaptureEnabled return { ok: runtime.ok, applied, persisted: true, runtimeApplied: runtime.ok, runtime, settings: structuredClone(settings), stats: configStats(), autoAntiDebug: autoAntiDebugEnabled(), - deferred: [ ...(applied.includes('startup') ? ['startup:next-hello'] : []), - ...(typeof capture?.autoDumpDex === 'boolean' ? ['autoDumpDex:next-automatic-capture-loop'] : []) ], + deferred: [ ...(applied.includes('startup') ? ['startup:hook-plan-template-only'] : []), + ...(['autoDumpDex','cryptoModule','fileModule','sysModule'].some(key=>Object.hasOwn(capture||{},key)) ? ['legacy-capture:hook-plan-template-only'] : []) ], maintenanceRequired: applied.includes('artifacts') || !!capture && ['retain', 'maxAgeDays'].some(key => Object.hasOwn(capture, key)), ...(!runtime.ok ? { code: 'SETTINGS_APPLY_FAILED', error: runtime.error || 'settings saved; some target operations failed' } : {}), }; diff --git a/daemon/src/state.ts b/daemon/src/state.ts index c92d3d7..8f2d922 100644 --- a/daemon/src/state.ts +++ b/daemon/src/state.ts @@ -82,6 +82,7 @@ export interface AgentSession { // evp/digest/hmac/pkey/aead/file/sys). Without it "capture_start returned ok" is the // only visible signal for whether the persistent hooks actually installed. captureHooks?: Record; + earlyPlan?: any; // target-reported receipt; never a verified device/session association } export type AgentMsg = | ({ t: 'hello' } & Partial) @@ -246,8 +247,8 @@ export interface Settings { } export const DEFAULT_SETTINGS: Settings = { // cryptoModule: which module's GOT holds the EVP/SSL calls the agent hooks. The agent bakes - // in NO module name (target-agnostic); this value drives it. Default 'libjavacrypto.so' = - // Conscrypt, the app-level JCE/TLS path present in every app — safe and isolated from + // in NO module name. P5 keeps this field as a legacy template; fresh installs use ''. + // A named Conscrypt module can narrow an explicit invocation away from // framework internals. Set '' to scan ALL file-backed modules (advanced: catches cronet's // bundled BoringSSL / renamed libs, but also hooks framework crypto on the main thread during // init and can destabilize startup — opt in per target, don't use as the default). @@ -258,7 +259,7 @@ export const DEFAULT_SETTINGS: Settings = { // installs nothing without failing, so a wrong default reads as "6 hooks silently missing" — // which is exactly what the sandbox-only defaults below used to do on every real app. The // sandbox self-test passes its own module explicitly (verify_v20_file.sh, verify_v05_detect.sh). - capture: { enabled: true, autoDumpDex: true, retain: 1000, maxAgeDays: 14, families: { digest: true, hmac: true, symmetric: true, asymmetric: true, tls: true, aead: true }, cryptoModule: 'libjavacrypto.so', fileModule: '', sysModule: '' }, + capture: { enabled: false, autoDumpDex: false, retain: 1000, maxAgeDays: 14, families: { digest: true, hmac: true, symmetric: true, asymmetric: true, tls: true, aead: true }, cryptoModule: '', fileModule: '', sysModule: '' }, ui: { displayCap: 300 }, artifacts: { maxBytes: 8 * 1024 ** 3, maxAgeDays: 14 }, startup: { antiDebug: false, module: 'libc.so', extraTargets: [], packages: [], widenAfterMs: 0, widenTargets: ['access', 'faccessat'] }, diff --git a/daemon/test/device_lan.test.ts b/daemon/test/device_lan.test.ts index 32a9069..4514dba 100644 --- a/daemon/test/device_lan.test.ts +++ b/daemon/test/device_lan.test.ts @@ -11,9 +11,24 @@ import {Operations,type Principal} from '../src/operations.ts'; import {describeTool} from '../src/operation_registry.ts'; import {DeviceRpcClient,DEVICE_PROTOCOL} from '../src/device_protocol.ts'; import {startDeviceFixture,FakeAdb,jvmManifest,pause} from './device_fixture.ts'; +import {canonical,digest,FAMILY_KEYS} from '../src/hook_plans.ts'; const ai:Principal={role:'ai',id:'lan-fixture',source:'test'},human:Principal={role:'operator',id:'human',source:'test'}; const skip=existsSync(jvmManifest)?false:'offline Kotlin fixture unavailable; never use a real device'; + +test('LAN early cache carries its grant and stops future delivery after USB authorization revocation',{skip},async()=>{ + const f=await fixture();try{const {usb,lan,grant}=await f.setup(),pkg='com.fixture.early'; + const scope=await f.one.read(usb,'scope.get');assert.equal((await f.one.write(usb,'scope.patch',{scopeRevision:scope.result.scopeRevision,add:[pkg]})).state,'succeeded'); + const plan={schemaVersion:1,id:'lan-early',title:'LAN early fixture',package:pkg,families:Object.fromEntries(FAMILY_KEYS.map(k=>[k,k==='digest'])),steps:[{id:'got',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libfixture.so',symbol:'read'}}]}; + const preview=await f.one.read(usb,'hooks.migration.preview',{package:pkg});const migration=await f.one.write(usb,'hooks.migration.apply',{package:pkg,scopeRevision:preview.result.scopeRevision,planDigest:digest(plan)});assert.equal(migration.state,'succeeded'); + const prepared=(await f.one.read(lan,'early.prepare',{package:pkg})).result; + const staged=await f.one.write(lan,'early.stage',{plan,canonicalPlan:canonical(plan),digest:digest(plan),binding:prepared.binding,expectedCacheRevision:prepared.cacheRevision,expiresAt:Math.floor(Date.now()/1000)+3600,offline:'keep-until-expiry'});assert.equal(staged.state,'succeeded',JSON.stringify(staged)); + assert.equal(staged.result.result.result.entry.sourceGrant,grant.grantId); + const eligible=async()=>(await f.one.read(usb,'module.status',{package:pkg,uid:prepared.binding.uid})).result.earlyEligible;assert.equal(await eligible(),true); + assert.equal((await f.one.write(usb,'pairings.revoke',{grantId:grant.grantId})).state,'succeeded');assert.equal(await eligible(),false); + assert.equal((await f.one.read(usb,'early.status',{package:pkg})).result.entry.state,'validated-cache','historical staging state must not claim runtime installation or renewed authorization'); + }finally{await f.close();} +}); const meta=(engine:Operations,resource:string)=>{const s=engine.snapshot(resource);return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; async function fixture(){ const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('usb-TLS','1',phone); diff --git a/daemon/test/fixtures/early_wire.cpp b/daemon/test/fixtures/early_wire.cpp new file mode 100644 index 0000000..8ded1c0 --- /dev/null +++ b/daemon/test/fixtures/early_wire.cpp @@ -0,0 +1,12 @@ +#include "../../../agent/src/bootstrap/early_wire.h" +#include +#include +#include +#include +int apply(const AdhEarlyStep&,int* id,void* pointer){int* remaining=static_cast(pointer);*id=7;return (*remaining)-- >0?1:0;} +int main(int argc,char** argv){ + if(argc==3&&std::string(argv[1])=="sha"){int fd=open(argv[2],O_RDONLY|O_BINARY);if(fd<0)return 2;auto hash=adh_sha_fd(fd);close(fd);std::puts(hash.c_str());return 0;} + if(argc!=8)return 2;int fd=open(argv[1],O_RDONLY|O_BINARY);if(fd<0)return 2;std::vector data;uint8_t chunk[4096];int n;while((n=read(fd,chunk,sizeof(chunk)))>0)data.insert(data.end(),chunk,chunk+n);close(fd); + AdhEarlyPlan plan{};bool valid=adh_early_parse(data.data(),data.size(),argv[2],std::strtoul(argv[3],nullptr,10),argv[4],std::strtoull(argv[5],nullptr,10),plan); + if(!valid){std::puts("rejected");return 0;}int remaining=std::atoi(argv[6]);auto receipt=adh_early_run(plan,apply,&remaining);std::printf("%s %d %d %s\n",receipt.applied?"applied":"partial-or-failed",receipt.attempted,receipt.confirmed,plan.digest);return 0; +} diff --git a/daemon/test/fixtures/p5_workbench.ts b/daemon/test/fixtures/p5_workbench.ts new file mode 100644 index 0000000..e27fad6 --- /dev/null +++ b/daemon/test/fixtures/p5_workbench.ts @@ -0,0 +1,16 @@ +// Host-only public entrypoints. No index.ts, device discovery, ADB or real target. +import cp from 'node:child_process'; +import {syncBuiltinESMExports} from 'node:module'; +import {mkdtempSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import http from 'node:http'; +process.env.ADH_DATA_DIR=mkdtempSync(join(tmpdir(),'adh-p5-panel-'));process.env.ADH_SKIP_ARTIFACT_LOAD='1';delete process.env.ADH_CAPTURES_DIR; +process.env.ADH_OPERATOR_TOKEN='synthetic-p5-operator-key'; +cp.execFile=(()=>{throw Error('ADB forbidden in P5 fixture');}) as unknown as typeof cp.execFile; +cp.spawn=(()=>{throw Error('device process forbidden in P5 fixture');}) as unknown as typeof cp.spawn;syncBuiltinESMExports(); +const {getOperations}=await import('../../src/operation_host.ts'); +const {handleHttp}=await import('../../src/http/router.ts'); +const server=http.createServer((req,res)=>handleHttp(req,res).catch(error=>{res.writeHead(500);res.end(JSON.stringify({error:String(error)}));})); +server.listen(0,'127.0.0.1',()=>console.log('P5_WORKBENCH='+JSON.stringify({url:'http://127.0.0.1:'+(server.address() as any).port,root:process.env.ADH_DATA_DIR}))); +const stop=()=>{server.closeAllConnections();server.close();getOperations().close();process.exit(0);};process.stdin.resume();process.stdin.on('data',line=>{if(String(line).trim()==='stop')stop();});process.on('SIGINT',stop); diff --git a/daemon/test/hook_early.test.ts b/daemon/test/hook_early.test.ts new file mode 100644 index 0000000..0005d74 --- /dev/null +++ b/daemon/test/hook_early.test.ts @@ -0,0 +1,58 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,rmSync,writeFileSync,readFileSync,existsSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {tmpdir} from 'node:os'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {startDeviceFixture,FakeAdb,jvmManifest} from './device_fixture.ts'; +import {Devices} from '../src/devices.ts'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {Operations} from '../src/operations.ts'; +import {describeTool} from '../src/operation_registry.ts'; +import {digest,canonical,FAMILY_KEYS} from '../src/hook_plans.ts'; + +const skip=existsSync(jvmManifest)?false:'offline JVM fixture not built; no real device fallback'; +test('production device cache stages bound Kotlin wire, rejects stale intent, and restores exact legacy bytes',{skip},async t=>{ + const jvm=await startDeviceFixture(),adb=new FakeAdb();adb.add('fixture-usb','1',jvm); + const root=mkdtempSync(join(tmpdir(),'adh-p5-early-')),engine=new Operations(join(root,'operations')); + const devices=new Devices(join(root,'devices.json'),new AdbDeviceTransport(adb.run)); + const ai={role:'ai' as const,id:'early-fixture',source:'test'}; + async function execute(args:any){const spec=describeTool('devices',args),c=engine.snapshot(engine.resource(spec));const op=await engine.execute(spec,args,ai,{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch},()=>args.action==='connect'?devices.connect(args.serial,args.transportId):devices.call(args));return {...op,body:engine.getOperation(op.id,true).result};} + try{ + const connected=await execute({action:'connect',serial:'fixture-usb',transportId:'1'}),peer=connected.body; + const read=async(method:string,params:any={})=>(await devices.call({deviceId:peer.deviceId,connectionId:peer.connectionId,method,params})).result; + const write=async(method:string,params:any)=>{const state=await read('device.state');return execute({action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,method,params});}; + const raw='{\n "version":19,"mode":"allowlist","packages":["com.fixture.app"],"policy":{"com.fixture.app":{"c":{"d":false,"future":7},"unknown":[1,2]}},"future":{"exact":true}\n}\n';writeFileSync(join(jvm.root,'scope.json'),raw); + const p={schemaVersion:1,id:'early',title:'Early fixture',package:'com.fixture.app',families:Object.fromEntries(FAMILY_KEYS.map(k=>[k,k==='hmac'])),steps:[{id:'got',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libfixture.so',symbol:'read'}},{id:'capture',tool:'capture_start',arguments:{cryptoModule:'libfixture.so',fileModule:'',sysModule:''}}]}; + const withMetadata:any=p;withMetadata.metadata={unicode:'中文 \u2028',fraction:0.0000001}; + const hash=digest(p),preview=await read('hooks.migration.preview',{package:p.package});assert.equal(preview.scopeRaw,raw); + const migration=await write('hooks.migration.apply',{package:p.package,scopeRevision:preview.scopeRevision,planDigest:hash});assert.equal(migration.state,'succeeded');assert.equal(migration.body.result.result.applied,false); + const prepared=await read('early.prepare',{package:p.package});assert.equal(prepared.supported,true); + const params={plan:p,canonicalPlan:canonical(p),digest:hash,binding:prepared.binding,expiresAt:Math.floor(Date.now()/1000)+3600,offline:'keep-until-expiry',expectedCacheRevision:prepared.cacheRevision}; + const staged=await write('early.stage',params);assert.equal(staged.state,'succeeded');const status=staged.body.result.result;assert.equal(status.entry.state,'validated-cache');assert.equal(status.applied,null); + const eligible=async(uid=prepared.binding.uid)=>(await read('module.status',{package:p.package,uid})).earlyEligible; + assert.equal(await eligible(),true);assert.equal(await eligible(99),false);writeFileSync(join(jvm.root,'hook-binding.json'),JSON.stringify({...prepared.binding,versionCode:'changed'}));assert.equal(await eligible(),false);writeFileSync(join(jvm.root,'hook-binding.json'),JSON.stringify(prepared.binding));assert.equal(await eligible(),true); + const stale=await write('early.stage',params);assert.equal(stale.state,'failed');assert.equal(stale.body?.result?.code||stale.error?.code,'STALE_EARLY_CACHE'); + const bad={...params,expectedCacheRevision:status.cacheRevision,binding:{...prepared.binding,uid:99}};const changed=await write('early.stage',bad);assert.equal(changed.state,'failed');assert.equal(changed.body.result.code,'TARGET_CHANGED'); + const unsupported=structuredClone(p);unsupported.steps[0].arguments.mode='inline';const refused=await write('early.stage',{...params,expectedCacheRevision:status.cacheRevision,plan:unsupported,canonicalPlan:canonical(unsupported),digest:digest(unsupported)});assert.equal(refused.state,'failed');assert.equal(refused.body?.result?.code||refused.error?.code,'UNSUPPORTED_EARLY_PLAN'); + // Native production parser and executor consume the exact bytes emitted by Kotlin. + const compiler=process.env.ADH_CXX||(process.platform==='win32'?'C:/Strawberry/c/bin/g++.exe':'g++'); + await t.test('Kotlin encoder → native validator/receipts, tamper/UID/agent/expiry rejection and SHA oracle', {skip:process.platform==='win32'&&!existsSync(compiler)?'portable C++ compiler unavailable':false},()=>{ + const binary=join(root,'early-wire.exe'),compiled=spawnSync(compiler,['-std=c++17','-O2',resolve('test/fixtures/early_wire.cpp'),'-o',binary],{encoding:'utf8',windowsHide:true});assert.equal(compiled.status,0,compiled.stderr); + const wire=Buffer.from(status.entry.wire,'base64'),file=join(root,'wire.bin');writeFileSync(file,wire);const now=Math.floor(Date.now()/1000); + const consume=(uid=prepared.binding.uid,agent=prepared.binding.agentSha256,time=now,confirmed=16)=>spawnSync(binary,[file,p.package,String(uid),agent,String(time),String(confirmed),'fixture'],{encoding:'utf8',windowsHide:true}).stdout.trim(); + assert.equal(consume(),`applied 2 2 ${hash}`);assert.equal(consume(undefined,undefined,undefined,1),`partial-or-failed 2 1 ${hash}`);assert.equal(consume(99),'rejected');assert.equal(consume(undefined,'0'.repeat(64)),'rejected');assert.equal(consume(undefined,undefined,params.expiresAt),'rejected'); + wire[wire.length-1]^=1;writeFileSync(file,wire);assert.equal(consume(),'rejected'); + for(const size of [0,1,55,56,63,64,65,128,1025]){const bytes=Buffer.alloc(size,97);writeFileSync(file,bytes);assert.equal(spawnSync(binary,['sha',file],{encoding:'utf8',windowsHide:true}).stdout.trim(),createHash('sha256').update(bytes).digest('hex'));} + }); + // A normal scope edit retains the full old policy; rollback refuses to erase it. + const scope=await read('scope.get'),migratedRaw=readFileSync(join(jvm.root,'scope.json'),'utf8');const edited=await write('scope.patch',{scopeRevision:scope.scopeRevision,add:['com.fixture.other']});assert.equal(edited.state,'succeeded'); + assert.deepEqual((await read('scope.get')).document.policy,JSON.parse(raw).policy); + const conflict=await write('hooks.migration.rollback',{migrationId:migration.body.result.result.migrationId,scopeRevision:migration.body.result.result.scopeRevision});assert.equal(conflict.state,'failed');assert.equal(conflict.body.result.code,'STALE_SCOPE'); + // Restore only the fixture's exact migrated document, then exercise exact rollback. + const stored=JSON.parse(readFileSync(join(jvm.root,'hook-cache.json'),'utf8'));writeFileSync(join(jvm.root,'scope.json'),migratedRaw); + const rolled=await write('hooks.migration.rollback',{migrationId:migration.body.result.result.migrationId,scopeRevision:migration.body.result.result.scopeRevision});assert.equal(rolled.state,'succeeded');assert.equal(readFileSync(join(jvm.root,'scope.json'),'utf8'),raw);assert.equal((await read('early.status',{package:p.package})).entry.state,'revoked'); + assert.equal(stored.entries[p.package].digest,hash);assert.ok(adb.commands.every(c=>!c.includes('reverse')&&!c.includes('install')&&!c.includes('kill-server'))); + }finally{devices.close();engine.close();await adb.close();await jvm.close();rmSync(root,{recursive:true,force:true});} +}); diff --git a/daemon/test/hook_entrypoints.test.ts b/daemon/test/hook_entrypoints.test.ts new file mode 100644 index 0000000..e1df050 --- /dev/null +++ b/daemon/test/hook_entrypoints.test.ts @@ -0,0 +1,32 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import {execFile} from 'node:child_process'; +import {promisify} from 'node:util'; +import {existsSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {handleHttp} from '../src/http/router.ts'; +import {getOperations,operationsRoot} from '../src/operation_host.ts'; +import {initializeOperatorAccess} from '../src/access_context.ts'; +import {DATA_DIR} from '../src/state.ts'; +import {FAMILY_KEYS} from '../src/hook_plans.ts'; + +test('MCP, panel REST and published CLI share immutable plans, CAS and durable write intents',async t=>{ + const engine=getOperations(),key=initializeOperatorAccess(operationsRoot),server=http.createServer((req,res)=>handleHttp(req,res).catch(error=>{res.writeHead(500);res.end(String(error));})); + await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+(server.address() as any).port; + const meta=()=>{const s=engine.snapshot('host');return {expectedRevision:s.revision,controlEpoch:s.epoch,hostEpoch:s.hostEpoch};}; + const rpc=async(name:string,args:any)=>{const v=await(await fetch(base+'/mcp',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})})).json() as any;return JSON.parse(v.result.content[0].text);}; + try{ + const plan={schemaVersion:1,id:'unified',title:'Entry fixture',package:'com.fixture.app',families:Object.fromEntries(FAMILY_KEYS.map(k=>[k,false])),steps:[{id:'got',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libfixture.so',symbol:'read'}}]}; + const intent={...meta(),idempotencyKey:'p5-shared-intent'},args={action:'put',plan,expectedLibraryRevision:0};const saved=await rpc('hook_plans',{...args,_operation:intent});assert.equal(saved.applied,false);assert.equal(saved.revision,1); + const repeated=await(await fetch(base+'/api/hook-plans',{method:'POST',headers:{'Content-Type':'application/json','X-Adh-Operation':JSON.stringify(intent)},body:JSON.stringify(args)})).json() as any;assert.equal(repeated._operation.id,saved._operation.id);assert.equal(repeated.revision,1); + const asset=await fetch(base+'/hook-plans-panel.js');assert.equal(asset.status,200);assert.match(await asset.text(),/tool:'hook_plans'/); + const stale=await rpc('hook_plans',{...args,expectedLibraryRevision:0,_operation:meta()});assert.equal(stale.code,'STALE_PLAN_LIBRARY'); + const cliSource=process.env.ADH_CLI_SOURCE||resolve('../..','adh-cli','src');if(!existsSync(join(cliSource,'adh','__init__.py'))){t.diagnostic('CLI source absent; set ADH_CLI_SOURCE for public CLI check');return;} + const execute=promisify(execFile),env={...process.env,PYTHONPATH:cliSource,ADH_CONFIG_PATH:join(DATA_DIR,'p5-cli.json'),ADH_OPERATOR_TOKEN:key,PYTHONIOENCODING:'utf-8'}; + try{await execute('python',['--version'],{windowsHide:true,timeout:5000});}catch(error){if((error as any).code==='ENOENT'){t.diagnostic('Python unavailable');return;}throw error;} + const output=await execute('python',['-m','adh','run','hook_plans','--arguments',JSON.stringify({...args,plan:{...plan,title:'CLI edited'},expectedLibraryRevision:1}),'--endpoint',base,'--json'],{env,windowsHide:true,timeout:15000});const submitted=JSON.parse(output.stdout).operation; + for(let n=0;n<100&&!engine.getOperation(submitted.id).settled;n++)await new Promise(r=>setTimeout(r,10));assert.equal(engine.getOperation(submitted.id).state,'succeeded'); + const list=await rpc('hook_plans',{action:'list'});assert.equal(list.revision,2);assert.equal(list.plans[0].title,'CLI edited');assert.equal((await rpc('hook_plans',{action:'get',digest:saved.digest})).plan.title,'Entry fixture'); + }finally{server.closeAllConnections();await new Promise(r=>server.close(()=>r()));engine.close();} +}); diff --git a/daemon/test/hook_plans.test.ts b/daemon/test/hook_plans.test.ts new file mode 100644 index 0000000..c0871e2 --- /dev/null +++ b/daemon/test/hook_plans.test.ts @@ -0,0 +1,71 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,rmSync,existsSync,writeFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {tmpdir} from 'node:os'; +import {HookPlans,FAMILY_KEYS,validatePlan,legacyPlan} from '../src/hook_plans.ts'; +import {MCP_MAP} from '../src/mcp.ts'; +import {Operations} from '../src/operations.ts'; +import {describeTool} from '../src/operation_registry.ts'; +import {sessions,agentSockets,pending,captureTimers,settings} from '../src/state.ts'; +import {startCaptureLoop} from '../src/service.ts'; + +const lookup=(name:string)=>MCP_MAP.get(name),ai={role:'ai' as const,id:'fixture',source:'test'}; +const plan=()=>({schemaVersion:1 as const,id:'fixture',title:'Fixture Hook',package:'com.fixture.app',families:Object.fromEntries(FAMILY_KEYS.map(k=>[k,k==='digest'])),steps:[{id:'native',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libfixture.so',symbol:'read'}}]}); +function fixture(){ + const root=mkdtempSync(join(tmpdir(),'adh-p5-plans-')),plans=new HookPlans(join(root,'plans')),engine=new Operations(join(root,'operations')); + const calls:any[]=[],hooks:any[]=[];let policy='d=0,h=0,s=0,a=0,t=0,e=0,y=0',stopAfterFirst=false,loseNative=false; + sessions.set('p5',{sessionId:'p5',online:true,package:'com.fixture.app',process:'com.fixture.app',pid:71,uid:10001,starttimeTicks:'55',policy,caps:{ops:['native_hook','capture_start','capture_policy']}} as any); + agentSockets.set('p5',{destroyed:false,write(frame:Buffer){const msg=JSON.parse(frame.subarray(5).toString());calls.push(msg); + queueMicrotask(()=>{let reply:any={ok:true};if(msg.op==='capture_policy'){if(msg.action!=='status')policy=msg.families;reply.policy=policy;} + else if(msg.op==='native_hook'){if(msg.action==='hook'){reply.hookId=hooks.length+1;hooks.push({id:reply.hookId,module:msg.module,symbol:msg.symbol});if(stopAfterFirst){const c=engine.snapshot('target:p5');engine.control('takeover','target:p5',{role:'operator',id:'human',source:'test'},{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch});}} + else if(msg.action==='status')reply.status={hooks};else hooks.splice(hooks.findIndex(h=>h.id===msg.hookId),1);} + else if(msg.op==='capture_start')reply={ok:true,digest:1};else if(msg.op==='capture_drain')reply={ok:true,count:0,captures:[],jcaptures:[],complete:true}; + if(msg.op==='native_hook'&&msg.action==='hook'&&loseNative)pending.get(msg.id)?.reject(Object.assign(new Error('synthetic response lost'),{code:'COMMAND_TIMEOUT',uncertain:true}));else pending.get(msg.id)?.resolve(reply);});return true;}} as any); + function execute(action:string,fn:()=>Promise){const c=engine.snapshot('target:p5');return engine.execute(describeTool('hook_plans',{action,session:'p5'}),{},ai,{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch},fn);} + return {root,plans,engine,calls,hooks,execute,setPolicy:(p:string)=>{policy=p;},stop:()=>{stopAfterFirst=true;},lose:()=>{loseNative=true;},close(){for(const timer of captureTimers.values())clearInterval(timer);captureTimers.clear();agentSockets.delete('p5');sessions.delete('p5');engine.close();rmSync(root,{recursive:true,force:true});}}; +} + +test('immutable library CAS, schema and legacy import preserve evidence without automatic effects',()=>{ + const f=fixture();try{assert.equal(existsSync(join(f.root,'plans')),false);assert.equal(f.plans.list().revision,0); + const first=f.plans.put(plan(),0,lookup);assert.equal(first.applied,false);assert.equal(first.revision,1);assert.equal(f.calls.length,0); + assert.throws(()=>f.plans.put(plan(),0,lookup),(e:any)=>e.code==='STALE_PLAN_LIBRARY'); + const changed=plan();changed.title='Human edit';const next=f.plans.put(changed,1,lookup);assert.notEqual(next.digest,first.digest);assert.equal(f.plans.get(first.digest).plan.title,'Fixture Hook'); + for(const invalid of [{...plan(),autoApply:true},{...plan(),families:{digest:true}},{...plan(),steps:[{id:'bad',tool:'native_hook',arguments:{action:'hook',session:'other'}}]}])assert.throws(()=>validatePlan(invalid,lookup)); + const scope={packages:['com.fixture.app'],policy:{'com.fixture.app':{c:{d:false,h:true,future:7},unknown:{nested:true}}},future:'kept'}; + const migrated=legacyPlan(scope,{capture:{cryptoModule:'libfixture.so'},startup:{antiDebug:false},future:13},'com.fixture.app','migrated');assert.deepEqual(migrated.metadata.legacy.scope,scope);assert.equal(migrated.families.digest,false);assert.equal(migrated.families.hmac,true); + writeFileSync(join(f.root,'plans','versions',first.digest+'.json'),'{}');assert.throws(()=>f.plans.get(first.digest),(e:any)=>e.code==='PLAN_LIBRARY_CORRUPT'); + }finally{f.close();} +}); +test('live plans dispatch actual primitives, preserve receipts and undo only verified owned hooks',async()=>{ + const f=fixture();try{const saved=f.plans.put(plan(),0,lookup);assert.equal(f.plans.preflight(saved.digest,'p5',lookup).ok,true); + const op=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));assert.equal(op.state,'succeeded');const run=f.plans.run(op.id);assert.equal(run.state,'applied');assert.equal(run.receipts[1].reply.hookId,1); + assert.deepEqual(f.calls.map(x=>x.op),['capture_policy','capture_policy','native_hook']);const undo=await f.execute('undo',()=>f.plans.undo(op.id,lookup));assert.equal(undo.state,'succeeded');assert.equal(f.hooks.length,0);assert.equal(f.plans.run(op.id).state,'undone'); + }finally{f.close();} +}); +test('old capability, changed generation, and human runtime changes fail before unsafe writes',async()=>{ + const f=fixture();try{const saved=f.plans.put(plan(),0,lookup);sessions.get('p5')!.caps!.ops=['native_hook'];assert.equal(f.plans.preflight(saved.digest,'p5',lookup).ok,false); + const bad=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));assert.equal(bad.state,'failed');assert.equal(f.calls.length,0); + sessions.get('p5')!.caps!.ops!.push('capture_policy');const op=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));f.setPolicy('d=0,h=1,s=0,a=0,t=0,e=0,y=0'); + const undo=await f.execute('undo',()=>f.plans.undo(op.id,lookup));assert.equal(undo.state,'failed');assert.equal(undo.error.code,'STALE_RUNTIME');assert.equal(f.hooks.length,1); + sessions.get('p5')!.starttimeTicks='other';await assert.rejects(()=>f.plans.observe(op.id,lookup),(e:any)=>e.code==='PLAN_TARGET_MISMATCH'); + }finally{f.close();} +}); +test('human takeover between plan steps fences the remaining program; hello draining never arms defaults',async()=>{ + const f=fixture();try{const p=plan();p.steps.push({...p.steps[0],id:'second'});const saved=f.plans.put(p,0,lookup);f.stop(); + const op=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));assert.notEqual(op.state,'succeeded');assert.equal(f.calls.filter(x=>x.op==='native_hook').length,1);assert.equal(f.plans.run(op.id).state,'partial-or-failed'); + settings.capture.enabled=true;settings.startup.antiDebug=true;startCaptureLoop('p5');await new Promise(r=>setTimeout(r,300));assert.equal(f.calls.filter(x=>x.op==='capture_start').length,0); + }finally{f.close();} +}); +test('lost step acknowledgement is unknown, keeps prior effects and never replays the plan',async()=>{ + const f=fixture();try{const p=plan();p.steps.push({...p.steps[0],id:'later'});const saved=f.plans.put(p,0,lookup);f.lose(); + const op=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));assert.equal(op.state,'unknown');assert.equal(f.plans.run(op.id).state,'unknown');assert.equal(f.hooks.length,1);assert.equal(f.calls.filter(x=>x.op==='native_hook').length,1);assert.ok(f.engine.snapshot('target:p5').uncertain); + const count=f.calls.length;await assert.rejects(()=>f.plans.undo(op.id,lookup),(e:any)=>e.code==='UNSUPPORTED_UNDO');assert.equal(f.calls.length,count,'unknown effects cannot be declared undone'); + }finally{f.close();} +}); +test('explicit capture module blanks cannot inherit broad legacy settings',async()=>{ + const f=fixture(),before=structuredClone(settings.capture);try{settings.capture.fileModule='legacy-file.so';settings.capture.sysModule='legacy-sys.so';settings.capture.cryptoModule='legacy-crypto.so'; + const p:any=plan();p.steps=[{id:'capture',tool:'capture_start',arguments:{cryptoModule:'libfixture.so',fileModule:'',sysModule:''}}];const saved=f.plans.put(p,0,lookup);const op=await f.execute('apply',()=>f.plans.apply(saved.digest,'p5',lookup));assert.equal(op.state,'succeeded');const armed=f.calls.find(x=>x.op==='capture_start');assert.equal(armed.cryptoModule,'libfixture.so');assert.equal(armed.fileModule,'');assert.equal(armed.sysModule,''); + const stopped=f.calls.filter(x=>x.op==='capture_stop').length;await assert.rejects(()=>f.plans.undo(op.id,lookup),(e:any)=>e.code==='UNSUPPORTED_UNDO');assert.equal(f.calls.filter(x=>x.op==='capture_stop').length,stopped); + }finally{Object.assign(settings.capture,before);f.close();} +}); diff --git a/daemon/test/settings_service.test.ts b/daemon/test/settings_service.test.ts index 8251330..365fa43 100644 --- a/daemon/test/settings_service.test.ts +++ b/daemon/test/settings_service.test.ts @@ -84,11 +84,12 @@ async function via(entry: string, patch: unknown): Promise<{ status: number; bod } for (const entry of ['mcp', '/api/config', '/api/settings/import']) { - test(`${entry}: enable installs on the simulated scoped target`, async () => { + test(`${entry}: enable resumes draining without installing legacy Hook defaults`, async () => { reset(); settings.capture.enabled = false; const calls = fakeAgent(); const result = await via(entry, { capture: { enabled: true } }); assert.equal(result.body.ok, true); assert.equal(result.body.runtimeApplied, true); - assert.ok(calls.includes('capture_start')); assert.equal(result.body.runtime.targets[0].ok, true); + assert.deepEqual(calls, []); assert.equal(result.body.runtime.targets[0].ok, true); + assert.equal(result.body.runtime.targets[0].skipped, 'drain-only; explicit hook plan required'); assert.equal(settings.capture.enabled, true); }); @@ -112,7 +113,7 @@ for (const entry of ['mcp', '/api/config', '/api/settings/import']) { }); test(`${entry}: persist failure changes neither live settings nor target`, async () => { - reset(); mkdirSync(SETTINGS_FILE, { recursive: true }); const calls = fakeAgent(); + reset(); settings.capture.enabled = true; mkdirSync(SETTINGS_FILE, { recursive: true }); const calls = fakeAgent(); const result = await via(entry, { capture: { enabled: false } }); assert.equal(result.body.ok, false); assert.equal(result.body.persisted, false); assert.equal(settings.capture.enabled, true); assert.deepEqual(calls, []); diff --git a/device/MAP.md b/device/MAP.md index 61af43d..1580485 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -6,6 +6,12 @@ Magisk 打包仍在 `injector/zygisk/`。 ## Modules +## P5 additions (2026-11-16) + +`core/EarlyPlanWire.kt` encodes the bounded early-plan/1 wire. `daemon/device/HookPlanCache.kt` owns validated, expiring app/Agent-bound cache and exact legacy backups through DeviceOperations. `AndroidHookBinding.kt` validates installed identity/ABI; `EarlyPlanBroker.kt` serves root companions only. Manager Binder v20 adds package-only CAS and Hook cache read/revoke; the fixed family editor is now a read-only legacy snapshot. Authoritative programmable editing stays on Host. No automatic app restart. See [P5_HOOK_PLANS.md](../docs/P5_HOOK_PLANS.md). + +## Modules reference + | Gradle | Package | Role | |---|---|---| | `:core` | `com.adh.core` | Scope 契约单一真相:路径常量、JSON 编解码、逐包 Hook 策略(`CaptureFamilies`)、`IAdhScopeService` AIDL、已安装应用目录 JSON、进程控制允许清单 | diff --git a/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl b/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl index 3f14c49..30f8637 100644 --- a/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl +++ b/device/core/src/main/aidl/com/adh/daemon/IAdhScopeService.aidl @@ -37,4 +37,8 @@ interface IAdhScopeService { String getDeviceCapabilitiesJson(); String getScopeSnapshotJson(); String setScopeVersionedJson(String json, String scopeRevision, long stateRevision); + /** v20: Host plan state/local revocation; Manager scope edits are package-only CAS. */ + String getHookPlanStateJson(String packageName); + String revokeHookPlanJson(String packageName, String deploymentId, long cacheRevision, long stateRevision); + String patchScopePackagesJson(String packagesJson, String scopeRevision, long stateRevision); } diff --git a/device/core/src/main/java/com/adh/core/AdhProtocol.kt b/device/core/src/main/java/com/adh/core/AdhProtocol.kt index 09b0082..a92be1a 100644 --- a/device/core/src/main/java/com/adh/core/AdhProtocol.kt +++ b/device/core/src/main/java/com/adh/core/AdhProtocol.kt @@ -7,7 +7,8 @@ object AdhProtocol { * v16 briefly carried an SSL-bypass section; that section was removed and a leftover `b` key * is ignored. v17 stores the host address an injected process dials when adb reverse is absent. * v18 stores user CA certificates that post-fs-data mounts into the system trust store. */ - const val VERSION = 19 + const val VERSION = 20 + const val MIN_HOST_PLANS_VERSION = 20 /** v19 adds a shared device domain, stable installation identity and USB RPC. */ const val MIN_DEVICE_DOMAIN_VERSION = 19 const val MIN_SCOPE_VERSION = 1 diff --git a/device/core/src/main/java/com/adh/core/DeviceRpc.kt b/device/core/src/main/java/com/adh/core/DeviceRpc.kt index ad63e2b..3abcfec 100644 --- a/device/core/src/main/java/com/adh/core/DeviceRpc.kt +++ b/device/core/src/main/java/com/adh/core/DeviceRpc.kt @@ -14,8 +14,8 @@ object DeviceRpc { const val SOCKET_NAME = "adh_device_rpc_v1" const val MAX_FRAME = 1024 * 1024 const val MAX_BUDGET_MS = 60_000L - val READ_METHODS = setOf("device.info", "device.capabilities", "device.state", "module.status", "scope.get", "applications.list", "processes.list", "certificates.list", "host.get", "operations.get", "operations.reconcile", "lan.status", "pairings.list") - val WRITE_METHODS = setOf("scope.patch", "scope.replace", "process.control", "certificates.put", "certificates.delete", "host.set", "operations.resolve", "lan.configure", "pairings.grant", "pairings.revoke") + val READ_METHODS = setOf("device.info", "device.capabilities", "device.state", "module.status", "scope.get", "applications.list", "processes.list", "certificates.list", "host.get", "operations.get", "operations.reconcile", "lan.status", "pairings.list", "early.prepare", "early.status", "hooks.migration.preview") + val WRITE_METHODS = setOf("scope.patch", "scope.replace", "process.control", "certificates.put", "certificates.delete", "host.set", "operations.resolve", "lan.configure", "pairings.grant", "pairings.revoke", "early.stage", "early.revoke", "hooks.migration.apply", "hooks.migration.rollback") // Reboot and arbitrary shell/helper execution are NOT remote RPC capabilities in P3. fun read(input: InputStream): JSONObject? { val first = input.read() diff --git a/device/core/src/main/java/com/adh/core/EarlyPlanWire.kt b/device/core/src/main/java/com/adh/core/EarlyPlanWire.kt new file mode 100644 index 0000000..492a295 --- /dev/null +++ b/device/core/src/main/java/com/adh/core/EarlyPlanWire.kt @@ -0,0 +1,42 @@ +package com.adh.core + +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.security.MessageDigest + +/** Bounded, non-executable wire for post-specialize/before-agent-start operations. */ +object EarlyPlanWire { + const val MAX_BYTES = 32768 + const val MARKER = "ADH_EARLY_PLAN_V1" + val FAMILIES = listOf("digest", "hmac", "symmetric", "asymmetric", "tls", "aead", "system") + fun validate(plan: JSONObject) { + require(plan.getInt("schemaVersion") == 1) + val families = plan.getJSONObject("families"); require(families.length() == 7) + for (key in FAMILIES) require(families.get(key) is Boolean) + val steps = plan.getJSONArray("steps"); require(steps.length() in 1..16) + for (i in 0 until steps.length()) { + val step=steps.getJSONObject(i); require(step.optLong("waitMs",0)==0L) + val args=step.getJSONObject("arguments") + when(step.getString("tool")) { + "capture_start" -> {require(args.keys().asSequence().all { it in setOf("cryptoModule","fileModule","sysModule") });for(key in listOf("cryptoModule","fileModule","sysModule")) module(args.getString(key),key!="cryptoModule")} + "native_hook" -> {require(args.keys().asSequence().all { it in setOf("action","mode","module","symbol","mem") });require(args.getString("action")=="hook"&&args.getString("mode")=="got");module(args.getString("module"),false);require(Regex("[A-Za-z_][A-Za-z0-9_.$@]{0,126}").matches(args.getString("symbol")));require(args.optString("mem") in setOf("","auto"))} + else -> throw IllegalArgumentException("early tool unsupported; live Host plan remains available") + } + } + } + private fun module(value:String,empty:Boolean){require((empty&&value.isEmpty())||value.length in 1..63&&value.split(',').size<=8&&Regex("[A-Za-z0-9_./+,-]+").matches(value))} + fun encode(plan:JSONObject,binding:JSONObject,deploymentId:String,planDigest:String,expiresAt:Long):ByteArray{ + validate(plan) + val bytes=ByteArrayOutputStream();val out=DataOutputStream(bytes) + fun text(value:String){val data=value.toByteArray(Charsets.US_ASCII);require(data.size<=255);out.writeShort(data.size);out.write(data)} + out.write("ADHEP1\r\n".toByteArray());text(deploymentId);text(planDigest);text(plan.getString("package"));out.writeInt(binding.getInt("uid"));text(binding.getString("agentSha256"));out.writeLong(expiresAt) + var mask=0;for((n,key)in FAMILIES.withIndex())if(plan.getJSONObject("families").getBoolean(key))mask=mask or (1 shl n) + out.writeByte(mask);out.writeByte(plan.getJSONArray("steps").length()) + for(i in 0 until plan.getJSONArray("steps").length()){ + val step=plan.getJSONArray("steps").getJSONObject(i);val args=step.getJSONObject("arguments");val capture=step.getString("tool")=="capture_start" + out.writeByte(if(capture)1 else 2);text(args.getString(if(capture)"cryptoModule" else "module"));text(args.getString(if(capture)"fileModule" else "symbol"));text(if(capture)args.getString("sysModule")else args.optString("mem")) + } + out.flush();val body=bytes.toByteArray();require(body.size+32<=MAX_BYTES);return MessageDigest.getInstance("SHA-256").digest(body)+body + } +} diff --git a/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt b/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt index 725908c..da6e8c5 100644 --- a/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt +++ b/device/core/src/test/java/com/adh/core/ScopeJsonTest.kt @@ -137,7 +137,7 @@ class ScopeJsonTest { assertFalse(apps[0].system) assertEquals("com.android.settings", apps[1].packageName) assertTrue(apps[1].system) - assertEquals(19, AdhProtocol.VERSION) + assertEquals(20, AdhProtocol.VERSION) assertEquals(19, AdhProtocol.MIN_DEVICE_DOMAIN_VERSION) assertEquals(AdhProtocol.MIN_HOST_ENDPOINT_VERSION, 17) assertEquals(AdhProtocol.MIN_CA_CERT_VERSION, 18) diff --git a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt index 1fa4b47..2a4a685 100644 --- a/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt +++ b/device/daemon/src/main/java/com/adh/daemon/AdhDeviceDaemon.kt @@ -12,6 +12,9 @@ import com.adh.daemon.device.DeviceIdentity import com.adh.daemon.device.DeviceOperations import com.adh.daemon.device.LocalDeviceRpcServer import com.adh.daemon.device.DeviceNetwork +import com.adh.daemon.device.HookPlanCache +import com.adh.daemon.device.ScopeDocuments +import com.adh.daemon.device.EarlyPlanBroker import android.system.Os object AdhDeviceDaemon { @@ -19,6 +22,7 @@ object AdhDeviceDaemon { private const val PUBLISH_INTERVAL_MS = 1_000L private var rpc: LocalDeviceRpcServer? = null private var network: DeviceNetwork? = null + private var earlyBroker:EarlyPlanBroker?=null private var domainLock: java.nio.channels.FileLock? = null @JvmStatic @@ -45,6 +49,8 @@ object AdhDeviceDaemon { val identity = DeviceIdentity(files, File("/proc/sys/kernel/random/boot_id").readText().trim()) val operations = DeviceOperations(identity, files, AndroidDeviceBackend(context, files)) network = DeviceNetwork(operations, files) // default disabled; restore only explicitly saved TLS configuration + val cache=HookPlanCache(operations,files,ScopeDocuments(File(AdhPaths.SCOPE_PATH),files),AndroidHookBinding(context)) + runCatching{earlyBroker=EarlyPlanBroker(cache)}.onFailure{Log.e(TAG,"early broker unavailable; cache delivery disabled",it)} val service = RootScopeBinder(ManagerCallerVerifier(context), operations) // RPC availability never tears down the pre-existing authenticated Binder service. runCatching { rpc = LocalDeviceRpcServer(operations) }.onFailure { Log.e(TAG, "USB RPC unavailable; Binder remains available", it) } diff --git a/device/daemon/src/main/java/com/adh/daemon/AgentEarlyAbi.kt b/device/daemon/src/main/java/com/adh/daemon/AgentEarlyAbi.kt new file mode 100644 index 0000000..b2e7f8d --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/AgentEarlyAbi.kt @@ -0,0 +1,24 @@ +package com.adh.daemon + +import java.io.File +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** Inspects the actual release .dynsym; an embedded marker or local symbol is insufficient. */ +internal object AgentEarlyAbi { + fun exported(file:File,symbol:String="adh_agent_apply_early_v1"):Boolean=runCatching{RandomAccessFile(file,"r").use{input-> + require(input.length()<=128L*1024*1024) + fun bytes(offset:Long,count:Int):ByteArray{require(offset>=0&&count>=0&&offset<=input.length()-count);return ByteArray(count).also{input.seek(offset);input.readFully(it)}} + val head=ByteBuffer.wrap(bytes(0,64)).order(ByteOrder.LITTLE_ENDIAN);require(head.getInt(0)==0x464c457f&&head.get(4).toInt()==2&&head.get(5).toInt()==1&&head.getShort(18).toInt()==183) + val offset=head.getLong(40);val size=head.getShort(58).toInt()and 65535;val count=head.getShort(60).toInt()and 65535;require(size==64&&count in 1..4096) + for(n in 0 until count){val section=ByteBuffer.wrap(bytes(offset+n*size,64)).order(ByteOrder.LITTLE_ENDIAN);if(section.getInt(4)!=11)continue + val table=section.getLong(24);val length=section.getLong(32);val linked=section.getInt(40);val entry=section.getLong(56);require(entry==24L&&length>=0&&length/entry<=200000&&linked in 0 until count) + val strings=ByteBuffer.wrap(bytes(offset+linked*size,64)).order(ByteOrder.LITTLE_ENDIAN);val stringOffset=strings.getLong(24);val stringSize=strings.getLong(32) + for(i in 0 until length/entry){val row=ByteBuffer.wrap(bytes(table+i*entry,24)).order(ByteOrder.LITTLE_ENDIAN);val name=row.getInt(0).toLong()and 0xffffffffL + if(name>=stringSize||row.getShort(6).toInt()==0||row.get(4).toInt()ushr 4 !in setOf(1,2)||row.get(5).toInt()and 3 !=0)continue + val text=bytes(stringOffset+name,minOf(symbol.length+1L,stringSize-name).toInt());if(text.size==symbol.length+1&&text.last()==0.toByte()&&String(text,0,symbol.length,Charsets.US_ASCII)==symbol)return@use true + } + };false + }}.getOrDefault(false) +} diff --git a/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt b/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt new file mode 100644 index 0000000..5f24965 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt @@ -0,0 +1,36 @@ +package com.adh.daemon + +import android.content.Context +import android.content.pm.PackageManager +import android.content.pm.ApplicationInfo +import android.os.Build +import android.system.Os +import com.adh.core.AdhPaths +import com.adh.core.DeviceRpc +import com.adh.daemon.device.HookBindingProbe +import com.adh.daemon.device.DeviceFault +import org.json.JSONObject +import org.json.JSONArray +import java.io.File +import java.security.MessageDigest + +/** Validation metadata only, never target code analysis or loading the agent in the daemon. */ +internal class AndroidHookBinding(private val context:Context):HookBindingProbe{ + private var previousKey="";private var previousAgent:JSONObject?=null + @Synchronized override fun inspect(packageName:String):JSONObject{ + val pm=context.packageManager + @Suppress("DEPRECATION") val info=try{pm.getPackageInfo(packageName,if(Build.VERSION.SDK_INT>=28)PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES)}catch(_:PackageManager.NameNotFoundException){throw DeviceFault("TARGET_NOT_FOUND","package is no longer installed")} + val app=checkNotNull(info.applicationInfo) + if(app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)!=0)throw DeviceFault("TARGET_DENIED","early cache is third-party only") + @Suppress("DEPRECATION") val signatures=if(Build.VERSION.SDK_INT>=28)info.signingInfo?.apkContentsSigners else info.signatures + val signerHashes=signatures?.map{DeviceRpc.sha256(it.toByteArray())}?.sorted()?:emptyList();if(signerHashes.isEmpty())throw DeviceFault("IDENTITY_UNVERIFIED","APK signer evidence unavailable") + val apkFiles=listOf(app.sourceDir)+app.splitSourceDirs.orEmpty().toList() + val apks=apkFiles.sorted().map{path->val st=Os.stat(path);JSONObject().put("path",path).put("size",st.st_size).put("inode",st.st_ino).put("mtime",st.st_mtime)} + val file=File(AdhPaths.MODULE_DIR,AdhPaths.AGENT_SO_NAME);if(!file.isFile||file.length()>128*1024*1024)throw DeviceFault("AGENT_UNAVAILABLE","module agent is absent or exceeds validation limit") + val st=Os.stat(file.path);val key="${st.st_dev}:${st.st_ino}:${st.st_size}:${st.st_mtime}" + if(key!=previousKey){val hash=MessageDigest.getInstance("SHA-256");file.inputStream().use{input->val bytes=ByteArray(65536);while(true){val n=input.read(bytes);if(n<0)break;hash.update(bytes,0,n)}} + previousAgent=JSONObject().put("agentSha256",hash.digest().joinToString(""){"%02x".format(it)}).put("earlySupported",AgentEarlyAbi.exported(file));previousKey=key} + @Suppress("DEPRECATION") val version=if(Build.VERSION.SDK_INT>=28)info.longVersionCode else info.versionCode.toLong() + return JSONObject(checkNotNull(previousAgent).toString()).put("package",packageName).put("uid",app.uid).put("versionCode",version.toString()).put("signers",JSONArray(signerHashes)).put("apks",JSONArray(apks)) + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt b/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt index 65a3e2b..55f0748 100644 --- a/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt +++ b/device/daemon/src/main/java/com/adh/daemon/RootScopeBinder.kt @@ -32,6 +32,13 @@ internal class RootScopeBinder(private val verifier: ManagerCallerVerifier, priv override fun getDeviceInfoJson(): String = read("device.info").toString() override fun getDeviceCapabilitiesJson(): String = read("device.capabilities").toString() override fun getScopeSnapshotJson(): String = read("scope.get").toString() + override fun getHookPlanStateJson(packageName:String?):String = read("early.status",JSONObject().put("package",packageName?:"")).toString() + override fun revokeHookPlanJson(packageName:String?,deploymentId:String?,cacheRevision:Long,stateRevision:Long):String { + verifier.enforce();return operations.write("early.revoke",JSONObject().put("package",packageName?:"").put("deploymentId",deploymentId?:"").put("expectedCacheRevision",cacheRevision),java.util.UUID.randomUUID().toString(),stateRevision,"operator",60000).toString() + } + override fun patchScopePackagesJson(packagesJson:String?,scopeRevision:String?,stateRevision:Long):String { + verifier.enforce();return operations.write("scope.patch",JSONObject().put("set",org.json.JSONArray(packagesJson?:"[]")).put("scopeRevision",scopeRevision?:""),java.util.UUID.randomUUID().toString(),stateRevision,"operator",60000).toString() + } override fun setScopeVersionedJson(json: String?, scopeRevision: String?, stateRevision: Long): String { verifier.enforce() return runCatching { operations.write("scope.replace", JSONObject().put("document", JSONObject(json ?: "")).put("scopeRevision", scopeRevision ?: ""), java.util.UUID.randomUUID().toString(), stateRevision, "operator", 60000).toString() } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt index 18310b1..42acf7d 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceOperations.kt @@ -18,6 +18,7 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: private var state: JSONObject private var storageUnavailable = false var network: DeviceNetwork? = null + var hookCache: HookPlanCache? = null init { check(!stateFile.exists() || stateFile.length() <= 2 * 1024 * 1024) { "device operation ledger exceeds limit" } state = if (stateFile.exists()) JSONObject(stateFile.readText()) else JSONObject().put("schemaVersion", 1).put("revision", 0L).put("operations", JSONObject()) @@ -37,8 +38,8 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: .put("methods", JSONObject().also { methods -> DeviceRpc.READ_METHODS.filter { available(it) }.forEach { methods.put(it, "read") }; DeviceRpc.WRITE_METHODS.filter { available(it) }.forEach { methods.put(it, "write") } }) .put("transports", JSONObject().put("usb", true).put("lanTls", network != null)) .put("unsupported", JSONObject().put("agent.route", "legacy target channel retained; not associated by serial").put("agent.hook", "target agent routing not migrated").put("agent.memory", "target agent routing not migrated").put("agent.trace", "target agent routing not migrated").put("diagnostics", "legacy ADB-only; no LAN fallback").put("fs", "not migrated").put("root.helper", "not migrated").put("shell", "no arbitrary remote root shell").put("reboot", "Manager-only").put("bulk", "not implemented")) - private fun available(method: String) = method !in setOf("lan.status", "lan.configure", "pairings.list", "pairings.grant", "pairings.revoke") || network != null - private fun execute(method: String, params: JSONObject): JSONObject = if (method in (network?.methods ?: emptySet())) network!!.execute(method, params) else backend.execute(method, params) + private fun available(method: String) = if(method.startsWith("early.")||method.startsWith("hooks.migration."))hookCache!=null else method !in setOf("lan.status", "lan.configure", "pairings.list", "pairings.grant", "pairings.revoke") || network != null + private fun execute(method: String, params: JSONObject,sourceGrant:String?=null): JSONObject = if(method in(hookCache?.methods?:emptySet()))hookCache!!.execute(method,params,sourceGrant)else if (method in (network?.methods ?: emptySet())) network!!.execute(method, params) else backend.execute(method, params) fun read(method: String, params: JSONObject = JSONObject(), authorize: () -> Unit = {}): JSONObject = synchronized(lock) { authorize() when (method) { @@ -61,7 +62,7 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: else -> execute(method, params).put("stateRevision", revision()) } } - fun write(method: String, params: JSONObject, operationId: String, expectedRevision: Long, actor: String, budgetMs: Long, receivedAt: Long = System.nanoTime(), authorize: () -> Unit = {}): JSONObject = synchronized(lock) { + fun write(method: String, params: JSONObject, operationId: String, expectedRevision: Long, actor: String, budgetMs: Long, receivedAt: Long = System.nanoTime(), authorize: () -> Unit = {},sourceGrant:String?=null): JSONObject = synchronized(lock) { authorize() require(Regex("[A-Za-z0-9_-]{1,128}").matches(operationId)) if (storageUnavailable) throw DeviceFault("DEVICE_LEDGER_UNAVAILABLE", "ledger persistence failed; writes disabled until inspected restart") @@ -74,13 +75,13 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: if ((System.nanoTime() - receivedAt) / 1_000_000 >= budgetMs) throw DeviceFault("DEADLINE_EXCEEDED", "expired before device dispatch") if (expectedRevision != revision()) throw DeviceFault("STALE_DEVICE_STATE", "device was modified; observe again, do not retry old intent") val unresolved = records().keys().asSequence().map { records().getJSONObject(it) }.filter { it.optString("state") == "unknown" && !it.has("resolvedAt") }.toList() - val securityOnly = method == "pairings.revoke" || method == "lan.configure" && params.opt("enabled") == false + val securityOnly = method=="early.revoke"||method == "pairings.revoke" || method == "lan.configure" && params.opt("enabled") == false if (unresolved.isNotEmpty() && method != "operations.resolve" && !securityOnly) throw DeviceFault("UNKNOWN_EXECUTION", "device has unresolved side effects") if (method == "operations.resolve" && (actor != "operator" || !params.optBoolean("acknowledge"))) throw DeviceFault("OPERATOR_REQUIRED", "explicit operator inspection required") if (method == "operations.resolve") { val old = records().optJSONObject(params.optString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") if (old.optString("state") != "unknown" || old.has("resolvedAt")) throw DeviceFault("INVALID_STATE", "operation is not unresolved unknown") - } else if (method in (network?.methods ?: emptySet())) network!!.validate(method, params) else backend.validate(method, params) + } else if(method in(hookCache?.methods?:emptySet()))hookCache!!.validate(method,params)else if (method in (network?.methods ?: emptySet())) network!!.validate(method, params) else backend.validate(method, params) if (records().length() >= 1024) throw DeviceFault("LEDGER_FULL", "device ledger needs explicit archival; nothing dispatched") val record = JSONObject().put("operationId", operationId).put("method", method).put("bootId", identity.bootId).put("fingerprint", fingerprint) .put("actor", actor).put("state", "running").put("mayHaveExecuted", true).put("startedAt", System.currentTimeMillis()) @@ -97,7 +98,7 @@ internal class DeviceOperations(val identity: DeviceIdentity, private val files: val old = records().optJSONObject(params.getString("operationId")) ?: throw DeviceFault("OPERATION_NOT_FOUND", "no uncertain operation") if (old.optString("state") != "unknown") throw DeviceFault("INVALID_STATE", "operation is not unknown") old.put("resolvedAt", System.currentTimeMillis()); JSONObject().put("ok", true).put("originalState", "unknown") - } else execute(method, params) + } else execute(method, params,sourceGrant) val encoded = result.toString().toByteArray() record.put("result", if (encoded.size <= 32 * 1024) result else JSONObject().put("omitted", true).put("bytes", encoded.size).put("sha256", DeviceRpc.sha256(encoded))) record.put("state", if (result.optBoolean("ok", true)) "succeeded" else "failed") diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt b/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt index 3b1a360..d4642d6 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DevicePairings.kt @@ -66,7 +66,7 @@ internal class DevicePairings(private val files: DeviceFiles) { if (unavailable) throw DeviceFault("AUTH_STORAGE_UNAVAILABLE", "authorization storage requires inspection") val grant = grants().optJSONObject(grantId) ?: throw DeviceFault("AUTH_REVOKED", "grant unavailable") if (grant.has("revokedAt")) throw DeviceFault("AUTH_REVOKED", "grant revoked") - val needed = if (method in setOf("lan.configure", "pairings.list", "pairings.grant", "pairings.revoke", "operations.resolve")) "manage" else if (method in DeviceRpc.WRITE_METHODS) "write" else "read" + val needed = if (method in setOf("early.stage","early.revoke","hooks.migration.apply","hooks.migration.rollback","lan.configure", "pairings.list", "pairings.grant", "pairings.revoke", "operations.resolve")) "manage" else if (method in DeviceRpc.WRITE_METHODS) "write" else "read" if (needed !in permissions(grant.getJSONArray("permissions"))) throw DeviceFault("PERMISSION_DENIED", "grant does not permit this capability") } @Synchronized fun authenticate(auth: JSONObject, message: ByteArray): String { diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt index 9d201d8..43440b0 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt @@ -61,7 +61,7 @@ internal class DeviceRpcSession(private val operations: DeviceOperations) { val budget = meta.getLong("budgetMs"); require(budget in 1..DeviceRpc.MAX_BUDGET_MS) // A full replacement must carry scope CAS, even on authenticated RPC. if (method in setOf("scope.patch", "scope.replace")) require(Regex("[a-f0-9]{64}").matches(arguments.optString("scopeRevision"))) - operations.write(method, arguments, meta.getString("operationId"), meta.getLong("expectedRevision"), meta.optString("actor", "ai"), budget, received, authorize = { check(method) }) + operations.write(method, arguments, meta.getString("operationId"), meta.getLong("expectedRevision"), meta.optString("actor", "ai"), budget, received, authorize = { check(method) },sourceGrant=grantId) } else -> throw DeviceFault("UNSUPPORTED_METHOD", "method not advertised by this device protocol") } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt b/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt new file mode 100644 index 0000000..3bf18a8 --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt @@ -0,0 +1,24 @@ +package com.adh.daemon.device + +import android.net.LocalServerSocket +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.TimeUnit +import java.io.DataOutputStream + +/** Root companion only. A timeout/missing broker denies cache delivery, never arms defaults. */ +internal class EarlyPlanBroker(private val cache:HookPlanCache):AutoCloseable{ + private val server=LocalServerSocket("adh_early_plans_v1") + private val workers=ThreadPoolExecutor(2,2,30,TimeUnit.SECONDS,ArrayBlockingQueue(2)) + private val thread=Thread({while(!server.isClosedCompat()){ + val socket=try{server.accept()}catch(_:Exception){break} + if(runCatching{socket.peerCredentials.uid}.getOrDefault(-1)!=0){socket.close();continue} + try{workers.execute{socket.use{try{it.soTimeout=250;val bytes=java.io.ByteArrayOutputStream();val input=it.inputStream + while(bytes.size()<512){val b=input.read();if(b<0||b==10)break;bytes.write(b)};require(bytes.size()<512) + val parts=bytes.toString("US-ASCII").split(' ');require(parts.size==2);val uid=parts[1].toInt();require(uid>0) + val wire=cache.forProcess(parts[0],uid);val out=DataOutputStream(it.outputStream);out.writeInt(wire?.size?:0);if(wire!=null)out.write(wire);out.flush() + }catch(_:Exception){runCatching{DataOutputStream(it.outputStream).apply{writeInt(0);flush()}}}}}}catch(_:java.util.concurrent.RejectedExecutionException){socket.close()} + }},"adh-early-broker").apply{isDaemon=true;start()} + private fun LocalServerSocket.isClosedCompat()=Thread.currentThread().isInterrupted + override fun close(){thread.interrupt();server.close();workers.shutdownNow()} +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/HookPlanCache.kt b/device/daemon/src/main/java/com/adh/daemon/device/HookPlanCache.kt new file mode 100644 index 0000000..01b705b --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/HookPlanCache.kt @@ -0,0 +1,75 @@ +package com.adh.daemon.device + +import com.adh.core.DeviceRpc +import com.adh.core.EarlyPlanWire +import org.json.JSONObject +import java.io.File +import java.util.Base64 +import java.util.UUID + +internal fun interface HookBindingProbe { fun inspect(packageName:String):JSONObject } +/** Authoritative root cache; staging, authorization and consumption are distinct states. */ +internal class HookPlanCache(private val operations:DeviceOperations,private val files:DeviceFiles,private val scope:ScopeDocuments,private val probe:HookBindingProbe){ + val methods=setOf("early.prepare","early.status","early.stage","early.revoke","hooks.migration.preview","hooks.migration.apply","hooks.migration.rollback") + private val file=File(files.directory,"hook-cache.json") + private var state=if(file.exists()){check(file.length()<=2*1024*1024);JSONObject(file.readText()).also{check(it.getInt("schemaVersion")==1&&it.getLong("revision")>=0)}}else JSONObject().put("schemaVersion",1).put("revision",0L).put("entries",JSONObject()).put("migrations",JSONObject()) + private var unavailable=false + init {val entries=state.getJSONObject("entries");val migrations=state.getJSONObject("migrations") + for(key in entries.keys()){val entry=entries.getJSONObject(key);require(key==entry.getString("package"));val wire=Base64.getDecoder().decode(entry.getString("wire"));require(wire.size<=EarlyPlanWire.MAX_BYTES&&DeviceRpc.sha256(wire)==entry.getString("wireSha256"));entry.getJSONObject("binding")} + for(key in migrations.keys()){val migration=migrations.getJSONObject(key);require(key==migration.getString("package")&&DeviceRpc.sha256(migration.getString("beforeRaw").toByteArray())==migration.getString("beforeHash"))} + operations.hookCache=this} + private fun commit(candidate:JSONObject){if(unavailable)throw DeviceFault("CACHE_STORAGE_UNAVAILABLE","cache persistence requires inspection");val text=candidate.toString();if(text.toByteArray().size>2*1024*1024)throw DeviceFault("CACHE_FULL","cache history requires explicit archival");try{files.write(file,text);state=candidate}catch(_:Exception){unavailable=true;throw DeviceFault("CACHE_STORAGE_UNAVAILABLE","cache persistence unconfirmed",true)}} + private fun revision()=state.getLong("revision") + private fun next()=JSONObject(state.toString()).put("revision",revision()+1) + private fun pkg(value:String):String{if(!Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+").matches(value)||value in setOf("com.adh.manager","com.adh.daemon"))throw DeviceFault("INVALID_ARGUMENT","explicit third-party package required");return value} + private fun requireRevision(params:JSONObject){if(params.getLong("expectedCacheRevision")!=revision())throw DeviceFault("STALE_EARLY_CACHE","cache changed; observe before new intent")} + fun validate(method:String,params:JSONObject){ + when(method){ + "early.stage"->{val plan=params.getJSONObject("plan");pkg(plan.getString("package"));val canonicalPlan=params.getString("canonicalPlan");require(canonicalPlan.toByteArray().size<=128*1024);if(DeviceRpc.canonical(JSONObject(canonicalPlan))!=DeviceRpc.canonical(plan)||DeviceRpc.sha256(canonicalPlan.toByteArray())!=params.getString("digest"))throw DeviceFault("PLAN_DIGEST_MISMATCH","plan body differs from immutable digest");try{EarlyPlanWire.validate(plan)}catch(_:Exception){throw DeviceFault("UNSUPPORTED_EARLY_PLAN","early supports named capture modules and observe-only GOT hooks, no waits/Java/inline/replay")};requireRevision(params);require(params.getString("offline")=="keep-until-expiry");val ttl=params.getLong("expiresAt")-System.currentTimeMillis()/1000;require(ttl in 1..86400)} + "early.revoke"->{pkg(params.getString("package"));requireRevision(params);require(params.getString("deploymentId").length==36)} + "hooks.migration.apply"->{pkg(params.getString("package"));require(Regex("[a-f0-9]{64}").matches(params.getString("planDigest")))} + "hooks.migration.rollback"->require(params.getString("migrationId").length==36) + } + } + @Synchronized fun execute(method:String,params:JSONObject,sourceGrant:String?=null):JSONObject{ + val packageName=params.optString("package") + return when(method){ + "early.prepare"->{val binding=probe.inspect(pkg(packageName));JSONObject().put("binding",binding).put("cacheRevision",revision()).put("phase","post-specialize-before-agent-start").put("supported",binding.optBoolean("earlySupported")).put("maxTtlSeconds",86400)} + "early.status"->{JSONObject().put("cacheRevision",revision()).put("available",!unavailable).put("entry",state.getJSONObject("entries").optJSONObject(packageName)?:JSONObject.NULL).put("migration",state.getJSONObject("migrations").optJSONObject(packageName)?:JSONObject.NULL).put("scopeRevision",scope.snapshot().getString("scopeRevision")).put("applied",JSONObject.NULL).put("note","staged/validated is not installed; runtime receipts are agent-reported")} + "early.stage"->{validate(method,params);val plan=params.getJSONObject("plan");val name=plan.getString("package");val snapshot=scope.snapshot();val authority=snapshot.getJSONObject("document").optJSONObject("hookPlans")?.optJSONObject(name) + if(authority?.optString("authority")!="host-plans/1")throw DeviceFault("MIGRATION_REQUIRED","preserve and migrate legacy policy before staging") + val actual=probe.inspect(name);if(!actual.optBoolean("earlySupported"))throw DeviceFault("UNSUPPORTED_AGENT","installed agent lacks early-plan/1 export") + if(DeviceRpc.canonical(actual)!=DeviceRpc.canonical(params.getJSONObject("binding")))throw DeviceFault("TARGET_CHANGED","APK/UID/version/signer/agent binding changed") + val deployment=UUID.randomUUID().toString();val wire=EarlyPlanWire.encode(plan,actual,deployment,params.getString("digest"),params.getLong("expiresAt"));val candidate=next() + candidate.getJSONObject("entries").put(name,JSONObject().put("deploymentId",deployment).put("digest",params.getString("digest")).put("package",name).put("binding",actual).put("expiresAt",params.getLong("expiresAt")).put("offline","keep-until-expiry").put("state","validated-cache").put("sourceGrant",sourceGrant?:JSONObject.NULL).put("wireSha256",DeviceRpc.sha256(wire)).put("wire",Base64.getEncoder().encodeToString(wire))) + commit(candidate);execute("early.status",JSONObject().put("package",name)).put("ok",true) + } + "early.revoke"->{validate(method,params);val old=state.getJSONObject("entries").optJSONObject(packageName)?:throw DeviceFault("EARLY_NOT_FOUND","no cache for package");if(old.getString("deploymentId")!=params.getString("deploymentId"))throw DeviceFault("TARGET_CHANGED","another deployment replaced this cache");val candidate=next();candidate.getJSONObject("entries").getJSONObject(packageName).put("state","revoked").put("revokedAt",System.currentTimeMillis());commit(candidate);JSONObject().put("ok",true).put("cacheRevision",revision()).put("existingProcessesUnaffected",true)} + "hooks.migration.preview"->{pkg(packageName);val raw=scope.raw();require(raw.toByteArray().size<=128*1024);JSONObject().put("scopeRaw",raw).put("scopeRevision",DeviceRpc.sha256(raw.toByteArray())).put("package",packageName).put("cacheRevision",revision()).put("willApply",false)} + "hooks.migration.apply"->{validate(method,params);val before=scope.snapshot();if(params.getString("scopeRevision")!=before.getString("scopeRevision"))throw DeviceFault("STALE_SCOPE","scope changed") + val doc=before.getJSONObject("document");if(!doc.getJSONArray("packages").toString().contains(JSONObject.quote(packageName)))throw DeviceFault("TARGET_DENIED","package not in scope") + if(doc.optJSONObject("hookPlans")?.has(packageName)==true)throw DeviceFault("ALREADY_MIGRATED","package already managed; inspect previous backup") + val raw=scope.raw();require(raw.toByteArray().size<=128*1024);val id=UUID.randomUUID().toString();val managed=JSONObject(doc.toString());val map=managed.optJSONObject("hookPlans")?:JSONObject();map.put(packageName,JSONObject().put("authority","host-plans/1").put("migrationId",id).put("sourcePlanDigest",params.getString("planDigest")));managed.put("hookPlans",map) + val after=managed.toString(2);val backup=JSONObject().put("migrationId",id).put("package",packageName).put("beforeRaw",raw).put("beforeHash",before.getString("scopeRevision")).put("afterHash",DeviceRpc.sha256(after.toByteArray())).put("state","prepared") + val reserved=next();reserved.getJSONObject("migrations").put(packageName,backup);commit(reserved) + scope.restoreExact(after,before.getString("scopeRevision"));val complete=next();complete.getJSONObject("migrations").getJSONObject(packageName).put("state","migrated");commit(complete) + JSONObject().put("ok",true).put("migrationId",id).put("scopeRevision",backup.getString("afterHash")).put("cacheRevision",revision()).put("applied",false) + } + "hooks.migration.rollback"->{validate(method,params);val match=state.getJSONObject("migrations").keys().asSequence().map{state.getJSONObject("migrations").getJSONObject(it)}.firstOrNull{it.getString("migrationId")==params.getString("migrationId")}?:throw DeviceFault("MIGRATION_NOT_FOUND","backup not found") + if(params.getString("scopeRevision")!=match.getString("afterHash"))throw DeviceFault("STALE_SCOPE","later scope edits prevent exact rollback") + if(DeviceRpc.sha256(match.getString("beforeRaw").toByteArray())!=match.getString("beforeHash"))throw DeviceFault("CACHE_CORRUPT","original scope backup differs") + scope.restoreExact(match.getString("beforeRaw"),params.getString("scopeRevision"));val candidate=next();candidate.getJSONObject("migrations").getJSONObject(match.getString("package")).put("state","rolled-back");candidate.getJSONObject("entries").optJSONObject(match.getString("package"))?.put("state","revoked");commit(candidate) + JSONObject().put("ok",true).put("scopeRevision",match.getString("beforeHash")).put("cacheRevision",revision()).put("existingProcessesUnaffected",true) + } + else->throw DeviceFault("UNSUPPORTED_METHOD","unknown hook cache capability") + } + } + @Synchronized fun forProcess(packageName:String,uid:Int):ByteArray?{ + if(unavailable)return null;val entry=state.getJSONObject("entries").optJSONObject(packageName)?:return null + if(entry.optString("state")!="validated-cache"||entry.getLong("expiresAt")<=System.currentTimeMillis()/1000)return null + val grant=entry.optString("sourceGrant").takeIf{it.isNotEmpty()&&it!="null"};if(grant!=null&&runCatching{operations.network?.pairings?.authorize(grant,"early.stage")?:throw DeviceFault("AUTH_REVOKED","authorization unavailable")}.isFailure)return null + val scopeDoc=scope.snapshot().getJSONObject("document");if(scopeDoc.optJSONObject("hookPlans")?.optJSONObject(packageName)?.optString("authority")!="host-plans/1"||(0 until scopeDoc.getJSONArray("packages").length()).none{scopeDoc.getJSONArray("packages").getString(it)==packageName})return null + val actual=probe.inspect(packageName);if(actual.getInt("uid")!=uid||DeviceRpc.canonical(actual)!=DeviceRpc.canonical(entry.getJSONObject("binding")))return null + val wire=Base64.getDecoder().decode(entry.getString("wire"));if(DeviceRpc.sha256(wire)!=entry.getString("wireSha256"))return null;return wire + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt b/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt index d598ba3..8517e5e 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/ScopeDocuments.kt @@ -8,6 +8,8 @@ import org.json.JSONObject import java.io.File internal class ScopeDocuments(private val file: File, private val files: DeviceFiles) { + fun raw():String {check(!file.exists()||file.length()<=512*1024);return (if(file.exists())file.readText()else ScopeJson.encode(ScopeConfig.EMPTY)).also{ScopeJson.decode(it)}} + fun restoreExact(raw:String,expected:String){if(snapshot().getString("scopeRevision")!=expected)throw DeviceFault("STALE_SCOPE","scope changed before exact restore");ScopeJson.decode(raw);files.write(file,raw,420)} fun snapshot(): JSONObject { check(!file.exists() || file.length() <= 512 * 1024) { "scope document too large" } val raw = if (file.exists()) file.readText() else ScopeJson.encode(ScopeConfig.EMPTY) @@ -36,6 +38,13 @@ internal class ScopeDocuments(private val file: File, private val files: DeviceF val before = snapshot() if (expected != null && expected != before.getString("scopeRevision")) throw DeviceFault("STALE_SCOPE", "scope changed outside this request") val input = JSONObject(raw) + val original=JSONObject(before.getJSONObject("document").toString()) + val authorities=original.optJSONObject("hookPlans")?:JSONObject() + if(input.has("hookPlans")&&DeviceRpc.canonical(input.get("hookPlans"))!=DeviceRpc.canonical(authorities))throw DeviceFault("HOOK_PLANS_MANAGED","authority changes require reversible Host migration") + for(pkg in authorities.keys()){ + val beforeConfig=ScopeJson.decode(original.toString());val nextConfig=ScopeJson.decode(raw) + if(beforeConfig.contains(pkg)&&nextConfig.contains(pkg)&&beforeConfig.familiesFor(pkg)!=nextConfig.familiesFor(pkg))throw DeviceFault("HOOK_PLANS_MANAGED","fixed phone Hook policy is managed by Host plans") + } val normalized = JSONObject(ScopeJson.encode(ScopeJson.decode(raw))) val merged = before.getJSONObject("document") for (key in input.keys()) if (key !in setOf("version", "mode", "packages", "policy")) merged.put(key, input.get(key)) @@ -74,6 +83,7 @@ internal class ScopeDocuments(private val file: File, private val files: DeviceF policy.put(pkg, entry.put("c", c)) } if (policy.length() > 0) merged.put("policy", policy) else merged.remove("policy") + for(pkg in authorities.keys())original.optJSONObject("policy")?.opt(pkg)?.let{val current=merged.optJSONObject("policy")?:JSONObject();current.put(pkg,it);merged.put("policy",current)} files.write(file, merged.toString(2), 420) return snapshot().put("ok", true) } diff --git a/device/daemon/src/test/java/com/adh/daemon/AgentEarlyAbiTest.kt b/device/daemon/src/test/java/com/adh/daemon/AgentEarlyAbiTest.kt new file mode 100644 index 0000000..aac7f1f --- /dev/null +++ b/device/daemon/src/test/java/com/adh/daemon/AgentEarlyAbiTest.kt @@ -0,0 +1,21 @@ +package com.adh.daemon + +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File +import java.nio.file.Files + +class AgentEarlyAbiTest { + @Test fun actualReleaseAgentExportsEarlyEntryAndKeepsInternalHelpersHidden(){ + val agent=File("../../agent/build/libadh_agent.so").canonicalFile + assumeTrue("isolated native release build unavailable; run tools/build_agent.sh without deploy",agent.isFile) + assertTrue("early entry must survive the production export map",AgentEarlyAbi.exported(agent)) + assertFalse(AgentEarlyAbi.exported(agent,"adh_agent_copy_owner")) + assertFalse(AgentEarlyAbi.exported(agent,"adh_early_status_json")) + } + @Test fun markerAloneOrMalformedElfCannotAdvertiseSupport(){ + val file=Files.createTempFile("adh-p5-abi-",".bin").toFile() + try{file.writeText("ADH_EARLY_PLAN_V1 adh_agent_apply_early_v1");assertFalse(AgentEarlyAbi.exported(file));file.writeBytes(ByteArray(128));assertFalse(AgentEarlyAbi.exported(file))}finally{file.delete()} + } +} diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt index 9a5bf58..24050b4 100644 --- a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt @@ -19,13 +19,14 @@ object DeviceRpcFixture { val counter = java.util.concurrent.atomic.AtomicInteger(if (countFile.exists()) countFile.readText().toInt() else 0) var endpoint = "" val certificates = org.json.JSONArray() + var cache:HookPlanCache?=null val backend = DeviceBackend { method, params -> when (method) { "device.info" -> JSONObject().put("model", "JVM fixture").put("synthetic", true) "scope.get" -> scopes.snapshot() "scope.patch" -> scopes.patch(params) "scope.replace" -> scopes.replace(params.getJSONObject("document").toString(), params.getString("scopeRevision")) - "module.status" -> JSONObject().put("synthetic", true).put("calls", counter.get()) + "module.status" -> JSONObject().put("synthetic", true).put("calls", counter.get()).put("earlyEligible",params.optString("package").takeIf{it.isNotEmpty()}?.let{cache?.forProcess(it,params.optInt("uid"))!=null}?:false) "applications.list" -> JSONObject().put("applications", org.json.JSONArray()).put("total", 0) "processes.list" -> JSONObject().put("processes", org.json.JSONArray()).put("complete", true).put("total", 0) "host.get" -> JSONObject().put("endpoint", endpoint) @@ -38,6 +39,10 @@ object DeviceRpcFixture { } } val operations = DeviceOperations(identity, files, backend) + cache=HookPlanCache(operations,files,scopes,HookBindingProbe { name -> + val bindingFile=File(root,"hook-binding.json") + if(bindingFile.exists())JSONObject(bindingFile.readText()) else JSONObject().put("package",name).put("uid",10001).put("versionCode","1").put("signers",org.json.JSONArray().put("b".repeat(64))).put("source",org.json.JSONArray().put(JSONObject().put("path","fixture.apk").put("size",100).put("inode",1).put("mtime",1))).put("agentSha256","a".repeat(64)).put("earlySupported",true) + }) val network = DeviceNetwork(operations, files, allowEphemeral = true) val server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); val workers = Executors.newFixedThreadPool(4) File(root, "ready.json").writeText(JSONObject().put("port", server.localPort).put("deviceId", identity.deviceId).put("lanPort", network.execute("lan.status", JSONObject()).opt("port")).toString()) diff --git a/device/manager/src/main/java/com/adh/manager/MainActivity.kt b/device/manager/src/main/java/com/adh/manager/MainActivity.kt index c24db77..dea7822 100644 --- a/device/manager/src/main/java/com/adh/manager/MainActivity.kt +++ b/device/manager/src/main/java/com/adh/manager/MainActivity.kt @@ -149,7 +149,7 @@ fun AdhApp(repository: ScopeRepository, webUiRepository: WebUiRepository) { packageName = Uri.decode(entry.arguments?.getString("packageName").orEmpty()), draft = draft, onBack = { nav.popBackStack() }, - onPersist = { persist() }, + repository = repo, ) } } diff --git a/device/manager/src/main/java/com/adh/manager/data/DaemonScopeRepository.kt b/device/manager/src/main/java/com/adh/manager/data/DaemonScopeRepository.kt index 0898204..a0f4df0 100644 --- a/device/manager/src/main/java/com/adh/manager/data/DaemonScopeRepository.kt +++ b/device/manager/src/main/java/com/adh/manager/data/DaemonScopeRepository.kt @@ -24,6 +24,10 @@ interface DaemonClient { fun putCaCert(encoded: ByteArray): Int fun deleteCaCert(fileName: String): Boolean fun rebootDevice(): Boolean + val scopeSnapshotJson:String get()="" + fun patchScopePackages(packagesJson:String,scopeRevision:String,stateRevision:Long):String = "" + fun hookPlanState(packageName:String):String = "" + fun revokeHookPlan(packageName:String,deploymentId:String,cacheRevision:Long,stateRevision:Long):String = "" val modulePresent: Boolean val loaderActive: Boolean val moduleVersion: String @@ -32,13 +36,21 @@ interface DaemonClient { class DaemonScopeRepository( private val clientProvider: (Long) -> DaemonClient? = DaemonBinderProvider::awaitClient, ) : ScopeRepository { + private var observed:org.json.JSONObject?=null override fun load(): ScopeConfig { val client = requireClient() + if(client.protocolVersion>=AdhProtocol.MIN_HOST_PLANS_VERSION){val snapshot=org.json.JSONObject(client.scopeSnapshotJson);observed=snapshot;return ScopeJson.decode(snapshot.getJSONObject("document").toString())} return ScopeJson.decode(client.scopeJson) } override fun save(config: ScopeConfig): Result = runCatching { val client = requireClient() + if(client.protocolVersion>=AdhProtocol.MIN_HOST_PLANS_VERSION){ + val snapshot=checkNotNull(observed){"load scope before editing"} + val reply=org.json.JSONObject(client.patchScopePackages(org.json.JSONArray(config.packages.sorted()).toString(),snapshot.getString("scopeRevision"),snapshot.getLong("stateRevision"))) + check(reply.getString("state")=="succeeded"){"scope changed or write unconfirmed; reload before editing"} + observed=reply.getJSONObject("result").put("stateRevision",reply.getLong("stateRevision"));return@runCatching + } if (config.policy.isNotEmpty()) { // An older daemon decodes into its own :core and re-encodes from it, so it drops a // policy it does not know AND still answers true — the UI would report "saved" for a @@ -56,6 +68,11 @@ class DaemonScopeRepository( return runCatching { InstalledAppsJson.decode(client.listApplicationsJson) } .getOrDefault(emptyList()) } + override fun hookPlanState(packageName:String):String?{val client=requireClient();return if(client.protocolVersion>=AdhProtocol.MIN_HOST_PLANS_VERSION)client.hookPlanState(packageName) else null} + override fun revokeHookPlan(packageName:String,deploymentId:String,cacheRevision:Long,stateRevision:Long):Result = runCatching { + val client=requireClient();check(client.protocolVersion>=AdhProtocol.MIN_HOST_PLANS_VERSION) + check(org.json.JSONObject(client.revokeHookPlan(packageName,deploymentId,cacheRevision,stateRevision)).getString("state")=="succeeded"){"revocation not confirmed; refresh actual state"} + } override fun applicationIcon(packageName: String): ByteArray? { val pkg = packageName.trim() diff --git a/device/manager/src/main/java/com/adh/manager/data/ScopeRepository.kt b/device/manager/src/main/java/com/adh/manager/data/ScopeRepository.kt index 15a5bc9..d9357d6 100644 --- a/device/manager/src/main/java/com/adh/manager/data/ScopeRepository.kt +++ b/device/manager/src/main/java/com/adh/manager/data/ScopeRepository.kt @@ -42,6 +42,8 @@ interface ScopeRepository { fun putCaCert(encoded: ByteArray): Int = -1 fun deleteCaCert(fileName: String): Boolean = false fun rebootDevice(): Boolean = false + fun hookPlanState(packageName:String):String? = null + fun revokeHookPlan(packageName:String,deploymentId:String,cacheRevision:Long,stateRevision:Long):Result = Result.failure(UnsupportedOperationException("Host plans unavailable")) } enum class HostRemember { Saved, Unsupported, Unavailable } diff --git a/device/manager/src/main/java/com/adh/manager/ipc/DaemonBinderProvider.kt b/device/manager/src/main/java/com/adh/manager/ipc/DaemonBinderProvider.kt index 9e3e788..50ae318 100644 --- a/device/manager/src/main/java/com/adh/manager/ipc/DaemonBinderProvider.kt +++ b/device/manager/src/main/java/com/adh/manager/ipc/DaemonBinderProvider.kt @@ -66,6 +66,10 @@ class DaemonBinderProvider : ContentProvider() { val adapter = object : DaemonClient { override val protocolVersion: Int get() = service.protocolVersion override val scopeJson: String get() = service.scopeJson + override val scopeSnapshotJson:String get()=service.scopeSnapshotJson + override fun patchScopePackages(packagesJson:String,scopeRevision:String,stateRevision:Long):String=service.patchScopePackagesJson(packagesJson,scopeRevision,stateRevision) + override fun hookPlanState(packageName:String):String=service.getHookPlanStateJson(packageName) + override fun revokeHookPlan(packageName:String,deploymentId:String,cacheRevision:Long,stateRevision:Long):String=service.revokeHookPlanJson(packageName,deploymentId,cacheRevision,stateRevision) override fun setScopeJson(json: String): Boolean = service.setScopeJson(json) override val listApplicationsJson: String get() = service.listApplications() override fun applicationIconPng(packageName: String): ByteArray = diff --git a/device/manager/src/main/java/com/adh/manager/ui/scope/HookConfigScreen.kt b/device/manager/src/main/java/com/adh/manager/ui/scope/HookConfigScreen.kt index 167fcdc..30a1e1a 100644 --- a/device/manager/src/main/java/com/adh/manager/ui/scope/HookConfigScreen.kt +++ b/device/manager/src/main/java/com/adh/manager/ui/scope/HookConfigScreen.kt @@ -1,234 +1,46 @@ -package com.adh.manager.ui.scope - -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context -import androidx.annotation.StringRes -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.adh.core.CaptureFamilies -import com.adh.manager.R - -private enum class HookTab { - Crypto, - Capture, - System, -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun HookConfigScreen( - packageName: String, - draft: ScopeDraft, - onBack: () -> Unit, - onPersist: () -> Unit, -) { - val context = LocalContext.current - val label = remember(packageName) { - runCatching { - val info = context.packageManager.getApplicationInfo(packageName, 0) - context.packageManager.getApplicationLabel(info).toString() - }.getOrDefault(packageName) - } - val families = draft.families[packageName] ?: CaptureFamilies.DEFAULT - var tab by remember { mutableStateOf(HookTab.Crypto) } - - fun update(next: CaptureFamilies) { - draft.families = if (next.isDefault) draft.families - packageName else draft.families + (packageName to next) - onPersist() - } - - Scaffold( - containerColor = MaterialTheme.colorScheme.background, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(R.string.hook_config_title), - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - }, - navigationIcon = { - IconButton(onClick = onBack) { - Icon( - Icons.AutoMirrored.Rounded.ArrowBack, - contentDescription = stringResource(R.string.back), - ) - } - }, - actions = { - Column( - modifier = Modifier - .widthIn(max = 168.dp) - .clip(RoundedCornerShape(8.dp)) - .clickable(onClickLabel = stringResource(R.string.hook_copy_package)) { - val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - clipboard.setPrimaryClip(ClipData.newPlainText(label, packageName)) - } - .padding(horizontal = 12.dp, vertical = 4.dp), - horizontalAlignment = Alignment.End, - ) { - if (label != packageName) { - Text( - text = label, - style = MaterialTheme.typography.labelLarge, - fontWeight = FontWeight.Medium, - textAlign = TextAlign.End, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Text( - text = packageName, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.End, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - }, - ) - }, - ) { padding -> - Column( - modifier = Modifier - .fillMaxSize() - .padding(padding), - ) { - if (draft.persistFailed) { - Text( - text = stringResource(R.string.scope_save_failed), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), - ) - } - HookTabBar( - tab = tab, - onTab = { tab = it }, - modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), - ) - LazyColumn(modifier = Modifier.weight(1f)) { - when (tab) { - HookTab.Crypto -> { - item { FamilyRow(R.string.hook_family_digest, families.digest) { update(families.copy(digest = it)) } } - item { FamilyRow(R.string.hook_family_hmac, families.hmac) { update(families.copy(hmac = it)) } } - item { FamilyRow(R.string.hook_family_symmetric, families.symmetric) { update(families.copy(symmetric = it)) } } - item { FamilyRow(R.string.hook_family_asymmetric, families.asymmetric) { update(families.copy(asymmetric = it)) } } - item { FamilyRow(R.string.hook_family_aead, families.aead) { update(families.copy(aead = it)) } } - } - HookTab.Capture -> { - item { FamilyRow(R.string.hook_family_tls, families.tls) { update(families.copy(tls = it)) } } - } - HookTab.System -> { - item { FamilyRow(R.string.hook_family_system, families.system) { update(families.copy(system = it)) } } - } - } - } - } - } -} - -@Composable -private fun HookTabBar( - tab: HookTab, - onTab: (HookTab) -> Unit, - modifier: Modifier = Modifier, -) { - Surface( - color = MaterialTheme.colorScheme.surfaceContainerHigh, - shape = RoundedCornerShape(28.dp), - modifier = modifier.fillMaxWidth(), - ) { - Row(modifier = Modifier.padding(4.dp)) { - HookTabSegment(R.string.hook_tab_crypto, tab == HookTab.Crypto, { onTab(HookTab.Crypto) }, Modifier.weight(1f)) - HookTabSegment(R.string.hook_tab_capture, tab == HookTab.Capture, { onTab(HookTab.Capture) }, Modifier.weight(1f)) - HookTabSegment(R.string.hook_tab_system, tab == HookTab.System, { onTab(HookTab.System) }, Modifier.weight(1f)) - } - } -} - -@Composable -private fun HookTabSegment( - @StringRes labelRes: Int, - selected: Boolean, - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - Box( - modifier = modifier - .height(40.dp) - .clip(RoundedCornerShape(24.dp)) - .background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent) - .clickable(onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Text( - text = stringResource(labelRes), - style = MaterialTheme.typography.labelLarge, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - color = if (selected) MaterialTheme.colorScheme.onPrimary - else MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 6.dp), - ) - } -} - -@Composable -private fun FamilyRow(@StringRes labelRes: Int, checked: Boolean, onCheckedChange: (Boolean) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - text = stringResource(labelRes), - style = MaterialTheme.typography.bodyLarge, - modifier = Modifier.weight(1f), - ) - Switch(checked = checked, onCheckedChange = onCheckedChange) - } -} +package com.adh.manager.ui.scope + +import androidx.compose.foundation.layout.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.adh.manager.R +import com.adh.manager.data.ScopeRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONObject + +/** Observation/revocation only. No fixed family editor and no silent Host plan creation. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun HookConfigScreen(packageName:String,draft:ScopeDraft,onBack:()->Unit,repository:ScopeRepository){ + var state by remember(packageName){mutableStateOf(null)} + var message by remember(packageName){mutableStateOf("")} + var busy by remember{mutableStateOf(false)} + val coroutine=rememberCoroutineScope() + fun refresh(){coroutine.launch{busy=true;message="";val result=withContext(Dispatchers.IO){runCatching{repository.hookPlanState(packageName)?.let{JSONObject(it)}}};state=result.getOrNull();if(result.isFailure)message=result.exceptionOrNull()?.message.orEmpty();busy=false}} + LaunchedEffect(packageName){refresh()} + Scaffold(topBar={TopAppBar(title={Text(stringResource(R.string.host_plan_title))},navigationIcon={IconButton(onClick=onBack){Icon(Icons.AutoMirrored.Rounded.ArrowBack,contentDescription=stringResource(R.string.back))}})}){padding-> + Column(Modifier.fillMaxSize().padding(padding).padding(20.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){ + Text(packageName,style=MaterialTheme.typography.titleMedium) + Text(stringResource(R.string.host_plan_guidance)) + Text(stringResource(R.string.host_plan_legacy)+(draft.families[packageName]?.toString()?:"default"),style=MaterialTheme.typography.bodySmall) + val snapshot=state;val entry=snapshot?.optJSONObject("entry") + if(snapshot==null)Text(stringResource(R.string.host_plan_unavailable)) + else if(entry==null)Text(stringResource(R.string.host_plan_no_cache)) + else {Text(entry.optString("state"));Text(entry.optString("digest"),style=MaterialTheme.typography.bodySmall);Text("TTL: "+entry.optLong("expiresAt"));Text(stringResource(R.string.host_plan_not_installed))} + if(message.isNotBlank())Text(message,color=MaterialTheme.colorScheme.error) + Button(onClick={refresh()},enabled=!busy){Text(stringResource(R.string.host_plan_refresh))} + OutlinedButton(enabled=!busy&&entry!=null&&entry.optString("state")!="revoked",onClick={ + val observed=state?:return@OutlinedButton;val selected=observed.optJSONObject("entry")?:return@OutlinedButton + coroutine.launch{busy=true;val result=withContext(Dispatchers.IO){repository.revokeHookPlan(packageName,selected.getString("deploymentId"),observed.getLong("cacheRevision"),observed.getLong("stateRevision"))};busy=false;message=if(result.isSuccess)"" else result.exceptionOrNull()?.message.orEmpty();if(result.isSuccess)refresh()} + }){Text(stringResource(R.string.host_plan_revoke))} + Text(stringResource(R.string.host_plan_revoke_note),style=MaterialTheme.typography.bodySmall) + } + } +} diff --git a/device/manager/src/main/res/values-en/strings.xml b/device/manager/src/main/res/values-en/strings.xml index 57d480d..cd4408e 100644 --- a/device/manager/src/main/res/values-en/strings.xml +++ b/device/manager/src/main/res/values-en/strings.xml @@ -66,9 +66,9 @@ Stopped %1$s, but it has no launchable activity This app cannot be stopped or restarted Unable to control %1$s - Hook config + Host Hook plans Hooks trimmed - Hook config + Host Hook plans Crypto Traffic Detect @@ -108,4 +108,13 @@ Could not reboot the device Could not delete the certificate Cancel + Host Hook plans + Manage plans through the Host AI, CLI or workbench. This phone only observes and revokes future-start caches. + Legacy snapshot (read-only): + Plan status is unsupported or unavailable. Inspect it on the Host; this does not prove installation. + No early cache for this package. Save, validate and explicitly deploy from the Host. + A saved cache is not an installed Hook. Inspect runtime receipts on the Host. + Refresh status + Revoke this early cache + Stops future cache retrieval only. Existing processes and installed Hooks are unaffected. diff --git a/device/manager/src/main/res/values/strings.xml b/device/manager/src/main/res/values/strings.xml index 2bfcf21..ec01294 100644 --- a/device/manager/src/main/res/values/strings.xml +++ b/device/manager/src/main/res/values/strings.xml @@ -66,9 +66,9 @@ 已终止 %1$s,但没有可启动的界面 不允许终止或重启该应用 无法操作 %1$s - Hook 配置 + Host Hook 方案 已裁剪钩子 - Hook 配置 + Host Hook 方案 加解密 系统抓包 系统检测 @@ -108,4 +108,13 @@ 无法重启设备 无法删除证书 取消 + Host Hook 方案 + Hook 方案由 Host 的 AI、CLI 或工作台管理。手机只查看状态和停用未来启动缓存。 + 旧配置快照(只读): + 当前服务不支持方案状态,或连接不可用。请在 Host 核对,不能据此判断已安装。 + 本包没有早期缓存。请在 Host 保存、验证并明确部署方案。 + 缓存已保存不等于 Hook 已安装;实际运行结果请在 Host 查看。 + 刷新状态 + 停用本包早期缓存 + 仅阻止之后获取缓存的启动,不停止当前进程,也不撤回已经安装的 Hook。 diff --git a/device/manager/src/test/java/com/adh/manager/data/DaemonScopeRepositoryTest.kt b/device/manager/src/test/java/com/adh/manager/data/DaemonScopeRepositoryTest.kt index dfc4940..73ccfdb 100644 --- a/device/manager/src/test/java/com/adh/manager/data/DaemonScopeRepositoryTest.kt +++ b/device/manager/src/test/java/com/adh/manager/data/DaemonScopeRepositoryTest.kt @@ -173,8 +173,32 @@ class DaemonScopeRepositoryTest { assertEquals(-1, repository.putCaCert(ByteArray(CaCertStore.MAX_BUNDLE_BYTES + 1))) } + @Test fun hostPlanManagerUsesFrozenVersionsAndPackageOnlyPatch() { + val base=FakeDaemonClient(protocol=20) + val original=org.json.JSONObject().put("version",20).put("mode","allowlist").put("packages",org.json.JSONArray().put("com.example.target")).put("policy",org.json.JSONObject().put("com.example.target",org.json.JSONObject().put("c",org.json.JSONObject().put("d",false)))) + var revision=3L;var snapshot=org.json.JSONObject().put("document",original).put("scopeRevision","scope-before").put("stateRevision",revision) + var legacyWrites=0;var packagePatches=0 + val client=object:DaemonClient by base { + override val scopeSnapshotJson:String get()=snapshot.toString() + override fun setScopeJson(json:String):Boolean {legacyWrites++;return false} + override fun patchScopePackages(packagesJson:String,scopeRevision:String,stateRevision:Long):String { + packagePatches++;if(stateRevision!=revision||scopeRevision!=snapshot.getString("scopeRevision"))return org.json.JSONObject().put("state","failed").put("code","STALE_SCOPE").toString() + original.put("packages",org.json.JSONArray(packagesJson));revision++;snapshot=org.json.JSONObject().put("document",original).put("scopeRevision","scope-after").put("stateRevision",revision) + return org.json.JSONObject().put("state","succeeded").put("stateRevision",revision).put("result",snapshot).toString() + } + override fun hookPlanState(packageName:String)="{\"entry\":null,\"cacheRevision\":2,\"stateRevision\":4}" + override fun revokeHookPlan(packageName:String,deploymentId:String,cacheRevision:Long,stateRevision:Long):String {assertEquals(2L,cacheRevision);assertEquals(4L,stateRevision);return "{\"state\":\"succeeded\"}"} + } + val repository=DaemonScopeRepository{client};val loaded=repository.load() + assertTrue(repository.save(loaded.copy(packages=setOf("com.example.target","com.example.other"))).isSuccess) + assertFalse(original.getJSONObject("policy").getJSONObject("com.example.target").getJSONObject("c").getBoolean("d")) + revision++ + assertTrue(repository.save(loaded).isFailure);assertEquals(0,legacyWrites);assertEquals(2,packagePatches) + assertTrue(repository.hookPlanState("com.example.target")!!.contains("cacheRevision"));assertTrue(repository.revokeHookPlan("com.example.target","fixture",2,4).isSuccess) + } + private class FakeDaemonClient( - protocol: Int = AdhProtocol.VERSION, + protocol: Int = 19, ) : DaemonClient { override val protocolVersion = protocol override var scopeJson = ScopeJson.encode(ScopeConfig.EMPTY) diff --git a/docs/P5_HOOK_PLANS.md b/docs/P5_HOOK_PLANS.md new file mode 100644 index 0000000..232bdc3 --- /dev/null +++ b/docs/P5_HOOK_PLANS.md @@ -0,0 +1,106 @@ +# P5:Host Hook 方案、早期缓存与可逆迁移 + +2026-11-16。Host 是方案与流程的权威;手机保留设备执行、验证缓存、状态和撤销入口。AI 默认持有控制,人类通过同一操作层查看、编辑和接管。P5 没有部署到现有手机,也没有重启现有 Host。 + +## 模块与统一入口 + +| 模块 | 职责 | +| --- | --- | +| `daemon/src/hook_plans.ts` | 严格方案校验、不可变版本、库 CAS、预检、顺序执行、逐步回执、观察和有限撤销 | +| `hook_plan_host.ts`、`http/routes_hook_plans.ts`、MCP `hook_plans` | 统一 action dispatcher;复用 P1 持久任务、目标代次、幂等键、版本、控制权及 unknown | +| `public/hook-plans-panel.js` | `/workbench` 和现场内嵌面板共用 JSON 编辑器、版本准备、任务提交及按意图键查询 | +| `device/.../HookPlanCache.kt` | 持久缓存与迁移账本、APK/Agent 绑定、TTL、授权与 scope 再校验 | +| `AndroidHookBinding.kt`、`EarlyPlanBroker.kt` | 包身份、Agent SHA/导出 ABI 检查;仅 root 可访问的本地有界缓存接口 | +| `core/EarlyPlanWire.kt`、`agent/src/bootstrap/early_wire.h` | Kotlin 编码与 native 验证同一受限指令格式、内容 SHA、目标与过期检查 | +| `agent/src/bootstrap/early_plan.cpp`、`injector/zygisk/jni/main.cpp` | Zygisk 获取缓存并绑定加载文件;Agent 先执行缓存,再启动 Host 通道,hello 带结果 | +| Manager `HookConfigScreen`、Binder v20 | 固定 Hook 编辑器改为旧策略快照、缓存状态与停止未来缓存;作用域改走包列表 CAS | + +MCP:`hook_plans`。REST:`GET/POST /api/hook-plans`。发布版 Python CLI 已有的 `adh call hook_plans --arguments ...`(查询)与 `adh run hook_plans --arguments ...`(持久写入)直接复用此工具,无第二套方案解释器。`daemon/src/cli.ts` 继续承担原有专用命令;通用方案入口使用 Python CLI。 + +可用 actions: + +- 查询:`list/get/validate/preflight/run/observe`、`early-prepare/early-status/migration-preview`。 +- 写入:`put/import-legacy/apply/undo`、`early-stage/early-revoke/migration-apply/migration-rollback`。 + +写入一律要求 P1 `_operation` 的当前状态版本与控制代次,建议持久 `taskId` 和 `idempotencyKey`。AI 不自动夺取人类控制,也不刷新旧版本重发失败指令。面板“读取提交版本”冻结当前参数和状态,修改草稿后必须重新读取;未知 HTTP 提交保留意图键,只查询记录。 + +## 方案与版本 + +```json +{ + "schemaVersion": 1, + "id": "observe-example", + "title": "观察示例模块", + "package": "com.example.app", + "families": { + "digest": true, "hmac": true, "symmetric": false, + "asymmetric": false, "tls": false, "aead": false, "system": false + }, + "steps": [{ + "id": "got-read", "tool": "native_hook", + "arguments": {"action": "hook", "mode": "got", "module": "libexample.so", "symbol": "read"} + }] +} +``` + +所有七个 family 必须显式指定,表示后续捕获安装的资格;不会自行安装这些 family。程序支持已有 `native_hook`、`java_hook`(hook/hookAll)、`jni_onload`(hook)、`module_watch`(start)和 `capture_start` 原语,步骤参数以当前 MCP schema 校验,不可覆盖 session、device 或授权上下文。最多 32 步、128 KiB,每步可选 `waitMs`(0..600000),等待受任务预算和检查点约束。没有手机端任意脚本求值器。 + +`capture_start` 必须写明三个模块参数。空 `cryptoModule` 是显式全模块扫描;空 file/sys 是不启用该模块组。省略参数的旧原语仍可使用旧模板;完整方案不从旧设置偷取模块值。 + +`put` 使用 `expectedLibraryRevision`,返回不可变 SHA-256 digest。Host 数据位于 `hook-plans/library.json`、`versions/.json`、`runs/.json`。构造或导入模块不会建库、清理历史或自动安装;损坏的索引/版本拒绝读取,不自动重建。库头写入失败时可能留下孤立不可变版本,重新观察版本后再做新意图。 + +保存不等于应用。`apply` 必须显式给出 digest 和在线 session;预检校验包名、进程代次和 `capture_policy` 等运行时能力。先记录 run,再读取/设置明确 family 策略,再调用现有原语。每步保存真实回执;Java 批次部分安装不会成为整套成功。具名捕获的部分符号不存在按原语返回 partial,完整性保留在回执中。 + +超时/取消由 P1 协调器返回事实状态:已派发命令不能收回,没有自动重试或推断成功。`run.state` 是历史记录,`run/observe` 同时返回权威 Operation;Host 崩溃后的 running 文件不能覆盖 Operation 的 unknown。断线对账延续 P4,仅附加设备账本证据,不重放。 + +撤销仅支持可核验的单个 native/Java Hook ID;先读当前状态并核对归属与策略。partial/unknown 运行、批次、watch 和持久 capture 集合返回 UNSUPPORTED_UNDO。历史捕获回执不能证明当前集合仍属于本方案,需核对后显式 capture_stop;不会退化为 unhook-all 或声称恢复原捕获集合。 + +## 早期缓存的实际边界 + +阶段是 **post-specialize / before-agent-start**,不是 `.init_array` 之前、不是 pre-specialize,也不是 Java 类加载前保证。支持 1..16 步的具名模块 `capture_start` 和只观测的 GOT `native_hook`;拒绝等待、Java、inline、改参数/返回值、主动调用或重放。该边界只覆盖此缓存格式,完整实时方案仍保留已有原语自由度。 + +流程: + +1. `migration-preview` 返回完整原 scope 原文及 hash;`import-legacy` 生成 Host 方案版本。 +2. `migration-apply` 显式标记该包的 authority 为 `host-plans/1`,保留完整旧数据与备份,不扩大注入范围,也不装 Hook。 +3. `early-prepare` 读取新鲜绑定、`cacheRevision` 与支持状态。绑定包含包名、UID、versionCode、APK signer、base/split APK 文件路径/大小/inode/mtime、Agent SHA-256 及 ELF 导出 `adh_agent_apply_early_v1`。 +4. `early-stage` 指定 digest、原 prepare binding、`expectedCacheRevision`、秒级 `expiresAt` 和 `offline:"keep-until-expiry"`。必须同时携带 P3/P4 的 deviceId、connectionId、bootId、daemonInstanceId、expectedDeviceRevision。TTL 为 1..86400 秒。新库版本不会替换已暂存 digest,需再次显式 stage。 +5. USB 和 LAN 调用同一 DeviceOperations。LAN stage/revoke/迁移要求 `manage` 权限,缓存记录来源 grant,消费前重新检查授权。未迁移设备方法返回 unsupported,不转旧 ADB 命令。 +6. root broker 为新进程检查 scope、authority、UID、绑定、有效期、来源授权和 wire SHA;Zygisk 校验 root peer,并对实际加载的 Agent 文件取 SHA。Agent 再验二进制内容、包/UID/Agent SHA/TTL,在同一进程最多消费一次,第一步未确认安装即停止后续步骤。 + +缓存文件是 root 私有的有界 JSON(2 MiB,不自动清理),本地 socket 无 HTTP/MCP 或设备分析逻辑。内容 SHA 用于完整性;授权来自既有 root 信任边界和 P4 的 TLS/权限,不把 SHA 称为签名或硬件证明。APK 元数据绑定不宣称完整 APK 内容测量;信任 Android 包管理器与 root 存储。 + +`early-status` 的 `validated-cache` 仅说明暂存验证通过,`applied:null`。Agent hello 的 `earlyPlan` 列出 attempted/confirmed/每步 installed/Hook ID,明确 `agent-reported`。GOT 缺失或安装失败返回 partial-or-failed,不因为 RPC 被接受而报成功。旧 target 通道仍未绑定设备身份;不得据此升级成已验证设备会话。 + +`early-revoke` 只阻止未来获取缓存,不卸载现有进程 Hook;已经交付给正在启动进程的包不能追回,仍受其原 TTL 限制。授权撤销同样在后续 broker 获取时生效。不会为了刷新 APK、安装新库或换进程而自动启停 App。broker 超时、旧 Agent、模块尚未载入均失败关闭;没有重试安装或恢复默认固定 Hook。 + +## 旧配置迁移与回滚 + +迁移保留旧 scope **精确原文字节**、beforeHash、预期 afterHash、migrationId 和阶段;先持久 prepared,再 CAS 写 scope,再记 migrated。Unknown/retired/未来字段保留。Host `import-legacy` 把 scope/settings 完整快照放入版本 metadata,将旧 family/捕获模块与兼容的启动 native Hook 转成显式步骤;输出过滤和已退役的 bypass 只存档,不冒充迁移后已执行。 + +`migration-rollback` 需要 migrationId 和原迁移后的 scopeRevision,重新校验备份与当前 scope,逐字节恢复 beforeRaw,并撤销未来缓存。后续哪怕是别的包的 scope 修改也会触发冲突;保留现场,由 AI/人类基于最新文档决定新的修复意图,不强行覆盖。迁移/回滚持久化中断保留 prepared/unknown 证据,不自动修复或重跑。 + +P5 的新 injector 默认 family 全关闭,完整策略由显式实时计划或已验证缓存提供。旧 policy、startup、模块模板和 autoDumpDex 数据仍保存;hello、重连、settings.enabled 不再按旧默认值布防或自动 dump。回滚恢复配置数据,不会自动恢复已退役的自动执行路径;如需回退软件版本,先完成受保护的配置回滚并保留备份,再另行部署旧版本。 + +手机固定 family 编辑器已移除。Manager 显示旧快照与 Host 指引、缓存 digest/state,并可 CAS 撤销未来缓存;旧 Binder 不支持时明确不可用。v20 包列表提交走 scope/state 双版本,不再用默认 family 值覆盖已迁移策略。完整 JSON 方案编辑与流程决定在 Host 面板、CLI、MCP 完成。 + +## 隔离验证 + +Host 测试入口 `node test/run.mjs` 为每个测试进程分配临时数据。新增测试覆盖方案 CAS/不可变版本/原语回执/旧能力拒绝/人类接管/撤销冲突、公共 MCP/REST/Python CLI、真实 Kotlin RPC 缓存/迁移账本,以及 Kotlin wire → 生产 C++ 解析/执行骨架(含 SHA oracle、篡改/UID/Agent/TTL 拒绝)。Manager/core/daemon 用离线 Gradle JVM 测试和 debug assemble 验证;Agent 和 Zygisk 用 NDK 构建,不 deploy。 + +浏览器 QA 用 `test/fixtures/p5_workbench.ts` 的随机 loopback 端口,禁止 fixture 内调用 ADB/子进程,复用正式页面和 handler。真机 PackageManager/SELinux/root socket、实际加载时序与 Hook 命中仍需后续独立冷启动验收;本次为保护现场没有执行这些步骤。编译通过与缓存字节验证不冒充真机早期命中证明。 +# 本次隔离验收记录 + +基座为 P4 `fa98813`,工作分支 `feat/adh-p5-hook-plans-20261116`。未部署产物。 + +| 验证 | 结果 | +| --- | --- | +| Host typecheck 与完整测试(含已发布 Python CLI 源码路径) | PASS,557/557,0 skip | +| 离线 Android JVM:core / daemon / Manager | PASS,22 / 18 / 29,0 skip | +| Device Daemon、Manager debug assemble | PASS,仅隔离构建 | +| NDK Agent、Zygisk | PASS;实际 release `.dynsym` 和设备验证器确认早期导出,内部辅助符号未导出 | +| MCP 注册表、生成文档、diff whitespace | PASS,94 tools | +| 随机端口正式面板浏览器验收 | PASS:保存不应用、并发冲突保留草稿、不重发、任务结果与副作用入口 | +| 现场保护 | 原仓、P2/P3/P4 worktree、adh-cli 无新增改动;8088 原 PID 与启动时间保持不变;临时面板已关闭 | + +补充边界:自动 `undo` 拒绝 partial/unknown 运行和持久 capture 集合,避免仅凭历史 Host 回执误停后来替换的集合。单 Hook 撤销仍要求当前进程、ID、模块/符号、策略核验;不支持的归属明确返回 `UNSUPPORTED_UNDO`。早期方案 digest 使用 Host 原规范文本及设备语义比对,避免 Kotlin/JavaScript 对 Unicode 和浮点 JSON 序列化差异造成误判。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index cbabfd6..6d85880 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -1,11 +1,13 @@ # ADH MCP Tools -Generated from the source registry (93 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). +Generated from the source registry (94 tools). Endpoint: `POST /mcp` (JSON-RPC 2.0). Writes require `_operation` state/control versions: [P1_OPERATIONS.md](P1_OPERATIONS.md). Human workbench, task CAS, intent lookup and effect metadata: [P2_WORKBENCH.md](P2_WORKBENCH.md). Read queries remain compatible; unversioned writes fail closed. Verified installation identities and USB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Paired LAN/TLS, permissions, revocation, the capability parity matrix and durable reconciliation: [P4_LAN_AUTH.md](P4_LAN_AUTH.md). Legacy target sessions remain unassociated; unmigrated device/LAN routes fail explicitly. +Host-owned Hook plans, early-cache limits and reversible legacy migration: [P5_HOOK_PLANS.md](P5_HOOK_PLANS.md). + | Tool | Description | Args | |---|---|---| | `analysis_guide` | START HERE when context or reversing experience is limited. action=guide (default) returns Host-only workflows without device operations: topic start/writer/crypto/trace/stuck, ordered templates, prerequisites, checks and failure branches. action=assess interprets CURRENT evidence for an explicit session: stage, facts, missingEvidence, doNotConclude, one proposed next call with purpose/effect/expected result, and a checkpoint for another agent. It reads retained Host records and may query native_hook status once with a 3-second budget; no hooks, trigger, replay, restart, capture drain or root upload is performed. No session returns target-selection advice, never an invented target. Optional hookId narrows to that hook; buffer/tid are caller-supplied writer candidates and never automatically trusted. Read-only assessment is not an algorithm proof or complete case history. Template $variables need actual correctly typed values. | action, topic, session, hookId, buffer, tid, _operation | @@ -101,3 +103,4 @@ Verified installation identities and USB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DO | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | | `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | | `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | +| `hook_plans` | Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device. | action, plan, digest, expectedLibraryRevision, session, runId, id, package, scope, settings, deviceId, connectionId, bootId, daemonInstanceId, expectedDeviceRevision, binding, expiresAt, offline, expectedCacheRevision, deploymentId, scopeRevision, migrationId, _operation | diff --git a/injector/zygisk/jni/main.cpp b/injector/zygisk/jni/main.cpp index f11c474..e03573a 100644 --- a/injector/zygisk/jni/main.cpp +++ b/injector/zygisk/jni/main.cpp @@ -17,6 +17,9 @@ #include #include #include +#include +#include +#include "../../../agent/src/bootstrap/early_wire.h" #include "zygisk.hpp" @@ -31,6 +34,18 @@ static constexpr const char *kScopePath = "/data/adb/adh/scope.json"; // == com.adh.core.AdhPaths.SCOPE_PATH static constexpr const char *kHostEndpointPath = "/data/adb/adh/host.endpoint"; // == com.adh.core.AdhPaths.HOST_ENDPOINT_PATH static constexpr const char *kLoaderMarker = "/data/adb/adh/zygisk_loaded"; // == com.adh.core.AdhPaths.LOADER_MARKER + +static bool read_exact_early(int fd,void* data,size_t n){auto* p=static_cast(data);while(n){ssize_t got=read(fd,p,n);if(got<=0)return false;p+=got;n-=size_t(got);}return true;} +static std::vector read_early_packet(int fd){unsigned char size[4];if(!read_exact_early(fd,size,4))return{};size_t n=(size_t(size[0])<<24)|(size_t(size[1])<<16)|(size_t(size[2])<<8)|size[3];if(!n||n>ADH_EARLY_MAX)return{};std::vector data(n);return read_exact_early(fd,data.data(),n)?data:std::vector{};} +static std::vector root_early_plan(const char* package,int uid){ + if(!package||uid<=0)return{};int fd=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(fd<0)return{}; + timeval timeout{0,250000};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout)); + sockaddr_un address{};address.sun_family=AF_UNIX;const char* name="adh_early_plans_v1";memcpy(address.sun_path+1,name,strlen(name)); + if(connect(fd,reinterpret_cast(&address),socklen_t(offsetof(sockaddr_un,sun_path)+1+strlen(name)))!=0){close(fd);return{};} + ucred peer{};socklen_t length=sizeof(peer);if(getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&peer,&length)!=0||peer.uid!=0){close(fd);return{};} + char request[512];int n=snprintf(request,sizeof(request),"%s %d\n",package,uid);if(n<=0||size_t(n)>=sizeof(request)||write(fd,request,size_t(n))!=n){close(fd);return{};} + auto data=read_early_packet(fd);close(fd);return data; +} static constexpr const char *kManagerPkg = "com.adh.manager"; // == com.adh.core.AdhPaths.MANAGER_PKG static constexpr const char *kAgentName = "libadh_agent.so"; // == com.adh.core.AdhPaths.AGENT_SO_NAME static constexpr const char *kQbdiName = "libQBDI.so"; // optional tracer, delivered on demand @@ -649,6 +664,7 @@ class AdhModule : public zygisk::ModuleBase { should_inject = false; agent_path.clear(); host_endpoint.clear(); + early_packet.clear(); if (!marker_requested) { marker_requested = true; int client = connect_companion(); @@ -717,26 +733,9 @@ class AdhModule : public zygisk::ModuleBase { // Which hook families this package is allowed to see installed. Asked here because the // companion socket does not survive specialization; the agent applies it when it starts. // Same two-key rule, narrow first: a policy written for one process beats the app's. - policy_flags.clear(); - for (int i = 0; i < n_keys && policy_flags.empty(); i++) { - int sock = connect_companion(); - if (sock >= 0) { - char req[320]; - int len = snprintf(req, sizeof(req), "policy %s\n", keys[i].c_str()); - char reply[80] = {0}; - if (len > 0 && send_all(sock, req, (size_t)len) && - read_reply_line(sock, reply, sizeof(reply))) { - if (reply[0] && strncmp(reply, "default", 7) != 0) policy_flags = reply; - } - close(sock); - } - if (policy_flags.empty()) { - // Same fallback order as the scope query: a direct read works when this instance - // happens to be root, and silence simply leaves the agent on its defaults. - char direct[64]; - if (policy_flags_for(keys[i].c_str(), direct, sizeof(direct))) policy_flags = direct; - } - } + // P5: legacy family fields remain reversible data, never install authority. The Host + // or an explicitly staged, validated cache provides the complete policy. + policy_flags="d=0,h=0,s=0,a=0,t=0,e=0,y=0"; if (!policy_flags.empty()) note("policy pkg=%s %s", package.c_str(), policy_flags.c_str()); // Asked here: the companion socket does not survive specialization, and the agent @@ -784,6 +783,7 @@ class AdhModule : public zygisk::ModuleBase { // (zygote) domain and the app-domain linker cannot even stat /proc/self/fd/N for it // ("unable to stat file for the library ... Permission denied", measured on the device). agent_fd = src_fd; + {int sock=connect_companion();if(sock>=0){timeval timeout{0,350000};setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));char req[512];int n=snprintf(req,sizeof(req),"early %s %d\n",pkg_name.c_str(),int(args->uid));if(n>0&&size_t(n)= 0) { + if(!early_packet.empty())actual_agent_sha=adh_sha_fd(memfd); handle = dlopen_agent_fd(memfd, "memfd:jit-cache"); close(memfd); if (handle) agent_path += " -> memfd:jit-cache (loaded)"; } if (!handle) { + if(!early_packet.empty())actual_agent_sha=adh_sha_fd(agent_fd); note("memfd load failed pkg=%s; loading from the module path instead", package_name.c_str()); handle = dlopen_agent_fd(agent_fd, agent_path + " (module path)"); } @@ -834,6 +837,14 @@ class AdhModule : public zygisk::ModuleBase { if (set_policy) set_policy(policy_flags.c_str()); else LOGE("adh_agent_set_policy not found; agent keeps every family on"); } + if(!early_packet.empty()&&!actual_agent_sha.empty()){ + using early_fn=int(*)(const void*,size_t,const char*,const char*); + auto apply_early=reinterpret_cast(dlsym(handle,"adh_agent_apply_early_v1")); + const auto target=package_of(package_name); + if(apply_early)apply_early(early_packet.data(),early_packet.size(),target.c_str(),actual_agent_sha.c_str()); + else LOGE("early-plan/1 unsupported by loaded agent; cache not applied"); + } + early_packet.clear(); if (!host_endpoint.empty()) { auto colon = host_endpoint.rfind(':'); using set_endpoint_fn = void (*)(const char *, int); @@ -884,6 +895,7 @@ class AdhModule : public zygisk::ModuleBase { std::string policy_flags; // "ipv4:port" remembered by the Manager. Empty → the agent dials loopback only. std::string host_endpoint; + std::vector early_packet; }; REGISTER_ZYGISK_MODULE(AdhModule) @@ -932,6 +944,11 @@ static void companion_serve(int client) { (void)send_all(client, reply, 2); continue; } + if(strncmp(req,"early ",6)==0){char pkg[256]{};int uid=0;char extra=0;std::vector data; + if(sscanf(req+6,"%255s %d %c",pkg,&uid,&extra)==2)data=root_early_plan(pkg,uid); + size_t n=data.size();unsigned char header[4]={static_cast(n>>24),static_cast(n>>16),static_cast(n>>8),static_cast(n)}; + if(send_all(client,reinterpret_cast(header),4)&&n)send_all(client,reinterpret_cast(data.data()),n);continue; + } if (strncmp(req, "policy ", 7) == 0) { // Per-package hook policy. "default" (not a flag line) means this package carries none, // so the instance hands over nothing and the agent keeps every family on. diff --git a/tools/generate_mcp_docs.mjs b/tools/generate_mcp_docs.mjs index 08859eb..dbef2bd 100644 --- a/tools/generate_mcp_docs.mjs +++ b/tools/generate_mcp_docs.mjs @@ -12,6 +12,8 @@ Writes require \`_operation\` state/control versions: [P1_OPERATIONS.md](P1_OPER Verified installation identities and USB RPC: [P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md). Paired LAN/TLS, permissions, revocation, the capability parity matrix and durable reconciliation: [P4_LAN_AUTH.md](P4_LAN_AUTH.md). Legacy target sessions remain unassociated; unmigrated device/LAN routes fail explicitly. +Host-owned Hook plans, early-cache limits and reversible legacy migration: [P5_HOOK_PLANS.md](P5_HOOK_PLANS.md). + | Tool | Description | Args | |---|---|---| `; From f7d726edeae8ce9ee4e4e8c789ba328bf55c9022 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:44:48 +0800 Subject: [PATCH 18/24] =?UTF-8?q?fix:=20=E5=AE=8C=E6=88=90P5=E7=9C=9F?= =?UTF-8?q?=E6=9C=BA=E9=9A=94=E7=A6=BB=E9=AA=8C=E6=94=B6=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E6=97=A9=E6=9C=9FHook=E4=B8=8E=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E9=80=9A=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + agent/CMakeLists.txt | 7 ++ agent/src/MAP.md | 2 + agent/src/bootstrap/agent_internal.h | 2 + agent/src/bootstrap/early_plan.cpp | 6 +- daemon/src/MAP.md | 2 + daemon/src/device_host.ts | 2 +- daemon/src/device_protocol.ts | 3 +- daemon/src/devices.ts | 6 +- daemon/src/mcp.ts | 2 +- daemon/src/transport/adb_device.ts | 29 +++++-- daemon/src/transport/device_transport.ts | 1 + daemon/test/device_stdio.test.ts | 21 +++++ device/MAP.md | 2 + .../src/main/java/com/adh/core/DeviceRpc.kt | 9 +++ .../test/java/com/adh/core/LanProofTest.kt | 9 +++ device/daemon/build.gradle.kts | 1 + .../java/com/adh/daemon/AndroidHookBinding.kt | 4 +- .../com/adh/daemon/device/DeviceIdentity.kt | 2 + .../com/adh/daemon/device/DeviceRpcRelay.kt | 23 ++++++ .../com/adh/daemon/device/DeviceRpcSession.kt | 2 +- .../com/adh/daemon/device/EarlyPlanBroker.kt | 4 +- .../adh/daemon/device/LocalDeviceRpcServer.kt | 8 +- .../java/com/adh/daemon/P5DeviceFixture.kt | 53 +++++++++++++ device/p5sandbox/.gitignore | 1 + device/p5sandbox/build.gradle.kts | 14 ++++ device/p5sandbox/src/main/AndroidManifest.xml | 7 ++ device/p5sandbox/src/main/cpp/CMakeLists.txt | 7 ++ device/p5sandbox/src/main/cpp/fixture.cpp | 19 +++++ device/p5sandbox/src/main/cpp/target.c | 2 + .../java/com/adh/p5sandbox/ProbeService.java | 20 +++++ device/settings.gradle.kts | 2 + docs/P5_ANDROID_ACCEPTANCE.md | 54 +++++++++++++ docs/P5_HOOK_PLANS.md | 2 + docs/PROGRESS.md | 8 ++ docs/mcp-tools.md | 2 +- tools/MAP.md | 6 ++ tools/build_agent.sh | 23 ++++-- tools/p5_isolated_host.ts | 22 ++++++ tools/verify_all.sh | 1 + tools/verify_p5_device.ts | 79 +++++++++++++++++++ tools/verify_v132_p5_stdio.sh | 10 +++ 42 files changed, 451 insertions(+), 30 deletions(-) create mode 100644 daemon/test/device_stdio.test.ts create mode 100644 device/core/src/test/java/com/adh/core/LanProofTest.kt create mode 100644 device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt create mode 100644 device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt create mode 100644 device/p5sandbox/.gitignore create mode 100644 device/p5sandbox/build.gradle.kts create mode 100644 device/p5sandbox/src/main/AndroidManifest.xml create mode 100644 device/p5sandbox/src/main/cpp/CMakeLists.txt create mode 100644 device/p5sandbox/src/main/cpp/fixture.cpp create mode 100644 device/p5sandbox/src/main/cpp/target.c create mode 100644 device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java create mode 100644 docs/P5_ANDROID_ACCEPTANCE.md create mode 100644 tools/p5_isolated_host.ts create mode 100644 tools/verify_p5_device.ts create mode 100644 tools/verify_v132_p5_stdio.sh diff --git a/README.md b/README.md index 047a1de..5b0f52f 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Android DecryptHub(ADH)是一套 Android 运行时分析工具。它把一 P5 分支将 Hook 方案和编辑器迁到 Host。MCP `hook_plans`、Python CLI `adh call/run hook_plans` 和任务工作台共用执行层。保存、暂存和实际安装分别报告,连接不自动套用旧捕获/启动默认值。迁移与兼容边界见 [P5_HOOK_PLANS.md](docs/P5_HOOK_PLANS.md)。此分支尚未部署到现有分析现场。 +P5 后续已完成真实 Android 独立沙盒的早期 GOT、过期、APK 绑定失效、LAN 授权撤销、缓存撤销和精确回滚验收,并修复早期参数与 Android 认证编码问题。详见 [实测与未验证清单](docs/P5_ANDROID_ACCEPTANCE.md);正式 Zygisk 全链仍未部署验证。 + ## 能做什么 **只影响勾选的应用。** 在手机上的 ADH Manager 里勾选注入范围并保存,然后重新打开该应用。主进程和 `:core` 这类子进程都会注入。没勾选的应用不会注入。 diff --git a/agent/CMakeLists.txt b/agent/CMakeLists.txt index 4bf0a86..9fe7e11 100644 --- a/agent/CMakeLists.txt +++ b/agent/CMakeLists.txt @@ -1,6 +1,13 @@ cmake_minimum_required(VERSION 3.22) project(adh_agent C CXX ASM) +# Explicit sandbox builds may select an owned port, never dial the active analysis Host. +set(ADH_AGENT_CONNECT_PORT "8761" CACHE STRING "Agent loopback RPC port") +if(NOT ADH_AGENT_CONNECT_PORT MATCHES "^[0-9]+$" OR ADH_AGENT_CONNECT_PORT LESS 1 OR ADH_AGENT_CONNECT_PORT GREATER 65535) + message(FATAL_ERROR "ADH_AGENT_CONNECT_PORT must be 1..65535") +endif() +add_compile_definitions(ADH_PORT=${ADH_AGENT_CONNECT_PORT}) + set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/agent/src/MAP.md b/agent/src/MAP.md index 29e5018..b89daa8 100644 --- a/agent/src/MAP.md +++ b/agent/src/MAP.md @@ -67,4 +67,6 @@ the build you think you flashed. Both the module zip and the agent must be rebui - `compat_probe` reports bootstrap vs current exec/anon-exec/RWX counters; base injection and GOT hooks must not add true anonymous executable pages. # P5 early-plan/1 addition +Real Android acceptance caught and fixed an invalid errno default in the early GOT consumer; failures now include a bounded reason. The explicit CMake `ADH_AGENT_CONNECT_PORT` defaults to 8761; port 18761 is used only in sandbox builds, and custom-port `--deploy` is refused. Before-agent-connect GOT hits are verified on Android, full Zygisk delivery is still unverified. See [P5_ANDROID_ACCEPTANCE.md](../../docs/P5_ANDROID_ACCEPTANCE.md). + `bootstrap/early_wire.h` is the shared bounded native validator and SHA implementation; `bootstrap/early_plan.cpp` consumes only verified named capture/GOT observation steps before `adh_agent_start`, stops on an unconfirmed installation and adds agent-reported receipts to hello. `capture_policy` explicitly sets/reads family eligibility. No .init_array timing guarantee. Full contract: [P5_HOOK_PLANS.md](../../docs/P5_HOOK_PLANS.md). diff --git a/agent/src/bootstrap/agent_internal.h b/agent/src/bootstrap/agent_internal.h index 3c19b58..0be0e6d 100644 --- a/agent/src/bootstrap/agent_internal.h +++ b/agent/src/bootstrap/agent_internal.h @@ -21,7 +21,9 @@ // way, so surfacing it adds no new string to the release image (v88 unaffected). #define AGENT_VER "0.8.0" #define ADH_HOST "127.0.0.1" +#ifndef ADH_PORT #define ADH_PORT 8761 +#endif // Loopback is always tried first (adb reverse). adh_agent_set_endpoint may name one extra // IPv4 the root companion already learned; connect_adhd uses it only after loopback fails. #define TAG "rt.agent" diff --git a/agent/src/bootstrap/early_plan.cpp b/agent/src/bootstrap/early_plan.cpp index 860c8ab..c216dde 100644 --- a/agent/src/bootstrap/early_plan.cpp +++ b/agent/src/bootstrap/early_plan.cpp @@ -7,10 +7,12 @@ #include extern "C" void adh_agent_set_policy(const char*); extern "C" int adh_agent_copy_owner(void); +extern "C" void json_escape(const char*,char*,size_t); static char status[2048]="null"; +static char last_error[256]=""; static bool attempted=false; static int apply(const AdhEarlyStep& step,int* hookId,void*){ - if(step.type==2){char error[512]{};int ok=adh_native_hook_install("got",step.a,step.b,"",0,0,0,-1,0,0,"",0,0,0,step.c,-1,0,"",-1,"","",0,"","",0,1,0,"",hookId,error,sizeof(error));return ok&&*hookId>0?1:0;} + if(step.type==2){char error[512]{};int ok=adh_native_hook_install("got",step.a,step.b,"",0,0,0,-1,0,0,"",0,0,0,step.c,-1,0,"",0,"","",0,"","",0,1,0,"",hookId,error,sizeof(error));if(!ok)snprintf(last_error,sizeof(last_error),"%.240s",error);return ok&&*hookId>0?1:0;} int fd=int(syscall(SYS_memfd_create,"adh-early-result",1));if(fd<0)return -1; adh_cmd_capture_start(fd,"early-cache",step.a,step.b,step.c); auto size=lseek(fd,0,SEEK_END);if(size<5||size>8192||lseek(fd,0,SEEK_SET)<0){close(fd);return -1;}char data[8193]{};auto n=read(fd,data,size_t(size));close(fd);if(n!=size)return -1; @@ -26,6 +28,6 @@ extern "C" __attribute__((visibility("default"))) int adh_agent_apply_early_v1(c if(!adh_early_parse(wire,size,package,uint32_t(getuid()),actualAgentSha,uint64_t(time(nullptr)),plan)){snprintf(status,sizeof(status),"{\"state\":\"rejected\",\"phase\":\"post-specialize-before-agent-start\"}");return 0;} char flags[64];snprintf(flags,sizeof(flags),"d=%d,h=%d,s=%d,a=%d,t=%d,e=%d,y=%d",!!(plan.families&1),!!(plan.families&2),!!(plan.families&4),!!(plan.families&8),!!(plan.families&16),!!(plan.families&32),!!(plan.families&64));adh_agent_set_policy(flags); auto result=adh_early_run(plan,apply,nullptr);std::string steps;for(unsigned n=0;ntypeof value==='string'&&/^[a export class DeviceError extends OperationError {} export function deviceFail(code:string,message:string,uncertain=false):never{throw new DeviceError(code,message,uncertain);} export function deviceMethodMode(method:string){if(DEVICE_READ_METHODS.has(method))return 'read';if(DEVICE_WRITE_METHODS.has(method))return 'write';return deviceFail('UNSUPPORTED_METHOD','device method is not supported; no shell/ADB fallback was attempted');} -export interface Bootstrap {schemaVersion:1;deviceId:string;identityFingerprint:string;token:string} +export const DEVICE_STDIO_COMMAND='CLASSPATH=/data/adb/modules/adh/daemon.apk app_process /system/bin com.adh.daemon.device.DeviceRpcRelay'; +export interface Bootstrap {schemaVersion:1;deviceId:string;identityFingerprint:string;token:string;stdioVersion?:number} export interface DevicePeer {deviceId:string;bootId:string;daemonInstanceId:string;identityFingerprint:string;info:any;capabilities:{methods:Record;[key:string]:any};protocol:string} export function parseBootstrap(raw:string):Bootstrap { let value:any;try{if(Buffer.byteLength(raw)>8192)throw Error();value=JSON.parse(raw);}catch{deviceFail('INVALID_BOOTSTRAP','USB bootstrap could not be parsed; credential content is never logged');} diff --git a/daemon/src/devices.ts b/daemon/src/devices.ts index b2e3be6..b79006d 100644 --- a/daemon/src/devices.ts +++ b/daemon/src/devices.ts @@ -27,13 +27,13 @@ export class Devices { list(){return {devices:Object.values(this.records).map(record=>({deviceId:record.deviceId,identityFingerprint:record.identityFingerprint,lastSeen:record.lastSeen,lastKnown:record.lastPeer,pairing:record.pairing?{...record.pairing,authorization:'cached enrollment; device rechecks every LAN request'}:undefined,lanEndpoint:record.lanEndpoint, online:[...this.connections.values()].some(c=>c.peer.deviceId===record.deviceId&&!c.rpc.stream.destroyed),connections:[...this.connections.values()].filter(c=>c.peer.deviceId===record.deviceId).map(c=>this.connectionView(c))})), legacyAgentAssociation:'unverified; no session is assigned by ADB serial',discoveryIsExplicit:true};} - private connectionView(c:DeviceConnection){return {connectionId:c.id,transport:c.transport,serial:c.serial,transportId:c.transportId,address:c.address,port:c.transport==='lan'?c.port:undefined,grantId:c.grantId,tlsVersion:c.tlsVersion,deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId,identityVerified:true,online:!c.rpc.stream.destroyed};} + private connectionView(c:DeviceConnection){return {connectionId:c.id,transport:c.transport,usbMode:c.transport==='adb'?(c.usbMode||'forward'):undefined,serial:c.serial,transportId:c.transportId,address:c.address,port:c.transport==='lan'?c.port:undefined,grantId:c.grantId,tlsVersion:c.tlsVersion,deviceId:c.peer.deviceId,bootId:c.peer.bootId,daemonInstanceId:c.peer.daemonInstanceId,identityVerified:true,online:!c.rpc.stream.destroyed};} async discover(transport='adb'){ if(transport==='lan')return {transports:Object.values(this.records).filter(r=>r.lanEndpoint).map(r=>({transport:'lan',deviceId:r.deviceId,...r.lanEndpoint,state:'last-known; not probed'})),...this.list()}; if(transport!=='adb')deviceFail('UNSUPPORTED_TRANSPORT','only adb and paired LAN are implemented');return {transports:await this.adapter.discover(),...this.list()}; } - async connect(serial:string,transportId?:string,expectedDeviceId?:string){ - const connection=await this.adapter.connect(serial,transportId); + async connect(serial:string,transportId?:string,expectedDeviceId?:string,usbMode:'forward'|'stdio'='forward'){ + const connection=await this.adapter.connect(serial,transportId,undefined,usbMode); return this.register(connection,expectedDeviceId); } async connectLan(deviceId:string,address?:string,port?:number){ diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index 68ea0cc..dc0e935 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -406,7 +406,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h ]; // Optional at schema level because reads need no control token; writes enforce it at dispatch. -MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); +MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects a raw root relay on enforcing ROMs, never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,usbMode:{type:'string',enum:['forward','stdio']},expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); MCP_TOOLS.push({name:'hook_plans',description:'Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','get','validate','put','import-legacy','preflight','apply','run','observe','undo','early-prepare','early-status','early-stage','early-revoke','migration-preview','migration-apply','migration-rollback']},plan:{type:'object'},digest:S,expectedLibraryRevision:{type:'integer'},session:S,runId:S,id:S,package:S,scope:{type:'object'},settings:{type:'object'},deviceId:S,connectionId:S,bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},binding:{type:'object'},expiresAt:{type:'integer'},offline:{type:'string',enum:['keep-until-expiry']},expectedCacheRevision:{type:'integer'},deploymentId:S,scopeRevision:S,migrationId:S}},handler:a=>hookPlanAction(a,name=>MCP_MAP.get(name))}); for (const tool of MCP_TOOLS) { diff --git a/daemon/src/transport/adb_device.ts b/daemon/src/transport/adb_device.ts index d1587ec..5876730 100644 --- a/daemon/src/transport/adb_device.ts +++ b/daemon/src/transport/adb_device.ts @@ -1,13 +1,20 @@ -import { execFile } from 'node:child_process'; +import { execFile,spawn } from 'node:child_process'; +import { Duplex } from 'node:stream'; import { promisify } from 'node:util'; import net from 'node:net'; import { randomBytes,randomUUID } from 'node:crypto'; -import { DEVICE_BOOTSTRAP,DEVICE_SOCKET,DeviceRpcClient,parseBootstrap,verifyHello,deviceFail,DeviceError,type DevicePeer } from '../device_protocol.ts'; +import { DEVICE_BOOTSTRAP,DEVICE_SOCKET,DEVICE_STDIO_COMMAND,DeviceRpcClient,parseBootstrap,verifyHello,deviceFail,DeviceError,type DevicePeer } from '../device_protocol.ts'; import { checkpoint,executionContext } from '../execution_context.ts'; import type {DeviceConnection} from './device_transport.ts'; export interface AdbDevice {serial:string;state:string;transportId?:string;model?:string;link:'usb'|'adb-tcp'|'unknown'} export type AdbRunner=(args:string[],options?:{timeout?:number;maxBuffer?:number})=>Promise; +export type AdbStdio=(args:string[])=>Duplex; +export const realAdbStdio:AdbStdio=args=>{ + if(process.env.ADH_SKIP_ARTIFACT_LOAD==='1')deviceFail('TEST_ADAPTER_REQUIRED','tests must inject a stdio adapter'); + const child=spawn(process.env.ADH_ADB_PATH||'adb',args,{windowsHide:true,stdio:['pipe','pipe','pipe']}); + const stream=Duplex.from({readable:child.stdout,writable:child.stdin});child.stderr.resume();child.on('error',()=>stream.destroy(new DeviceError('ADB_FAILED','USB stdio relay failed')));child.on('close',()=>stream.destroy());stream.on('close',()=>{if(child.exitCode===null)child.kill();});return stream; +}; const exec=promisify(execFile); export const realAdbRunner:AdbRunner=async(args,options={})=>{ if(process.env.ADH_SKIP_ARTIFACT_LOAD==='1')deviceFail('TEST_ADAPTER_REQUIRED','tests must inject an ADB adapter; real devices are forbidden'); @@ -24,17 +31,27 @@ export function parseAdbDevices(raw:string):AdbDevice[]{ } export interface AdbConnection extends DeviceConnection {transport:'adb';serial:string} export class AdbDeviceTransport { - readonly run:AdbRunner;private dial:(port:number)=>Promise; + readonly run:AdbRunner;private dial:(port:number)=>Promise;private stdio:AdbStdio; constructor(run:AdbRunner=realAdbRunner,dial:(port:number)=>Promise=port=>new Promise((resolve,reject)=>{ const socket=net.connect({host:'127.0.0.1',port});const timer=setTimeout(()=>socket.destroy(new Error('connect timeout')),5000);socket.once('connect',()=>{clearTimeout(timer);resolve(socket);});socket.once('error',error=>{clearTimeout(timer);reject(error);}); - })){this.run=run;this.dial=dial;} + }),stdio:AdbStdio=realAdbStdio){this.run=run;this.dial=dial;this.stdio=stdio;} async discover(){checkpoint();return parseAdbDevices(await this.run(['devices','-l']));} - async connect(serial:string,transportId?:string,onClose:()=>void=()=>{}):Promise{ + async connect(serial:string,transportId?:string,onClose:()=>void=()=>{},usbMode:'forward'|'stdio'='forward'):Promise{ + if(!['forward','stdio'].includes(usbMode))deviceFail('UNSUPPORTED_TRANSPORT','choose an explicit USB mode'); const devices=await this.discover(),matches=devices.filter(d=>d.serial===serial&&(!transportId||d.transportId===transportId)); if(matches.length!==1)deviceFail('DEVICE_AMBIGUOUS','select one exact serial/transportId from discovery');const selected=matches[0]; if(selected.state!=='device')deviceFail('DEVICE_NOT_READY','ADB transport is '+selected.state+'; no device RPC was attempted'); const prefix=selected.transportId?['-t',selected.transportId]:['-s',selected.serial]; checkpoint();const bootstrap=parseBootstrap(await this.run([...prefix,'exec-out','su','-c',`cat ${DEVICE_BOOTSTRAP}`],{maxBuffer:8192})); + if(usbMode==='stdio'){ + if(bootstrap.stdioVersion!==1)deviceFail('UNSUPPORTED_TRANSPORT','device does not advertise USB stdio/1; no fallback attempted'); + // KernelSU's fd wrapper can transform binary control bytes. Negotiate before any RPC. + const help=await this.run([...prefix,'exec-out','su','--help']);const suFlags=help.includes('--no-wrapper')?['-W']:[]; + const ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'adb',action:'device.stdio.connect'});let rpc:DeviceRpcClient|undefined; + try{rpc=new DeviceRpcClient(this.stdio([...prefix,'shell','-T','su',...suFlags,'-c',"'"+DEVICE_STDIO_COMMAND+"'"]),onClose);const id=randomUUID(),nonce=randomBytes(32).toString('hex');const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:bootstrap.token}},undefined,undefined,5000,id);const peer=verifyHello(reply,bootstrap,id,nonce);ctx?.acknowledged(false,effect); + return {id:randomUUID(),transport:'adb',usbMode,serial:selected.serial,transportId:selected.transportId,port:0,peer,rpc,close:async()=>{rpc!.close();return {removed:true,confirmed:true,reason:'owned stdio stream closed; no forward created'};}}; + }catch(error){rpc?.close();ctx?.acknowledged(false,effect,true);throw error;} + } const ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'adb',action:'device.forward.create'}); let port:number; try{const raw=await this.run([...prefix,'forward','--no-rebind','tcp:0','localabstract:'+DEVICE_SOCKET]);port=Number(raw.trim());if(!Number.isInteger(port)||port<1||port>65535)deviceFail('FORWARD_UNCONFIRMED','ADB did not confirm an owned forward',true);ctx?.acknowledged(false,effect);} @@ -55,7 +72,7 @@ export class AdbDeviceTransport { const id=randomUUID(),nonce=randomBytes(32).toString('hex'); const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:bootstrap.token}},undefined,undefined,5000,id); const peer=verifyHello(reply,bootstrap,id,nonce); - return {id:randomUUID(),transport:'adb',serial:selected.serial,transportId:selected.transportId,port,peer,rpc,close:async()=>{rpc!.close();return remove();}}; + return {id:randomUUID(),transport:'adb',usbMode,serial:selected.serial,transportId:selected.transportId,port,peer,rpc,close:async()=>{rpc!.close();return remove();}}; }catch(error){rpc?.close();try{if(!(await remove()).confirmed)throw Error();}catch{throw new DeviceError('FORWARD_CLEANUP_UNCONFIRMED','handshake failed and the owned forward cleanup was not confirmed',true);}throw error;} } } diff --git a/daemon/src/transport/device_transport.ts b/daemon/src/transport/device_transport.ts index 315696c..a6f5771 100644 --- a/daemon/src/transport/device_transport.ts +++ b/daemon/src/transport/device_transport.ts @@ -4,5 +4,6 @@ export interface DeviceConnection { id:string;transport:'adb'|'lan';serial?:string;transportId?:string;address?:string;port:number; peer:DevicePeer;rpc:DeviceRpcClient;clientId?:string;grantId?:string; tlsVersion?:string; + usbMode?:'forward'|'stdio'; close():Promise<{removed:boolean;confirmed:boolean;reason?:string}>; } diff --git a/daemon/test/device_stdio.test.ts b/daemon/test/device_stdio.test.ts new file mode 100644 index 0000000..1215074 --- /dev/null +++ b/daemon/test/device_stdio.test.ts @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import net from 'node:net'; +import {existsSync,readFileSync,writeFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; +import {startDeviceFixture,FakeAdb,jvmManifest} from './device_fixture.ts'; + +test('USB stdio authenticates the production Kotlin dispatcher and carries large binary-framed replies without forwards',{skip:existsSync(jvmManifest)?false:'build offline JVM fixture; no real device fallback'},async()=>{ + const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('stdio-fixture','77',phone);const opens:string[][]=[];let connection:any; + const runner=async(args:string[])=>args.slice(2).join(' ')==='exec-out su --help'?'KernelSU --no-wrapper':adb.run(args); + const adapter=new AdbDeviceTransport(runner,async()=>{throw Error('stdio must never dial a forward');},args=>{opens.push(args);return net.connect({host:'127.0.0.1',port:phone.port});}); + try{ + connection=await adapter.connect('stdio-fixture','77',undefined,'stdio');assert.equal(connection.usbMode,'stdio');assert.equal(connection.peer.deviceId,phone.deviceId);assert.ok(opens[0].includes('-W'));assert.ok(opens[0].includes('-T'));assert.ok(opens[0].at(-1)!.includes('com.adh.daemon.device.DeviceRpcRelay')); + writeFileSync(join(phone.root,'scope.json'),JSON.stringify({version:19,mode:'allowlist',packages:[],future:'\r\n\u0003'.repeat(12000)})); + const peer=connection.peer;const reply=await connection.rpc.request('scope.get',{},{deviceId:peer.deviceId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId});assert.equal(reply.future,undefined);assert.equal(reply.document.future.length,36000);assert.equal(adb.forwards.size,0);assert.ok(!adb.commands.some(c=>c.includes('forward'))); + assert.equal((await connection.close()).confirmed,true);connection=undefined; + const file=join(phone.root,'usb-access.json'),legacy=JSON.parse(readFileSync(file,'utf8'));delete legacy.stdioVersion;writeFileSync(file,JSON.stringify(legacy)); + await assert.rejects(()=>adapter.connect('stdio-fixture','77',undefined,'stdio'),(e:any)=>e.code==='UNSUPPORTED_TRANSPORT');assert.equal(opens.length,1,'legacy devices never silently fall back or start a relay'); + }finally{if(connection)await connection.close();await adb.close();await phone.close();} +}); diff --git a/device/MAP.md b/device/MAP.md index 1580485..97b4308 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -8,6 +8,8 @@ Magisk 打包仍在 `injector/zygisk/`。 ## P5 additions (2026-11-16) +Real Android follow-up: `core/DeviceRpc.lanProof` fixes Android/JVM authentication-byte differences. `daemon/device/DeviceRpcRelay` is a root-only raw USB relay with unchanged dispatcher; isolated socket parameters default to production names. `daemon/src/p5Fixture` and the separate `:p5sandbox` module require `adhP5Sandbox=true` and are absent from the normal bundle graph. See [P5_ANDROID_ACCEPTANCE.md](../docs/P5_ANDROID_ACCEPTANCE.md). + `core/EarlyPlanWire.kt` encodes the bounded early-plan/1 wire. `daemon/device/HookPlanCache.kt` owns validated, expiring app/Agent-bound cache and exact legacy backups through DeviceOperations. `AndroidHookBinding.kt` validates installed identity/ABI; `EarlyPlanBroker.kt` serves root companions only. Manager Binder v20 adds package-only CAS and Hook cache read/revoke; the fixed family editor is now a read-only legacy snapshot. Authoritative programmable editing stays on Host. No automatic app restart. See [P5_HOOK_PLANS.md](../docs/P5_HOOK_PLANS.md). ## Modules reference diff --git a/device/core/src/main/java/com/adh/core/DeviceRpc.kt b/device/core/src/main/java/com/adh/core/DeviceRpc.kt index 3abcfec..09e680b 100644 --- a/device/core/src/main/java/com/adh/core/DeviceRpc.kt +++ b/device/core/src/main/java/com/adh/core/DeviceRpc.kt @@ -33,6 +33,15 @@ object DeviceRpc { DataOutputStream(output).apply { writeInt(payload.size); write(payload); flush() } } fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + // Android's org.json escapes '/', desktop org.json and JSON.stringify do not. + // Keep the authentication transcript byte-identical without changing persisted op hashes. + fun lanProof(values:List):ByteArray = values.joinToString(",","[","]"){wireQuote(it)}.toByteArray(Charsets.UTF_8) + private fun wireQuote(value:String):String = buildString { + append('"');for((i,c) in value.withIndex())when(c){ + '"'->append("\\\"");'\\'->append("\\\\");'\b'->append("\\b");'\u000c'->append("\\f");'\n'->append("\\n");'\r'->append("\\r");'\t'->append("\\t") + else->{val loneHigh=c.isHighSurrogate()&&(i+1==value.length||!value[i+1].isLowSurrogate());val loneLow=c.isLowSurrogate()&&(i==0||!value[i-1].isHighSurrogate());if(c.code<32||loneHigh||loneLow)append("\\u"+c.code.toString(16).padStart(4,'0'))else append(c)} + };append('"') + } fun canonical(value: Any?): String = when (value) { null, JSONObject.NULL -> "null" is JSONObject -> value.keys().asSequence().toList().sorted().joinToString(",", "{", "}") { JSONObject.quote(it) + ":" + canonical(value.get(it)) } diff --git a/device/core/src/test/java/com/adh/core/LanProofTest.kt b/device/core/src/test/java/com/adh/core/LanProofTest.kt new file mode 100644 index 0000000..b6df69e --- /dev/null +++ b/device/core/src/test/java/com/adh/core/LanProofTest.kt @@ -0,0 +1,9 @@ +package com.adh.core +import org.junit.Assert.assertEquals +import org.junit.Test +class LanProofTest { + @Test fun matchesJsonStringifyBytesIncludingAndroidSlashAndSurrogates(){ + val proof=String(DeviceRpc.lanProof(listOf("adh.device/1","lan-auth/1","x\\y\"z\n\t\u0001","中文😀",String(charArrayOf('\ud800')))),Charsets.UTF_8) + assertEquals("[\"adh.device/1\",\"lan-auth/1\",\"x\\\\y\\\"z\\n\\t\\u0001\",\"中文😀\",\"\\ud800\"]",proof) + } +} diff --git a/device/daemon/build.gradle.kts b/device/daemon/build.gradle.kts index 6acc026..c3b3333 100644 --- a/device/daemon/build.gradle.kts +++ b/device/daemon/build.gradle.kts @@ -23,6 +23,7 @@ android { buildFeatures { buildConfig = true } + if(providers.gradleProperty("adhP5Sandbox").orNull=="true") sourceSets["debug"].java.srcDir("src/p5Fixture/java") compileOptions { sourceCompatibility = JavaVersion.VERSION_17 diff --git a/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt b/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt index 5f24965..d94dcdb 100644 --- a/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt +++ b/device/daemon/src/main/java/com/adh/daemon/AndroidHookBinding.kt @@ -15,7 +15,7 @@ import java.io.File import java.security.MessageDigest /** Validation metadata only, never target code analysis or loading the agent in the daemon. */ -internal class AndroidHookBinding(private val context:Context):HookBindingProbe{ +internal class AndroidHookBinding(private val context:Context,private val agentFile:File=File(AdhPaths.MODULE_DIR,AdhPaths.AGENT_SO_NAME)):HookBindingProbe{ private var previousKey="";private var previousAgent:JSONObject?=null @Synchronized override fun inspect(packageName:String):JSONObject{ val pm=context.packageManager @@ -26,7 +26,7 @@ internal class AndroidHookBinding(private val context:Context):HookBindingProbe{ val signerHashes=signatures?.map{DeviceRpc.sha256(it.toByteArray())}?.sorted()?:emptyList();if(signerHashes.isEmpty())throw DeviceFault("IDENTITY_UNVERIFIED","APK signer evidence unavailable") val apkFiles=listOf(app.sourceDir)+app.splitSourceDirs.orEmpty().toList() val apks=apkFiles.sorted().map{path->val st=Os.stat(path);JSONObject().put("path",path).put("size",st.st_size).put("inode",st.st_ino).put("mtime",st.st_mtime)} - val file=File(AdhPaths.MODULE_DIR,AdhPaths.AGENT_SO_NAME);if(!file.isFile||file.length()>128*1024*1024)throw DeviceFault("AGENT_UNAVAILABLE","module agent is absent or exceeds validation limit") + val file=agentFile;if(!file.isFile||file.length()>128*1024*1024)throw DeviceFault("AGENT_UNAVAILABLE","module agent is absent or exceeds validation limit") val st=Os.stat(file.path);val key="${st.st_dev}:${st.st_ino}:${st.st_size}:${st.st_mtime}" if(key!=previousKey){val hash=MessageDigest.getInstance("SHA-256");file.inputStream().use{input->val bytes=ByteArray(65536);while(true){val n=input.read(bytes);if(n<0)break;hash.update(bytes,0,n)}} previousAgent=JSONObject().put("agentSha256",hash.digest().joinToString(""){"%02x".format(it)}).put("earlySupported",AgentEarlyAbi.exported(file));previousKey=key} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt index 6b35e20..147ec6c 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt @@ -48,6 +48,8 @@ internal class DeviceIdentity(private val files: DeviceFiles, val bootId: String val access = JSONObject(accessFile.readText()) check(access.getInt("schemaVersion") == 1 && access.getString("deviceId") == deviceId && access.getString("identityFingerprint") == fingerprint) { "USB bootstrap identity mismatch" } token = access.getString("token"); check(Regex("[a-f0-9]{64}").matches(token)) + // Preserve identity and credential when adding transport capability metadata. + if(access.optInt("stdioVersion")!=1)files.write(accessFile,access.put("stdioVersion",1).toString()) } fun authenticated(candidate: String): Boolean = java.security.MessageDigest.isEqual(token.toByteArray(), candidate.toByteArray()) fun sign(bytes: ByteArray): ByteArray = Signature.getInstance("SHA256withRSA").run { initSign(privateKey); update(bytes); sign() } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt new file mode 100644 index 0000000..09141be --- /dev/null +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt @@ -0,0 +1,23 @@ +package com.adh.daemon.device +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Process +import com.adh.core.DeviceRpc +import java.io.FileDescriptor +import java.io.FileInputStream +import java.io.FileOutputStream + +/** Root-only byte relay for USB on enforcing ROMs. No interpreter, listener or replay. */ +object DeviceRpcRelay { + @JvmStatic fun main(args:Array){ + check(Process.myUid()==0) + val name=if(args.isEmpty())DeviceRpc.SOCKET_NAME else args.single().also{require(it.matches(Regex("adh_p5_[a-f0-9]{12}")))} + LocalSocket().use { socket-> + socket.connect(LocalSocketAddress(name,LocalSocketAddress.Namespace.ABSTRACT));socket.soTimeout=60000;check(socket.peerCredentials.uid==0) + // app_process redirects System.out to logcat; RPC must use the raw descriptors. + val output=FileOutputStream(FileDescriptor.out) + Thread({try{FileInputStream(FileDescriptor.`in`).copyTo(socket.outputStream);socket.shutdownOutput()}catch(_:Exception){runCatching{socket.close()}}},"adh-usb-stdin").apply{isDaemon=true;start()} + try{socket.inputStream.copyTo(output);output.flush()}catch(_:Exception){/* close, never retry */} + } + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt index 43440b0..60e073e 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcSession.kt @@ -28,7 +28,7 @@ internal class DeviceRpcSession(private val operations: DeviceOperations) { else { require(auth.optString("type") == "client-signature") val identity = operations.identity - val proof = org.json.JSONArray(listOf(DeviceRpc.PROTOCOL, "lan-auth/1", identity.deviceId, identity.bootId, identity.instanceId, challenge, nonce, helloId, auth.getString("clientId"), auth.getString("grantId"))).toString().toByteArray(Charsets.UTF_8) + val proof = DeviceRpc.lanProof(listOf(DeviceRpc.PROTOCOL, "lan-auth/1", identity.deviceId, identity.bootId, identity.instanceId, challenge, nonce, helloId, auth.getString("clientId"), auth.getString("grantId"))) grantId = pairings.authenticate(auth, proof); authenticated(checkNotNull(grantId)) } true diff --git a/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt b/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt index 3bf18a8..15a6ad3 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/EarlyPlanBroker.kt @@ -7,8 +7,8 @@ import java.util.concurrent.TimeUnit import java.io.DataOutputStream /** Root companion only. A timeout/missing broker denies cache delivery, never arms defaults. */ -internal class EarlyPlanBroker(private val cache:HookPlanCache):AutoCloseable{ - private val server=LocalServerSocket("adh_early_plans_v1") +internal class EarlyPlanBroker(private val cache:HookPlanCache,socketName:String="adh_early_plans_v1"):AutoCloseable{ + private val server=LocalServerSocket(socketName) private val workers=ThreadPoolExecutor(2,2,30,TimeUnit.SECONDS,ArrayBlockingQueue(2)) private val thread=Thread({while(!server.isClosedCompat()){ val socket=try{server.accept()}catch(_:Exception){break} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt b/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt index 1204775..fa04330 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/LocalDeviceRpcServer.kt @@ -8,8 +8,8 @@ import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit /** USB ADB forwards to this abstract UDS. No TCP/LAN listener is opened on the phone. */ -internal class LocalDeviceRpcServer(private val operations: DeviceOperations) : AutoCloseable { - private val socket = LocalServerSocket(DeviceRpc.SOCKET_NAME) +internal class LocalDeviceRpcServer(private val operations: DeviceOperations,socketName:String=DeviceRpc.SOCKET_NAME,private val onError:(Exception)->Unit={}) : AutoCloseable { + private val socket = LocalServerSocket(socketName) private val clients = java.util.concurrent.ConcurrentHashMap.newKeySet() private val workers = ThreadPoolExecutor(4, 4, 30, TimeUnit.SECONDS, ArrayBlockingQueue(4)) private val accept = Thread({ @@ -17,11 +17,11 @@ internal class LocalDeviceRpcServer(private val operations: DeviceOperations) : val client = try { socket.accept() } catch (_: Exception) { break } // adbd may run as root or shell. An app UID cannot use this root RPC endpoint. val uid = runCatching { client.peerCredentials.uid }.getOrDefault(-1) - if (uid !in setOf(0, 2000)) { client.close(); continue } + if (uid !in setOf(0, 2000)) { onError(IllegalStateException("local RPC peer denied uid=$uid"));client.close(); continue } clients.add(client) try { workers.execute { try { client.soTimeout = 30_000; client.use { DeviceRpcSession(operations).serve(it.inputStream, it.outputStream) } } - catch (_: Exception) { /* close incomplete/authenticated streams; never replay */ } + catch (error: Exception) { onError(error) /* close incomplete/authenticated streams; never replay */ } finally { clients.remove(client); runCatching { client.close() } } } } catch (_: java.util.concurrent.RejectedExecutionException) { clients.remove(client); client.close() } } diff --git a/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt new file mode 100644 index 0000000..4485ac4 --- /dev/null +++ b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt @@ -0,0 +1,53 @@ +package com.adh.daemon + +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Looper +import android.os.Handler +import android.os.Process +import android.system.Os +import android.system.OsConstants +import com.adh.daemon.device.* +import org.json.JSONObject +import java.io.File +import java.io.DataInputStream + +/** Debug APK only. Own namespace and root, no Binder publisher or AndroidDeviceBackend. */ +object P5DeviceFixture { + @JvmStatic fun main(args:Array){ + check(Process.myUid()==0);require(args.size==2) + val root=File(args[0]).canonicalFile;val name=args[1] + require(root.path.matches(Regex("/data/local/tmp/adh-p5-[a-f0-9]{12}"))&&name.matches(Regex("adh_p5_[a-f0-9]{12}"))) + Thread.setDefaultUncaughtExceptionHandler { _,error->File(root,"crash.txt").writeText(error.stackTraceToString());kotlin.system.exitProcess(1) } + Looper.prepareMainLooper();val context=SystemContext.create() + val app=context.packageManager.getApplicationInfo("com.adh.p5sandbox",0) + val agent=File(app.nativeLibraryDir,"libadh_agent.so");check(agent.isFile) + val files=DeviceFiles(File(root,"domain"),{f,m->Os.chmod(f.path,m)},{directory->val fd=Os.open(directory.path,OsConstants.O_RDONLY,0);try{Os.fsync(fd)}finally{Os.close(fd)}});files.initialize() + val scope=ScopeDocuments(File(root,"scope.json"),files) + val identity=DeviceIdentity(files,File("/proc/sys/kernel/random/boot_id").readText().trim()) + val operations=DeviceOperations(identity,files,DeviceBackend { method,params->when(method){ + "device.info"->JSONObject().put("model",android.os.Build.MODEL).put("sdk",android.os.Build.VERSION.SDK_INT).put("isolatedFixture",true) + "scope.get"->scope.snapshot() + "scope.patch"->scope.patch(params) + else->throw DeviceFault("UNSUPPORTED_METHOD","fixture never dispatches Android device control") + }}) + val probe=HookBindingProbe { name->val installed=context.packageManager.getApplicationInfo(name,0);AndroidHookBinding(context,File(installed.nativeLibraryDir,"libadh_agent.so")).inspect(name) } + val cache=HookPlanCache(operations,files,scope,probe) + val network=DeviceNetwork(operations,files,allowEphemeral=true) + val broker=EarlyPlanBroker(cache,name+"_early");val rpc=LocalDeviceRpcServer(operations,name){it.printStackTrace()} + File(root,"ready.json").writeText(JSONObject().put("pid",Process.myPid()).put("uid",app.uid).put("agentPath",agent.path).put("deviceId",identity.deviceId).toString()) + val deadline=System.nanoTime()+900_000_000_000L;val handler=Handler(Looper.getMainLooper()) + val stop=object:Runnable {override fun run(){if(File(root,"stop").exists()||System.nanoTime()>deadline){rpc.close();broker.close();network.close();kotlin.system.exitProcess(0)};handler.postDelayed(this,250)}};handler.post(stop) + Looper.loop() + } +} + +/** Root client exercises actual LocalSocket credentials/timeouts instead of reading cache files. */ +object P5BrokerFetch { + @JvmStatic fun main(args:Array){ + check(Process.myUid()==0);require(args.size==3&&args[0].matches(Regex("adh_p5_[a-f0-9]{12}_early"))) + val file=File(args[2]).canonicalFile;require(file.path.matches(Regex("/data/local/tmp/adh-p5-[a-f0-9]{12}/wire.bin"))) + LocalSocket().use{socket->socket.connect(LocalSocketAddress(args[0],LocalSocketAddress.Namespace.ABSTRACT));socket.soTimeout=3000;check(socket.peerCredentials.uid==0) + socket.outputStream.write("com.adh.p5sandbox ${args[1].toInt()}\n".toByteArray());val input=DataInputStream(socket.inputStream);val size=input.readInt();require(size in 0..32768);val bytes=ByteArray(size);input.readFully(bytes);file.writeBytes(bytes);java.io.FileOutputStream(java.io.FileDescriptor.out).apply{write("WIRE_BYTES=$size\n".toByteArray());flush()}} + } +} diff --git a/device/p5sandbox/.gitignore b/device/p5sandbox/.gitignore new file mode 100644 index 0000000..13cf554 --- /dev/null +++ b/device/p5sandbox/.gitignore @@ -0,0 +1 @@ +src/main/jniLibs/ diff --git a/device/p5sandbox/build.gradle.kts b/device/p5sandbox/build.gradle.kts new file mode 100644 index 0000000..3a4a862 --- /dev/null +++ b/device/p5sandbox/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { alias(libs.plugins.android.application) } +android { + namespace="com.adh.p5sandbox";compileSdk=36;ndkVersion="28.2.13676358" + defaultConfig { + applicationId="com.adh.p5sandbox";minSdk=26;targetSdk=28 + versionCode=providers.gradleProperty("adhP5SandboxVersion").orElse("1").get().toInt();versionName="p5-fixture" + ndk { abiFilters += "arm64-v8a" } + externalNativeBuild { cmake { arguments += "-DANDROID_STL=c++_static" } } + } + externalNativeBuild { cmake { path=file("src/main/cpp/CMakeLists.txt");version="3.22.1" } } + buildTypes { debug { isDebuggable=true } } + sourceSets["main"].jniLibs.srcDir("src/main/jniLibs") + compileOptions { sourceCompatibility=JavaVersion.VERSION_17;targetCompatibility=JavaVersion.VERSION_17 } +} diff --git a/device/p5sandbox/src/main/AndroidManifest.xml b/device/p5sandbox/src/main/AndroidManifest.xml new file mode 100644 index 0000000..39ae2c7 --- /dev/null +++ b/device/p5sandbox/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/device/p5sandbox/src/main/cpp/CMakeLists.txt b/device/p5sandbox/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..bdccf7e --- /dev/null +++ b/device/p5sandbox/src/main/cpp/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.22) +project(p5fixture C CXX) +set(CMAKE_CXX_STANDARD 17) +add_library(p5target SHARED target.c) +target_compile_options(p5target PRIVATE -fno-builtin) +add_library(p5fixture SHARED fixture.cpp) +target_link_libraries(p5fixture dl log) diff --git a/device/p5sandbox/src/main/cpp/fixture.cpp b/device/p5sandbox/src/main/cpp/fixture.cpp new file mode 100644 index 0000000..3070309 --- /dev/null +++ b/device/p5sandbox/src/main/cpp/fixture.cpp @@ -0,0 +1,19 @@ +#include +#include +#include +#include +#include +#include +#include +extern "C" JNIEXPORT jstring JNICALL Java_com_adh_p5sandbox_ProbeService_bootstrap(JNIEnv* env,jclass,jstring dir,jstring wire,jstring sha){ + const char* d=env->GetStringUTFChars(dir,nullptr);const char* w=env->GetStringUTFChars(wire,nullptr);const char* hash=env->GetStringUTFChars(sha,nullptr); + std::string directory=d;void* target=dlopen((directory+"/libp5target.so").c_str(),RTLD_NOW);void* agent=dlopen((directory+"/libadh_agent.so").c_str(),RTLD_NOW); + if(!target||!agent){env->ThrowNew(env->FindClass("java/lang/IllegalStateException"),dlerror());return nullptr;} + auto probe=reinterpret_cast(dlsym(target,"p5_target_probe"));auto package=reinterpret_cast(dlsym(agent,"adh_agent_set_package"));auto policy=reinterpret_cast(dlsym(agent,"adh_agent_set_policy"));auto early=reinterpret_cast(dlsym(agent,"adh_agent_apply_early_v1"));auto start=reinterpret_cast(dlsym(agent,"adh_agent_start")); + if(!probe||!package||!policy||!early||!start){env->ThrowNew(env->FindClass("java/lang/IllegalStateException"),"missing fixture exports");return nullptr;} + std::ifstream input(w,std::ios::binary);std::vector bytes((std::istreambuf_iterator(input)),std::istreambuf_iterator()); + package("com.adh.p5sandbox");policy("d=0,h=0,s=0,a=0,t=0,e=0,y=0");int result=bytes.empty()?-1:early(bytes.data(),bytes.size(),"com.adh.p5sandbox",hash); + // The only getpid import in the target is exercised before starting any Host channel. + long value=probe();char receipt[256];snprintf(receipt,sizeof(receipt),"{\"pid\":%d,\"uid\":%d,\"wireBytes\":%zu,\"earlyApply\":%d,\"probeReturn\":%ld,\"probeBeforeAgentStart\":true}",getpid(),getuid(),bytes.size(),result,value); + start();env->ReleaseStringUTFChars(dir,d);env->ReleaseStringUTFChars(wire,w);env->ReleaseStringUTFChars(sha,hash);return env->NewStringUTF(receipt); +} diff --git a/device/p5sandbox/src/main/cpp/target.c b/device/p5sandbox/src/main/cpp/target.c new file mode 100644 index 0000000..b748c6b --- /dev/null +++ b/device/p5sandbox/src/main/cpp/target.c @@ -0,0 +1,2 @@ +#include +__attribute__((visibility("default"),noinline)) long p5_target_probe(void){return (long)getpid();} diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java new file mode 100644 index 0000000..01ab152 --- /dev/null +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java @@ -0,0 +1,20 @@ +package com.adh.p5sandbox; +import android.app.*; +import android.content.Intent; +import android.os.*; +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/** No Activity: never brings the sandbox in front of the user's analysis app. */ +public final class ProbeService extends Service { + private boolean started=false; + private static native String bootstrap(String directory,String wire,String sha); + public IBinder onBind(Intent intent){return null;} + public int onStartCommand(Intent intent,int flags,int startId){ + NotificationManager manager=getSystemService(NotificationManager.class);manager.createNotificationChannel(new NotificationChannel("p5-test","P5 isolated verification",NotificationManager.IMPORTANCE_LOW)); + startForeground(5,new Notification.Builder(this,"p5-test").setContentTitle("ADH P5 isolated test").setSmallIcon(android.R.drawable.ic_menu_info_details).build()); + if(!started){started=true;try{System.loadLibrary("p5fixture");String result=bootstrap(getApplicationInfo().nativeLibraryDir,new File(getFilesDir(),"p5-wire.bin").getPath(),intent.getStringExtra("agentSha"));Files.write(new File(getFilesDir(),"p5-result.json").toPath(),result.getBytes(StandardCharsets.UTF_8));}catch(Throwable e){throw new RuntimeException(e);}new Handler(Looper.getMainLooper()).postDelayed(()->stopSelf(),120000);} + return START_NOT_STICKY; + } +} diff --git a/device/settings.gradle.kts b/device/settings.gradle.kts index e2c3488..324ce79 100644 --- a/device/settings.gradle.kts +++ b/device/settings.gradle.kts @@ -18,3 +18,5 @@ rootProject.name = "ADH Device" include(":core") include(":daemon") include(":manager") +// Verification-only package, excluded from normal release/bundle project graphs. +if (providers.gradleProperty("adhP5Sandbox").orNull == "true") include(":p5sandbox") diff --git a/docs/P5_ANDROID_ACCEPTANCE.md b/docs/P5_ANDROID_ACCEPTANCE.md new file mode 100644 index 0000000..2007bdc --- /dev/null +++ b/docs/P5_ANDROID_ACCEPTANCE.md @@ -0,0 +1,54 @@ +# P5 Android 沙盒验收与修复(2026-11-16) + +最终独立验收 **7 PASS / 0 FAIL**。设备为 PGP110、Android 15 / API 35、arm64-v8a、KernelSU,SELinux 保持 enforcing。使用独立 worktree,未安装或替换生产 Zygisk 模块、Manager、Device Daemon,未重启现有服务。 + +## 实测证据与边界 + +| 项目 | 实测结果 | +| --- | --- | +| Android 安装绑定 | 正式 `AndroidHookBinding` 验证 PackageManager UID、版本、APK signer、源文件信息、实际 Agent SHA 和 release 导出,支持状态为 true | +| 早期 GOT 命中 | 新包 `com.adh.p5sandbox` 先加载测试 so 和 Agent,调用正式 early-plan 导出,再调用测试 so 的 getpid,最后才启动 Agent 通道。回执 attempted=confirmed=1、installed=1、Hook ID=1;正式 native status 的 hits=1,返回值仍为该进程 PID | +| 缓存过期 | 真正等待秒级 TTL 到期,正式 root broker 返回 0 bytes;新沙盒进程无 early receipt、无 Hook | +| 绑定失效 | 实际把同一测试 APK 从 versionCode 1 更新至 2,Android APK 路径和版本变化;旧缓存不再交付,新进程无 Hook | +| 授权撤销 | 通过真实 LAN TLS 1.3 和配对 grant 暂存缓存,先证明确能命中;再经 USB 撤销该 grant,后续 broker 返回 0 bytes,新进程无 Hook | +| 显式缓存撤销 | CAS 撤销后,后续 broker 返回 0 bytes,新进程无 Hook | +| 旧配置回滚 | 自有 scope 的未知/退役字段保留。并发新增包后回滚被 STALE_SCOPE 拒绝;显式恢复本测试的迁移后版本后,再回滚,实际文件 SHA-256 与原始文本逐字节一致 | + +“早期”在本验收中只代表 **真实 Android 沙盒 self-load 后、Agent 连接 Host 前**。测试调用正式 Agent 消费函数,broker 使用正式 root LocalSocket 服务,缓存/任务/RPC/配对/TLS 都走正式实现。沙盒只提供可确定的调用顺序和 getpid 触发器,不充当另一套 Hook 实现。 + +以下仍未验证: + +- 正式 Zygisk 模块在 pre/post-specialize 中获取并投递缓存的整条路径、SELinux 对该 companion 的实际许可与时序;本次没有刷模块或重启手机。 +- `.init_array` 前、Java 类加载前的命中保证;这些也不属于当前缓存协议承诺。 +- 整机重启、生产模块更新、真实业务 App、Java/inline 早期步骤。后两种步骤当前明确 unsupported。 +- 早期 `capture_start` 各捕获族、独立 UID 变更和 Agent 二进制替换的真机反例;本次真实绑定失效反例是 APK v1→v2。 +- 真机的早期 `capture_start` 捕获族、单独替换 Agent 二进制或更换 UID、其他 ROM。此次早期命中正例是 GOT getpid,绑定失效反例是实际 APK 升级;不把它扩写成所有组合均已通过。 + +## 发现并修复的问题 + +1. **GOT 安装参数错误。** early consumer 把 errno 默认值传成 -1,正式 native primitive 只接受 0..4095。真实沙盒因此拒绝安装,之前只覆盖编码/解析骨架的测试没有发现。现改为 0,并在部分失败回执里保留有界、JSON 转义后的原生原因;正例由真实调用和 hits 证明。 +2. **Android LAN 签名转义差异。** Android `org.json` 会转义 `/`,而 JVM 夹具和 Host `JSON.stringify` 的挑战文本不同。新 `DeviceRpc.lanProof` 固定线上的紧凑 JSON 字节,覆盖斜杠、反斜杠、控制字符、Unicode 和孤立 surrogate;不改变已有持久操作 hash。真实 Android TLS 配对认证和撤销已通过。 +3. **enforcing 下 USB forward 被拒绝。** 内核审计明确记录 adbd → su Unix socket 的 connectto 拒绝。增加显式 `devices connect transport=adb usbMode=stdio`:root byte relay 连接同一个 UDS,仍使用 `adh.device/1`、同一个 bootstrap token、签名身份、设备代次、任务和去重账本。默认 forward 保留;无自动回退、重试、放宽 SELinux 或新增网络监听。 + +stdio 通过 `adb shell -T` 保持双向原始流。连接前只读检查 su 帮助;仅在实现明确提供 `--no-wrapper` 时选择 KernelSU `-W`。Android relay 使用原始 FileDescriptor,而非会被 app_process 重定向到 logcat 的 System.out;LocalSocket 在连接后才设超时。新 bootstrap 的 stdioVersion=1 只增加传输能力标记,保留原身份和凭据;旧设备未声明时返回 unsupported。 + +## 隔离设施与复现 + +- `device/p5sandbox` 是 opt-in Gradle 模块,只有 `-PadhP5Sandbox=true` 才加入。使用新包名和前台 Service,没有 Activity,不抢占原分析 App 的界面。 +- `device/daemon/src/p5Fixture` 只有同一 opt-in 属性启用时编入测试 APK;不进入普通 bundle。它运行独立 root 进程,不发布 Binder,不使用 AndroidDeviceBackend,不能调生产启停/证书/宿主设置。 +- 每次创建 `/data/local/tmp/adh-p5-<随机值>`、独立数据和 UDS 名;身份/授权/迁移账本在 root 私有 domain 目录。Host 使用独立数据、18088/18761。正式 8088/8761 映射不改写。 +- 专用 Agent 构建把默认连接端口编为 18761;运行前核对 CMakeCache 和 APK 内实际 Agent SHA,防止新沙盒误连正式 Host。`build_agent.sh` 拒绝把自定义端口 Agent 用 `--deploy` 推出。 +- `tools/verify_p5_device.ts` 显式接收 serial、transportId、构建资产目录、新输出目录。拒绝已有同名包和已占用端口;不默认选第一台设备。测试开始与结束核对原会话 ID/PID/进程代次、原 root daemon 与业务 PID、模块/配置哈希及 ADB reverse 映射。失败也记录 unknown,不把设备账本的晚到成功改称已确认成功。 +- 测试只停止/卸载自身新包、关闭自身 Host/连接和 root fixture、删除自己建立的 reverse 映射;私有原始报告与失败诊断留在工作区外的 `.tmp`,不提交。设备 UUID 目录保留以便检查,其中无业务采集数据;不自动清理生产目录。 + +构建顺序(示例在 Windows Git Bash / PowerShell 中按现有 SDK 路径执行): + +1. `ADH_AGENT_CONNECT_PORT=18761 bash tools/build_agent.sh`,独立产物位于 `agent/build-isolated-18761/`,自动暂存到 `device/p5sandbox/src/main/jniLibs/arm64-v8a/`;不会覆盖正常端口的 canonical 产物。 +2. `device/gradlew --offline -PadhP5Sandbox=true :daemon:assembleDebug :p5sandbox:assembleDebug`。保存 daemon.apk 与 versionCode 1 的 sandbox-v1.apk;再用 `-PadhP5SandboxVersion=2` 构建并保存 sandbox-v2.apk。只保存到自有资产目录,不刷模块。 +3. `node tools/verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT`。资产文件名是 daemon.apk、sandbox-v1.apk、sandbox-v2.apk。必须确保 SERIAL 是获准的专用 root 机;脚本不对日常机执行安装。 + +Host 自动回归通过 `tools/verify_v132_p5_stdio.sh` 注册到既有 host gates,覆盖真实 Kotlin dispatcher 的 stdio 认证、长二进制帧和旧能力拒绝。真机脚本保留为显式入口,避免 verify_all 自动重启共享沙盒的行为破坏现场。 + +最终原始报告在本机工作区外 `.tmp/adh-p5-android-run-24/report.json`,包含 7 个真实用例和 sceneUnchanged=true;run-23 同样为 7/7。此前失败报告保留,没有计为通过。它是本次有日期的验收证据,不能替代下次运行时重新选择设备和检查现场。 + +收口回归:Host typecheck 和 **558/558** 通过;Android JVM **70/70**(core23、daemon18、Manager29);普通及 opt-in Android 构建通过,普通 APK 的 DEX 确认不含 P5 fixture、包含生产 stdio relay。原生正常/隔离端口构建、v132、94 项 MCP 注册及生成文档检查通过。 diff --git a/docs/P5_HOOK_PLANS.md b/docs/P5_HOOK_PLANS.md index 232bdc3..bfe2767 100644 --- a/docs/P5_HOOK_PLANS.md +++ b/docs/P5_HOOK_PLANS.md @@ -1,5 +1,7 @@ # P5:Host Hook 方案、早期缓存与可逆迁移 +后续已有真实 Android 沙盒验收与修复,见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。原文下面的“未验证”是初次实现快照;正式 Zygisk 整条投递路径仍未验证。 + 2026-11-16。Host 是方案与流程的权威;手机保留设备执行、验证缓存、状态和撤销入口。AI 默认持有控制,人类通过同一操作层查看、编辑和接管。P5 没有部署到现有手机,也没有重启现有 Host。 ## 模块与统一入口 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 104b7b5..3eddd89 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -5020,3 +5020,11 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 边界:只完成隔离 JVM TLS/模拟 ADB 路径与构建;真实 Android JSSE/provider、UDS/SELinux/防火墙/无线网络、真实 Binder/进程和系统 CA 效果未验证。没有 agent 本地路由、bulk、广播发现、无 USB 首次配对/手机配对 UI、在线证书轮换/归档;未迁能力继续如实 unsupported。完整协议/权限、能力矩阵、配对/恢复顺序和数据文件见 [P4_LAN_AUTH.md](P4_LAN_AUTH.md)。 未部署、未推送、未发布安装包、未执行真实 ADB、未启停目标、未改 reverse/forward、未重启当前分析服务;交付本轮源码提交。 + +## 2026-11-16 — P5 真机隔离验收与修复 + +在 `feat/adh-p5-device-acceptance-20261116`(基座 P5 de9d134)实现并验收独立 Android 沙盒。新包、opt-in 构建、私有 root 数据/UDS/Host 端口,不替换模块、Manager 或现有 daemon,不重启任何原服务。最终两次独立运行各 **7/7**,包含 before-Agent-start GOT getpid 命中、真实 TTL 过期、实际 APK v1→v2 绑定失效、LAN TLS1.3 grant 撤销、缓存撤销、并发回滚冲突拒绝与 scope 原文精确 hash 恢复;原会话、PID、模块/配置 hash、ADB 映射前后一致。 + +修复 early GOT 默认 errno=-1(改为0并保留失败原因)、Android org.json 斜杠转义导致的 LAN 挑战签名字节差异。enforcing ROM 的 adbd→su UDS connectto 拒绝通过新增显式 USB stdio/1 传输处理:同一协议/身份/账本,旧能力返回 unsupported,无自动回退/重发,不放宽 SELinux。沙盒 Agent 使用独立构建/产物端口18761,不能 --deploy,也不覆盖正常8761产物。默认 APK 排除所有 p5Fixture 类。 + +回归:Host typecheck、**558/558**;Android JVM **70/70**(23/18/29);普通/opt-in APK、原生默认/隔离端口构建、v132 host gate、94项MCP注册和生成文档检查通过。实测证据与正式 Zygisk、capture_start/其他绑定组合等未验证边界见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。没有把模拟自加载扩写为已验证整个 Zygisk 时序。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 6d85880..be45650 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -102,5 +102,5 @@ Host-owned Hook plans, early-cache limits and reversible legacy migration: [P5_H | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | _operation | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | | `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | -| `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | +| `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects a raw root relay on enforcing ROMs, never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, usbMode, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | | `hook_plans` | Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device. | action, plan, digest, expectedLibraryRevision, session, runId, id, package, scope, settings, deviceId, connectionId, bootId, daemonInstanceId, expectedDeviceRevision, binding, expiresAt, offline, expectedCacheRevision, deploymentId, scopeRevision, migrationId, _operation | diff --git a/tools/MAP.md b/tools/MAP.md index 107d3ab..8a275c5 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -5,6 +5,12 @@ script or touching `verify_all.sh`.** ## Shared libraries (source these, don't execute) +## P5 isolated Android acceptance (2026-11-16) + +`verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT` is explicit real-device acceptance with a new package, private root domain, UDS, Host ports/data and cleanup/protection checks. It never flashes a module or restarts the running service. Build `:p5sandbox` and `:daemon` with `-PadhP5Sandbox=true` and an Agent built for port 18761. `p5_isolated_host.ts` maps only the private fixture endpoints into the production dispatcher. `verify_v132_p5_stdio.sh` is the registered host-only Kotlin interoperability gate; missing offline fixture is SKIP, never real-device fallback. Details and real/unverified boundaries: [P5_ANDROID_ACCEPTANCE.md](../docs/P5_ANDROID_ACCEPTANCE.md). + +## Shared library reference + 2026-10-24 analysis checks: `verify_v122_native_controls.sh` uses an existing Android sandbox (not run on the new agent this round); v123 verifies real paged QBDI and diagnostics; v124 verifies random-parameter crypto evidence; v125 verifies native controls/FP8/aggregate returns/unhook; diff --git a/tools/build_agent.sh b/tools/build_agent.sh index 974b5aa..3ddddba 100644 --- a/tools/build_agent.sh +++ b/tools/build_agent.sh @@ -18,6 +18,12 @@ source "$(dirname "${BASH_SOURCE[0]}")/lib/env.sh" DEPLOY=0 for arg in "$@"; do case "$arg" in --deploy) DEPLOY=1 ;; *) echo "unknown flag: $arg" >&2; exit 2 ;; esac; done +CONNECT_PORT="${ADH_AGENT_CONNECT_PORT:-8761}" +if [[ ! "$CONNECT_PORT" =~ ^[1-9][0-9]{0,4}$ ]] || [ "$CONNECT_PORT" -gt 65535 ]; then echo 'invalid ADH_AGENT_CONNECT_PORT' >&2; exit 2; fi +if [ "$DEPLOY" = 1 ] && [ "$CONNECT_PORT" != 8761 ]; then + echo "custom-port agents are sandbox-only; refusing --deploy" >&2 + exit 2 +fi # ---- toolchain: pinned Windows paths first, host fallbacks second -------------------------- TC="$TOOLCHAIN" @@ -36,9 +42,12 @@ STRIP="$NDK/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe" [ -n "$STRIP" ] && [ -x "$STRIP" ] || { echo "missing strip tool (neither the pinned NDK nor the host NDK provides llvm-strip)"; exit 1; } # ---- build dir: never reuse the other host's cache ---------------------------------------- -BUILD_DIR="${ADH_BUILD_DIR:-$ROOT/agent/build}" -if [ -f "$BUILD_DIR/CMakeCache.txt" ] && grep -qE '^CMAKE_TOOLCHAIN_FILE:[^=]*=[A-Za-z]:[/\\]' "$BUILD_DIR/CMakeCache.txt"; then - BUILD_DIR="$ROOT/agent/build-$(uname -s | tr 'A-Z' 'a-z')" +DEFAULT_BUILD_DIR="$ROOT/agent/build" +if [ "$CONNECT_PORT" != 8761 ]; then DEFAULT_BUILD_DIR="$ROOT/agent/build-isolated-$CONNECT_PORT"; fi +BUILD_DIR="${ADH_BUILD_DIR:-$DEFAULT_BUILD_DIR}" +if [ "$CONNECT_PORT" != 8761 ] && [ "$BUILD_DIR" = "$ROOT/agent/build" ]; then echo 'isolated port cannot overwrite canonical agent/build' >&2; exit 2; fi +if ! command -v cygpath >/dev/null 2>&1 && [ -f "$BUILD_DIR/CMakeCache.txt" ] && grep -qE '^CMAKE_TOOLCHAIN_FILE:[^=]*=[A-Za-z]:[/\\]' "$BUILD_DIR/CMakeCache.txt"; then + BUILD_DIR="$DEFAULT_BUILD_DIR-$(uname -s | tr 'A-Z' 'a-z')" echo ">> existing cache at $ROOT/agent/build is from another host — building in $BUILD_DIR" fi @@ -58,7 +67,8 @@ echo ">> configuring agent ($ABI) with $CMAKE_BIN" -DANDROID_ABI="$ABI" \ -DANDROID_PLATFORM=android-26 \ -DANDROID_STL=c++_static \ - -DCMAKE_BUILD_TYPE=Release >/dev/null + -DCMAKE_BUILD_TYPE=Release \ + -DADH_AGENT_CONNECT_PORT="${ADH_AGENT_CONNECT_PORT:-8761}" >/dev/null echo ">> building" # Do NOT hide build output — a hidden compile error once shipped a stale .so. @@ -67,6 +77,7 @@ if ! "$CMAKE_BIN" --build "$BUILD_DIR"; then echo "!! AGENT BUILD FAILED"; exit SO="$BUILD_DIR/libadh_agent.so" DEBUG_SO="$BUILD_DIR/libadh_agent.so.debug" DEST="$ROOT/sandbox-app/app/src/main/jniLibs/$ABI" +if [ "$CONNECT_PORT" != 8761 ]; then DEST="$ROOT/device/p5sandbox/src/main/jniLibs/$ABI"; fi # Keep debug info locally (gitignored) for crash symbolication, but ship a # stripped .so: an unstripped agent carries thousands of internal names and @@ -83,12 +94,12 @@ mkdir -p "$DEST" cp "$SO" "$DEST/libadh_agent.so" # The canonical artifact path: host-side gates (verify_v26_footprint, verify_v88_agent_signatures) # read agent/build/libadh_agent.so, so on a host-suffixed build dir it must still hold THIS build. -if [ "$BUILD_DIR" != "$ROOT/agent/build" ]; then +if [ "$CONNECT_PORT" = 8761 ] && [ "$BUILD_DIR" != "$ROOT/agent/build" ]; then mkdir -p "$ROOT/agent/build" cp "$SO" "$ROOT/agent/build/libadh_agent.so" fi echo ">> built $(ls -la "$SO" | awk '{print $5}') bytes -> $DEST/libadh_agent.so" -if [ "$BUILD_DIR" != "$ROOT/agent/build" ]; then echo ">> canonical copy -> agent/build/libadh_agent.so"; fi +if [ "$CONNECT_PORT" = 8761 ] && [ "$BUILD_DIR" != "$ROOT/agent/build" ]; then echo ">> canonical copy -> agent/build/libadh_agent.so"; fi if [ -f "$DEBUG_SO" ]; then echo ">> unstripped debug copy -> $DEBUG_SO"; fi "$READELF" --dyn-syms "$SO" \ | grep -iE "adh_agent_set_package|adh_agent_set_endpoint|adh_agent_start|JNI_OnLoad" | awk '{print " export:", $8}' diff --git a/tools/p5_isolated_host.ts b/tools/p5_isolated_host.ts new file mode 100644 index 0000000..e9fc2d7 --- /dev/null +++ b/tools/p5_isolated_host.ts @@ -0,0 +1,22 @@ +// Private test Host. The adapter translates only bootstrap/socket names into its own namespace. +import {execFile,spawn} from 'node:child_process'; +import {Duplex} from 'node:stream'; +import {promisify} from 'node:util'; +import {join} from 'node:path'; +const [serial,transport,remote,socket,root]=process.argv.slice(2); +if(!serial||!/^\d+$/.test(transport)||!/^\/data\/local\/tmp\/adh-p5-[a-f0-9]{12}$/.test(remote)||!/^adh_p5_[a-f0-9]{12}$/.test(socket)||!root)throw Error('explicit isolated Host arguments required'); +process.env.ADH_DATA_DIR=root;process.env.ADH_SKIP_ARTIFACT_LOAD='1';process.env.ANDROID_SERIAL=serial;process.env.ADH_HTTP_PORT='18088';process.env.ADH_AGENT_PORT='18761';delete process.env.ADH_CAPTURES_DIR; +const {Devices}=await import('../daemon/src/devices.ts');const {AdbDeviceTransport}=await import('../daemon/src/transport/adb_device.ts');const {setDevicesForTests}=await import('../daemon/src/device_host.ts');const {DEVICE_BOOTSTRAP,DEVICE_SOCKET}=await import('../daemon/src/device_protocol.ts'); +const exec=promisify(execFile),adb=process.env.ADH_ADB_PATH||'adb'; +const run=async(args:string[])=>{ + if(args.join(' ')==='devices -l')return (await exec(adb,args,{windowsHide:true})).stdout; + if(args[0]!=='-t'||args[1]!==transport)throw Error('unselected device command rejected'); + if(args.slice(2).join(' ')==='exec-out su --help')return (await exec(adb,args,{windowsHide:true})).stdout; + if(args[2]==='exec-out'&&args[3]==='su'&&args[4]==='-c'&&args[5]==='cat '+DEVICE_BOOTSTRAP)args=[...args.slice(0,5),'cat '+remote+'/domain/usb-access.json']; + else if(args[2]==='forward'&&args.includes('localabstract:'+DEVICE_SOCKET))args=args.map(a=>a==='localabstract:'+DEVICE_SOCKET?'localabstract:'+socket:a); + else if(args[2]!=='forward'||!['--list','--remove'].includes(args[3]))throw Error('fixture allows only owned forwarding and bootstrap reads'); + const output=(await exec(adb,args,{windowsHide:true,timeout:10000})).stdout;return output.replaceAll('localabstract:'+socket,'localabstract:'+DEVICE_SOCKET); +}; +const stdio=(args:string[])=>{if(args[0]!=='-t'||args[1]!==transport||args[2]!=='shell'||args[3]!=='-T'||args[4]!=='su')throw Error('invalid stdio request');const command=`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-usb-relay com.adh.daemon.device.DeviceRpcRelay ${socket}`;const child=spawn(adb,[...args.slice(0,-1),"'"+command+"'"],{windowsHide:true,stdio:['pipe','pipe','pipe']});const stream=Duplex.from({readable:child.stdout,writable:child.stdin});child.stderr.resume();child.on('error',error=>stream.destroy(error));child.on('close',()=>stream.destroy());stream.on('close',()=>{if(child.exitCode===null)child.kill();});return stream;}; +setDevicesForTests(new Devices(join(root,'devices.json'),new AdbDeviceTransport(run,undefined,stdio))); +await import('../daemon/src/index.ts'); diff --git a/tools/verify_all.sh b/tools/verify_all.sh index a6b9d01..6d8a62f 100644 --- a/tools/verify_all.sh +++ b/tools/verify_all.sh @@ -282,6 +282,7 @@ SCRIPTS=( "verify_v129_qbdi_delivery.sh:device" # v130: scope merge rules + the analyze_app/scope_* MCP tool contract (host only, no device write). "verify_v130_scope_analyze.sh:host" + "verify_v132_p5_stdio.sh:host" ) pass=0; fail=0; skip=0; FAILED="" diff --git a/tools/verify_p5_device.ts b/tools/verify_p5_device.ts new file mode 100644 index 0000000..d4d7cd5 --- /dev/null +++ b/tools/verify_p5_device.ts @@ -0,0 +1,79 @@ +// Explicit opt-in real-device sandbox. Never installs the production module/Manager/daemon. +import assert from 'node:assert/strict'; +import {execFile,spawn} from 'node:child_process'; +import {promisify} from 'node:util'; +import {readFileSync,writeFileSync,mkdirSync,existsSync,openSync,closeSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +import {randomBytes,createHash} from 'node:crypto'; +import net from 'node:net'; +const [serial,transport,assets,output]=process.argv.slice(2); +assert.ok(serial&&serial!=='a22fecdd'&&/^\d+$/.test(transport)&&assets&&output,'explicit dedicated root serial, transport id, built assets and private output required'); +const root=resolve(import.meta.dirname,'..'),dir=resolve(output);assert.ok(!existsSync(dir),'use a fresh private result directory');mkdirSync(dir,{recursive:true}); +const nonce=randomBytes(6).toString('hex'),remote='/data/local/tmp/adh-p5-'+nonce,socket='adh_p5_'+nonce,pkg='com.adh.p5sandbox'; +const run=promisify(execFile),adb=process.env.ADH_ADB_PATH||'adb',prefix=['-t',transport]; +const command=async(args:string[],timeout=20000)=>(await run(adb,[...prefix,...args],{windowsHide:true,timeout,maxBuffer:1024*1024})).stdout.trim(); +const quote=(v:string)=>"'"+v.replaceAll("'","'\\''")+"'"; +const su=(cmd:string,timeout=20000)=>command(['exec-out','su','-c',cmd],timeout); +const pause=(ms:number)=>new Promise(r=>setTimeout(r,ms)); +const report:any={schemaVersion:1,mode:'real-android-sandbox',cases:[],unverified:['production Zygisk pre/post-specialize delivery (module unchanged)','full-device reboot and reconnect','Java/inline early steps (unsupported)'],remote}; +let host:ReturnType|undefined,deviceChild:ReturnType|undefined,usb:any,lan:any,installed=false,started=false,baseline:any; +const base='http://127.0.0.1:18088';let sequence=0; +const request=async(path:string,body?:any)=>{const response=await fetch(base+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return response.json() as Promise;}; +async function tool(name:string,args:any,write=false){if(write){const path=name==='devices'?'/api/devices':'/api/hook-plans';const c=await request('/api/operations/prepare',{path,method:'POST',arguments:args});assert.equal(c.ok,true,JSON.stringify(c));args={...args,_operation:{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch,idempotencyKey:'p5-'+nonce+'-'+(++sequence)}};} + const response=await request('/mcp',{jsonrpc:'2.0',id:sequence,method:'tools/call',params:{name,arguments:args}});if(!response.result)throw Error(JSON.stringify(response));return JSON.parse(response.result.content[0].text);} +async function read(peer:any,method:string,params:any={}){const v=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,method,params});assert.equal(v.ok,true,JSON.stringify(v));return v.result;} +async function deviceWrite(peer:any,method:string,params:any={}){const state=await read(peer,'device.state');const value=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,method,params},true);assert.equal(value._operation?.state,'succeeded',JSON.stringify(value));return value.result.result;} +async function hookDevice(peer:any,action:string,extra:any={},write=false){const state=await read(peer,'device.state');const value=await tool('hook_plans',{action,deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,package:pkg,...extra},write);return value;} +async function until(fn:()=>Promise,label:string,budget=12000){const deadline=Date.now()+budget;let last;do{try{const v=await fn();if(v)return v;}catch(e){last=e;}await pause(150);}while(Date.now()Promise){console.log('RUN '+name);const result=await fn();report.cases.push({name,state:'pass',evidence:result??null});console.log('PASS '+name);} +async function baselineNow(){const live:any=await(await fetch('http://127.0.0.1:8088/api/agents')).json();const hashes=await su('sha256sum /data/adb/adh/scope.json /data/adb/adh/host.endpoint /data/adb/modules/adh/libadh_agent.so');assert.equal(hashes.split('\n').filter(line=>/^[a-f0-9]{64}\s/.test(line)).length,3,'real scene hashes required');return {hashes,sessions:live.filter((s:any)=>s.online).map((s:any)=>({id:s.sessionId,pid:s.pid,start:s.starttimeTicks})),processes:await su("ps -A -o PID,NAME | grep -E 'adh-device-daemon|com.shizhuang.duapp'"),reverse:await command(['reverse','--list'])};} +const unwrap=(v:any)=>{assert.equal(v._operation?.state,'succeeded',JSON.stringify(v));return v.result.result;}; +let binding:any,cacheRevision:number,migration:any,originalScope:string,planDigest:string; +async function stage(peer:any,ttl=180){const prepared=(await hookDevice(peer,'early-prepare')).result;binding=prepared.binding;cacheRevision=prepared.cacheRevision;const info=await hookDevice(peer,'early-stage',{digest:planDigest,binding,expectedCacheRevision:cacheRevision,expiresAt:Math.floor(Date.now()/1000)+ttl,offline:'keep-until-expiry'},true);return unwrap(info);} +async function brokerWire(){return su(`CLASSPATH=${remote}/daemon.apk app_process /system/bin com.adh.daemon.P5BrokerFetch ${socket}_early ${binding.uid} ${remote}/wire.bin`);} +async function launch(expect:boolean){ + await command(['shell','am','force-stop',pkg]);const wire=await brokerWire();const count=Number(/WIRE_BYTES=(\d+)/.exec(wire)?.[1]);assert.equal(count>0,expect,wire); + await su(`mkdir -p /data/user/0/${pkg}/files; rm -f /data/user/0/${pkg}/files/p5-result.json; cp ${remote}/wire.bin /data/user/0/${pkg}/files/p5-wire.bin; chown -R ${binding.uid}:${binding.uid} /data/user/0/${pkg}/files; chmod 600 /data/user/0/${pkg}/files/p5-wire.bin`); + const result=await command(['shell','am','start-foreground-service','-n',pkg+'/.ProbeService','--es','agentSha',binding.agentSha256]);assert.ok(!result.includes('Error'),result); + const receipt=await until(async()=>{try{return JSON.parse(await su(`cat /data/user/0/${pkg}/files/p5-result.json`))}catch{return null;}},'sandbox bootstrap'); + writeFileSync(join(dir,'bootstrap-'+receipt.pid+'.json'),JSON.stringify(receipt));assert.equal(receipt.probeReturn,receipt.pid);assert.equal(receipt.probeBeforeAgentStart,true);assert.equal(receipt.earlyApply,expect?1:-1,JSON.stringify(receipt)); + const session=await until(async()=>{const all=await request('/api/agents');return all.find((s:any)=>s.online&&s.package===pkg&&s.pid===receipt.pid);},'isolated agent hello'); + const status=await tool('native_hook',{action:'status',session:session.sessionId});const hooks=status.status?.hooks||status.hooks||[]; + if(expect){assert.equal(session.earlyPlan?.state,'applied',JSON.stringify(session.earlyPlan));const owned=hooks.find((h:any)=>h.id===session.earlyPlan.steps[0].hookId);assert.ok(owned,JSON.stringify(status));assert.ok(owned.hits>=1,JSON.stringify(owned));assert.equal(owned.symbol,'getpid');return {receipt,early:session.earlyPlan,hits:owned.hits};} + assert.equal(session.earlyPlan,null);assert.equal(hooks.length,0);return {receipt,early:null}; +} +try{ + for(const port of [18088,18761])await new Promise((yes,no)=>{const s=net.createServer();s.once('error',no);s.listen(port,'0.0.0.0',()=>s.close(()=>yes()));}); + const discovery=await(await run(adb,['devices','-l'],{windowsHide:true})).stdout;assert.ok(discovery.split('\n').some(s=>s.startsWith(serial+' ')&&s.includes('transport_id:'+transport)),'selected serial/transport changed');assert.match(await su('id'),/uid=0\(root\)/); + assert.equal(await command(['shell','getprop','ro.product.cpu.abi']),'arm64-v8a');const existing=await command(['shell','pm','path',pkg]).catch(error=>{if(error.code===1&&!String(error.stdout||'').trim())return '';throw error;});assert.equal(existing,'','sandbox package already exists; do not overwrite unknown work'); + baseline=await baselineNow();assert.ok(!baseline.reverse.includes('tcp:18088')&&!baseline.reverse.includes('tcp:18761'),'isolated reverse ports already owned');assert.ok(!(await su('cat /data/adb/adh/scope.json')).includes(pkg),'sandbox must not enter the active Zygisk scope'); + const cache=readFileSync(join(root,'agent','build-isolated-18761','CMakeCache.txt'),'utf8');assert.match(cache,/ADH_AGENT_CONNECT_PORT:STRING=18761/,'build agent with ADH_AGENT_CONNECT_PORT=18761 first'); + await command(['shell','mkdir','-m','755',remote]);await command(['push',join(assets,'daemon.apk'),remote+'/daemon.apk']);await su(`chmod 444 ${remote}/daemon.apk`);await command(['push',join(assets,'sandbox-v1.apk'),remote+'/sandbox.apk']);assert.match(await su(`pm install -r ${remote}/sandbox.apk`,90000),/Success/);installed=true; + originalScope='{\n "version":19,"mode":"allowlist","packages":["com.adh.p5sandbox"],"policy":{"com.adh.p5sandbox":{"c":{"d":false,"h":true,"future":7},"retired":{"bypass":true}}},"future":{"preserved":[1,2]}\n}\n';writeFileSync(join(dir,'scope-before.json'),originalScope);await command(['push',join(dir,'scope-before.json'),remote+'/scope.json']); + const deviceLog=openSync(join(dir,'device.log'),'a');deviceChild=spawn(adb,[...prefix,'exec-out','su','-c',`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-${nonce} com.adh.daemon.P5DeviceFixture ${remote} ${socket}`],{windowsHide:true,stdio:['ignore',deviceLog,deviceLog]});closeSync(deviceLog);started=true; + const ready=await until(async()=>{try{return JSON.parse(await su(`cat ${remote}/ready.json`));}catch{return null;}},'private device domain ready');report.device={serial,model:await command(['shell','getprop','ro.product.model']),sdk:await command(['shell','getprop','ro.build.version.sdk']),abi:'arm64-v8a'}; + const log=openSync(join(dir,'host.log'),'a');host=spawn(process.execPath,[join(root,'tools','p5_isolated_host.ts'),serial,transport,remote,socket,join(dir,'host')],{cwd:join(root,'daemon'),windowsHide:true,stdio:['ignore',log,log]});closeSync(log);await until(()=>request('/health'),'private Host ready'); + usb=await tool('devices',{action:'connect',serial,transportId:transport,usbMode:'stdio'},true);assert.equal(usb._operation?.state,'succeeded',JSON.stringify(usb)); + const plan={schemaVersion:1,id:'p5-early-device',title:'Isolated Android GOT proof',package:pkg,families:{digest:false,hmac:false,symmetric:false,asymmetric:false,tls:false,aead:false,system:false},steps:[{id:'getpid-before-host',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libp5target.so',symbol:'getpid'}}]}; + const saved=await tool('hook_plans',{action:'put',plan,expectedLibraryRevision:0},true);assert.equal(saved.applied,false);planDigest=saved.digest; + const preview=await hookDevice(usb,'migration-preview');assert.equal(preview.result.scopeRaw,originalScope);migration=unwrap(await hookDevice(usb,'migration-apply',{digest:planDigest,scopeRevision:preview.result.scopeRevision},true)); + await check('Android PackageManager and release ABI binding',async()=>{const p=(await hookDevice(usb,'early-prepare')).result;assert.equal(p.supported,true);const expected=createHash('sha256').update(readFileSync(join(root,'agent','build-isolated-18761','libadh_agent.so'))).digest('hex');assert.equal(p.binding.agentSha256,expected,'APK must contain the port-isolated Agent before starting it');binding=p.binding;assert.equal(binding.uid,ready.uid);return {supported:true,uid:binding.uid,signers:binding.signers.length,apkFiles:binding.apks.length};}); + await check('early GOT installed and hit before Agent Host connection',async()=>{await stage(usb);return launch(true);}); + await check('expired cache denies real broker delivery and installs no Hook',async()=>{const s=await stage(usb,3);const delay=s.entry.expiresAt*1000-Date.now()+300;await pause(Math.max(0,delay));return launch(false);}); + await check('real APK replacement invalidates the cached binding',async()=>{await stage(usb);await command(['shell','am','force-stop',pkg]);await command(['push',join(assets,'sandbox-v2.apk'),remote+'/sandbox-v2.apk']);assert.match(await su(`pm install -r ${remote}/sandbox-v2.apk`,90000),/Success/);const after=(await hookDevice(usb,'early-prepare')).result.binding;assert.notDeepEqual(after,binding);const result=await launch(false);return {...result,beforeVersion:binding.versionCode,afterVersion:after.versionCode};}); + await check('LAN grant revocation denies future early cache delivery',async()=>{const address=(await command(['shell','ip','-4','addr','show','wlan0'])).match(/inet (\d+\.\d+\.\d+\.\d+)/)?.[1];assert.ok(address);const cfg=await deviceWrite(usb,'lan.configure',{enabled:true,address,port:0});const state=await read(usb,'device.state');const paired=await tool('devices',{action:'pair',deviceId:usb.deviceId,connectionId:usb.connectionId,bootId:usb.bootId,daemonInstanceId:usb.daemonInstanceId,expectedDeviceRevision:state.stateRevision,permissions:['read','write','manage']},true);assert.equal(paired.ok,true,JSON.stringify(paired));const grant=paired.result.result;lan=await tool('devices',{action:'connect',transport:'lan',deviceId:usb.deviceId,address,port:cfg.port},true);assert.equal(lan._operation?.state,'succeeded',JSON.stringify(lan));const staged=await stage(lan);assert.equal(staged.entry.sourceGrant,grant.grantId);await launch(true);await deviceWrite(usb,'pairings.revoke',{grantId:grant.grantId});const result=await launch(false);return {...result,tls:lan.tlsVersion};}); + await check('explicit early revoke blocks future delivery',async()=>{const staged=await stage(usb);unwrap(await hookDevice(usb,'early-revoke',{deploymentId:staged.entry.deploymentId,expectedCacheRevision:staged.cacheRevision},true));return launch(false);}); + await check('legacy rollback refuses concurrent scope edits then restores exact bytes',async()=>{const scope=await read(usb,'scope.get'),migratedRaw=await su(`cat ${remote}/scope.json`);await deviceWrite(usb,'scope.patch',{scopeRevision:scope.scopeRevision,add:['com.fixture.concurrent']});const conflict=await hookDevice(usb,'migration-rollback',{migrationId:migration.migrationId,scopeRevision:migration.scopeRevision},true);assert.equal(conflict.result?.code||conflict.code,'STALE_SCOPE',JSON.stringify(conflict));assert.ok((await read(usb,'scope.get')).document.packages.includes('com.fixture.concurrent')); + // Repair only our fixture document with the exact pre-edit bytes from the private domain. + writeFileSync(join(dir,'scope-migrated.json'),migratedRaw);await command(['push',join(dir,'scope-migrated.json'),remote+'/scope.json']);const restored=await hookDevice(usb,'migration-rollback',{migrationId:migration.migrationId,scopeRevision:migration.scopeRevision},true);const outcome=unwrap(restored);assert.equal(outcome.scopeRevision,createHash('sha256').update(originalScope).digest('hex'));assert.equal(await su('cat '+remote+'/scope.json'),originalScope.trimEnd());assert.ok((await su('sha256sum '+remote+'/scope.json')).startsWith(outcome.scopeRevision+' '),'actual restored bytes must match the original raw hash');return {exactHash:outcome.scopeRevision,concurrentEditRejected:true};}); +}catch(error){report.failure={message:(error as Error).message,stack:(error as Error).stack};console.error('FAIL '+(error as Error).message);process.exitCode=1;} +finally{ + if(installed){await command(['shell','am','force-stop',pkg]).catch(()=>{});await su('pm uninstall '+pkg).catch(()=>{});} + if(usb&&host?.exitCode===null){for(const peer of [lan,usb].filter(Boolean))await tool('devices',{action:'disconnect',deviceId:peer.deviceId,connectionId:peer.connectionId},true).catch(()=>{});} + if(host&&host.exitCode===null){host.kill();await new Promise(r=>{host!.once('exit',()=>r());setTimeout(r,3000);});} + if(started)await su(`touch ${remote}/stop`).catch(()=>{}); + if(deviceChild&&deviceChild.exitCode===null){await new Promise(r=>{deviceChild!.once('exit',()=>r());setTimeout(r,3000);});if(deviceChild.exitCode===null)deviceChild.kill();} + if(host)for(const port of [18088,18761]){const rows=await command(['reverse','--list']).catch(()=>'');if(rows.split('\n').some(line=>line.trim().endsWith(`tcp:${port} tcp:${port}`)))await command(['reverse','--remove','tcp:'+port]).catch(()=>{});} + if(baseline)try{await pause(500);const after=await baselineNow();assert.equal(after.hashes,baseline.hashes);assert.deepEqual(after.sessions,baseline.sessions);assert.equal(after.processes,baseline.processes);assert.equal(after.reverse,baseline.reverse);report.sceneUnchanged=true;}catch(error){report.sceneUnchanged=false;report.protectionError=(error as Error).message;process.exitCode=1;} + report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({passed:report.cases.length,failure:report.failure?.message,sceneUnchanged:report.sceneUnchanged,report:join(dir,'report.json')})); +} diff --git a/tools/verify_v132_p5_stdio.sh b/tools/verify_v132_p5_stdio.sh new file mode 100644 index 0000000..2a16181 --- /dev/null +++ b/tools/verify_v132_p5_stdio.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Host-only regression. Real Android acceptance is the separate explicit-serial TypeScript tool. +set -euo pipefail +cd "$(dirname "$0")/.." +if [ ! -f device/daemon/build/device-rpc-fixture-classpath.json ]; then + echo 'RESULT:SKIP offline Kotlin classpath unavailable; no device fallback' + exit 0 +fi +(cd daemon && node test/run.mjs test/device_stdio.test.ts) +echo 'RESULT:PASS P5 USB stdio protocol/auth/large frames/unsupported' From efe8e78e984f0965792f09d537d41e4877bbb65a Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:33:20 +0800 Subject: [PATCH 19/24] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90P5=E6=B2=99?= =?UTF-8?q?=E7=9B=92=E9=AA=8C=E6=94=B6=E5=B9=B6=E4=BF=AE=E5=A4=8D=E6=8D=95?= =?UTF-8?q?=E8=8E=B7=E4=B8=B2=E6=97=8F=E4=B8=8EUSB=E5=B8=A7=E6=8D=9F?= =?UTF-8?q?=E5=9D=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- agent/src/bootstrap/agent_main.c | 2 +- agent/src/bootstrap/early_plan.cpp | 7 +- agent/src/capture/capture.c | 13 +++- daemon/src/MAP.md | 4 + daemon/src/device_protocol.ts | 2 +- daemon/src/mcp.ts | 2 +- daemon/src/transport/adb_device.ts | 5 +- daemon/src/transport/stdio_armor.ts | 7 ++ daemon/test/device_stdio.test.ts | 17 +++-- daemon/test/stdio_armor.test.ts | 19 +++++ device/MAP.md | 4 + .../src/main/java/com/adh/core/DeviceStdio.kt | 22 ++++++ .../test/java/com/adh/core/DeviceStdioTest.kt | 18 +++++ .../com/adh/daemon/device/DeviceIdentity.kt | 2 +- .../com/adh/daemon/device/DeviceRpcRelay.kt | 9 ++- .../java/com/adh/daemon/P5DeviceFixture.kt | 6 +- .../com/adh/daemon/device/DeviceRpcFixture.kt | 11 +++ device/p5sandbox/src/main/cpp/CMakeLists.txt | 1 + device/p5sandbox/src/main/cpp/fixture.cpp | 32 +++++--- device/p5sandbox/src/main/cpp/target.c | 1 + .../java/com/adh/p5sandbox/ProbeService.java | 40 +++++++++- docs/P5_ANDROID_ACCEPTANCE.md | 46 +++++++++++- docs/P5_HOOK_PLANS.md | 2 + docs/PROGRESS.md | 8 ++ docs/mcp-tools.md | 2 +- tools/MAP.md | 4 + tools/p5_final_cases.ts | 73 +++++++++++++++++++ tools/p5_isolated_host.ts | 7 +- tools/verify_p5_device.ts | 43 ++++++++--- tools/verify_v132_p5_stdio.sh | 2 +- 30 files changed, 357 insertions(+), 54 deletions(-) create mode 100644 daemon/src/transport/stdio_armor.ts create mode 100644 daemon/test/stdio_armor.test.ts create mode 100644 device/core/src/main/java/com/adh/core/DeviceStdio.kt create mode 100644 device/core/src/test/java/com/adh/core/DeviceStdioTest.kt create mode 100644 tools/p5_final_cases.ts diff --git a/agent/src/bootstrap/agent_main.c b/agent/src/bootstrap/agent_main.c index b0d96ca..c9a9009 100644 --- a/agent/src/bootstrap/agent_main.c +++ b/agent/src/bootstrap/agent_main.c @@ -130,7 +130,7 @@ static void report(int fd) { if (adh_self_starttime_ticks(ticks, sizeof(ticks))) snprintf(generation, sizeof(generation), "\"starttimeTicks\":\"%s\",", ticks); - char hello[4096]; + char hello[8192]; snprintf(hello, sizeof(hello), "{\"t\":\"hello\",\"agentVer\":\"%s\",\"pid\":%d,\"uid\":%d," "%s\"package\":\"%s\",\"process\":\"%s\",\"abi\":\"%s\",\"android\":\"%s\",\"sdk\":%s," diff --git a/agent/src/bootstrap/early_plan.cpp b/agent/src/bootstrap/early_plan.cpp index c216dde..2bcbbf1 100644 --- a/agent/src/bootstrap/early_plan.cpp +++ b/agent/src/bootstrap/early_plan.cpp @@ -8,7 +8,9 @@ extern "C" void adh_agent_set_policy(const char*); extern "C" int adh_agent_copy_owner(void); extern "C" void json_escape(const char*,char*,size_t); -static char status[2048]="null"; +static char status[6144]="null"; +// Bounded last capture receipt; counters are evidence, unconditional ok is not a verdict. +static char capture_receipt[2048]="null"; static char last_error[256]=""; static bool attempted=false; static int apply(const AdhEarlyStep& step,int* hookId,void*){ @@ -17,6 +19,7 @@ static int apply(const AdhEarlyStep& step,int* hookId,void*){ adh_cmd_capture_start(fd,"early-cache",step.a,step.b,step.c); auto size=lseek(fd,0,SEEK_END);if(size<5||size>8192||lseek(fd,0,SEEK_SET)<0){close(fd);return -1;}char data[8193]{};auto n=read(fd,data,size_t(size));close(fd);if(n!=size)return -1; const auto* h=reinterpret_cast(data);size_t len=(size_t(h[0])<<24)|(size_t(h[1])<<16)|(size_t(h[2])<<8)|h[3];if(len+5!=size_t(size)||h[4]!=1)return -1; + if(len>=sizeof(capture_receipt))return -1;memcpy(capture_receipt,data+5,len);capture_receipt[len]=0; // This response contains install counters only, except sysModules. Count positive counters, // never the agent's unconditional ok:true or the number of requested system modules. int installed=0;const char* p=data+5;while((p=strstr(p,"\":"))){const char* end=p;const char* begin=end;while(begin>data+5&&begin[-1]!='"')begin--;bool modules=size_t(end-begin)==10&&!memcmp(begin,"sysModules",10);p+=2;while(*p==' ')p++;if(*p>='0'&&*p<='9'){char* next=nullptr;long v=strtol(p,&next,10);if(!modules&&v>0&&v<100000)installed+=int(v);p=next;}} @@ -28,6 +31,6 @@ extern "C" __attribute__((visibility("default"))) int adh_agent_apply_early_v1(c if(!adh_early_parse(wire,size,package,uint32_t(getuid()),actualAgentSha,uint64_t(time(nullptr)),plan)){snprintf(status,sizeof(status),"{\"state\":\"rejected\",\"phase\":\"post-specialize-before-agent-start\"}");return 0;} char flags[64];snprintf(flags,sizeof(flags),"d=%d,h=%d,s=%d,a=%d,t=%d,e=%d,y=%d",!!(plan.families&1),!!(plan.families&2),!!(plan.families&4),!!(plan.families&8),!!(plan.families&16),!!(plan.families&32),!!(plan.families&64));adh_agent_set_policy(flags); auto result=adh_early_run(plan,apply,nullptr);std::string steps;for(unsigned n=0;ntypeof value==='string'&&/^[a export class DeviceError extends OperationError {} export function deviceFail(code:string,message:string,uncertain=false):never{throw new DeviceError(code,message,uncertain);} export function deviceMethodMode(method:string){if(DEVICE_READ_METHODS.has(method))return 'read';if(DEVICE_WRITE_METHODS.has(method))return 'write';return deviceFail('UNSUPPORTED_METHOD','device method is not supported; no shell/ADB fallback was attempted');} -export const DEVICE_STDIO_COMMAND='CLASSPATH=/data/adb/modules/adh/daemon.apk app_process /system/bin com.adh.daemon.device.DeviceRpcRelay'; +export const DEVICE_STDIO_COMMAND='CLASSPATH=/data/adb/modules/adh/daemon.apk app_process /system/bin com.adh.daemon.device.DeviceRpcRelay --base64'; export interface Bootstrap {schemaVersion:1;deviceId:string;identityFingerprint:string;token:string;stdioVersion?:number} export interface DevicePeer {deviceId:string;bootId:string;daemonInstanceId:string;identityFingerprint:string;info:any;capabilities:{methods:Record;[key:string]:any};protocol:string} export function parseBootstrap(raw:string):Bootstrap { diff --git a/daemon/src/mcp.ts b/daemon/src/mcp.ts index dc0e935..d33d2c7 100644 --- a/daemon/src/mcp.ts +++ b/daemon/src/mcp.ts @@ -406,7 +406,7 @@ export const MCP_TOOLS: { name: string; description: string; inputSchema: any; h ]; // Optional at schema level because reads need no control token; writes enforce it at dispatch. -MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects a raw root relay on enforcing ROMs, never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,usbMode:{type:'string',enum:['forward','stdio']},expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); +MCP_TOOLS.push({name:'devices',description:'Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects an authenticated root stdio/2 relay with bounded Base64 transport on enforcing ROMs (inner RPC unchanged; legacy stdio/1 unsupported), never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','discover','connect','disconnect','pair','info','capabilities','call','reconcile']},transport:{type:'string',enum:['adb','lan']},serial:S,transportId:S,usbMode:{type:'string',enum:['forward','stdio']},expectedDeviceId:S,deviceId:S,connectionId:S,address:S,port:{type:'integer'},label:S,permissions:{type:'array',items:{type:'string',enum:['read','write','manage']}},grantId:S,operationIds:{type:'array',items:S},method:S,params:{type:'object'},bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},budgetMs:{type:'integer'}}},handler:deviceAction}); MCP_TOOLS.push({name:'hook_plans',description:'Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device.',inputSchema:{type:'object',properties:{action:{type:'string',enum:['list','get','validate','put','import-legacy','preflight','apply','run','observe','undo','early-prepare','early-status','early-stage','early-revoke','migration-preview','migration-apply','migration-rollback']},plan:{type:'object'},digest:S,expectedLibraryRevision:{type:'integer'},session:S,runId:S,id:S,package:S,scope:{type:'object'},settings:{type:'object'},deviceId:S,connectionId:S,bootId:S,daemonInstanceId:S,expectedDeviceRevision:{type:'integer'},binding:{type:'object'},expiresAt:{type:'integer'},offline:{type:'string',enum:['keep-until-expiry']},expectedCacheRevision:{type:'integer'},deploymentId:S,scopeRevision:S,migrationId:S}},handler:a=>hookPlanAction(a,name=>MCP_MAP.get(name))}); for (const tool of MCP_TOOLS) { diff --git a/daemon/src/transport/adb_device.ts b/daemon/src/transport/adb_device.ts index 5876730..077ac13 100644 --- a/daemon/src/transport/adb_device.ts +++ b/daemon/src/transport/adb_device.ts @@ -1,3 +1,4 @@ +import {armoredStdio} from './stdio_armor.ts'; import { execFile,spawn } from 'node:child_process'; import { Duplex } from 'node:stream'; import { promisify } from 'node:util'; @@ -44,11 +45,11 @@ export class AdbDeviceTransport { const prefix=selected.transportId?['-t',selected.transportId]:['-s',selected.serial]; checkpoint();const bootstrap=parseBootstrap(await this.run([...prefix,'exec-out','su','-c',`cat ${DEVICE_BOOTSTRAP}`],{maxBuffer:8192})); if(usbMode==='stdio'){ - if(bootstrap.stdioVersion!==1)deviceFail('UNSUPPORTED_TRANSPORT','device does not advertise USB stdio/1; no fallback attempted'); + if(bootstrap.stdioVersion!==2)deviceFail('UNSUPPORTED_TRANSPORT','device does not advertise USB stdio/2; no fallback attempted'); // KernelSU's fd wrapper can transform binary control bytes. Negotiate before any RPC. const help=await this.run([...prefix,'exec-out','su','--help']);const suFlags=help.includes('--no-wrapper')?['-W']:[]; const ctx=executionContext.getStore();checkpoint();const effect=ctx?.dispatched({kind:'adb',action:'device.stdio.connect'});let rpc:DeviceRpcClient|undefined; - try{rpc=new DeviceRpcClient(this.stdio([...prefix,'shell','-T','su',...suFlags,'-c',"'"+DEVICE_STDIO_COMMAND+"'"]),onClose);const id=randomUUID(),nonce=randomBytes(32).toString('hex');const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:bootstrap.token}},undefined,undefined,5000,id);const peer=verifyHello(reply,bootstrap,id,nonce);ctx?.acknowledged(false,effect); + try{rpc=new DeviceRpcClient(armoredStdio(this.stdio([...prefix,'shell','-T','su',...suFlags,'-c',"'"+DEVICE_STDIO_COMMAND+"'"])),onClose);const id=randomUUID(),nonce=randomBytes(32).toString('hex');const reply=await rpc.request('device.hello',{clientNonce:nonce,authentication:{type:'usb-token',credential:bootstrap.token}},undefined,undefined,5000,id);const peer=verifyHello(reply,bootstrap,id,nonce);ctx?.acknowledged(false,effect); return {id:randomUUID(),transport:'adb',usbMode,serial:selected.serial,transportId:selected.transportId,port:0,peer,rpc,close:async()=>{rpc!.close();return {removed:true,confirmed:true,reason:'owned stdio stream closed; no forward created'};}}; }catch(error){rpc?.close();ctx?.acknowledged(false,effect,true);throw error;} } diff --git a/daemon/src/transport/stdio_armor.ts b/daemon/src/transport/stdio_armor.ts new file mode 100644 index 0000000..bf70b28 --- /dev/null +++ b/daemon/src/transport/stdio_armor.ts @@ -0,0 +1,7 @@ +import {Duplex,Transform} from 'node:stream'; +import {DEVICE_FRAME_MAX} from '../device_protocol.ts'; +const MAX_LINE=Math.ceil((DEVICE_FRAME_MAX+4)/3)*4; +/** Bounded transforms: Windows adb shell may expand LF even with -T and su -W. */ +export function stdioEncoder(){let buffer=Buffer.alloc(0);return new Transform({transform(chunk,_encoding,done){try{buffer=Buffer.concat([buffer,chunk]);while(buffer.length>=4){const n=buffer.readUInt32BE();if(n<1||n>DEVICE_FRAME_MAX)throw Error('stdio frame limit');if(buffer.lengthDEVICE_FRAME_MAX+4)throw Error('stdio frame limit');done();}catch(error){done(error as Error);}},flush(done){done(buffer.length?Error('partial stdio frame'):undefined);}});} +export function stdioDecoder(){let buffer=Buffer.alloc(0);return new Transform({transform(chunk,_encoding,done){try{buffer=Buffer.concat([buffer,chunk]);let end:number;while((end=buffer.indexOf(10))>=0){if(end>MAX_LINE+1)throw Error('stdio line limit');let line=buffer.subarray(0,end).toString('latin1');buffer=buffer.subarray(end+1);if(line.endsWith('\r'))line=line.slice(0,-1);if(!line.length||line.length>MAX_LINE||line.length%4||!/^[A-Za-z0-9+/]+={0,2}$/.test(line))throw Error('invalid stdio armor');const frame=Buffer.from(line,'base64');if(frame.toString('base64')!==line||frame.length<5||frame.readUInt32BE()!==frame.length-4||frame.length>DEVICE_FRAME_MAX+4)throw Error('invalid stdio frame');this.push(frame);}if(buffer.length>MAX_LINE+1)throw Error('stdio line limit');done();}catch(error){done(error as Error);}},flush(done){done(buffer.length?Error('partial stdio armor'):undefined);}});} +export function armoredStdio(raw:Duplex){const encoder=stdioEncoder(),decoder=stdioDecoder();encoder.pipe(raw);raw.pipe(decoder);const stream=Duplex.from({readable:decoder,writable:encoder});raw.on('error',error=>stream.destroy(error));raw.on('close',()=>{if(!stream.destroyed)stream.destroy();});stream.on('close',()=>{raw.destroy();encoder.destroy();decoder.destroy();});return stream;} diff --git a/daemon/test/device_stdio.test.ts b/daemon/test/device_stdio.test.ts index 1215074..d9a11cb 100644 --- a/daemon/test/device_stdio.test.ts +++ b/daemon/test/device_stdio.test.ts @@ -1,21 +1,28 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import net from 'node:net'; +import {spawn} from 'node:child_process'; +import {Duplex,Transform} from 'node:stream'; import {existsSync,readFileSync,writeFileSync} from 'node:fs'; -import {join} from 'node:path'; +import {join,delimiter} from 'node:path'; import {AdbDeviceTransport} from '../src/transport/adb_device.ts'; import {startDeviceFixture,FakeAdb,jvmManifest} from './device_fixture.ts'; test('USB stdio authenticates the production Kotlin dispatcher and carries large binary-framed replies without forwards',{skip:existsSync(jvmManifest)?false:'build offline JVM fixture; no real device fallback'},async()=>{ const phone=await startDeviceFixture(),adb=new FakeAdb();adb.add('stdio-fixture','77',phone);const opens:string[][]=[];let connection:any; const runner=async(args:string[])=>args.slice(2).join(' ')==='exec-out su --help'?'KernelSU --no-wrapper':adb.run(args); - const adapter=new AdbDeviceTransport(runner,async()=>{throw Error('stdio must never dial a forward');},args=>{opens.push(args);return net.connect({host:'127.0.0.1',port:phone.port});}); + const adapter=new AdbDeviceTransport(runner,async()=>{throw Error('stdio must never dial a forward');},args=>{ + opens.push(args);const cp=JSON.parse(readFileSync(jvmManifest,'utf8')); + const child=spawn(process.env.JAVA_HOME?join(process.env.JAVA_HOME,'bin','java.exe'):'java',['-cp',cp.join(delimiter),'com.adh.daemon.device.DeviceStdioFixture',String(phone.port)],{windowsHide:true,stdio:['pipe','pipe','pipe']}); + // Reproduce the measured Windows adb stdout LF expansion, including split byte streams. + const output=new Transform({transform(chunk,_encoding,done){this.push(Buffer.from(chunk.toString('ascii').replaceAll('\n','\r\n')));done();}});child.stdout.pipe(output);child.stderr.resume(); + const stream=Duplex.from({readable:output,writable:child.stdin});child.on('error',e=>stream.destroy(e));child.on('close',()=>stream.destroy());stream.on('close',()=>{if(child.exitCode===null)child.kill();});return stream; + }); try{ - connection=await adapter.connect('stdio-fixture','77',undefined,'stdio');assert.equal(connection.usbMode,'stdio');assert.equal(connection.peer.deviceId,phone.deviceId);assert.ok(opens[0].includes('-W'));assert.ok(opens[0].includes('-T'));assert.ok(opens[0].at(-1)!.includes('com.adh.daemon.device.DeviceRpcRelay')); + connection=await adapter.connect('stdio-fixture','77',undefined,'stdio');assert.equal(connection.usbMode,'stdio');assert.equal(connection.peer.deviceId,phone.deviceId);assert.ok(opens[0].includes('-W'));assert.ok(opens[0].includes('-T'));assert.ok(opens[0].at(-1)!.includes('com.adh.daemon.device.DeviceRpcRelay --base64')); writeFileSync(join(phone.root,'scope.json'),JSON.stringify({version:19,mode:'allowlist',packages:[],future:'\r\n\u0003'.repeat(12000)})); const peer=connection.peer;const reply=await connection.rpc.request('scope.get',{},{deviceId:peer.deviceId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId});assert.equal(reply.future,undefined);assert.equal(reply.document.future.length,36000);assert.equal(adb.forwards.size,0);assert.ok(!adb.commands.some(c=>c.includes('forward'))); assert.equal((await connection.close()).confirmed,true);connection=undefined; - const file=join(phone.root,'usb-access.json'),legacy=JSON.parse(readFileSync(file,'utf8'));delete legacy.stdioVersion;writeFileSync(file,JSON.stringify(legacy)); + const file=join(phone.root,'usb-access.json'),legacy=JSON.parse(readFileSync(file,'utf8'));legacy.stdioVersion=1;writeFileSync(file,JSON.stringify(legacy)); await assert.rejects(()=>adapter.connect('stdio-fixture','77',undefined,'stdio'),(e:any)=>e.code==='UNSUPPORTED_TRANSPORT');assert.equal(opens.length,1,'legacy devices never silently fall back or start a relay'); }finally{if(connection)await connection.close();await adb.close();await phone.close();} }); diff --git a/daemon/test/stdio_armor.test.ts b/daemon/test/stdio_armor.test.ts new file mode 100644 index 0000000..e828737 --- /dev/null +++ b/daemon/test/stdio_armor.test.ts @@ -0,0 +1,19 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {Readable} from 'node:stream'; +import {stdioEncoder,stdioDecoder} from '../src/transport/stdio_armor.ts'; +import {DEVICE_FRAME_MAX} from '../src/device_protocol.ts'; +function frame(size:number){const value=Buffer.alloc(size+4);value.writeUInt32BE(size);for(let n=0;n){const chunks:Buffer[]=[];for await(const chunk of stream)chunks.push(chunk);return Buffer.concat(chunks);} +test('stdio armor preserves control bytes and frame headers across arbitrary chunk and CRLF boundaries',async()=>{ + const raw=Buffer.concat(Array.from({length:256},(_,i)=>frame(i+1))); + const encoded=await collect(Readable.from(Array.from(raw,n=>Buffer.from([n]))).pipe(stdioEncoder())); + const windows=Buffer.from(encoded.toString('ascii').replaceAll('\n','\r\n')); + assert.deepEqual(await collect(Readable.from(Array.from(windows,n=>Buffer.from([n]))).pipe(stdioDecoder())),raw); +}); +test('stdio armor carries a maximum frame and refuses malformed, truncated, non-ASCII and oversized peers',async()=>{ + const raw=frame(DEVICE_FRAME_MAX),encoded=await collect(Readable.from([raw]).pipe(stdioEncoder()));assert.deepEqual(await collect(Readable.from([encoded]).pipe(stdioDecoder())),raw); + for(const bytes of [Buffer.from('!!!!\n'),Buffer.from('AAAAAA==\n'),Buffer.from('AAAAAQ==\n'),Buffer.from('AAAAAQE='),Buffer.from('A'.repeat(1_400_000)+'\n'),Buffer.from([0xc1,0x41,0x41,0x41,10])])await assert.rejects(()=>collect(Readable.from([bytes]).pipe(stdioDecoder()))); + await assert.rejects(()=>collect(Readable.from([Buffer.from([0,16,0,1])]).pipe(stdioEncoder()))); + await assert.rejects(()=>collect(Readable.from([Buffer.from([0,0])]).pipe(stdioEncoder()))); +}); diff --git a/device/MAP.md b/device/MAP.md index 97b4308..58a19a1 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -141,3 +141,7 @@ JVM `DeviceDomainTest` tests recovery/CAS/storage errors; `DeviceRpcFixture` exp ## P4 authenticated LAN (2026-11-16) `DeviceTls` builds a self-signed installation certificate using public JCA/JSSE, independent of imported system CAs. `DeviceNetwork` restores only explicitly enabled TLS configuration; its default is disabled. `DevicePairings` persists bounded public grants and revocations, closes revoked streams and fails closed on storage errors. The same DeviceRpcSession negotiates USB-token or LAN client-signature authentication, then dispatches through DeviceOperations with a per-request authorization guard inside the domain lock. Capabilities are filtered by grant; no TCP plaintext, remote root shell, HTTP/MCP, database or analysis is introduced. Existing Binder numbering stays v19; its API was not changed this slice. See docs/P4_LAN_AUTH.md for USB-first enrollment, permissions, recovery and unsupported legacy capabilities. Real Android TLS/SELinux and device effects remain a separate hardware gate. + +### P5 stdio/2 与最终验收(2026-11-16) + +`:core` 的 DeviceStdio.kt 只做有界帧/外层 Base64 编解码,供 :daemon 的 root DeviceRpcRelay 使用,处理 Windows ADB 的 CRLF 转换;不承载分析。DeviceIdentity 保留身份/凭据并标记 stdioVersion=2。opt-in p5Fixture 和 p5sandbox 的隔离边界、真实七族探针及绑定拒绝见 docs/P5_ANDROID_ACCEPTANCE.md;普通 APK 不含 P5 fixture。 diff --git a/device/core/src/main/java/com/adh/core/DeviceStdio.kt b/device/core/src/main/java/com/adh/core/DeviceStdio.kt new file mode 100644 index 0000000..9b06c86 --- /dev/null +++ b/device/core/src/main/java/com/adh/core/DeviceStdio.kt @@ -0,0 +1,22 @@ +package com.adh.core +import java.io.* +import java.util.Base64 + +/** stdio/2 armor only; the inner adh.device/1 frame is byte-for-byte unchanged. */ +object DeviceStdio { + private const val MAX_LINE=((DeviceRpc.MAX_FRAME+4+2)/3)*4 + fun frame(input:InputStream):ByteArray? { + val first=input.read();if(first<0)return null + val data=DataInputStream(input);val size=(first shl 24) or (data.readUnsignedByte() shl 16) or (data.readUnsignedByte() shl 8) or data.readUnsignedByte() + require(size in 1..DeviceRpc.MAX_FRAME) + val bytes=ByteArray(size+4);bytes[0]=first.toByte();bytes[1]=(size ushr 16).toByte();bytes[2]=(size ushr 8).toByte();bytes[3]=size.toByte();data.readFully(bytes,4,size);return bytes + } + fun read(input:InputStream):ByteArray? { + val line=ByteArrayOutputStream();while(true){val b=input.read();if(b<0){if(line.size()==0)return null;throw EOFException("partial stdio frame")};if(b==10)break;require(line.size()DataOutputStream(out).apply{writeInt(n);write(ByteArray(n){it.toByte()})}}.toByteArray() + @Test fun allHeaderLowBytesAndBinaryPayloadsSurviveWindowsLines(){ + val bytes=ByteArrayOutputStream();val frames=(1..256).map{frame(it)} + frames.forEach{DeviceStdio.write(bytes,it)} + val windows=bytes.toString("US-ASCII").replace("\n","\r\n").byteInputStream() + frames.forEach{assertArrayEquals(it,DeviceStdio.read(windows))};assertNull(DeviceStdio.read(windows)) + } + @Test fun maximumFrameSurvivesWithoutTruncation(){val expected=frame(DeviceRpc.MAX_FRAME);val encoded=ByteArrayOutputStream();DeviceStdio.write(encoded,expected);assertArrayEquals(expected,DeviceStdio.read(encoded.toByteArray().inputStream()))} + @Test fun malformedTruncatedAndOversizeFramesAreRefused(){ + for(text in listOf("!!!!\n","AAAAAA==\n","AAAAAQ==\n","AAAAAwAB\n","AAAAAQE=","A".repeat(1_400_000)+"\n"))assertTrue(text.take(24),runCatching{DeviceStdio.read(text.byteInputStream())}.isFailure) + } +} diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt index 147ec6c..0065265 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceIdentity.kt @@ -49,7 +49,7 @@ internal class DeviceIdentity(private val files: DeviceFiles, val bootId: String check(access.getInt("schemaVersion") == 1 && access.getString("deviceId") == deviceId && access.getString("identityFingerprint") == fingerprint) { "USB bootstrap identity mismatch" } token = access.getString("token"); check(Regex("[a-f0-9]{64}").matches(token)) // Preserve identity and credential when adding transport capability metadata. - if(access.optInt("stdioVersion")!=1)files.write(accessFile,access.put("stdioVersion",1).toString()) + if(access.optInt("stdioVersion")!=2)files.write(accessFile,access.put("stdioVersion",2).toString()) } fun authenticated(candidate: String): Boolean = java.security.MessageDigest.isEqual(token.toByteArray(), candidate.toByteArray()) fun sign(bytes: ByteArray): ByteArray = Signature.getInstance("SHA256withRSA").run { initSign(privateKey); update(bytes); sign() } diff --git a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt index 09141be..e3d7247 100644 --- a/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt +++ b/device/daemon/src/main/java/com/adh/daemon/device/DeviceRpcRelay.kt @@ -3,6 +3,8 @@ import android.net.LocalSocket import android.net.LocalSocketAddress import android.os.Process import com.adh.core.DeviceRpc +import com.adh.core.DeviceStdio +import java.io.BufferedInputStream import java.io.FileDescriptor import java.io.FileInputStream import java.io.FileOutputStream @@ -11,13 +13,14 @@ import java.io.FileOutputStream object DeviceRpcRelay { @JvmStatic fun main(args:Array){ check(Process.myUid()==0) - val name=if(args.isEmpty())DeviceRpc.SOCKET_NAME else args.single().also{require(it.matches(Regex("adh_p5_[a-f0-9]{12}")))} + val armored=args.firstOrNull()=="--base64";val names=if(armored)args.drop(1)else args.toList() + val name=if(names.isEmpty())DeviceRpc.SOCKET_NAME else names.single().also{require(it.matches(Regex("adh_p5_[a-f0-9]{12}")))} LocalSocket().use { socket-> socket.connect(LocalSocketAddress(name,LocalSocketAddress.Namespace.ABSTRACT));socket.soTimeout=60000;check(socket.peerCredentials.uid==0) // app_process redirects System.out to logcat; RPC must use the raw descriptors. val output=FileOutputStream(FileDescriptor.out) - Thread({try{FileInputStream(FileDescriptor.`in`).copyTo(socket.outputStream);socket.shutdownOutput()}catch(_:Exception){runCatching{socket.close()}}},"adh-usb-stdin").apply{isDaemon=true;start()} - try{socket.inputStream.copyTo(output);output.flush()}catch(_:Exception){/* close, never retry */} + Thread({try{val input=BufferedInputStream(FileInputStream(FileDescriptor.`in`));if(armored){while(true){val frame=DeviceStdio.read(input)?:break;socket.outputStream.write(frame)}}else input.copyTo(socket.outputStream);socket.shutdownOutput()}catch(_:Exception){runCatching{socket.close()}}},"adh-usb-stdin").apply{isDaemon=true;start()} + try{val input=BufferedInputStream(socket.inputStream);if(armored){while(true){val frame=DeviceStdio.frame(input)?:break;DeviceStdio.write(output,frame)}}else socket.inputStream.copyTo(output);output.flush()}catch(_:Exception){/* close, never retry */} } } } diff --git a/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt index 4485ac4..c2c96ed 100644 --- a/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt +++ b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt @@ -26,7 +26,7 @@ object P5DeviceFixture { val scope=ScopeDocuments(File(root,"scope.json"),files) val identity=DeviceIdentity(files,File("/proc/sys/kernel/random/boot_id").readText().trim()) val operations=DeviceOperations(identity,files,DeviceBackend { method,params->when(method){ - "device.info"->JSONObject().put("model",android.os.Build.MODEL).put("sdk",android.os.Build.VERSION.SDK_INT).put("isolatedFixture",true) + "device.info"->JSONObject().put("model",android.os.Build.MODEL).put("sdk",android.os.Build.VERSION.SDK_INT).put("isolatedFixture",true).put("padding",params.optString("padding").also{require(it.length<=512)}) "scope.get"->scope.snapshot() "scope.patch"->scope.patch(params) else->throw DeviceFault("UNSUPPORTED_METHOD","fixture never dispatches Android device control") @@ -37,7 +37,9 @@ object P5DeviceFixture { val broker=EarlyPlanBroker(cache,name+"_early");val rpc=LocalDeviceRpcServer(operations,name){it.printStackTrace()} File(root,"ready.json").writeText(JSONObject().put("pid",Process.myPid()).put("uid",app.uid).put("agentPath",agent.path).put("deviceId",identity.deviceId).toString()) val deadline=System.nanoTime()+900_000_000_000L;val handler=Handler(Looper.getMainLooper()) - val stop=object:Runnable {override fun run(){if(File(root,"stop").exists()||System.nanoTime()>deadline){rpc.close();broker.close();network.close();kotlin.system.exitProcess(0)};handler.postDelayed(this,250)}};handler.post(stop) + val stop=object:Runnable {override fun run(){ + val request=File(root,"stacks-request");if(request.exists()){request.delete();File(root,"stacks.txt").writeText(Thread.getAllStackTraces().entries.joinToString("\n\n"){(thread,stack)->thread.name+" "+thread.state+"\n"+stack.joinToString("\n")})} + if(File(root,"stop").exists()||System.nanoTime()>deadline){rpc.close();broker.close();network.close();kotlin.system.exitProcess(0)};handler.postDelayed(this,250)}};handler.post(stop) Looper.loop() } } diff --git a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt index 24050b4..0e8fa9e 100644 --- a/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt +++ b/device/daemon/src/test/java/com/adh/daemon/device/DeviceRpcFixture.kt @@ -50,3 +50,14 @@ object DeviceRpcFixture { while (!server.isClosed) { val client = server.accept(); workers.execute { client.use { try { DeviceRpcSession(operations).serve(it.getInputStream(), it.getOutputStream()) } catch (_: Exception) { } } } } } } + +/** Pure JVM stdio/2 peer. Uses the production armor codec, only connects to the owned loopback fixture. */ +object DeviceStdioFixture { + @JvmStatic fun main(args:Array){ + require(args.size==1);val port=args[0].toInt();require(port in 1..65535) + java.net.Socket("127.0.0.1",port).use{socket-> + Thread({try{val input=java.io.BufferedInputStream(System.`in`);while(true){val frame=com.adh.core.DeviceStdio.read(input)?:break;socket.getOutputStream().write(frame)};socket.shutdownOutput()}catch(_:Exception){socket.close()}},"stdio-fixture-input").apply{isDaemon=true;start()} + val input=java.io.BufferedInputStream(socket.getInputStream());while(true){val frame=com.adh.core.DeviceStdio.frame(input)?:break;com.adh.core.DeviceStdio.write(System.out,frame)} + } + } +} diff --git a/device/p5sandbox/src/main/cpp/CMakeLists.txt b/device/p5sandbox/src/main/cpp/CMakeLists.txt index bdccf7e..c82a7af 100644 --- a/device/p5sandbox/src/main/cpp/CMakeLists.txt +++ b/device/p5sandbox/src/main/cpp/CMakeLists.txt @@ -4,4 +4,5 @@ set(CMAKE_CXX_STANDARD 17) add_library(p5target SHARED target.c) target_compile_options(p5target PRIVATE -fno-builtin) add_library(p5fixture SHARED fixture.cpp) +target_include_directories(p5fixture PRIVATE ../../../../../agent/src/bootstrap) target_link_libraries(p5fixture dl log) diff --git a/device/p5sandbox/src/main/cpp/fixture.cpp b/device/p5sandbox/src/main/cpp/fixture.cpp index 3070309..be74392 100644 --- a/device/p5sandbox/src/main/cpp/fixture.cpp +++ b/device/p5sandbox/src/main/cpp/fixture.cpp @@ -1,19 +1,29 @@ #include #include +#include #include #include #include #include #include -extern "C" JNIEXPORT jstring JNICALL Java_com_adh_p5sandbox_ProbeService_bootstrap(JNIEnv* env,jclass,jstring dir,jstring wire,jstring sha){ - const char* d=env->GetStringUTFChars(dir,nullptr);const char* w=env->GetStringUTFChars(wire,nullptr);const char* hash=env->GetStringUTFChars(sha,nullptr); - std::string directory=d;void* target=dlopen((directory+"/libp5target.so").c_str(),RTLD_NOW);void* agent=dlopen((directory+"/libadh_agent.so").c_str(),RTLD_NOW); - if(!target||!agent){env->ThrowNew(env->FindClass("java/lang/IllegalStateException"),dlerror());return nullptr;} - auto probe=reinterpret_cast(dlsym(target,"p5_target_probe"));auto package=reinterpret_cast(dlsym(agent,"adh_agent_set_package"));auto policy=reinterpret_cast(dlsym(agent,"adh_agent_set_policy"));auto early=reinterpret_cast(dlsym(agent,"adh_agent_apply_early_v1"));auto start=reinterpret_cast(dlsym(agent,"adh_agent_start")); - if(!probe||!package||!policy||!early||!start){env->ThrowNew(env->FindClass("java/lang/IllegalStateException"),"missing fixture exports");return nullptr;} - std::ifstream input(w,std::ios::binary);std::vector bytes((std::istreambuf_iterator(input)),std::istreambuf_iterator()); - package("com.adh.p5sandbox");policy("d=0,h=0,s=0,a=0,t=0,e=0,y=0");int result=bytes.empty()?-1:early(bytes.data(),bytes.size(),"com.adh.p5sandbox",hash); - // The only getpid import in the target is exercised before starting any Host channel. - long value=probe();char receipt[256];snprintf(receipt,sizeof(receipt),"{\"pid\":%d,\"uid\":%d,\"wireBytes\":%zu,\"earlyApply\":%d,\"probeReturn\":%ld,\"probeBeforeAgentStart\":true}",getpid(),getuid(),bytes.size(),result,value); - start();env->ReleaseStringUTFChars(dir,d);env->ReleaseStringUTFChars(wire,w);env->ReleaseStringUTFChars(sha,hash);return env->NewStringUTF(receipt); +#include "early_wire.h" +static void (*start_agent)()=nullptr; +static int (*system_probe)(const char*)=nullptr; +static jstring fail(JNIEnv* env,const char* message){env->ThrowNew(env->FindClass("java/lang/IllegalStateException"),message);return nullptr;} +extern "C" JNIEXPORT jstring JNICALL Java_com_adh_p5sandbox_ProbeService_bootstrap(JNIEnv* env,jclass,jstring dir,jstring wire,jstring sha,jboolean deferred){ + const char* d=env->GetStringUTFChars(dir,nullptr);const char* w=env->GetStringUTFChars(wire,nullptr);const char* expected=env->GetStringUTFChars(sha,nullptr); + std::string directory=d,path=w,wanted=expected;env->ReleaseStringUTFChars(dir,d);env->ReleaseStringUTFChars(wire,w);env->ReleaseStringUTFChars(sha,expected); + // Hash the actual loaded file, never trust the test driver's supplied digest. + int fd=open((directory+"/libadh_agent.so").c_str(),O_RDONLY|O_CLOEXEC);if(fd<0)return fail(env,"open Agent failed");std::string actual=adh_sha_fd(fd);close(fd); + if(actual.empty()||actual!=wanted)return fail(env,"actual Agent SHA mismatch"); + void* target=dlopen((directory+"/libp5target.so").c_str(),RTLD_NOW);void* agent=dlopen((directory+"/libadh_agent.so").c_str(),RTLD_NOW); + if(!target||!agent)return fail(env,dlerror()); + auto probe=reinterpret_cast(dlsym(target,"p5_target_probe"));system_probe=reinterpret_cast(dlsym(target,"p5_system_probe"));auto package=reinterpret_cast(dlsym(agent,"adh_agent_set_package"));auto policy=reinterpret_cast(dlsym(agent,"adh_agent_set_policy"));auto early=reinterpret_cast(dlsym(agent,"adh_agent_apply_early_v1"));start_agent=reinterpret_cast(dlsym(agent,"adh_agent_start")); + if(!probe||!system_probe||!package||!policy||!early||!start_agent)return fail(env,"missing fixture exports"); + std::ifstream input(path,std::ios::binary);std::vector bytes((std::istreambuf_iterator(input)),std::istreambuf_iterator());if(bytes.size()>32768)return fail(env,"wire too large"); + package("com.adh.p5sandbox");policy("d=0,h=0,s=0,a=0,t=0,e=0,y=0");int result=bytes.empty()?-1:early(bytes.data(),bytes.size(),"com.adh.p5sandbox",actual.c_str());long value=probe(); + char receipt[512];snprintf(receipt,sizeof(receipt),"{\"pid\":%d,\"uid\":%d,\"wireBytes\":%zu,\"earlyApply\":%d,\"probeReturn\":%ld,\"actualAgentSha\":\"%s\",\"probeBeforeAgentStart\":true}",getpid(),getuid(),bytes.size(),result,value,actual.c_str()); + if(!deferred)start_agent();return env->NewStringUTF(receipt); } +extern "C" JNIEXPORT void JNICALL Java_com_adh_p5sandbox_ProbeService_startAgent(JNIEnv*,jclass){if(start_agent)start_agent();} +extern "C" JNIEXPORT jint JNICALL Java_com_adh_p5sandbox_ProbeService_systemProbe(JNIEnv* env,jclass,jstring path){const char* p=env->GetStringUTFChars(path,nullptr);int rc=system_probe?system_probe(p):-9;env->ReleaseStringUTFChars(path,p);return rc;} diff --git a/device/p5sandbox/src/main/cpp/target.c b/device/p5sandbox/src/main/cpp/target.c index b748c6b..15ff9c6 100644 --- a/device/p5sandbox/src/main/cpp/target.c +++ b/device/p5sandbox/src/main/cpp/target.c @@ -1,2 +1,3 @@ #include +__attribute__((visibility("default"),noinline)) int p5_system_probe(const char *path){return access(path,F_OK);} __attribute__((visibility("default"),noinline)) long p5_target_probe(void){return (long)getpid();} diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java index 01ab152..5c367ca 100644 --- a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java @@ -2,19 +2,51 @@ import android.app.*; import android.content.Intent; import android.os.*; -import java.io.File; +import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.security.*; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import javax.crypto.*; +import javax.crypto.spec.*; +import javax.net.ssl.*; +import org.json.JSONObject; -/** No Activity: never brings the sandbox in front of the user's analysis app. */ +/** Opt-in test APK, no Activity and no production configuration access. */ public final class ProbeService extends Service { private boolean started=false; - private static native String bootstrap(String directory,String wire,String sha); + private static native String bootstrap(String directory,String wire,String sha,boolean deferred); + private static native void startAgent(); + private static native int systemProbe(String path); public IBinder onBind(Intent intent){return null;} + private static byte[] data(String marker,String family){return (marker+"_"+family).getBytes(StandardCharsets.UTF_8);} + private static JSONObject crypto(String marker) throws Exception { + JSONObject result=new JSONObject(); + byte[] digest=MessageDigest.getInstance("SHA-256","AndroidOpenSSL").digest(data(marker,"digest"));result.put("digest",digest.length==32); + Mac mac=Mac.getInstance("HmacSHA256","AndroidOpenSSL");mac.init(new SecretKeySpec(new byte[32],"HmacSHA256"));result.put("hmac",mac.doFinal(data(marker,"hmac")).length==32); + SecretKeySpec key=new SecretKeySpec(new byte[16],"AES");byte[] plain=data(marker,"symmetric"),iv=new byte[16];Cipher c=Cipher.getInstance("AES/CBC/PKCS5Padding","AndroidOpenSSL");c.init(Cipher.ENCRYPT_MODE,key,new IvParameterSpec(iv));byte[] enc=c.doFinal(plain);c.init(Cipher.DECRYPT_MODE,key,new IvParameterSpec(iv));result.put("symmetric",Arrays.equals(plain,c.doFinal(enc))); + KeyPairGenerator gen=KeyPairGenerator.getInstance("EC","AndroidOpenSSL");gen.initialize(256);KeyPair pair=gen.generateKeyPair();Signature sig=Signature.getInstance("SHA256withECDSA","AndroidOpenSSL");sig.initSign(pair.getPrivate());sig.update(data(marker,"asymmetric"));byte[] signed=sig.sign();sig.initVerify(pair.getPublic());sig.update(data(marker,"asymmetric"));result.put("asymmetric",sig.verify(signed)); + plain=data(marker,"aead");c=Cipher.getInstance("AES/GCM/NoPadding","AndroidOpenSSL");c.init(Cipher.ENCRYPT_MODE,key,new GCMParameterSpec(128,new byte[12]));enc=c.doFinal(plain);c.init(Cipher.DECRYPT_MODE,key,new GCMParameterSpec(128,new byte[12]));result.put("aead",Arrays.equals(plain,c.doFinal(enc)));return result; + } + private static boolean tls(String marker,int port) throws Exception { + // Fixture loopback only. No external network or changes to the device trust store. + TrustManager[] trust={new X509TrustManager(){public X509Certificate[] getAcceptedIssuers(){return new X509Certificate[0];}public void checkClientTrusted(X509Certificate[] c,String a){}public void checkServerTrusted(X509Certificate[] c,String a){}}}; + SSLContext context=SSLContext.getInstance("TLS");context.init(null,trust,new SecureRandom()); + try(SSLSocket socket=(SSLSocket)context.getSocketFactory().createSocket("127.0.0.1",port)){ + socket.setSoTimeout(5000);socket.startHandshake();byte[] hello=new JSONObject().put("protocol","adh.device/1").put("id",marker+"_tls").put("method","device.hello").toString().getBytes(StandardCharsets.UTF_8); + DataOutputStream out=new DataOutputStream(socket.getOutputStream());out.writeInt(hello.length);out.write(hello);out.flush();DataInputStream in=new DataInputStream(socket.getInputStream());int size=in.readInt();if(size<1||size>4096)throw new IOException("invalid fixture reply");byte[] reply=new byte[size];in.readFully(reply);return new JSONObject(new String(reply,StandardCharsets.UTF_8)).getJSONObject("error").getString("code").equals("AUTH_FAILED"); + } + } public int onStartCommand(Intent intent,int flags,int startId){ NotificationManager manager=getSystemService(NotificationManager.class);manager.createNotificationChannel(new NotificationChannel("p5-test","P5 isolated verification",NotificationManager.IMPORTANCE_LOW)); startForeground(5,new Notification.Builder(this,"p5-test").setContentTitle("ADH P5 isolated test").setSmallIcon(android.R.drawable.ic_menu_info_details).build()); - if(!started){started=true;try{System.loadLibrary("p5fixture");String result=bootstrap(getApplicationInfo().nativeLibraryDir,new File(getFilesDir(),"p5-wire.bin").getPath(),intent.getStringExtra("agentSha"));Files.write(new File(getFilesDir(),"p5-result.json").toPath(),result.getBytes(StandardCharsets.UTF_8));}catch(Throwable e){throw new RuntimeException(e);}new Handler(Looper.getMainLooper()).postDelayed(()->stopSelf(),120000);} + if(!started){started=true;new Thread(()->{try{ + String marker=intent.getStringExtra("marker");boolean capture=marker!=null;if(capture)crypto("warmup");System.loadLibrary("p5fixture"); + JSONObject result=new JSONObject(bootstrap(getApplicationInfo().nativeLibraryDir,new File(getFilesDir(),"p5-wire.bin").getPath(),intent.getStringExtra("agentSha"),capture)); + if(capture){JSONObject probes=crypto(marker);probes.put("system",systemProbe("/data/local/tmp/"+marker+"_system")==-1);probes.put("tls",tls(marker,intent.getIntExtra("tlsPort",0)));result.put("probes",probes).put("marker",marker).put("allProbesBeforeAgentStart",true);startAgent();} + Files.write(new File(getFilesDir(),"p5-result.json").toPath(),result.toString().getBytes(StandardCharsets.UTF_8)); + }catch(Throwable e){try{Files.write(new File(getFilesDir(),"p5-result.json").toPath(),new JSONObject().put("error",e.toString()).toString().getBytes(StandardCharsets.UTF_8));}catch(Exception ignored){}}},"p5-probes").start();new Handler(Looper.getMainLooper()).postDelayed(()->stopSelf(),120000);} return START_NOT_STICKY; } } diff --git a/docs/P5_ANDROID_ACCEPTANCE.md b/docs/P5_ANDROID_ACCEPTANCE.md index 2007bdc..48adb97 100644 --- a/docs/P5_ANDROID_ACCEPTANCE.md +++ b/docs/P5_ANDROID_ACCEPTANCE.md @@ -1,6 +1,6 @@ # P5 Android 沙盒验收与修复(2026-11-16) -最终独立验收 **7 PASS / 0 FAIL**。设备为 PGP110、Android 15 / API 35、arm64-v8a、KernelSU,SELinux 保持 enforcing。使用独立 worktree,未安装或替换生产 Zygisk 模块、Manager、Device Daemon,未重启现有服务。 +首轮独立验收 **7 PASS / 0 FAIL**;最后一轮 capture/绑定验收与沙盒阶段收口见本文末节。设备为 PGP110、Android 15 / API 35、arm64-v8a、KernelSU,SELinux 保持 enforcing。使用独立 worktree,未安装或替换生产 Zygisk 模块、Manager、Device Daemon,未重启现有服务。 ## 实测证据与边界 @@ -21,8 +21,7 @@ - 正式 Zygisk 模块在 pre/post-specialize 中获取并投递缓存的整条路径、SELinux 对该 companion 的实际许可与时序;本次没有刷模块或重启手机。 - `.init_array` 前、Java 类加载前的命中保证;这些也不属于当前缓存协议承诺。 - 整机重启、生产模块更新、真实业务 App、Java/inline 早期步骤。后两种步骤当前明确 unsupported。 -- 早期 `capture_start` 各捕获族、独立 UID 变更和 Agent 二进制替换的真机反例;本次真实绑定失效反例是 APK v1→v2。 -- 真机的早期 `capture_start` 捕获族、单独替换 Agent 二进制或更换 UID、其他 ROM。此次早期命中正例是 GOT getpid,绑定失效反例是实际 APK 升级;不把它扩写成所有组合均已通过。 +- 其他 ROM、所有算法/模块/布尔组合。本轮补齐七族代表性真实探针、UID 与 Agent 替换反例,见末节;这不代表穷举覆盖。 ## 发现并修复的问题 @@ -30,7 +29,7 @@ 2. **Android LAN 签名转义差异。** Android `org.json` 会转义 `/`,而 JVM 夹具和 Host `JSON.stringify` 的挑战文本不同。新 `DeviceRpc.lanProof` 固定线上的紧凑 JSON 字节,覆盖斜杠、反斜杠、控制字符、Unicode 和孤立 surrogate;不改变已有持久操作 hash。真实 Android TLS 配对认证和撤销已通过。 3. **enforcing 下 USB forward 被拒绝。** 内核审计明确记录 adbd → su Unix socket 的 connectto 拒绝。增加显式 `devices connect transport=adb usbMode=stdio`:root byte relay 连接同一个 UDS,仍使用 `adh.device/1`、同一个 bootstrap token、签名身份、设备代次、任务和去重账本。默认 forward 保留;无自动回退、重试、放宽 SELinux 或新增网络监听。 -stdio 通过 `adb shell -T` 保持双向原始流。连接前只读检查 su 帮助;仅在实现明确提供 `--no-wrapper` 时选择 KernelSU `-W`。Android relay 使用原始 FileDescriptor,而非会被 app_process 重定向到 logcat 的 System.out;LocalSocket 在连接后才设超时。新 bootstrap 的 stdioVersion=1 只增加传输能力标记,保留原身份和凭据;旧设备未声明时返回 unsupported。 +stdio 通过 `adb shell -T` 保持双向原始流。连接前只读检查 su 帮助;仅在实现明确提供 `--no-wrapper` 时选择 KernelSU `-W`。Android relay 使用原始 FileDescriptor,而非会被 app_process 重定向到 logcat 的 System.out;LocalSocket 在连接后才设超时。首轮 bootstrap 的 stdioVersion=1 只增加传输能力标记(最终轮升级为2,见末节),保留原身份和凭据;旧设备未声明时返回 unsupported。 ## 隔离设施与复现 @@ -52,3 +51,42 @@ Host 自动回归通过 `tools/verify_v132_p5_stdio.sh` 注册到既有 host gat 最终原始报告在本机工作区外 `.tmp/adh-p5-android-run-24/report.json`,包含 7 个真实用例和 sceneUnchanged=true;run-23 同样为 7/7。此前失败报告保留,没有计为通过。它是本次有日期的验收证据,不能替代下次运行时重新选择设备和检查现场。 收口回归:Host typecheck 和 **558/558** 通过;Android JVM **70/70**(core23、daemon18、Manager29);普通及 opt-in Android 构建通过,普通 APK 的 DEX 确认不含 P5 fixture、包含生产 stdio relay。原生正常/隔离端口构建、v132、94 项 MCP 注册及生成文档检查通过。 + +## 最后一轮:capture_start 与缓存绑定(2026-11-16) + +在 `feat/adh-p5-final-sandbox-20261116`、基座 f7d726e 上补齐限定范围。仍为独立 Android self-load 沙盒,正式 Zygisk 模块和现有服务没有更新。七族逐一启用、每次执行全部七族探针,加全禁用对照、UID 变化、Agent 替换,共 10 个范围内用例,另加 stdio/2 的 256 次真实往返回归,总计 11 项。 + +| 捕获族 | 实际触发与捕获证据 | +| --- | --- | +| digest | AndroidOpenSSL SHA-256;EVP_DigestUpdate 中匹配本轮唯一明文 | +| hmac | HmacSHA256;HMAC_Update 中匹配唯一明文 | +| symmetric | AES/CBC/PKCS5Padding 加解密往返;EVP_CipherUpdate 匹配明文 | +| asymmetric | SHA256withECDSA 签名/验签;本机走 EVP_DSignUpdate_asym,匹配签名输入;同时观察 Final/Verify 回调 | +| tls | 仅连接独立 Root 域的临时 loopback TLS 端口;SSL_write 匹配本轮请求,SSL_read 返回 AUTH_FAILED,无授权或业务操作 | +| aead | AES/GCM/NoPadding 加解密往返;EVP_AEAD_seal_pt/open_pt 匹配明文 | +| system | 独立 libp5target.so 调用 access 检查不存在的唯一路径;命中 access 记录,无系统修改 | + +每个新进程先预热真实系统 JCA provider,再应用早期缓存,在 **Agent 启动/连接之前**执行全部探针;测试回执验证运算往返/签名验签成功。匹配记录按精确 session 和唯一标记读取,检查完整窗口、累计 dropped/jdropped=0、backlog=0、complete=true。所有被禁用族的专用 GOT 安装计数均不大于 0,且对应探针没有记录;全禁用时安装总数为 0、记录为空,early 状态如实为 partial-or-failed,不把 unconditional ok:true 算作安装成功。 + +DigestSign Init/Update/Final/Verify 是 HMAC 与非对称族共用的导入:任一族启用时可为其安装共享基础 Hook,不能把共享槽描述成“另一个族绝无物理 Hook”。本轮要求并实测的是禁用族专用 Hook 不安装、共享回调不产生禁用族记录;两族均关闭时共享槽也不安装。 + +首轮发现仅 HMAC 启用仍泄出 ECDSA DigestSign 记录,修复 `capture.c` 四个共享数据回调的实际族资格判断,保持原调用和返回值。Agent hello 新增有界 `lastCaptureInstall`,保留最后一条 capture_start 的原始安装计数(非成功判定),相应扩大有界 status/hello 缓冲区。该字段不代表此前所有 capture 步骤或完整 Hook 清单。 + +缓存反例分两层验: + +- **UID**:有效缓存先证实 GOT getpid 安装/命中;保存旧 wire,卸载/重装相同测试 APK,确认 OS 分配新 UID、Agent hash 不变。正式 broker 拒发(0 bytes);把旧 wire 送入新进程,正式 Agent 依据实际 getuid 拒绝,native Hook 数为 0。重装也会改变 APK 源路径,因此不声称 Root 层仅 UID 一项变化;Agent wire 层的包名/Agent hash/有效期不变。 +- **Agent 文件**:新缓存先证实命中,仅在已停止的自身测试包提取目录替换 libadh_agent.so(有效 ELF 追加测试尾标,机器码/ABI 不变),不更新 APK。AndroidHookBinding 确认 UID、版本、signer、APK 元数据完全相同,只有真实 Agent SHA 改变且 earlySupported 仍为 true。broker 拒发;加载新文件并重新取其实际 SHA 后消费旧 wire,被拒且无 native Hook。测试包 JNI 不信任启动参数提供的 hash。 + +复现:按前节构建隔离端口 Agent 和 opt-in APK,资产只需 `daemon.apk`、`sandbox-v1.apk`。执行 `node tools/verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT final`。显式 `final` 模式复用同一隔离前置检查、正式 MCP/共享执行器和清理;默认模式仍为之前 7 项。测试只读采样自身 Host 的累计 ring 元数据,不读取生产捕获内容。 + +原始报告保存在本机聚合工作区外的 `.tmp/adh-p5-final-run-*`,不提交原始捕获、APK、so 或私有身份。run-01 复现串族失败;run-02 修复后 10/10 且 sceneUnchanged=true;run-03/04/05/06 的后续 RPC 超时均保留 unknown,不重发、不计为通过;Root 私有账本显示执行已完成,主线程栈显示等待下一个请求。run-07 为新增夹具断言字段取错,已修正,也不计为通过。 + +### 最终收口 + +另一个实际缺陷是本机 **Windows ADB shell 的 stdout 文本转换**:即使 `shell -T`、KernelSU `-W`,实际回包帧头 `00 00 09 0a` 会变成 `00 00 09 0d 0a`;用测试 wire 中原有 CRLF 做只读对照,exec-out 保持原字节、shell 多出 CR,`-x` 也不解决。帧长度被破坏导致 Host 等待缺失字节,业务已完成却只能报告 unknown。该结论来自自身测试流,不推断所有 ADB/平台均相同;[ADB 源码的 shell 输出与 exec-out 路径](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/client/commandline.cpp)也分开处理这些路径。 + +修复为显式 `stdioVersion=2`:两端对完整、有界的 adh.device/1 原帧做 Base64 行封装,读端只容许行尾 CRLF/LF,验证长度、规范 Base64、非 ASCII/半帧/超限并拒绝异常。USB 认证、签名身份、CAS、任务账本与错误状态不变。旧/缺失 stdioVersion=1 明确 unsupported,不自动降级、重连或重放。设备只升级能力标记,保留原身份与凭据;本次只在自身 fixture 进程运行新代码,未修改现有生产 bootstrap。JVM 互操作回归通过正式 Kotlin codec,并在 Host 端模拟 Windows LF 扩张;额外覆盖 1 MiB 上限和碎片/控制字节。 + +**最终实测**:run-08 与 run-09 各 **11 PASS / 0 FAIL / 0 UNKNOWN**;两轮 `sceneUnchanged=true`、`cleanupVerified=true`。自有 root fixture 退出、包已卸载、18088/18761 已释放,自有映射已移除;原在线会话/进程代次、业务/root daemon PID、模块/配置 SHA 和原映射前后一致。原始报告为本机聚合目录 `.tmp/adh-p5-final-run-08/report.json` 与 run-09 同路径,均在 git 仓外。所有失败记录保留。 + +Host 类型检查和 **560/560**(0 skip),Android JVM **73/73**(core26、daemon18、Manager29,0 skip);默认/隔离 Agent 构建、普通/opt-in Device APK、v132、94 项 MCP 注册与生成文档检查完成。**P5 沙盒阶段在约定范围内收口**。仍未验证正式 Zygisk pre/post-specialize 全链、整机重启/生产升级、其他 ROM/真实业务 App,以及全部算法/模块/布尔组合;Java/inline 早期步骤继续 unsupported。self-load before-agent-start 的通过不替代这些验证。 diff --git a/docs/P5_HOOK_PLANS.md b/docs/P5_HOOK_PLANS.md index bfe2767..084a3d0 100644 --- a/docs/P5_HOOK_PLANS.md +++ b/docs/P5_HOOK_PLANS.md @@ -61,6 +61,8 @@ MCP:`hook_plans`。REST:`GET/POST /api/hook-plans`。发布版 Python CLI 阶段是 **post-specialize / before-agent-start**,不是 `.init_array` 之前、不是 pre-specialize,也不是 Java 类加载前保证。支持 1..16 步的具名模块 `capture_start` 和只观测的 GOT `native_hook`;拒绝等待、Java、inline、改参数/返回值、主动调用或重放。该边界只覆盖此缓存格式,完整实时方案仍保留已有原语自由度。 +早期 hello 的 `lastCaptureInstall` 仅记录最后一条 capture_start 的有界原始计数,不把 ok:true 当作成功,也不是所有步骤的 Hook 清单。专用导入按 family 决定布防;HMAC/非对称共用 DigestSign 槽,回调还按实际上下文的族资格过滤事件。禁用族不能借共享 Hook 输出数据。七族真实沙盒、全禁用和 UID/Agent 替换证据见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。 + 流程: 1. `migration-preview` 返回完整原 scope 原文及 hash;`import-legacy` 生成 Host 方案版本。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 3eddd89..80c51e4 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -5028,3 +5028,11 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 修复 early GOT 默认 errno=-1(改为0并保留失败原因)、Android org.json 斜杠转义导致的 LAN 挑战签名字节差异。enforcing ROM 的 adbd→su UDS connectto 拒绝通过新增显式 USB stdio/1 传输处理:同一协议/身份/账本,旧能力返回 unsupported,无自动回退/重发,不放宽 SELinux。沙盒 Agent 使用独立构建/产物端口18761,不能 --deploy,也不覆盖正常8761产物。默认 APK 排除所有 p5Fixture 类。 回归:Host typecheck、**558/558**;Android JVM **70/70**(23/18/29);普通/opt-in APK、原生默认/隔离端口构建、v132 host gate、94项MCP注册和生成文档检查通过。实测证据与正式 Zygisk、capture_start/其他绑定组合等未验证边界见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。没有把模拟自加载扩写为已验证整个 Zygisk 时序。 + +## 2026-11-16 — P5 最后一轮沙盒验收收口 + +在独立 `feat/adh-p5-final-sandbox-20261116`(基座 f7d726e)补齐七族 capture_start 真命中/禁用、全禁用、实际 UID 更换和仅 Agent 文件替换。各进程先应用正式 early cache,再于 Agent 启动前执行全部实际 JCA/TLS/access 探针;同时验证专用安装计数、唯一标记、完整无丢失捕获窗口。两种绑定失效均检查 Root broker 返回0及直接投递旧 wire 被 Agent 拒绝,native Hook 为0。 + +修复 HMAC/非对称共用 DigestSign 回调越过禁用策略输出数据;增加有界 lastCaptureInstall 证据。复跑发现 Windows adb shell 转换二进制 LF 帧头造成已执行却回包超时,改为显式 stdio/2 Base64 传输(内层 RPC/认证/账本不变,旧版 unsupported),不重发 unknown;新增 Kotlin/Node 大帧、碎片、控制字节、CRLF 和错误边界回归及真机256种长度低字节往返。夹具检查失败和 unknown 均独立保留,增加自身清理的可验证结果。 + +最终 run-08/09 各 **11/11**,sceneUnchanged/cleanupVerified=true;Host **560/560**、Android JVM **73/73**,无 skip,类型/构建/MCP门禁通过。测试包已卸载、自建服务/映射清理;原服务未重启,当前业务现场的会话/PID/模块配置哈希/映射保持一致。P5 **沙盒阶段**已按范围收口;正式 Zygisk 整链、整机重启、生产升级、其他 ROM 和穷举算法组合继续未验证,Java/inline early 继续 unsupported。详情与所有失败记录口径见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。 diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index be45650..e3f2a4c 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -102,5 +102,5 @@ Host-owned Hook plans, early-cache limits and reversible legacy migration: [P5_H | `scope_list` | The phone injection allowlist (scope.json): the packages the Zygisk companion is allowed to inject. Read through root, so it is the device truth rather than a cached page. A package not listed here is never injected, no matter how many tools are called. | _operation | | `scope_set` | Change the phone injection allowlist: pass add / remove / set (arrays of package names). The file is written through root and read back, so a silent half-write cannot pass as success. A newly added package is injected only on its next cold start; analyze_app does the cold start for you. | add, remove, set, _operation | | `operations` | Shared durable Host tasks and control. snapshot returns resource/revision/epoch/hostEpoch. Writes require _operation.expectedRevision, controlEpoch and hostEpoch; missing/stale values never auto-refresh. create/list/get/submit manage analysis tasks; pause/resume/cancel/complete manage taskId, cancel can use operation id. submit runs an existing tool asynchronously and returns an operation id. get includeResult:true reads a stored result. takeover/release/resolve require the operator credential at the transport boundary, never actor JSON. Cancel requested is not confirmed cancellation; unknown effects block writes until inspected/resolved. Task get returns revision, operationCounts and resources; task state actions may supply _operation.expectedTaskRevision for CAS (the human workbench always does). list supports q/state/owner and separate task/operation pagination. get can recover the current role's operation by idempotencyKey without resubmitting. Effects contain bounded dispatch/acknowledgement metadata, not command payloads or proof of target outcome. | action, id, taskId, session, resource, title, tool, arguments, _operation, includeResult, acknowledge, limit, offset, q, state, owner, idempotencyKey | -| `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects a raw root relay on enforcing ROMs, never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, usbMode, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | +| `devices` | Verified device identities, shared USB/LAN RPC and authorization. list is cached; discover transport=adb explicitly lists ADB transports, transport=lan lists known endpoints without scanning. connect transport=adb requires serial/transportId; usbMode=forward (default) or explicit stdio selects an authenticated root stdio/2 relay with bounded Base64 transport on enforcing ROMs (inner RPC unchanged; legacy stdio/1 unsupported), never automatic fallback; transport=lan requires paired deviceId and numeric address/port (or a previously verified endpoint). pair enrolls the Host public key over verified USB, permissions=read/write/manage; grantId explicitly adopts an already observed active grant without granting twice. Device methods lan.configure, lan.status, pairings.list/revoke manage opt-in TLS and durable authorization. Same deviceId deduplicates USB/LAN; select connectionId when multiple connections exist. Writes require observed bootId, daemonInstanceId, expectedDeviceRevision and Host _operation versions; scope writes also require params.scopeRevision. reconcile operationIds queries actual device execution and durably attaches evidence without changing Host unknown or replaying anything. Connection recovery can operate under unknown quarantine but cannot dispatch device mutations. Unmigrated agent/diagnostics/fs/helper/bulk capabilities are unsupported; there is no ADB fallback, automatic failover or retry. | action, transport, serial, transportId, usbMode, expectedDeviceId, deviceId, connectionId, address, port, label, permissions, grantId, operationIds, method, params, bootId, daemonInstanceId, expectedDeviceRevision, budgetMs, _operation | | `hook_plans` | Host-owned programmable Hook plans with immutable digests and CAS library revisions. list/get/validate/preflight never install hooks. put or import-legacy saves a version; apply targets one explicit session generation and requires current Host control versions and advertised agent capabilities. Programs use explicit native/Java/JNI/module/capture primitives and complete family eligibility, with bounded waits and actual per-step receipts; saving is not installation. run/observe inspect history and current hooks; undo removes only verified owned IDs and refuses ambiguous batches or changed runtime. early-prepare/status use the verified device domain; early-stage installs an explicitly enabled, app/agent-bound, expiring cache with a limited pre-start instruction set; missing early mechanisms are unsupported, never guessed. migration-preview/apply/rollback preserve the full legacy document and reject concurrent changes. Connections never automatically arm old startup/capture defaults. Agent early reports do not authenticate a legacy session as a device. | action, plan, digest, expectedLibraryRevision, session, runId, id, package, scope, settings, deviceId, connectionId, bootId, daemonInstanceId, expectedDeviceRevision, binding, expiresAt, offline, expectedCacheRevision, deploymentId, scopeRevision, migrationId, _operation | diff --git a/tools/MAP.md b/tools/MAP.md index 8a275c5..e5b69cc 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -207,3 +207,7 @@ event-limit accounting, explicit stop and wrong-TID refusal. It does not run the ## MCP registry documentation `node tools/generate_mcp_docs.mjs` regenerates docs/mcp-tools.md from the source registry; `--check` validates it. It uses isolated, pure imports and performs no Host initialization, discovery or ADB operation. The generator is tracked so fresh clones do not depend on an ignored adhd-data script. + +### P5 最终沙盒入口(2026-11-16) + +`verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT final` 显式执行 stdio/2 的256种长度往返、七族 capture_start、全禁用、UID变化与Agent替换,共11项;细节在 p5_final_cases.ts。拒绝已有测试包/占用端口,不走 verify_all 的共享沙盒启停。通过、失败、unknown、现场和自有资源清理分别记录,超时不重发。原始报告与产物不提交,见 docs/P5_ANDROID_ACCEPTANCE.md。 diff --git a/tools/p5_final_cases.ts b/tools/p5_final_cases.ts new file mode 100644 index 0000000..b0b66c3 --- /dev/null +++ b/tools/p5_final_cases.ts @@ -0,0 +1,73 @@ +// Invoked only by verify_p5_device.ts after its device, package and scene isolation checks. +import assert from 'node:assert/strict'; +import {readFileSync,writeFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {createHash} from 'node:crypto'; +const families=['digest','hmac','symmetric','asymmetric','tls','aead','system']; +const off=()=>Object.fromEntries(families.map(k=>[k,false])); +export async function finalCases(c:any){ + const {check,tool,deviceWrite,hookDevice,stage,launch,command,su,until,pause,usb,remote,pkg,dir,assets,root}=c; + const prepared=(await hookDevice(usb,'early-prepare')).result;c.binding=prepared.binding; + const originalSha=createHash('sha256').update(readFileSync(join(root,'agent/build-isolated-18761/libadh_agent.so'))).digest('hex'); + assert.equal(c.binding.agentSha256,originalSha);assert.equal(prepared.supported,true); + await check('USB stdio/2 preserves all 256 frame-length low bytes and control payloads',async()=>{ + const marker='P5\r\n\u0003\u001a\0/\\☃';for(let n=0;n<256;n++){const padding=marker+'x'.repeat(n);const info=await c.read(usb,'device.info',{padding});assert.equal(info.info.padding,padding);} + return {roundTrips:256,allLowBytes:true,innerProtocolUnchanged:true}; + }); + const tls=await deviceWrite(usb,'lan.configure',{enabled:true,address:'127.0.0.1',port:0}); + const save=async(family:string,got=false)=>{ + const plan={schemaVersion:1,id:'p5-final-'+family,title:'P5 isolated '+family,package:pkg,families:{...off(),...(families.includes(family)?{[family]:true}:{})},steps:got? + [{id:'before-host',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libp5target.so',symbol:'getpid'}}]: + [{id:'before-host',tool:'capture_start',arguments:{cryptoModule:'libjavacrypto.so',fileModule:'',sysModule:'libp5target.so'}}]}; + const library=await tool('hook_plans',{action:'list'});const saved=await tool('hook_plans',{action:'put',plan,expectedLibraryRevision:library.revision},true);assert.equal(saved.ok,true,JSON.stringify(saved));c.planDigest=saved.digest; + }; + for(const family of [...families,'off'])await check('early capture_start '+family+': real probes and disabled-family isolation',async()=>{ + await save(family);await stage(usb,600);const marker='P5_'+family+'_'+Date.now(); + const result=await launch(true,{marker,tlsPort:tls.port,earlyApply:family==='off'?0:1});const {session,receipt,hooks}=result; + assert.equal(hooks.length,0,'capture_start must not create native_hook entries'); + const install=session.earlyPlan?.lastCaptureInstall;assert.ok(install,JSON.stringify(session.earlyPlan)); + const counters:any={digest:[install.digest],hmac:[install.hmac],symmetric:[install.evp,install.cipherInit,install.cipherCtxFree],asymmetric:Object.values(install.pkey),tls:[install.sslWrite,install.sslRead],aead:Object.values(install.aead),system:Object.values(install.sys)}; + for(const key of families){assert.ok(counters[key].every((v:any)=>Number.isInteger(v)),key+' counters missing');if(key===family)assert.ok(counters[key].some((v:number)=>v>0),key+' was not installed');else assert.ok(counters[key].every((v:number)=>v<=0),key+' unexpectedly armed');} + // Shared DigestSign symbols are needed by HMAC and signatures. They must be absent if both are off. + if(family!=='hmac'&&family!=='asymmetric'){assert.ok(install.digestSign<=0);assert.ok(Object.values(install.digestSignVerify).every((n:any)=>n<=0));} + const health=await until(async()=>{const all=JSON.parse(readFileSync(join(dir,'host/p5-capture-health.json'),'utf8'));const h=all.sessions[session.sessionId];return h&&h.ts&&h.backlog===0?h:null;},'fully drained sandbox ring'); + assert.equal(health.dropped,0);assert.equal(health.jdropped,0);assert.equal(health.complete,true); + await pause(400);const captures=await tool('live_captures',{session:session.sessionId,includeText:true,encoding:'b64',limit:1000}); + assert.equal(captures.total,captures.captures.length,'acceptance must inspect the full session window'); + const rows=captures.captures.map((r:any)=>({...r,bytes:Buffer.from(r.b64||'','base64')})); + const matches:any={ + digest:(r:any)=>r.func==='EVP_DigestUpdate'&&r.bytes.includes(Buffer.from(marker+'_digest')), + hmac:(r:any)=>['HMAC_Update','EVP_DigestSignUpdate'].includes(r.func)&&r.bytes.includes(Buffer.from(marker+'_hmac')), + symmetric:(r:any)=>r.func==='EVP_CipherUpdate'&&r.bytes.includes(Buffer.from(marker+'_symmetric')), + asymmetric:(r:any)=>(r.func==='ECDSA_sign_digest'&&r.bytes.includes(createHash('sha256').update(marker+'_asymmetric').digest()))||(r.func==='EVP_DSignUpdate_asym'&&r.bytes.includes(Buffer.from(marker+'_asymmetric'))), + tls:(r:any)=>r.func==='SSL_write'&&r.bytes.includes(Buffer.from(marker+'_tls')), + aead:(r:any)=>r.func.includes('AEAD')&&r.bytes.includes(Buffer.from(marker+'_aead')), + system:(r:any)=>r.func==='access'&&r.bytes.includes(Buffer.from(marker+'_system')), + }; + const hitCounts=Object.fromEntries(families.map(k=>[k,rows.filter(matches[k]).length])); + writeFileSync(join(dir,'family-'+family+'.json'),JSON.stringify({receipt,early:session.earlyPlan,health,hitCounts,functions:[...new Set(rows.map((r:any)=>r.func))]},null,2)); + for(const k of families)assert.equal(hitCounts[k]>0,k===family,k+' marker evidence '+JSON.stringify({hitCounts,functions:rows.map((r:any)=>r.func)})); + if(family==='off')assert.equal(rows.length,0,'all-off policy must capture nothing'); + return {beforeAgentStart:true,install:counters,sharedDigestSign:install.digestSign,hitCounts,health:{dropped:health.dropped,jdropped:health.jdropped,backlog:health.backlog,complete:health.complete}}; + }); + await check('real UID change rejects cached delivery and stale-wire installation',async()=>{ + await save('uid',true);await stage(usb,600);await launch(true);const before=structuredClone(c.binding); + await c.brokerWire();await su(`cp ${remote}/wire.bin ${remote}/uid-stale.bin`);await command(['shell','am','force-stop',pkg]); + assert.match(await su('pm uninstall '+pkg),/Success/);assert.match(await su(`pm install ${remote}/sandbox.apk`,90000),/Success/); + c.binding=(await hookDevice(usb,'early-prepare')).result.binding;assert.notEqual(c.binding.uid,before.uid,'OS did not allocate a new UID; cannot claim this case');assert.equal(c.binding.agentSha256,before.agentSha256); + await launch(false);const rejected=await launch(false,{stalePath:remote+'/uid-stale.bin',earlyApply:0,rejected:true}); + return {oldUid:before.uid,newUid:c.binding.uid,agentHashUnchanged:true,brokerDenied:true,staleWire:rejected}; + }); + await check('actual Agent replacement alone rejects cached delivery and stale-wire installation',async()=>{ + await save('agent',true);await stage(usb,600);await launch(true);const before=structuredClone(c.binding);await c.brokerWire();await su(`cp ${remote}/wire.bin ${remote}/agent-stale.bin`);await command(['shell','am','force-stop',pkg]); + const apk=(await command(['shell','pm','path',pkg])).replace(/^package:/,'');assert.match(apk,/^\/data\/app\/[A-Za-z0-9_~+\/=.\-]+\/com\.adh\.p5sandbox-[A-Za-z0-9_~+=.\-]+\/base\.apk$/); + const agent=apk.replace(/base\.apk$/,'lib/arm64/libadh_agent.so');assert.equal((await su('sha256sum '+agent)).split(' ')[0],before.agentSha256); + // A valid ELF with a different byte hash, without changing APK/UID/signers or executable code. + const variant=Buffer.concat([readFileSync(join(root,'agent/build-isolated-18761/libadh_agent.so')),Buffer.from('\nP5-SANDBOX-REPLACEMENT\n')]);const variantFile=join(dir,'agent-variant.so');writeFileSync(variantFile,variant); + await command(['push',variantFile,remote+'/agent-variant.so']);await su(`cp ${remote}/agent-variant.so ${agent}; chmod 755 ${agent}`); + c.binding=(await hookDevice(usb,'early-prepare')).result.binding;assert.equal(c.binding.agentSha256,createHash('sha256').update(variant).digest('hex'));assert.notEqual(c.binding.agentSha256,before.agentSha256);assert.equal(c.binding.earlySupported,true); + const {agentSha256:oldHash,...rest}=before;const {agentSha256:newHash,...after}=c.binding;assert.deepEqual(after,rest,'only Agent hash may change in this case'); + await launch(false);const rejected=await launch(false,{stalePath:remote+'/agent-stale.bin',earlyApply:0,rejected:true}); + return {uid:c.binding.uid,apkMetadataUnchanged:true,actualAgentHashChanged:true,brokerDenied:true,staleWire:rejected}; + }); +} diff --git a/tools/p5_isolated_host.ts b/tools/p5_isolated_host.ts index e9fc2d7..019d870 100644 --- a/tools/p5_isolated_host.ts +++ b/tools/p5_isolated_host.ts @@ -17,6 +17,11 @@ const run=async(args:string[])=>{ else if(args[2]!=='forward'||!['--list','--remove'].includes(args[3]))throw Error('fixture allows only owned forwarding and bootstrap reads'); const output=(await exec(adb,args,{windowsHide:true,timeout:10000})).stdout;return output.replaceAll('localabstract:'+socket,'localabstract:'+DEVICE_SOCKET); }; -const stdio=(args:string[])=>{if(args[0]!=='-t'||args[1]!==transport||args[2]!=='shell'||args[3]!=='-T'||args[4]!=='su')throw Error('invalid stdio request');const command=`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-usb-relay com.adh.daemon.device.DeviceRpcRelay ${socket}`;const child=spawn(adb,[...args.slice(0,-1),"'"+command+"'"],{windowsHide:true,stdio:['pipe','pipe','pipe']});const stream=Duplex.from({readable:child.stdout,writable:child.stdin});child.stderr.resume();child.on('error',error=>stream.destroy(error));child.on('close',()=>stream.destroy());stream.on('close',()=>{if(child.exitCode===null)child.kill();});return stream;}; +const stdio=(args:string[])=>{if(args[0]!=='-t'||args[1]!==transport||args[2]!=='shell'||args[3]!=='-T'||args[4]!=='su')throw Error('invalid stdio request');const command=`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-usb-relay com.adh.daemon.device.DeviceRpcRelay --base64 ${socket}`;const child=spawn(adb,[...args.slice(0,-1),"'"+command+"'"],{windowsHide:true,stdio:['pipe','pipe','pipe']});const stream=Duplex.from({readable:child.stdout,writable:child.stdin});child.stderr.resume();child.on('error',error=>stream.destroy(error));child.on('close',()=>stream.destroy());stream.on('close',()=>{if(child.exitCode===null)child.kill();});return stream;}; setDevicesForTests(new Devices(join(root,'devices.json'),new AdbDeviceTransport(run,undefined,stdio))); await import('../daemon/src/index.ts'); + +// Read-only cumulative ring metadata for the opt-in acceptance runner, never capture payloads. +const {capStats}=await import('../daemon/src/state.ts'); +const {writeFileSync,renameSync}=await import('node:fs'); +setInterval(()=>{const path=join(root,'p5-capture-health.json');writeFileSync(path+'.tmp',JSON.stringify({at:Date.now(),sessions:Object.fromEntries(capStats)}));renameSync(path+'.tmp',path);},300).unref(); diff --git a/tools/verify_p5_device.ts b/tools/verify_p5_device.ts index d4d7cd5..e2512f9 100644 --- a/tools/verify_p5_device.ts +++ b/tools/verify_p5_device.ts @@ -6,7 +6,8 @@ import {readFileSync,writeFileSync,mkdirSync,existsSync,openSync,closeSync} from import {resolve,join} from 'node:path'; import {randomBytes,createHash} from 'node:crypto'; import net from 'node:net'; -const [serial,transport,assets,output]=process.argv.slice(2); +const [serial,transport,assets,output,suite]=process.argv.slice(2); +assert.ok(suite===undefined||suite==='final','suite must be omitted (baseline) or final'); assert.ok(serial&&serial!=='a22fecdd'&&/^\d+$/.test(transport)&&assets&&output,'explicit dedicated root serial, transport id, built assets and private output required'); const root=resolve(import.meta.dirname,'..'),dir=resolve(output);assert.ok(!existsSync(dir),'use a fresh private result directory');mkdirSync(dir,{recursive:true}); const nonce=randomBytes(6).toString('hex'),remote='/data/local/tmp/adh-p5-'+nonce,socket='adh_p5_'+nonce,pkg='com.adh.p5sandbox'; @@ -20,25 +21,28 @@ let host:ReturnType|undefined,deviceChild:ReturnType const base='http://127.0.0.1:18088';let sequence=0; const request=async(path:string,body?:any)=>{const response=await fetch(base+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return response.json() as Promise;}; async function tool(name:string,args:any,write=false){if(write){const path=name==='devices'?'/api/devices':'/api/hook-plans';const c=await request('/api/operations/prepare',{path,method:'POST',arguments:args});assert.equal(c.ok,true,JSON.stringify(c));args={...args,_operation:{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch,idempotencyKey:'p5-'+nonce+'-'+(++sequence)}};} - const response=await request('/mcp',{jsonrpc:'2.0',id:sequence,method:'tools/call',params:{name,arguments:args}});if(!response.result)throw Error(JSON.stringify(response));return JSON.parse(response.result.content[0].text);} + const response=await request('/mcp',{jsonrpc:'2.0',id:sequence,method:'tools/call',params:{name,arguments:args}});if(!response.result)throw Error(JSON.stringify(response));const value=JSON.parse(response.result.content[0].text);if(value._operation?.state==='unknown')(report.unknownOperations??=[]).push(value._operation);return value;} async function read(peer:any,method:string,params:any={}){const v=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,method,params});assert.equal(v.ok,true,JSON.stringify(v));return v.result;} async function deviceWrite(peer:any,method:string,params:any={}){const state=await read(peer,'device.state');const value=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,method,params},true);assert.equal(value._operation?.state,'succeeded',JSON.stringify(value));return value.result.result;} async function hookDevice(peer:any,action:string,extra:any={},write=false){const state=await read(peer,'device.state');const value=await tool('hook_plans',{action,deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,package:pkg,...extra},write);return value;} async function until(fn:()=>Promise,label:string,budget=12000){const deadline=Date.now()+budget;let last;do{try{const v=await fn();if(v)return v;}catch(e){last=e;}await pause(150);}while(Date.now()Promise){console.log('RUN '+name);const result=await fn();report.cases.push({name,state:'pass',evidence:result??null});console.log('PASS '+name);} +async function check(name:string,fn:()=>Promise){console.log('RUN '+name);try{const result=await fn();report.cases.push({name,state:'pass',evidence:result??null});console.log('PASS '+name);}catch(error){report.cases.push({name,state:report.unknownOperations?.length?'unknown':'fail',error:(error as Error).message});throw error;}} async function baselineNow(){const live:any=await(await fetch('http://127.0.0.1:8088/api/agents')).json();const hashes=await su('sha256sum /data/adb/adh/scope.json /data/adb/adh/host.endpoint /data/adb/modules/adh/libadh_agent.so');assert.equal(hashes.split('\n').filter(line=>/^[a-f0-9]{64}\s/.test(line)).length,3,'real scene hashes required');return {hashes,sessions:live.filter((s:any)=>s.online).map((s:any)=>({id:s.sessionId,pid:s.pid,start:s.starttimeTicks})),processes:await su("ps -A -o PID,NAME | grep -E 'adh-device-daemon|com.shizhuang.duapp'"),reverse:await command(['reverse','--list'])};} const unwrap=(v:any)=>{assert.equal(v._operation?.state,'succeeded',JSON.stringify(v));return v.result.result;}; let binding:any,cacheRevision:number,migration:any,originalScope:string,planDigest:string; async function stage(peer:any,ttl=180){const prepared=(await hookDevice(peer,'early-prepare')).result;binding=prepared.binding;cacheRevision=prepared.cacheRevision;const info=await hookDevice(peer,'early-stage',{digest:planDigest,binding,expectedCacheRevision:cacheRevision,expiresAt:Math.floor(Date.now()/1000)+ttl,offline:'keep-until-expiry'},true);return unwrap(info);} async function brokerWire(){return su(`CLASSPATH=${remote}/daemon.apk app_process /system/bin com.adh.daemon.P5BrokerFetch ${socket}_early ${binding.uid} ${remote}/wire.bin`);} -async function launch(expect:boolean){ +async function launch(expect:boolean,opts:any={}){ await command(['shell','am','force-stop',pkg]);const wire=await brokerWire();const count=Number(/WIRE_BYTES=(\d+)/.exec(wire)?.[1]);assert.equal(count>0,expect,wire); - await su(`mkdir -p /data/user/0/${pkg}/files; rm -f /data/user/0/${pkg}/files/p5-result.json; cp ${remote}/wire.bin /data/user/0/${pkg}/files/p5-wire.bin; chown -R ${binding.uid}:${binding.uid} /data/user/0/${pkg}/files; chmod 600 /data/user/0/${pkg}/files/p5-wire.bin`); - const result=await command(['shell','am','start-foreground-service','-n',pkg+'/.ProbeService','--es','agentSha',binding.agentSha256]);assert.ok(!result.includes('Error'),result); + await su(`mkdir -p /data/user/0/${pkg}/files; rm -f /data/user/0/${pkg}/files/p5-result.json; cp ${opts.stalePath||remote+'/wire.bin'} /data/user/0/${pkg}/files/p5-wire.bin; chown -R ${binding.uid}:${binding.uid} /data/user/0/${pkg}/files; chmod 600 /data/user/0/${pkg}/files/p5-wire.bin`); + const extras=opts.marker?['--es','marker',opts.marker,'--ei','tlsPort',String(opts.tlsPort)]:[]; + const result=await command(['shell','am','start-foreground-service','-n',pkg+'/.ProbeService','--es','agentSha',binding.agentSha256,...extras]);assert.ok(!result.includes('Error'),result); const receipt=await until(async()=>{try{return JSON.parse(await su(`cat /data/user/0/${pkg}/files/p5-result.json`))}catch{return null;}},'sandbox bootstrap'); - writeFileSync(join(dir,'bootstrap-'+receipt.pid+'.json'),JSON.stringify(receipt));assert.equal(receipt.probeReturn,receipt.pid);assert.equal(receipt.probeBeforeAgentStart,true);assert.equal(receipt.earlyApply,expect?1:-1,JSON.stringify(receipt)); + assert.ok(!receipt.error,JSON.stringify(receipt));writeFileSync(join(dir,'bootstrap-'+receipt.pid+'.json'),JSON.stringify(receipt));assert.equal(receipt.probeReturn,receipt.pid);assert.equal(receipt.probeBeforeAgentStart,true);assert.equal(receipt.earlyApply,opts.earlyApply??(expect?1:-1),JSON.stringify(receipt)); const session=await until(async()=>{const all=await request('/api/agents');return all.find((s:any)=>s.online&&s.package===pkg&&s.pid===receipt.pid);},'isolated agent hello'); const status=await tool('native_hook',{action:'status',session:session.sessionId});const hooks=status.status?.hooks||status.hooks||[]; + if(opts.marker){assert.equal(receipt.allProbesBeforeAgentStart,true);for(const [family,ok] of Object.entries(receipt.probes))assert.equal(ok,true,family);return {receipt,session,hooks};} + if(opts.rejected){assert.equal(session.earlyPlan?.state,'rejected');assert.equal(hooks.length,0);return {receipt,early:session.earlyPlan};} if(expect){assert.equal(session.earlyPlan?.state,'applied',JSON.stringify(session.earlyPlan));const owned=hooks.find((h:any)=>h.id===session.earlyPlan.steps[0].hookId);assert.ok(owned,JSON.stringify(status));assert.ok(owned.hits>=1,JSON.stringify(owned));assert.equal(owned.symbol,'getpid');return {receipt,early:session.earlyPlan,hits:owned.hits};} assert.equal(session.earlyPlan,null);assert.equal(hooks.length,0);return {receipt,early:null}; } @@ -51,12 +55,17 @@ try{ await command(['shell','mkdir','-m','755',remote]);await command(['push',join(assets,'daemon.apk'),remote+'/daemon.apk']);await su(`chmod 444 ${remote}/daemon.apk`);await command(['push',join(assets,'sandbox-v1.apk'),remote+'/sandbox.apk']);assert.match(await su(`pm install -r ${remote}/sandbox.apk`,90000),/Success/);installed=true; originalScope='{\n "version":19,"mode":"allowlist","packages":["com.adh.p5sandbox"],"policy":{"com.adh.p5sandbox":{"c":{"d":false,"h":true,"future":7},"retired":{"bypass":true}}},"future":{"preserved":[1,2]}\n}\n';writeFileSync(join(dir,'scope-before.json'),originalScope);await command(['push',join(dir,'scope-before.json'),remote+'/scope.json']); const deviceLog=openSync(join(dir,'device.log'),'a');deviceChild=spawn(adb,[...prefix,'exec-out','su','-c',`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-${nonce} com.adh.daemon.P5DeviceFixture ${remote} ${socket}`],{windowsHide:true,stdio:['ignore',deviceLog,deviceLog]});closeSync(deviceLog);started=true; - const ready=await until(async()=>{try{return JSON.parse(await su(`cat ${remote}/ready.json`));}catch{return null;}},'private device domain ready');report.device={serial,model:await command(['shell','getprop','ro.product.model']),sdk:await command(['shell','getprop','ro.build.version.sdk']),abi:'arm64-v8a'}; + const ready=await until(async()=>{try{return JSON.parse(await su(`cat ${remote}/ready.json`));}catch{return null;}},'private device domain ready');report.fixturePid=ready.pid;report.device={serial,model:await command(['shell','getprop','ro.product.model']),sdk:await command(['shell','getprop','ro.build.version.sdk']),abi:'arm64-v8a'}; const log=openSync(join(dir,'host.log'),'a');host=spawn(process.execPath,[join(root,'tools','p5_isolated_host.ts'),serial,transport,remote,socket,join(dir,'host')],{cwd:join(root,'daemon'),windowsHide:true,stdio:['ignore',log,log]});closeSync(log);await until(()=>request('/health'),'private Host ready'); usb=await tool('devices',{action:'connect',serial,transportId:transport,usbMode:'stdio'},true);assert.equal(usb._operation?.state,'succeeded',JSON.stringify(usb)); const plan={schemaVersion:1,id:'p5-early-device',title:'Isolated Android GOT proof',package:pkg,families:{digest:false,hmac:false,symmetric:false,asymmetric:false,tls:false,aead:false,system:false},steps:[{id:'getpid-before-host',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libp5target.so',symbol:'getpid'}}]}; const saved=await tool('hook_plans',{action:'put',plan,expectedLibraryRevision:0},true);assert.equal(saved.applied,false);planDigest=saved.digest; const preview=await hookDevice(usb,'migration-preview');assert.equal(preview.result.scopeRaw,originalScope);migration=unwrap(await hookDevice(usb,'migration-apply',{digest:planDigest,scopeRevision:preview.result.scopeRevision},true)); + if(suite==='final'){ + const {finalCases}=await import('./p5_final_cases.ts'); + await finalCases({check,tool,read,deviceWrite,hookDevice,stage,launch,brokerWire,command,su,until,pause,usb,remote,pkg,dir,assets,root,ready, + get binding(){return binding},set binding(value){binding=value},set planDigest(value){planDigest=value}}); + }else{ await check('Android PackageManager and release ABI binding',async()=>{const p=(await hookDevice(usb,'early-prepare')).result;assert.equal(p.supported,true);const expected=createHash('sha256').update(readFileSync(join(root,'agent','build-isolated-18761','libadh_agent.so'))).digest('hex');assert.equal(p.binding.agentSha256,expected,'APK must contain the port-isolated Agent before starting it');binding=p.binding;assert.equal(binding.uid,ready.uid);return {supported:true,uid:binding.uid,signers:binding.signers.length,apkFiles:binding.apks.length};}); await check('early GOT installed and hit before Agent Host connection',async()=>{await stage(usb);return launch(true);}); await check('expired cache denies real broker delivery and installs no Hook',async()=>{const s=await stage(usb,3);const delay=s.entry.expiresAt*1000-Date.now()+300;await pause(Math.max(0,delay));return launch(false);}); @@ -66,7 +75,14 @@ try{ await check('legacy rollback refuses concurrent scope edits then restores exact bytes',async()=>{const scope=await read(usb,'scope.get'),migratedRaw=await su(`cat ${remote}/scope.json`);await deviceWrite(usb,'scope.patch',{scopeRevision:scope.scopeRevision,add:['com.fixture.concurrent']});const conflict=await hookDevice(usb,'migration-rollback',{migrationId:migration.migrationId,scopeRevision:migration.scopeRevision},true);assert.equal(conflict.result?.code||conflict.code,'STALE_SCOPE',JSON.stringify(conflict));assert.ok((await read(usb,'scope.get')).document.packages.includes('com.fixture.concurrent')); // Repair only our fixture document with the exact pre-edit bytes from the private domain. writeFileSync(join(dir,'scope-migrated.json'),migratedRaw);await command(['push',join(dir,'scope-migrated.json'),remote+'/scope.json']);const restored=await hookDevice(usb,'migration-rollback',{migrationId:migration.migrationId,scopeRevision:migration.scopeRevision},true);const outcome=unwrap(restored);assert.equal(outcome.scopeRevision,createHash('sha256').update(originalScope).digest('hex'));assert.equal(await su('cat '+remote+'/scope.json'),originalScope.trimEnd());assert.ok((await su('sha256sum '+remote+'/scope.json')).startsWith(outcome.scopeRevision+' '),'actual restored bytes must match the original raw hash');return {exactHash:outcome.scopeRevision,concurrentEditRejected:true};}); -}catch(error){report.failure={message:(error as Error).message,stack:(error as Error).stack};console.error('FAIL '+(error as Error).message);process.exitCode=1;} + } +}catch(error){ + if(report.unknownOperations?.length&&started){ + // Diagnose only this fixture. Never replay a timed-out write or turn a later result into success. + await su(`touch ${remote}/stacks-request`).catch(()=>{});await pause(600); + for(const [name,path] of [['device-stacks.txt','stacks.txt'],['device-ledger.json','domain/operations.json']])try{writeFileSync(join(dir,name),await su(`cat ${remote}/${path}`));}catch{} + } + report.failure={message:(error as Error).message,stack:(error as Error).stack};console.error('FAIL '+(error as Error).message);process.exitCode=1;} finally{ if(installed){await command(['shell','am','force-stop',pkg]).catch(()=>{});await su('pm uninstall '+pkg).catch(()=>{});} if(usb&&host?.exitCode===null){for(const peer of [lan,usb].filter(Boolean))await tool('devices',{action:'disconnect',deviceId:peer.deviceId,connectionId:peer.connectionId},true).catch(()=>{});} @@ -75,5 +91,12 @@ finally{ if(deviceChild&&deviceChild.exitCode===null){await new Promise(r=>{deviceChild!.once('exit',()=>r());setTimeout(r,3000);});if(deviceChild.exitCode===null)deviceChild.kill();} if(host)for(const port of [18088,18761]){const rows=await command(['reverse','--list']).catch(()=>'');if(rows.split('\n').some(line=>line.trim().endsWith(`tcp:${port} tcp:${port}`)))await command(['reverse','--remove','tcp:'+port]).catch(()=>{});} if(baseline)try{await pause(500);const after=await baselineNow();assert.equal(after.hashes,baseline.hashes);assert.deepEqual(after.sessions,baseline.sessions);assert.equal(after.processes,baseline.processes);assert.equal(after.reverse,baseline.reverse);report.sceneUnchanged=true;}catch(error){report.sceneUnchanged=false;report.protectionError=(error as Error).message;process.exitCode=1;} - report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({passed:report.cases.length,failure:report.failure?.message,sceneUnchanged:report.sceneUnchanged,report:join(dir,'report.json')})); + if(started)try{ + assert.ok(Number.isInteger(report.fixturePid)&&report.fixturePid>1,'root fixture PID unavailable; cleanup unconfirmed'); + await until(async()=>await su(`if [ ! -d /proc/${report.fixturePid} ]; then echo stopped; fi`)==='stopped','own root fixture stopped',6000); + const packagePath=await command(['shell','pm','path',pkg]).catch((error:any)=>{if(error.code===1&&!String(error.stdout||'').trim())return '';throw error;});assert.equal(packagePath,'','own test package must be uninstalled'); + for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));}); + report.cleanupVerified=true; + }catch(error){report.cleanupVerified=false;report.cleanupError=(error as Error).message;process.exitCode=1;} + report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({passed:report.cases.filter((c:any)=>c.state==='pass').length,notPassed:report.cases.filter((c:any)=>c.state!=='pass').length,failure:report.failure?.message,sceneUnchanged:report.sceneUnchanged,cleanupVerified:report.cleanupVerified,report:join(dir,'report.json')})); } diff --git a/tools/verify_v132_p5_stdio.sh b/tools/verify_v132_p5_stdio.sh index 2a16181..d89ee53 100644 --- a/tools/verify_v132_p5_stdio.sh +++ b/tools/verify_v132_p5_stdio.sh @@ -7,4 +7,4 @@ if [ ! -f device/daemon/build/device-rpc-fixture-classpath.json ]; then exit 0 fi (cd daemon && node test/run.mjs test/device_stdio.test.ts) -echo 'RESULT:PASS P5 USB stdio protocol/auth/large frames/unsupported' +echo 'RESULT:PASS P5 USB stdio/2 auth/CRLF/large frames/legacy unsupported' From e58f2ba6afc417f19a1c2a111df312093b830673 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:42:15 +0800 Subject: [PATCH 20/24] =?UTF-8?q?test:=20=E8=A1=A5=E9=BD=90P5=E6=AD=A3?= =?UTF-8?q?=E5=BC=8FZygisk=E5=85=A8=E9=93=BE=E9=9A=94=E7=A6=BB=E7=9C=9F?= =?UTF-8?q?=E6=9C=BA=E9=AA=8C=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon/test/zygisk_gate.test.ts | 15 +++ device/MAP.md | 4 + .../java/com/adh/daemon/P5DeviceFixture.kt | 10 +- device/p5sandbox/src/main/AndroidManifest.xml | 3 +- .../java/com/adh/p5sandbox/ProbeActivity.java | 16 +++ .../com/adh/p5sandbox/ProbeApplication.java | 17 +++ .../java/com/adh/p5sandbox/ProbeService.java | 7 +- docs/P5_ANDROID_ACCEPTANCE.md | 4 +- docs/P5_HOOK_PLANS.md | 2 +- docs/P5_ZYGISK_ACCEPTANCE.md | 59 ++++++++++ docs/PROGRESS.md | 8 ++ injector/MAP.md | 4 + injector/zygisk/fixture/CMakeLists.txt | 14 +++ injector/zygisk/fixture/test_namespace.h.in | 3 + injector/zygisk/jni/main.cpp | 25 ++-- tools/MAP.md | 4 + tools/build_p5_zygisk.sh | 16 +++ tools/verify_p5_zygisk.ts | 108 ++++++++++++++++++ 18 files changed, 302 insertions(+), 17 deletions(-) create mode 100644 daemon/test/zygisk_gate.test.ts create mode 100644 device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeActivity.java create mode 100644 device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java create mode 100644 docs/P5_ZYGISK_ACCEPTANCE.md create mode 100644 injector/zygisk/fixture/CMakeLists.txt create mode 100644 injector/zygisk/fixture/test_namespace.h.in create mode 100644 tools/build_p5_zygisk.sh create mode 100644 tools/verify_p5_zygisk.ts diff --git a/daemon/test/zygisk_gate.test.ts b/daemon/test/zygisk_gate.test.ts new file mode 100644 index 0000000..e1f2d78 --- /dev/null +++ b/daemon/test/zygisk_gate.test.ts @@ -0,0 +1,15 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {mkdtempSync,rmdirSync,existsSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +test('real Zygisk gate refuses missing reboot opt-in and the daily device before creating state or invoking ADB',()=>{ + const directory=mkdtempSync(join(tmpdir(),'adh-p5-zygisk-refuse-')),output=join(directory,'must-not-exist'); + try{for(const args of [['aa165071','no-assets',output],['a22fecdd','no-assets',output,'--allow-device-reboot']]){ + const result=spawnSync(process.execPath,[fileURLToPath(new URL('../../tools/verify_p5_zygisk.ts',import.meta.url)),...args],{windowsHide:true,encoding:'utf8',env:{...process.env,ADH_ADB_PATH:'must-never-run-this-adb.exe'}}); + assert.notEqual(result.status,0);assert.match(result.stderr,/explicit dedicated serial, assets, fresh output and --allow-device-reboot required/);assert.doesNotMatch(result.stderr,/ENOENT/);assert.equal(existsSync(output),false); + }}finally{rmdirSync(directory);} +}); diff --git a/device/MAP.md b/device/MAP.md index 58a19a1..033114d 100644 --- a/device/MAP.md +++ b/device/MAP.md @@ -145,3 +145,7 @@ JVM `DeviceDomainTest` tests recovery/CAS/storage errors; `DeviceRpcFixture` exp ### P5 stdio/2 与最终验收(2026-11-16) `:core` 的 DeviceStdio.kt 只做有界帧/外层 Base64 编解码,供 :daemon 的 root DeviceRpcRelay 使用,处理 Windows ADB 的 CRLF 转换;不承载分析。DeviceIdentity 保留身份/凭据并标记 stdioVersion=2。opt-in p5Fixture 和 p5sandbox 的隔离边界、真实七族探针及绑定拒绝见 docs/P5_ANDROID_ACCEPTANCE.md;普通 APK 不含 P5 fixture。 + +## P5 正式注入夹具(2026-11-16) + +opt-in P5DeviceFixture 可选 nonce 约束的临时模块ID,绑定该模块Agent及私有/data/adb状态,不改默认路径。p5sandbox 的 ProbeApplication 记录首次Os.getpid窗口;ProbeActivity仅给真实Zygisk模式保持自身前台/常亮,ProbeService在zygiskOnly分支不执行任何Agent自加载。普通APK排除这些fixture类。见 docs/P5_ZYGISK_ACCEPTANCE.md。 diff --git a/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt index c2c96ed..139bccf 100644 --- a/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt +++ b/device/daemon/src/p5Fixture/java/com/adh/daemon/P5DeviceFixture.kt @@ -15,15 +15,17 @@ import java.io.DataInputStream /** Debug APK only. Own namespace and root, no Binder publisher or AndroidDeviceBackend. */ object P5DeviceFixture { @JvmStatic fun main(args:Array){ - check(Process.myUid()==0);require(args.size==2) + check(Process.myUid()==0);require(args.size==2||args.size==3) val root=File(args[0]).canonicalFile;val name=args[1] require(root.path.matches(Regex("/data/local/tmp/adh-p5-[a-f0-9]{12}"))&&name.matches(Regex("adh_p5_[a-f0-9]{12}"))) Thread.setDefaultUncaughtExceptionHandler { _,error->File(root,"crash.txt").writeText(error.stackTraceToString());kotlin.system.exitProcess(1) } Looper.prepareMainLooper();val context=SystemContext.create() val app=context.packageManager.getApplicationInfo("com.adh.p5sandbox",0) - val agent=File(app.nativeLibraryDir,"libadh_agent.so");check(agent.isFile) + val moduleId=args.getOrNull(2)?.also{require(it=="adh_p5_"+root.name.removePrefix("adh-p5-"))} + val stateRoot=if(moduleId==null)root else File("/data/adb/adh-p5-"+root.name.removePrefix("adh-p5-")) + val agent=if(moduleId==null)File(app.nativeLibraryDir,"libadh_agent.so")else File("/data/adb/modules/$moduleId/libadh_agent.so");check(agent.isFile) val files=DeviceFiles(File(root,"domain"),{f,m->Os.chmod(f.path,m)},{directory->val fd=Os.open(directory.path,OsConstants.O_RDONLY,0);try{Os.fsync(fd)}finally{Os.close(fd)}});files.initialize() - val scope=ScopeDocuments(File(root,"scope.json"),files) + val scope=ScopeDocuments(File(stateRoot,"scope.json"),files) val identity=DeviceIdentity(files,File("/proc/sys/kernel/random/boot_id").readText().trim()) val operations=DeviceOperations(identity,files,DeviceBackend { method,params->when(method){ "device.info"->JSONObject().put("model",android.os.Build.MODEL).put("sdk",android.os.Build.VERSION.SDK_INT).put("isolatedFixture",true).put("padding",params.optString("padding").also{require(it.length<=512)}) @@ -31,7 +33,7 @@ object P5DeviceFixture { "scope.patch"->scope.patch(params) else->throw DeviceFault("UNSUPPORTED_METHOD","fixture never dispatches Android device control") }}) - val probe=HookBindingProbe { name->val installed=context.packageManager.getApplicationInfo(name,0);AndroidHookBinding(context,File(installed.nativeLibraryDir,"libadh_agent.so")).inspect(name) } + val probe=HookBindingProbe { name->val installed=context.packageManager.getApplicationInfo(name,0);AndroidHookBinding(context,if(moduleId==null)File(installed.nativeLibraryDir,"libadh_agent.so")else agent).inspect(name) } val cache=HookPlanCache(operations,files,scope,probe) val network=DeviceNetwork(operations,files,allowEphemeral=true) val broker=EarlyPlanBroker(cache,name+"_early");val rpc=LocalDeviceRpcServer(operations,name){it.printStackTrace()} diff --git a/device/p5sandbox/src/main/AndroidManifest.xml b/device/p5sandbox/src/main/AndroidManifest.xml index 39ae2c7..6f61909 100644 --- a/device/p5sandbox/src/main/AndroidManifest.xml +++ b/device/p5sandbox/src/main/AndroidManifest.xml @@ -1,7 +1,8 @@ - + + diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeActivity.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeActivity.java new file mode 100644 index 0000000..9ef527f --- /dev/null +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeActivity.java @@ -0,0 +1,16 @@ +package com.adh.p5sandbox; +import android.app.Activity; +import android.os.Bundle; +import android.content.Intent; +import android.view.WindowManager; +import android.widget.TextView; + +/** Own visible fixture only. Avoid ROM background freezing without changing system policy. */ +public final class ProbeActivity extends Activity { + public void onCreate(Bundle saved){super.onCreate(saved); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + setShowWhenLocked(true);setTurnScreenOn(true); + TextView label=new TextView(this);label.setText("ADH isolated Zygisk test");label.setTextSize(22);label.setGravity(android.view.Gravity.CENTER);setContentView(label); + startForegroundService(new Intent(this,ProbeService.class).putExtra("zygiskOnly",true)); + } +} diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java new file mode 100644 index 0000000..1d62e2a --- /dev/null +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java @@ -0,0 +1,17 @@ +package com.adh.p5sandbox; +import android.app.Application; +import android.os.Process; +import java.io.File; +import java.nio.file.Files; +import java.nio.charset.StandardCharsets; +import org.json.JSONObject; + +/** First app callback. Never dlopens an Agent or calls an early-plan export. */ +public final class ProbeApplication extends Application { + public void onCreate(){super.onCreate();try{ + String maps=new String(Files.readAllBytes(new File("/proc/self/maps").toPath()),StandardCharsets.UTF_8); + long before=System.nanoTime();int pid=android.system.Os.getpid();long after=System.nanoTime(); + JSONObject receipt=new JSONObject().put("pid",pid).put("uid",Process.myUid()).put("beforeNs",Long.toString(before)).put("afterNs",Long.toString(after)).put("agentMemfdBeforeApplicationProbe",maps.contains("memfd:jit-cache")).put("applicationCallback",true); + Files.write(new File(getFilesDir(),"p5-zygisk-application.json").toPath(),receipt.toString().getBytes(StandardCharsets.UTF_8)); + }catch(Exception e){throw new RuntimeException(e);}} +} diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java index 5c367ca..78233a8 100644 --- a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java @@ -13,7 +13,7 @@ import javax.net.ssl.*; import org.json.JSONObject; -/** Opt-in test APK, no Activity and no production configuration access. */ +/** Opt-in test APK. Only its own fixture UI/service, no production configuration access. */ public final class ProbeService extends Service { private boolean started=false; private static native String bootstrap(String directory,String wire,String sha,boolean deferred); @@ -42,6 +42,11 @@ public int onStartCommand(Intent intent,int flags,int startId){ NotificationManager manager=getSystemService(NotificationManager.class);manager.createNotificationChannel(new NotificationChannel("p5-test","P5 isolated verification",NotificationManager.IMPORTANCE_LOW)); startForeground(5,new Notification.Builder(this,"p5-test").setContentTitle("ADH P5 isolated test").setSmallIcon(android.R.drawable.ic_menu_info_details).build()); if(!started){started=true;new Thread(()->{try{ + if(intent.getBooleanExtra("zygiskOnly",false)){ + JSONObject receipt=new JSONObject(new String(Files.readAllBytes(new File(getFilesDir(),"p5-zygisk-application.json").toPath()),StandardCharsets.UTF_8)); + receipt.put("selfLoad",false).put("servicePid",android.os.Process.myPid()); + Files.write(new File(getFilesDir(),"p5-result.json").toPath(),receipt.toString().getBytes(StandardCharsets.UTF_8));return; + } String marker=intent.getStringExtra("marker");boolean capture=marker!=null;if(capture)crypto("warmup");System.loadLibrary("p5fixture"); JSONObject result=new JSONObject(bootstrap(getApplicationInfo().nativeLibraryDir,new File(getFilesDir(),"p5-wire.bin").getPath(),intent.getStringExtra("agentSha"),capture)); if(capture){JSONObject probes=crypto(marker);probes.put("system",systemProbe("/data/local/tmp/"+marker+"_system")==-1);probes.put("tls",tls(marker,intent.getIntExtra("tlsPort",0)));result.put("probes",probes).put("marker",marker).put("allProbesBeforeAgentStart",true);startAgent();} diff --git a/docs/P5_ANDROID_ACCEPTANCE.md b/docs/P5_ANDROID_ACCEPTANCE.md index 48adb97..59a8bd5 100644 --- a/docs/P5_ANDROID_ACCEPTANCE.md +++ b/docs/P5_ANDROID_ACCEPTANCE.md @@ -2,6 +2,8 @@ 首轮独立验收 **7 PASS / 0 FAIL**;最后一轮 capture/绑定验收与沙盒阶段收口见本文末节。设备为 PGP110、Android 15 / API 35、arm64-v8a、KernelSU,SELinux 保持 enforcing。使用独立 worktree,未安装或替换生产 Zygisk 模块、Manager、Device Daemon,未重启现有服务。 +后续用户授权手机重启后,已完成[真实 Zygisk 调用链的隔离真机验收](P5_ZYGISK_ACCEPTANCE.md)。本文“不重启”与“正式链未验证”均是当轮 self-load 沙盒的历史边界,不代表后续验收没有执行。默认生产部署/升级继续未验证。 + ## 实测证据与边界 | 项目 | 实测结果 | @@ -33,7 +35,7 @@ stdio 通过 `adb shell -T` 保持双向原始流。连接前只读检查 su 帮 ## 隔离设施与复现 -- `device/p5sandbox` 是 opt-in Gradle 模块,只有 `-PadhP5Sandbox=true` 才加入。使用新包名和前台 Service,没有 Activity,不抢占原分析 App 的界面。 +- `device/p5sandbox` 是 opt-in Gradle 模块,只有 `-PadhP5Sandbox=true` 才加入。self-load 入口使用新包名和前台 Service,不启动 Activity;后续真实 Zygisk 入口另用自身 Activity 保持前台/常亮,适用本轮用户的手机操作授权。 - `device/daemon/src/p5Fixture` 只有同一 opt-in 属性启用时编入测试 APK;不进入普通 bundle。它运行独立 root 进程,不发布 Binder,不使用 AndroidDeviceBackend,不能调生产启停/证书/宿主设置。 - 每次创建 `/data/local/tmp/adh-p5-<随机值>`、独立数据和 UDS 名;身份/授权/迁移账本在 root 私有 domain 目录。Host 使用独立数据、18088/18761。正式 8088/8761 映射不改写。 - 专用 Agent 构建把默认连接端口编为 18761;运行前核对 CMakeCache 和 APK 内实际 Agent SHA,防止新沙盒误连正式 Host。`build_agent.sh` 拒绝把自定义端口 Agent 用 `--deploy` 推出。 diff --git a/docs/P5_HOOK_PLANS.md b/docs/P5_HOOK_PLANS.md index 084a3d0..9b511d3 100644 --- a/docs/P5_HOOK_PLANS.md +++ b/docs/P5_HOOK_PLANS.md @@ -1,6 +1,6 @@ # P5:Host Hook 方案、早期缓存与可逆迁移 -后续已有真实 Android 沙盒验收与修复,见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。原文下面的“未验证”是初次实现快照;正式 Zygisk 整条投递路径仍未验证。 +后续已有真实 Android 沙盒验收与修复,见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。原文下面的“未验证”是初次实现快照;后续已完成[真实 Zygisk 调用链的隔离真机验收](P5_ZYGISK_ACCEPTANCE.md),默认生产命名空间部署/升级仍未进行。 2026-11-16。Host 是方案与流程的权威;手机保留设备执行、验证缓存、状态和撤销入口。AI 默认持有控制,人类通过同一操作层查看、编辑和接管。P5 没有部署到现有手机,也没有重启现有 Host。 diff --git a/docs/P5_ZYGISK_ACCEPTANCE.md b/docs/P5_ZYGISK_ACCEPTANCE.md new file mode 100644 index 0000000..7d32145 --- /dev/null +++ b/docs/P5_ZYGISK_ACCEPTANCE.md @@ -0,0 +1,59 @@ +# P5:真实 Zygisk 投递链隔离验收(2026-11-16) + +最终 **6 PASS / 0 FAIL**,`cleanupVerified=true`、`originalHostAndFilesUnchanged=true`。设备为用户本轮明确授权可重启的 aa165071,PGP110 / Android 15 API35 / arm64-v8a / KernelSU,Zygisk Next 1.5.2,SELinux 保持 enforcing。使用独立 `feat/adh-p5-zygisk-e2e-20261116` worktree,基座 efe8e78。 + +这是**真实 Zygisk 回调、companion、Root broker、Agent 消费与命中链路**的实测;不是测试 App 主动 dlopen Agent。默认生产目录的部署/升级仍未进行。此前 self-load 沙盒结果保留于 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。 + +## 验收范围和证据 + +| 项目 | 实测与判定 | +| --- | --- | +| companion 获取 | 系统启动真实加载临时 Zygisk 模块,框架调用正式 companion。正式 Root EarlyPlanBroker 校验 root peer,读取正式 HookPlanCache。companion 审计包含包名、实际目标 UID、非零 wire 长度;没有测试端代推 wire | +| post-specialize 应用 | 正式 pre 回调经 getModuleDir/openat 保留 Agent FD,post 回调复制为 memfd、计算实际加载内容 SHA、调用 adh_agent_apply_early_v1,再启动 Agent。目标 UID 与 PackageManager、Agent hello 一致;自身 App 调试文件保留 result=1、before_agent_start=1 的 post 审计 | +| Application 首次测试调用 | 测试包不调用 bootstrap/early export、不自行加载 Agent;Application.onCreate 内用 System.nanoTime 夹住 android.system.Os.getpid。libjavacore.so/getpid 的 NATIVE_HOOK 事件须属于本次 session、Hook ID、主线程,tsNs 落入该窗口;原返回 PID 与服务 PID 一致。状态还要求 GOT slotCurrent= replacement,不能只凭历史 hits | +| TTL 过期 | 真正等待缓存过期,实际 companion 返回 0 bytes;新进程 earlyPlan=null,native Hook 数为0 | +| 显式撤销 | CAS revoke 后实际 companion 返回0,新进程无早期 Hook | +| UID 变化 | 相同测试 APK 卸载/重装,实际 UID 改变而 Agent SHA 不变;旧缓存不再交付,新进程无 Hook。重装同时改变 APK 源路径,不声称 Root 层只有 UID 一项变化 | +| Agent 文件替换 | 仅替换临时模块的 Agent 文件(有效 ELF 追加测试尾标),APK/UID/版本/signer/源文件元数据不变、earlySupported仍true,只有 Agent SHA 改变。真实模块 FD/memfd 路径仍加载新 Agent,旧缓存被拒、无 Hook | +| broker 不可用 | 有效缓存先证实命中,再正常关闭自身 Root fixture;实际 companion 交付0 bytes,新 Agent 不启用默认 Hook | + +六个用例中,第一个合并验证投递、应用与首次调用命中;后五个分别验证五类拒绝。正例在绑定反例之前重新执行,避免把“一直没加载成功”误算成拒绝成功。`earlyPlan` 仍是 Agent 自报历史回执,不因此成为已认证的设备/session 绑定。 + +`/proc/self/maps` 中的 jit-cache 字样只是辅助事实,ART 自己也使用同名 memfd;它不能单独证明 Agent 已加载。上述通过依赖实际 Agent hello、companion/post 回执、精确调用窗口内的 Hook 事件和当前 GOT 值。 + +## 隔离和副作用 + +- 临时模块 ID 为 `adh_p5_<12hex>`,只有 Zygisk so 和隔离端口 Agent,无生产 installer/action/service/post-fs-data 脚本。状态目录 `/data/adb/adh-p5-<12hex>`、broker `adh_p5_<12hex>_early`、Root RPC/数据及 Host 18088/18761 均独立;作用域只含 com.adh.p5sandbox。 +- `injector/zygisk/fixture` 编译**同一个 main.cpp**,只覆盖状态目录和 broker 名称。默认构建继续使用 `/data/adb/adh`、`adh_early_plans_v1`,与 Device/core 契约不变;默认目标也编译并核对真实 ELF 中的契约字符串。最终在原构建目录重建的测试 so 与实测 so 逐字节一致。 +- 手机重启是本轮用户的新授权,明确不同于此前“不得重启手机”的沙盒限制。每轮加载和卸载各重启一次;这会终止手机原进程,不承诺保留其内存现场。首次操作前原 Host 没有在线 Agent;电脑端现有 Host 从未被重启。 +- 清理卸载自身测试包、关闭自身 Host/Root fixture、核对 nonce 所有权后删除自身临时模块,再重启手机确保卸载生效。入口只支持保留既有 TCP reverse,其他类型在设备写入前拒绝。原有 TCP reverse 映射按原端点恢复,冲突时不覆盖。原 scope、host.endpoint、Agent、Zygisk so、daemon.apk、module.prop 共六个文件 SHA 前后一致;原 Host PID/启动时间及映射一致,隔离端口释放。 +- 私有 nonce 诊断目录保留,Root domain 权限仍为私有。APK/so、捕获、内存地址、任务身份和原始报告均不提交。全程未关闭 SELinux、未改系统冻结策略、未对真实业务包执行启动/force-stop。 + +## 发现的问题和修正 + +1. **临时模块文件标签。** 单纯 mkdir/cp 得到 adb_data_file,无法照搬正常模块加载假设。夹具按原模块实际上下文设置自身目录的 system_file、so 的 system_lib_file;不扩大 SELinux allow。首轮未收到 Agent hello,不计通过。 +2. **日志和探针不能冒充命中证明。** 本 ROM 的该阶段 logcat 为空;夹具预备自身 cache 目录,使用已有显式调试文件通道保存 post 审计。增加 companion 的 bytes/UID 和 post 的结果/实际 UID 元数据,不记录缓存正文。最初 libandroid_runtime.so/getpid 的 GOT 后续值已被覆盖,不能凭早期历史 hits 宣称 Application 仍命中;后续使用预载的 libjavacore.so,并增加当前槽值与精确时间窗口断言。覆盖的具体 ROM/其他模块成因未定位,不自动重装 Hook。 +3. **后台冻结导致采集未确认。** run-03/04 中,Agent hello/status 已收到,但 capture_drain 超时。自身进程所有线程的内核栈均为 do_freezer_trap,不能归因为 Agent 死锁或缺少命中。夹具增加仅自身的前台 ProbeActivity、常亮窗口,继续由 Service 产出回执;不解冻真实目标、不改全局策略。debuggerd 对冻结进程超时的记录保留。 + +最终 run-05 六项全部通过;run-01/02 不通过,run-03/04 部分项目通过、后续捕获未确认,全部保留,均未计为整轮成功。原始报告位于本机聚合工作区 `.tmp/adh-p5-zygisk-run-05/report.json`,不在 Git 仓内。此前失败报告也在同级私有目录。 + +## 复现与回归 + +先构建 `ADH_AGENT_CONNECT_PORT=18761 bash tools/build_agent.sh`,再用 `device/gradlew --offline -PadhP5Sandbox=true :daemon:assembleDebug :p5sandbox:assembleDebug` 保存 daemon.apk、sandbox-v1.apk 至私有资产目录。显式运行: + +```text +node tools/verify_p5_zygisk.ts SERIAL PRIVATE_ASSETS NEW_PRIVATE_OUTPUT --allow-device-reboot +``` + +入口拒绝缺失重启 opt-in、日常机 a22fecdd、已有测试包、占用端口或原作用域包含测试包。测试模块由 build_p5_zygisk.sh 在私有输出目录构建,该构建脚本自身不调用 ADB。运行需要 root、可重启且可启动测试包的设备,并预先确认允许前台测试窗口;不使用 dev_up/verify_all 或 kill-server。 + +回归实测:Host 类型检查、**561/561**(0 skip);Android JVM **73/73**(core26/daemon18/Manager29,0 skip);默认/隔离 Agent、默认契约/隔离 Zygisk、普通/opt-in APK 构建;94项 MCP registry 与文档检查通过。新增入口拒绝回归验证没有 opt-in 或选中日常机时,在创建输出状态、调用 ADB 之前拒绝。 + +## 保留的未验证项 + +- 默认生产命名空间的部署/升级、生产 Device Daemon 启动与配对状态迁移,没有替换原模块或 Manager。 +- 其他 ROM、架构、Root/Zygisk 实现、真实业务 App 和热升级;本机结果不外推。 +- `.init_array` 前、任意 Java 类加载前、任意模块仍未加载时的 Hook 保证;Java/inline early 当前仍 unsupported。 +- 正式 Zygisk 链路中的 capture_start 七族和所有算法/模块组合、LAN grant 撤销;此前 self-load/Root broker 的通过不能外推为这些组合已经实测。 + +本轮收口的是此设备、隔离命名空间下的正式 Zygisk 调用链和上述六项结果。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 80c51e4..2ef213f 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -5036,3 +5036,11 @@ v71 另触发的 1000 条历史捕获尚未完整恢复:现存事件日志缺 修复 HMAC/非对称共用 DigestSign 回调越过禁用策略输出数据;增加有界 lastCaptureInstall 证据。复跑发现 Windows adb shell 转换二进制 LF 帧头造成已执行却回包超时,改为显式 stdio/2 Base64 传输(内层 RPC/认证/账本不变,旧版 unsupported),不重发 unknown;新增 Kotlin/Node 大帧、碎片、控制字节、CRLF 和错误边界回归及真机256种长度低字节往返。夹具检查失败和 unknown 均独立保留,增加自身清理的可验证结果。 最终 run-08/09 各 **11/11**,sceneUnchanged/cleanupVerified=true;Host **560/560**、Android JVM **73/73**,无 skip,类型/构建/MCP门禁通过。测试包已卸载、自建服务/映射清理;原服务未重启,当前业务现场的会话/PID/模块配置哈希/映射保持一致。P5 **沙盒阶段**已按范围收口;正式 Zygisk 整链、整机重启、生产升级、其他 ROM 和穷举算法组合继续未验证,Java/inline early 继续 unsupported。详情与所有失败记录口径见 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。 + +## 2026-11-16 — P5 正式 Zygisk 调用链隔离真机验收 + +用户本轮明确允许 aa165071 重启后,在独立 worktree/临时模块/状态目录/broker/Host/测试包上实测真实 Zygisk callbacks、companion 获取、模块FD→post-specialize memfd/实际SHA校验、Application首次 Os.getpid 调用窗口命中。测试 App 不自加载 Agent,当前GOT槽值和事件主线程/纳秒窗口均核对。最终私有 run-05 **6/6**:正例、TTL、显式撤销、实际UID更换、仅模块Agent文件更换、broker不可用。临时模块已删除并重启卸载,测试包/自建服务清理,原Host PID/启动时间与六个原配置/模块文件SHA、原映射一致。手机原进程因获授权的重启而终止,不再沿用此前“不重启手机”的现场承诺。 + +改进临时模块SELinux标签、post/companion审计和默认路径契约构建。实际识别 libandroid_runtime GOT 后续被覆盖,改用预载libjavacore并检验当前槽及首次Application事件,未伪报历史hits为持续命中。后台采集失败的内核栈确认为所有线程do_freezer_trap,夹具使用自身前台窗口常亮;不修改系统冻结策略,不自动重装Hook。失败/采集未确认记录均保留,未计通过。 + +Host **561/561**、JVM **73/73** 无skip,类型、默认/隔离构建、94项MCP门禁通过;测试so原目录重建逐字节一致。此设备的正式调用链已收口;默认生产部署/升级、其他ROM/Root/Zygisk、真实业务App、正式capture_start各族及LAN grant撤销组合等仍未验证。详见 [P5_ZYGISK_ACCEPTANCE.md](P5_ZYGISK_ACCEPTANCE.md)。 diff --git a/injector/MAP.md b/injector/MAP.md index a9a9056..f4381c0 100644 --- a/injector/MAP.md +++ b/injector/MAP.md @@ -35,3 +35,7 @@ bash tools/build_zygisk.sh # -> injector/zygisk/dist/adh-zygisk.zip bash tools/build_bundle.sh # -> injector/zygisk/dist/adh-bundle-vX.Y.Z.zip bash tools/flash_device.sh --reboot # KernelSU ksud / Magisk install + reboot ``` + +## P5 真实 Zygisk 隔离验收(2026-11-16) + +`zygisk/fixture` 只在显式构建中给同一 main.cpp 覆盖状态目录/broker;默认宏仍是 Device/core 契约。额外默认契约构建不安装。`tools/build_p5_zygisk.sh` 只构建,`tools/verify_p5_zygisk.ts` 显式 opt-in 负责私有模块/包与两次手机重启;不调用生产 installer/service 脚本。companion/post 增加有界元数据审计,无缓存正文。实测与默认部署未验证边界见 docs/P5_ZYGISK_ACCEPTANCE.md。 diff --git a/injector/zygisk/fixture/CMakeLists.txt b/injector/zygisk/fixture/CMakeLists.txt new file mode 100644 index 0000000..842fac4 --- /dev/null +++ b/injector/zygisk/fixture/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.22) +project(adh_zygisk_fixture CXX) +string(LENGTH "${ADH_P5_NONCE}" nonce_length) +if(NOT ADH_P5_NONCE MATCHES "^[a-f0-9]+$" OR NOT nonce_length EQUAL 12) + message(FATAL_ERROR "explicit 12-hex test namespace required") +endif() +configure_file(test_namespace.h.in test_namespace.h @ONLY) +add_library(adh SHARED ../jni/main.cpp) +target_compile_options(adh PRIVATE -std=c++17 -fno-exceptions -fno-rtti -Wall -Wextra -Oz -include ${CMAKE_CURRENT_BINARY_DIR}/test_namespace.h) +target_link_libraries(adh log dl) +# Compile the same source without overrides, so the default contract also gets a build signal. +add_library(adh_default_contract SHARED ../jni/main.cpp) +target_compile_options(adh_default_contract PRIVATE -std=c++17 -fno-exceptions -fno-rtti -Wall -Wextra -Oz) +target_link_libraries(adh_default_contract log dl) diff --git a/injector/zygisk/fixture/test_namespace.h.in b/injector/zygisk/fixture/test_namespace.h.in new file mode 100644 index 0000000..ce3bede --- /dev/null +++ b/injector/zygisk/fixture/test_namespace.h.in @@ -0,0 +1,3 @@ +// Generated only for the explicit opt-in real Zygisk fixture. No production path writes. +#define ADH_STATE_DIR "/data/adb/adh-p5-@ADH_P5_NONCE@" +#define ADH_EARLY_BROKER "adh_p5_@ADH_P5_NONCE@_early" diff --git a/injector/zygisk/jni/main.cpp b/injector/zygisk/jni/main.cpp index e03573a..5224696 100644 --- a/injector/zygisk/jni/main.cpp +++ b/injector/zygisk/jni/main.cpp @@ -27,20 +27,27 @@ // Injection decisions must be auditable after the fact: logd is not reliably reachable in the // pre-specialize window, and a silent "no inject" is impossible to debug from outside. Every // decision is written to a root-readable file as well as to logcat. -#define ADH_DECISION_LOG "/data/adb/adh/zygisk_inject.log" +// Defaults are the Device/core contract. Only the opt-in test build overrides its namespace. +#ifndef ADH_STATE_DIR +#define ADH_STATE_DIR "/data/adb/adh" +#endif +#ifndef ADH_EARLY_BROKER +#define ADH_EARLY_BROKER "adh_early_plans_v1" +#endif +#define ADH_DECISION_LOG ADH_STATE_DIR "/zygisk_inject.log" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) -static constexpr const char *kScopePath = "/data/adb/adh/scope.json"; // == com.adh.core.AdhPaths.SCOPE_PATH -static constexpr const char *kHostEndpointPath = "/data/adb/adh/host.endpoint"; // == com.adh.core.AdhPaths.HOST_ENDPOINT_PATH -static constexpr const char *kLoaderMarker = "/data/adb/adh/zygisk_loaded"; // == com.adh.core.AdhPaths.LOADER_MARKER +static constexpr const char *kScopePath = ADH_STATE_DIR "/scope.json"; // == com.adh.core.AdhPaths.SCOPE_PATH +static constexpr const char *kHostEndpointPath = ADH_STATE_DIR "/host.endpoint"; // == com.adh.core.AdhPaths.HOST_ENDPOINT_PATH +static constexpr const char *kLoaderMarker = ADH_STATE_DIR "/zygisk_loaded"; // == com.adh.core.AdhPaths.LOADER_MARKER static bool read_exact_early(int fd,void* data,size_t n){auto* p=static_cast(data);while(n){ssize_t got=read(fd,p,n);if(got<=0)return false;p+=got;n-=size_t(got);}return true;} static std::vector read_early_packet(int fd){unsigned char size[4];if(!read_exact_early(fd,size,4))return{};size_t n=(size_t(size[0])<<24)|(size_t(size[1])<<16)|(size_t(size[2])<<8)|size[3];if(!n||n>ADH_EARLY_MAX)return{};std::vector data(n);return read_exact_early(fd,data.data(),n)?data:std::vector{};} static std::vector root_early_plan(const char* package,int uid){ if(!package||uid<=0)return{};int fd=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(fd<0)return{}; timeval timeout{0,250000};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout)); - sockaddr_un address{};address.sun_family=AF_UNIX;const char* name="adh_early_plans_v1";memcpy(address.sun_path+1,name,strlen(name)); + sockaddr_un address{};address.sun_family=AF_UNIX;const char* name=ADH_EARLY_BROKER;memcpy(address.sun_path+1,name,strlen(name)); if(connect(fd,reinterpret_cast(&address),socklen_t(offsetof(sockaddr_un,sun_path)+1+strlen(name)))!=0){close(fd);return{};} ucred peer{};socklen_t length=sizeof(peer);if(getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&peer,&length)!=0||peer.uid!=0){close(fd);return{};} char request[512];int n=snprintf(request,sizeof(request),"%s %d\n",package,uid);if(n<=0||size_t(n)>=sizeof(request)||write(fd,request,size_t(n))!=n){close(fd);return{};} @@ -49,7 +56,7 @@ static std::vector root_early_plan(const char* package,int uid){ static constexpr const char *kManagerPkg = "com.adh.manager"; // == com.adh.core.AdhPaths.MANAGER_PKG static constexpr const char *kAgentName = "libadh_agent.so"; // == com.adh.core.AdhPaths.AGENT_SO_NAME static constexpr const char *kQbdiName = "libQBDI.so"; // optional tracer, delivered on demand -static constexpr const char *kQbdiFlagPath = "/data/adb/adh/qbdi.enabled"; // presence = deliver the tracer +static constexpr const char *kQbdiFlagPath = ADH_STATE_DIR "/qbdi.enabled"; // presence = deliver the tracer #include static zygisk::Api *g_api_for_log = nullptr; // set in onLoad, used to relay logs (see note()) @@ -677,7 +684,7 @@ class AdhModule : public zygisk::ModuleBase { } } if (!g_debug_pkg[0]) { - g_debug_verbose = (access("/data/adb/adh/zygisk_debug", F_OK) == 0); + g_debug_verbose = (access(ADH_STATE_DIR "/zygisk_debug", F_OK) == 0); } note("preAppSpecialize uid=%d debug=%d", (int)getuid(), g_debug_verbose ? 1 : 0); if (!args || !args->nice_name) return; @@ -841,7 +848,7 @@ class AdhModule : public zygisk::ModuleBase { using early_fn=int(*)(const void*,size_t,const char*,const char*); auto apply_early=reinterpret_cast(dlsym(handle,"adh_agent_apply_early_v1")); const auto target=package_of(package_name); - if(apply_early)apply_early(early_packet.data(),early_packet.size(),target.c_str(),actual_agent_sha.c_str()); + if(apply_early){int applied=apply_early(early_packet.data(),early_packet.size(),target.c_str(),actual_agent_sha.c_str());note("early post-specialize pkg=%s uid=%d bytes=%zu result=%d before_agent_start=1",target.c_str(),int(getuid()),early_packet.size(),applied);} else LOGE("early-plan/1 unsupported by loaded agent; cache not applied"); } early_packet.clear(); @@ -946,7 +953,7 @@ static void companion_serve(int client) { } if(strncmp(req,"early ",6)==0){char pkg[256]{};int uid=0;char extra=0;std::vector data; if(sscanf(req+6,"%255s %d %c",pkg,&uid,&extra)==2)data=root_early_plan(pkg,uid); - size_t n=data.size();unsigned char header[4]={static_cast(n>>24),static_cast(n>>16),static_cast(n>>8),static_cast(n)}; + size_t n=data.size();note("early companion pkg=%s uid=%d bytes=%zu",pkg,uid,n);unsigned char header[4]={static_cast(n>>24),static_cast(n>>16),static_cast(n>>8),static_cast(n)}; if(send_all(client,reinterpret_cast(header),4)&&n)send_all(client,reinterpret_cast(data.data()),n);continue; } if (strncmp(req, "policy ", 7) == 0) { diff --git a/tools/MAP.md b/tools/MAP.md index e5b69cc..c1eb4fb 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -211,3 +211,7 @@ event-limit accounting, explicit stop and wrong-TID refusal. It does not run the ### P5 最终沙盒入口(2026-11-16) `verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT final` 显式执行 stdio/2 的256种长度往返、七族 capture_start、全禁用、UID变化与Agent替换,共11项;细节在 p5_final_cases.ts。拒绝已有测试包/占用端口,不走 verify_all 的共享沙盒启停。通过、失败、unknown、现场和自有资源清理分别记录,超时不重发。原始报告与产物不提交,见 docs/P5_ANDROID_ACCEPTANCE.md。 + +## P5 真实 Zygisk 显式入口(2026-11-16) + +`build_p5_zygisk.sh NONCE PRIVATE_OUTPUT` 无ADB;`verify_p5_zygisk.ts SERIAL PRIVATE_ASSETS NEW_PRIVATE_OUTPUT --allow-device-reboot` 在专用授权手机安装仅自身包作用域的临时模块,加载/卸载各重启一次,验证6项真实链路并检查原Host/文件/映射和自身清理。缺少重启opt-in/日常机在任何状态或ADB前被拒绝。该入口不注册到verify_all自动执行。原始产物和报告不提交;详情见 docs/P5_ZYGISK_ACCEPTANCE.md。 diff --git a/tools/build_p5_zygisk.sh b/tools/build_p5_zygisk.sh new file mode 100644 index 0000000..aeb4c52 --- /dev/null +++ b/tools/build_p5_zygisk.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Build only. No ADB, install, service, production module packaging or deploy. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/env.sh" +NONCE="${1:?explicit 12-hex nonce required}" +OUTPUT="${2:?explicit isolated output directory required}" +[[ "$NONCE" =~ ^[a-f0-9]{12}$ ]] || exit 2 +"$CMAKE" -S "$ROOT/injector/zygisk/fixture" -B "$OUTPUT/companion-build" -G Ninja \ + -DCMAKE_MAKE_PROGRAM="$NINJA" -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DANDROID_ABI=arm64-v8a \ + -DANDROID_PLATFORM=android-26 -DANDROID_STL=c++_static -DCMAKE_BUILD_TYPE=Release \ + -DADH_P5_NONCE="$NONCE" >/dev/null +"$CMAKE" --build "$OUTPUT/companion-build" +for symbol in zygisk_module_entry zygisk_companion_entry; do + "$READELF" --dyn-syms --wide "$OUTPUT/companion-build/libadh.so" | awk -v name="$symbol" '$NF == name {found=1} END {exit !found}' +done +echo 'PASS isolated companion exports; no device operation performed' diff --git a/tools/verify_p5_zygisk.ts b/tools/verify_p5_zygisk.ts new file mode 100644 index 0000000..eccf2d4 --- /dev/null +++ b/tools/verify_p5_zygisk.ts @@ -0,0 +1,108 @@ +// Opt-in real Zygisk integration. Two phone reboots; never restarts the existing PC Host. +import assert from 'node:assert/strict'; +import {execFile,spawn} from 'node:child_process'; +import {promisify} from 'node:util'; +import {readFileSync,writeFileSync,mkdirSync,existsSync,openSync,closeSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +import {randomBytes,createHash} from 'node:crypto'; +import net from 'node:net'; +const [serial,assets,output,approval]=process.argv.slice(2); +assert.ok(serial&&serial!=='a22fecdd'&&assets&&output&&approval==='--allow-device-reboot','explicit dedicated serial, assets, fresh output and --allow-device-reboot required'); +const root=resolve(import.meta.dirname,'..'),dir=resolve(output);assert.ok(!existsSync(dir),'fresh output required');mkdirSync(dir,{recursive:true}); +const nonce=randomBytes(6).toString('hex'),remote='/data/local/tmp/adh-p5-'+nonce,socket='adh_p5_'+nonce,pkg='com.adh.p5sandbox',moduleId='adh_p5_'+nonce,modulePath='/data/adb/modules/'+moduleId,stateRoot='/data/adb/adh-p5-'+nonce; +const run=promisify(execFile),adb=process.env.ADH_ADB_PATH||'adb'; +const command=async(args:string[],timeout=15000)=>(await run(adb,['-s',serial,...args],{windowsHide:true,timeout,maxBuffer:1024*1024})).stdout.trim(); +const su=(cmd:string,timeout=15000)=>command(['exec-out','su','-c',cmd],timeout); +const pause=(ms:number)=>new Promise(r=>setTimeout(r,ms)); +const report:any={schemaVersion:1,mode:'real-zygisk-private-namespace',deviceRebootAuthorized:true,ownFixtureForeground:true,nonce,remote,stateRoot,moduleId,cases:[],reboots:[],unverified:['default production namespace deployment/upgrade','other ROMs/architectures','init_array-before-load and Java/inline early steps','capture_start families and LAN-grant revocation through the Zygisk chain']}; +let host:ReturnType|undefined,deviceChild:ReturnType|undefined,usb:any,installed=false,moduleInstalled=false,baseline:any,fixturePid:number|undefined,binding:any,planDigest:string; +const base='http://127.0.0.1:18088';let sequence=0; +const request=async(path:string,body?:any)=>{const response=await fetch(base+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return response.json() as Promise;}; +async function tool(name:string,args:any,write=false){if(write){const path=name==='devices'?'/api/devices':'/api/hook-plans';const c=await request('/api/operations/prepare',{path,method:'POST',arguments:args});assert.equal(c.ok,true,JSON.stringify(c));args={...args,_operation:{expectedRevision:c.revision,controlEpoch:c.epoch,hostEpoch:c.hostEpoch,idempotencyKey:'p5-'+nonce+'-'+(++sequence)}};} + const response=await request('/mcp',{jsonrpc:'2.0',id:sequence,method:'tools/call',params:{name,arguments:args}});if(!response.result)throw Error(JSON.stringify(response));const value=JSON.parse(response.result.content[0].text);if(value._operation?.state==='unknown')(report.unknownOperations??=[]).push(value._operation);return value;} +async function read(peer:any,method:string,params:any={}){const v=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,method,params});assert.equal(v.ok,true,JSON.stringify(v));return v.result;} +async function deviceWrite(peer:any,method:string,params:any={}){const state=await read(peer,'device.state');const value=await tool('devices',{action:'call',deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,method,params},true);assert.equal(value._operation?.state,'succeeded',JSON.stringify(value));return value.result.result;} +async function hookDevice(peer:any,action:string,extra:any={},write=false){const state=await read(peer,'device.state');const value=await tool('hook_plans',{action,deviceId:peer.deviceId,connectionId:peer.connectionId,bootId:peer.bootId,daemonInstanceId:peer.daemonInstanceId,expectedDeviceRevision:state.stateRevision,package:pkg,...extra},write);return value;} +async function until(fn:()=>Promise,label:string,budget=12000){const deadline=Date.now()+budget;let last;do{try{const v=await fn();if(v)return v;}catch(e){last=e;}await pause(150);}while(Date.now()Promise){console.log('RUN '+name);try{const result=await fn();report.cases.push({name,state:'pass',evidence:result??null});console.log('PASS '+name);}catch(error){report.cases.push({name,state:report.unknownOperations?.length?'unknown':'fail',error:(error as Error).message});throw error;}} +const unwrap=(v:any)=>{assert.equal(v._operation?.state,'succeeded',JSON.stringify(v));return v.result.result;}; +const protectedFiles='/data/adb/adh/scope.json /data/adb/adh/host.endpoint /data/adb/modules/adh/libadh_agent.so /data/adb/modules/adh/zygisk/arm64-v8a.so /data/adb/modules/adh/daemon.apk /data/adb/modules/adh/module.prop'; +async function hostIdentity(){const value=await run('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$adhConnection=Get-NetTCPConnection -LocalPort 8088 -State Listen | Select-Object -First 1; $adhProcess=Get-Process -Id $adhConnection.OwningProcess; @{pid=$adhProcess.Id;started=$adhProcess.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json -Compress"],{windowsHide:true});return JSON.parse(value.stdout);} +async function mappings(){return (await command(['reverse','--list'])).split('\n').filter(Boolean).map(line=>line.trim().split(/\s+/).slice(-2).join(' ')).sort();} +async function restoreMappings(){for(const row of baseline.reverse){const [source,destination]=row.split(' ');assert.match(source,/^tcp:\d+$/);assert.match(destination,/^tcp:\d+$/);const current=(await mappings()).find(line=>line.startsWith(source+' '));if(current){assert.equal(current,row,'a mapping was replaced; never overwrite it');continue;}await command(['reverse','--no-rebind',source,destination]);}} +async function reboot(label:string){ + const before=await su('cat /proc/sys/kernel/random/boot_id');console.log('REBOOT '+label);await command(['reboot']);await pause(2500);const deadline=Date.now()+240000;let logged=0; + while(Date.now()20000){console.log('BOOT_WAIT '+label);logged=Date.now();}await pause(2000);} + throw Error('device boot deadline; phone state and cleanup unconfirmed'); +} +async function stage(ttl=180){const p=(await hookDevice(usb,'early-prepare')).result;binding=p.binding;return unwrap(await hookDevice(usb,'early-stage',{digest:planDigest,binding,expectedCacheRevision:p.cacheRevision,expiresAt:Math.floor(Date.now()/1000)+ttl,offline:'keep-until-expiry'},true));} +async function launch(expect:boolean){ + await command(['shell','am','force-stop',pkg]);await su(`mkdir -p /data/user/0/${pkg}/cache; chown ${binding.uid}:${binding.uid} /data/user/0/${pkg}/cache; rm -f /data/user/0/${pkg}/cache/adh_zygisk.log /data/user/0/${pkg}/files/p5-result.json /data/user/0/${pkg}/files/p5-zygisk-application.json; : > ${stateRoot}/zygisk_inject.log`); + const started=await command(['shell','am','start','-W','-n',pkg+'/.ProbeActivity']);assert.ok(!started.includes('Error'),started); + const receipt=await until(async()=>{try{return JSON.parse(await su(`cat /data/user/0/${pkg}/files/p5-result.json`));}catch{return null;}},'Application receipt',18000);assert.ok(!receipt.error,JSON.stringify(receipt));assert.equal(receipt.selfLoad,false);assert.equal(receipt.applicationCallback,true);assert.equal(receipt.servicePid,receipt.pid);assert.equal(receipt.uid,binding.uid);assert.equal(receipt.agentMemfdBeforeApplicationProbe,true,'Agent must already be present at the first app callback; no self-load allowed'); + report.lastPid=receipt.pid;writeFileSync(join(dir,'application-'+receipt.pid+'.json'),JSON.stringify(receipt)); + const session=await until(async()=>{const all=await request('/api/agents');return all.find((s:any)=>s.online&&s.package===pkg&&s.pid===receipt.pid);},'injected Agent hello');assert.match(session.selfModule||'',/memfd:jit-cache/); + report.lastSession=session.sessionId;const status=await tool('native_hook',{action:'status',session:session.sessionId});const hooks=status.status?.hooks||status.hooks||[]; + const decisions=await su('cat '+stateRoot+'/zygisk_inject.log');const appLog=await su(`cat /data/user/0/${pkg}/cache/adh_zygisk.log`).catch(()=>'');const logcat=await command(['logcat','-d','--pid',String(receipt.pid),'-s','adh-zygisk:I','*:S']); + writeFileSync(join(dir,'launch-'+receipt.pid+'.json'),JSON.stringify({receipt,early:session.earlyPlan,status,decisions,appLog,logcat},null,2)); + const pattern=new RegExp('early companion pkg='+pkg.replaceAll('.','\\.')+' uid='+binding.uid+' bytes=(\\d+)');const bytes=Number(pattern.exec(decisions)?.[1]);assert.ok(Number.isFinite(bytes),'real companion delivery audit missing');assert.equal(bytes>0,expect,decisions); + if(expect){assert.equal(session.earlyPlan?.state,'applied',JSON.stringify(session.earlyPlan));assert.equal(session.earlyPlan.digest,planDigest);const owned=hooks.find((h:any)=>h.id===session.earlyPlan.steps[0].hookId);assert.ok(owned);assert.equal(owned.module,'libjavacore.so');assert.equal(owned.symbol,'getpid');assert.ok(owned.hits>=1,JSON.stringify(owned));assert.equal(session.uid,binding.uid);assert.equal(owned.slotCurrent,owned.replacement,'Hook must still be installed at Application startup'); + const evidence=await until(async()=>{const list=await tool('live_captures',{session:session.sessionId,includeText:true,encoding:'b64',limit:1000});writeFileSync(join(dir,'capture-window-'+receipt.pid+'.json'),JSON.stringify(list));return list.captures?.find((r:any)=>r.func==='NATIVE_HOOK'&&r.hookId===owned.id&&BigInt(String(r.tsNs))>=BigInt(receipt.beforeNs)&&BigInt(String(r.tsNs))<=BigInt(receipt.afterNs));},'Hook event inside first Application call window'); + assert.equal(evidence.tid,receipt.pid);writeFileSync(join(dir,'early-hit-'+receipt.pid+'.json'),JSON.stringify({hookId:owned.id,eventId:evidence.id,tsNs:evidence.tsNs,window:[receipt.beforeNs,receipt.afterNs],sameMainThread:true})); + assert.match(appLog+logcat,/early post-specialize .*result=1 before_agent_start=1/);return {receipt,companionBytes:bytes,early:session.earlyPlan,hits:owned.hits,firstApplicationEvent:evidence.id,postLogSource:appLog?'own-app-debug-file':'logcat'};} + assert.equal(session.earlyPlan,null);assert.equal(hooks.length,0);return {receipt,companionBytes:bytes,early:null,hooks:0}; +} +try{ + for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));}); + assert.match(await su('id'),/uid=0\(root\)/);assert.equal(await su('getenforce'),'Enforcing');assert.equal(await command(['shell','getprop','ro.product.cpu.abi']),'arm64-v8a'); + const packagePath=await command(['shell','pm','path',pkg]).catch((e:any)=>{if(e.code===1&&!String(e.stdout||'').trim())return '';throw e;});assert.equal(packagePath,'','existing test package must not be overwritten'); + const online=(await(await fetch('http://127.0.0.1:8088/api/agents')).json() as any[]).filter(s=>s.online);assert.equal(online.length,0,'new active Host analysis appeared; stop before reboot'); + const hashes=await su('sha256sum '+protectedFiles);assert.equal(hashes.split('\n').length,6);baseline={host:await hostIdentity(),hashes,reverse:await mappings()};report.before=baseline;for(const mapping of baseline.reverse)assert.match(mapping,/^tcp:\d+ tcp:\d+$/,'only existing TCP reverse mappings are supported; refuse before device mutation'); + assert.ok(!baseline.reverse.some((r:string)=>/^tcp:(18088|18761) /.test(r)));assert.ok(!(await su('cat /data/adb/adh/scope.json')).includes(pkg),'test package is in the original module scope'); + assert.match(readFileSync(join(root,'agent/build-isolated-18761/CMakeCache.txt'),'utf8'),/ADH_AGENT_CONNECT_PORT:STRING=18761/); + const buildLog=await run('C:/Program Files/Git/bin/bash.exe',['-lc',`bash tools/build_p5_zygisk.sh ${nonce} '${dir.replaceAll('\\','/')}'`],{cwd:root,windowsHide:true,timeout:90000,maxBuffer:1024*1024});writeFileSync(join(dir,'companion-build.log'),buildLog.stdout+buildLog.stderr); + await command(['shell','mkdir','-m','755',remote]);for(const [file,name] of [[join(assets,'daemon.apk'),'daemon.apk'],[join(assets,'sandbox-v1.apk'),'sandbox.apk'],[join(root,'agent/build-isolated-18761/libadh_agent.so'),'libadh_agent.so'],[join(dir,'companion-build/libadh.so'),'arm64-v8a.so']])await command(['push',file,remote+'/'+name]); + await su(`chmod 444 ${remote}/daemon.apk`);assert.match(await su(`pm install ${remote}/sandbox.apk`,90000),/Success/);installed=true; + const document={version:1,mode:'allowlist',packages:[pkg],policy:{[pkg]:{c:{d:false,h:false,s:false,a:false,t:false,e:false,y:false}}}};writeFileSync(join(dir,'scope.json'),JSON.stringify(document));await command(['push',join(dir,'scope.json'),remote+'/scope.json']); + // No installer/action/boot script from the production module is invoked. + assert.equal(await su(`if [ -e ${modulePath} ] || [ -e ${stateRoot} ]; then echo exists; fi`),'');moduleInstalled=true; + await su(`mkdir ${modulePath} && echo ${nonce} > ${modulePath}/p5-owner && mkdir ${modulePath}/zygisk && cp ${remote}/arm64-v8a.so ${modulePath}/zygisk/arm64-v8a.so && cp ${remote}/libadh_agent.so ${modulePath}/libadh_agent.so && chmod 755 ${modulePath} ${modulePath}/zygisk ${modulePath}/zygisk/arm64-v8a.so && touch ${modulePath}/skip_mount && printf 'id=${moduleId}\nname=ADH P5 isolated Zygisk test\nversion=0.0.0-test\nversionCode=1\nauthor=ADH test\ndescription=Temporary own-package-only fixture\n' > ${modulePath}/module.prop && mkdir -m 700 ${stateRoot} && cp ${remote}/scope.json ${stateRoot}/scope.json && : > ${stateRoot}/host.endpoint && touch ${stateRoot}/zygisk_debug`); + // Match existing module labels instead of widening SELinux or trusting mkdir defaults. + for(const [source,target] of [['/data/adb/modules/adh',modulePath],['/data/adb/modules/adh/zygisk',modulePath+'/zygisk'],['/data/adb/modules/adh/libadh_agent.so',modulePath+'/libadh_agent.so'],['/data/adb/modules/adh/zygisk/arm64-v8a.so',modulePath+'/zygisk/arm64-v8a.so']]){ + const context=(await su('ls -Zd '+source)).split(/\s+/)[0];assert.match(context,/^[A-Za-z0-9_:,.-]+$/);await su(`chcon ${context} ${target}`); + } + await reboot('load isolated module'); + const deviceLog=openSync(join(dir,'device.log'),'a');deviceChild=spawn(adb,['-s',serial,'exec-out','su','-c',`CLASSPATH=${remote}/daemon.apk app_process /system/bin --nice-name=adh-p5-${nonce} com.adh.daemon.P5DeviceFixture ${remote} ${socket} ${moduleId}`],{windowsHide:true,stdio:['ignore',deviceLog,deviceLog]});closeSync(deviceLog); + const ready=await until(async()=>{try{return JSON.parse(await su('cat '+remote+'/ready.json'));}catch{return null;}},'private root domain');fixturePid=ready.pid;assert.equal(ready.agentPath,modulePath+'/libadh_agent.so'); + const discovery=(await run(adb,['devices','-l'],{windowsHide:true})).stdout;const row=discovery.split('\n').find(s=>s.startsWith(serial+' '));const transport=/transport_id:(\d+)/.exec(row||'')?.[1];assert.ok(transport); + const hostLog=openSync(join(dir,'host.log'),'a');host=spawn(process.execPath,[join(root,'tools/p5_isolated_host.ts'),serial,transport,remote,socket,join(dir,'host')],{cwd:join(root,'daemon'),windowsHide:true,stdio:['ignore',hostLog,hostLog]});closeSync(hostLog);await until(()=>request('/health'),'private Host'); + usb=await tool('devices',{action:'connect',serial,transportId:transport,usbMode:'stdio'},true);assert.equal(usb._operation?.state,'succeeded',JSON.stringify(usb)); + const plan={schemaVersion:1,id:'zygisk-before-application',title:'Actual post-specialize early GOT',package:pkg,families:{digest:false,hmac:false,symmetric:false,asymmetric:false,tls:false,aead:false,system:false},steps:[{id:'runtime-getpid',tool:'native_hook',arguments:{action:'hook',mode:'got',module:'libjavacore.so',symbol:'getpid'}}]}; + const saved=await tool('hook_plans',{action:'put',plan,expectedLibraryRevision:0},true);assert.equal(saved.ok,true);planDigest=saved.digest;const preview=(await hookDevice(usb,'migration-preview')).result;unwrap(await hookDevice(usb,'migration-apply',{digest:planDigest,scopeRevision:preview.scopeRevision},true)); + await check('real companion delivery, post-specialize apply and pre-Application GOT hit',async()=>{await stage();return launch(true);}); + await check('expired cache is refused by actual companion; no Hook',async()=>{const s=await stage(3);await pause(Math.max(0,s.entry.expiresAt*1000-Date.now()+300));return launch(false);}); + await check('revoked cache is refused by actual companion; no Hook',async()=>{const s=await stage();unwrap(await hookDevice(usb,'early-revoke',{deploymentId:s.entry.deploymentId,expectedCacheRevision:s.cacheRevision},true));return launch(false);}); + await check('actual UID change rejects old cache through Zygisk',async()=>{await stage();await launch(true);const old=structuredClone(binding);await command(['shell','am','force-stop',pkg]);assert.match(await su('pm uninstall '+pkg),/Success/);assert.match(await su(`pm install ${remote}/sandbox.apk`,90000),/Success/);binding=(await hookDevice(usb,'early-prepare')).result.binding;assert.notEqual(binding.uid,old.uid);assert.equal(binding.agentSha256,old.agentSha256);return {oldUid:old.uid,newUid:binding.uid,...await launch(false)};}); + await check('module Agent bytes alone change; actual FD load rejects old cache',async()=>{await stage();await launch(true);const before=structuredClone(binding);await command(['shell','am','force-stop',pkg]);const variant=Buffer.concat([readFileSync(join(root,'agent/build-isolated-18761/libadh_agent.so')),Buffer.from('\nP5-ZYGISK-REPLACEMENT\n')]);writeFileSync(join(dir,'agent-variant.so'),variant);await command(['push',join(dir,'agent-variant.so'),remote+'/agent-variant.so']);await su(`cp ${remote}/agent-variant.so ${modulePath}/libadh_agent.so`);binding=(await hookDevice(usb,'early-prepare')).result.binding;const {agentSha256:oldHash,...old}=before,{agentSha256:newHash,...fresh}=binding;assert.deepEqual(fresh,old);assert.equal(newHash,createHash('sha256').update(variant).digest('hex'));assert.notEqual(oldHash,newHash);return {onlyAgentHashChanged:true,...await launch(false)};}); + await check('missing root broker fails closed through actual companion',async()=>{await stage();await launch(true);await su('touch '+remote+'/stop');await until(async()=>await su(`if [ ! -d /proc/${fixturePid} ]; then echo stopped; fi`)==='stopped','own broker stopped');return launch(false);}); +}catch(error){ + try{writeFileSync(join(dir,'failure-decisions.txt'),await su('cat '+stateRoot+'/zygisk_inject.log'));if(report.lastPid)writeFileSync(join(dir,'failure-logcat.txt'),await command(['logcat','-d','--pid',String(report.lastPid),'-s','adh-zygisk:I','*:S']));}catch{} + if(report.lastPid)try{ + const pid=String(report.lastPid);assert.match(pid,/^\d+$/);assert.ok((await su(`cat /proc/${pid}/cmdline`)).startsWith(pkg)); + writeFileSync(join(dir,'failure-threads.txt'),await su(`cat /proc/${pid}/status; for p5task in /proc/${pid}/task/*; do echo TASK:$p5task; cat $p5task/comm $p5task/wchan $p5task/stack; done`)); + writeFileSync(join(dir,'failure-backtrace.txt'),await su(`debuggerd -b ${pid}`,18000)); + }catch{} + report.failure={message:(error as Error).message,stack:(error as Error).stack};console.error('FAIL '+(error as Error).message);process.exitCode=1;} +finally{ + try{ + if(installed){await command(['shell','am','force-stop',pkg]);assert.match(await su('pm uninstall '+pkg),/Success/);} + if(host&&host.exitCode===null){host.kill();await new Promise(r=>{host!.once('exit',()=>r());setTimeout(r,3000);});} + if(deviceChild?.exitCode===null)await su('touch '+remote+'/stop').catch(()=>{}); + if(moduleInstalled){assert.equal(await su('cat '+modulePath+'/p5-owner'),nonce,'never remove an unowned module');await su('rm -rf '+modulePath);await reboot('unload isolated module');assert.equal(await su(`if [ -e ${modulePath} ]; then echo exists; fi`),'');} + if(baseline){assert.equal(await su('sha256sum '+protectedFiles),baseline.hashes);assert.deepEqual(await hostIdentity(),baseline.host);assert.deepEqual(await mappings(),baseline.reverse);report.originalHostAndFilesUnchanged=true;} + for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));});report.cleanupVerified=true; + }catch(error){report.cleanupVerified=false;report.cleanupError=(error as Error).message;process.exitCode=1;} + if(host?.exitCode===null)host.kill();if(deviceChild?.exitCode===null)deviceChild.kill();report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({passed:report.cases.filter((c:any)=>c.state==='pass').length,failure:report.failure?.message,cleanupVerified:report.cleanupVerified,hostAndFilesUnchanged:report.originalHostAndFilesUnchanged,report:join(dir,'report.json')})); +} From 50b4cda115776e5de343d31cb3e0b6885e8f630f Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:58:52 +0800 Subject: [PATCH 21/24] =?UTF-8?q?docs:=20=E6=94=B6=E5=8F=A3ADH=20P0?= =?UTF-8?q?=E8=87=B3P5=E4=BA=A4=E4=BB=98=E4=B8=8E=E5=90=8E=E7=BB=AD?= =?UTF-8?q?=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/AI_FIRST_CLOSEOUT.md | 41 +++++++++++++++++++++++++++++++++++++++ docs/PROGRESS.md | 2 ++ 2 files changed, 43 insertions(+) create mode 100644 docs/AI_FIRST_CLOSEOUT.md diff --git a/docs/AI_FIRST_CLOSEOUT.md b/docs/AI_FIRST_CLOSEOUT.md new file mode 100644 index 0000000..7833f1b --- /dev/null +++ b/docs/AI_FIRST_CLOSEOUT.md @@ -0,0 +1,41 @@ +# ADH P0–P5 收尾索引(2026-11-17) + +约定的实现与隔离验收已完成,最新代码基准为 e58f2ba(2026-11-16)。本次收尾只核对状态、补齐交付索引并执行 Host 文档回归;没有重跑真机验收、安装/重启手机或启停现有服务。 + +## 交付位置 + +AndroidDecryptHub 的完整提交链位于 `feat/adh-p5-zygisk-e2e-20261116`,已核对其包含下表全部前序提交;各阶段独立 worktree 保留。配套 adh-cli 为 f086459,分支 `feat/adh-p1-operations-20261116`。本会话没有执行合并、推送、发布或默认环境部署,原 AndroidDecryptHub 工作区仍在 P1 分支;不能把最新隔离分支等同于已上线版本。 + +| 阶段 | 已交付 | 提交与详情 | +| --- | --- | --- | +| P0 | 作用域策略保留、统一设置应用、初始化/数据清理拆分 | 7f71626,[P0_HOST_STATE.md](P0_HOST_STATE.md) | +| P1 | 共用操作层、持久任务、版本与控制权、超时/取消状态 | be80e29;CLI f086459,[P1_OPERATIONS.md](P1_OPERATIONS.md) | +| P2 | 人类任务工作台、配置冲突、暂停/恢复、接管/交还 | 91be0f5,[P2_WORKBENCH.md](P2_WORKBENCH.md) | +| P3 | 设备域、稳定身份、发现/能力、统一 USB RPC | 258e69a,[P3_DEVICE_DOMAIN.md](P3_DEVICE_DOMAIN.md) | +| P4 | LAN TLS、配对/撤销、断线对账、未迁能力 unsupported | fa98813,[P4_LAN_AUTH.md](P4_LAN_AUTH.md) | +| P5 | Host Hook 方案、经验证的早期缓存、可逆迁移 | de9d134,[P5_HOOK_PLANS.md](P5_HOOK_PLANS.md) | +| P5 沙盒 | Android 绑定、七族代表性捕获/禁用、UID/Agent 失效、stdio/2 | f7d726e、efe8e78,[P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md) | +| P5 正式链 | 真实 Zygisk callbacks/companion/post-specialize、首次调用命中及拒绝 | e58f2ba,[P5_ZYGISK_ACCEPTANCE.md](P5_ZYGISK_ACCEPTANCE.md) | + +最近一次已执行验收:self-load 沙盒最终两轮各11/11;真实 Zygisk 隔离命名空间6/6;Host561/561、Android JVM73/73,均无skip,94项MCP门禁通过。各自日期、原始报告入口和严格边界以对应验收文档为准,不用本索引覆盖失败历史。 + +## 本轮可关闭的事项 + +- 约定范围内没有待提交的实现修复;测试代码、验收脚本、问题修正和进度记录均已提交。 +- 收尾只读核对确认:临时 Zygisk 模块、测试包、自建测试进程无运行残留,隔离端口已释放;原 TCP reverse 映射保留。 +- 私有原始报告、失败/unknown 历史和诊断目录按既有约定保留,不重放、不清空、不提交。源码 worktree 保留以便审阅和集成。 + +## 后续事项,未计为本轮完成 + +| 事项 | 当前边界 | +| --- | --- | +| 分支集成与发布 | 尚未执行,需同时考虑 AndroidDecryptHub 与配套 adh-cli;未发布新的默认运行版本 | +| 默认生产部署/升级 | 未替换原模块、Manager 或生产 Device Daemon;其启动、配对状态迁移仍未验收 | +| 正式链扩展覆盖 | capture_start 七族、LAN grant 撤销、全部算法/模块组合尚未通过正式 Zygisk 链复测 | +| 其他环境 | 其他 ROM/Root/Zygisk/架构、真实业务 App、热升级等未验证 | +| 设备 RPC 未迁能力 | Hook/内存/Trace/dump 等未迁能力仍明确 unsupported,不能外推为所有分析功能已完成 USB/LAN 对等 | +| 早期时序限制 | 不承诺 init_array 前、任意 Java 类加载前或目标模块尚未加载时命中;Java/inline early 仍 unsupported | +| GOT 覆盖成因 | 本 ROM 的 libandroid_runtime/getpid 槽后续被覆盖,具体 runtime/其他模块成因未定位;已有审计与限制记录,不自动重装。正式通过使用预载 libjavacore,并验证当前槽及首次调用事件 | +| 原业务算法目标 | 本轮交付的是工具改造与验收,没有交付或验证得物 dhw 的纯算法还原;工具测试通过不能当作业务算法已还原 | + +本轮到此收尾,不继续扩大真机验证或推进部署。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 2ef213f..080d3a8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,5 +1,7 @@ # PROGRESS — 跨会话进度看板 +2026-11-17 收尾入口:[AI_FIRST_CLOSEOUT.md](AI_FIRST_CLOSEOUT.md)。P0–P5 实现与约定隔离验收已提交,完整代码基准 e58f2ba;本次核对测试运行残留并补齐交付索引,不继续扩验或部署。分支集成/发布、默认部署、正式 capture_start 各族/LAN 撤销组合及已知 GOT 覆盖成因等仍按索引保留,未标成已完成。 + > 这是"我们现在在哪"的唯一真相。每个会话开始先读它,结束前更新它。 > 详细规格见 `REQUIREMENTS.md`,路线与架构见 `DEVELOPMENT_PLAN.md`。 From 0ad72ef271e39a4684bb6508b7335a633f020bfa Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:08:35 +0800 Subject: [PATCH 22/24] =?UTF-8?q?fix:=20=E5=8D=B8=E8=BD=BDGOT=20Hook?= =?UTF-8?q?=E6=97=B6=E4=BF=9D=E7=95=99=E5=A4=96=E9=83=A8=E6=94=B9=E5=86=99?= =?UTF-8?q?=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=94=B6=E5=B0=BE=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- agent/src/MAP.md | 5 +++ agent/src/hook/got.c | 24 ++++++++++++++ agent/src/hook/got.h | 4 +++ agent/src/hook/native_hooks.cpp | 27 ++++++++++------ agent/test/got_restore.c | 50 ++++++++++++++++++++++++++++++ docs/AI_FIRST_CLOSEOUT.md | 8 +++++ docs/NATIVE_GOT_CLOSEOUT.md | 41 ++++++++++++++++++++++++ docs/PROGRESS.md | 7 ++++- tools/MAP.md | 5 +++ tools/build_got_restore_fixture.sh | 10 ++++++ tools/verify_got_restore.ts | 32 +++++++++++++++++++ 11 files changed, 202 insertions(+), 11 deletions(-) create mode 100644 agent/test/got_restore.c create mode 100644 docs/NATIVE_GOT_CLOSEOUT.md create mode 100644 tools/build_got_restore_fixture.sh create mode 100644 tools/verify_got_restore.ts diff --git a/agent/src/MAP.md b/agent/src/MAP.md index b89daa8..aa9a7c2 100644 --- a/agent/src/MAP.md +++ b/agent/src/MAP.md @@ -4,6 +4,11 @@ ## Layout +2026-11-17: `hook/got.c` also owns `adh_restore_pointer_if_owned`: native GOT unhook uses +atomic compare/exchange and refuses another writer's pointer. Status reports `slotOwned` and +`ownership-lost`/`slot-unreadable` before interpreting historical hits. See +[NATIVE_GOT_CLOSEOUT.md](../../docs/NATIVE_GOT_CLOSEOUT.md) for the exact runtime coverage. + 2026-10-24: `trace/qbdi_trace.c` additionally owns one explicitly requested, <=65536-instruction paged command-thread recording (allocated on request, released after Host drain); `qbdi_read` never mixes trace IDs. The hook-time path remains replay with incomplete context, explicitly tagged. diff --git a/agent/src/hook/got.c b/agent/src/hook/got.c index 2e5bd4e..06c1f86 100644 --- a/agent/src/hook/got.c +++ b/agent/src/hook/got.c @@ -78,6 +78,30 @@ int adh_swap_pointer_in_ro_page(void **slot, void *newval) { return got_write_slot(slot, newval, perms_to_prot(perms), pagesz); } +int adh_restore_pointer_if_owned(void **slot, void *replacement, void *original) { + if (!slot || (uintptr_t)slot % sizeof(void *)) return 0; + char perms[8]; + perms_of_addr((unsigned long long)(uintptr_t)slot, perms, sizeof(perms)); + if (perms[0] != 'r') return 0; + void *current = __atomic_load_n(slot, __ATOMIC_ACQUIRE); + if (current == original) return 1; + if (current != replacement) return -1; + long pagesz = sysconf(_SC_PAGESIZE); + if (pagesz <= 0) pagesz = 4096; + void *page = (void *)((uintptr_t)slot & ~((uintptr_t)pagesz - 1)); + const int writable = perms[1] == 'w'; + const int prot = perms_to_prot(perms); + if (!writable && mprotect(page, pagesz, prot | PROT_WRITE) != 0) return 0; + // The slot may have changed after our first read or while making RELRO writable. + // A check followed by an unconditional store would still erase that writer's value. + void *expected = replacement; + const int swapped = __atomic_compare_exchange_n(slot, &expected, original, 0, + __ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE); + const int protected_again = writable || mprotect(page, pagesz, prot) == 0; + if (!protected_again) return 0; + return swapped || expected == original ? 1 : -1; +} + // Patch raw code bytes in place: make every page covering [addr, addr+len) writable (keeping X), // memcpy, flush the instruction cache and restore the original protection. Used to write a saved // original prologue back over an inline hook without asking Dobby to free its trampoline pool diff --git a/agent/src/hook/got.h b/agent/src/hook/got.h index 98a9402..1469688 100644 --- a/agent/src/hook/got.h +++ b/agent/src/hook/got.h @@ -52,6 +52,10 @@ int adh_addr_is_executable(void *addr); // Swap one pointer-sized slot in a (possibly read-only/RELRO) page and restore the // original protection. Returns 1 on success. Used by the JNIEnv function-table hooks. int adh_swap_pointer_in_ro_page(void **slot, void *newval); +// Restore only our own published pointer (atomic compare/exchange), or accept an already +// restored slot. 1 = restored, -1 = another writer owns the slot (left untouched), +// 0 = invalid/unreadable slot or protection failure. Never reclaims the old stub. +int adh_restore_pointer_if_owned(void **slot, void *replacement, void *original); // Copy the /proc/self/maps permission string ("r--p") of the mapping containing addr, // or "?" when unmapped. Used to prove a temporarily-writable page was restored. void adh_perms_of_addr(void *addr, char *out, int out_size); diff --git a/agent/src/hook/native_hooks.cpp b/agent/src/hook/native_hooks.cpp index 001cacc..68b2b6a 100644 --- a/agent/src/hook/native_hooks.cpp +++ b/agent/src/hook/native_hooks.cpp @@ -2175,11 +2175,13 @@ extern "C" int adh_native_hook_unhook(int hook_id, int hard, char *error, size_t return 1; // idempotent restore+retire, never a promise of resource reclamation } if (ctx->mode == 0) { - int restored=ctx->slot_addr && (*(void **)ctx->slot_addr==ctx->original || - (adh_swap_pointer_in_ro_page((void **)ctx->slot_addr,ctx->original) && *(void **)ctx->slot_addr==ctx->original)); - if (!restored) { + const int restored = adh_restore_pointer_if_owned((void **)ctx->slot_addr, + ctx->replacement, ctx->original); + if (restored != 1) { pthread_mutex_unlock(&g_native_hooks_lock); - return (set_error(error, error_size, "native unhook failed id=%d", hook_id), 0); + return (set_error(error, error_size, restored < 0 + ? "not-unhooked: GOT ownership lost id=%d; current slot left untouched, stub retained" + : "not-unhooked: GOT restore/protection unconfirmed id=%d; stub retained", hook_id), 0); } __atomic_store_n(&ctx->active, 0, __ATOMIC_RELEASE); ctx->unhook_pending = 1; @@ -2377,11 +2379,14 @@ extern "C" int adh_native_hook_status_json(char *out, size_t out_size) { // mode 0 mechanism facts. address/target/original are all the slot's pre-patch VALUE for a // got hook, so they say nothing about which slot was touched; these do. A hook that installs // and never fires otherwise looks exactly like a target with no traffic to observe. - char gotbuf[288] = ""; + char gotbuf[384] = ""; + int got_owned = 1; if (ctx.mode == 0 && ctx.slot_addr) { char perms_now[8] = "?"; adh_perms_of_addr((void *)ctx.slot_addr, perms_now, sizeof(perms_now)); - void *cur = *(void **)ctx.slot_addr; + const int readable = perms_now[0] == 'r'; + void *cur = readable ? __atomic_load_n((void **)ctx.slot_addr, __ATOMIC_ACQUIRE) : NULL; + got_owned = readable ? (cur == ctx.replacement ? 1 : 0) : -1; // got_write_slot puts the page protection back; comparing the live value with the one we // recorded before the write is what proves it. Leaving a RELRO page writable is a // footprint a target can see. @@ -2389,21 +2394,23 @@ extern "C" int adh_native_hook_status_json(char *out, size_t out_size) { strncmp(perms_now, ctx.slot_perms_before, 3) == 0; snprintf(gotbuf, sizeof(gotbuf), ",\"slot\":\"0x%llx\",\"slotCurrent\":\"0x%llx\",\"pageProtRestored\":%s," - "\"pagePermsBefore\":\"%s\",\"pagePermsNow\":\"%s\"", + "\"pagePermsBefore\":\"%s\",\"pagePermsNow\":\"%s\",\"slotOwned\":%s", (unsigned long long)ctx.slot_addr, (unsigned long long)(uintptr_t)cur, - prot_restored ? "true" : "false", ctx.slot_perms_before, perms_now); + prot_restored ? "true" : "false", ctx.slot_perms_before, perms_now, + got_owned < 0 ? "null" : got_owned ? "true" : "false"); } // got rewrites exactly one relocation slot (its install refuses anything else); sites/vtable // report how many they rewrote. Inline patches a function entry rather than a slot. const int slots_patched = (ctx.mode == 0) ? (ctx.slot_addr ? 1 : 0) : ctx.site_count; const uint64_t first_hit = g_native_hook_first_hit_ms[i].load(std::memory_order_relaxed); - const char *verdict = hits > 0 ? "fired" : "installed-never-fired"; + const char *verdict = got_owned < 0 ? "slot-unreadable" : !got_owned ? "ownership-lost" : + hits > 0 ? "fired" : "installed-never-fired"; // "x1+0:8" = the hit writes 8 bytes at *(x1). Empty when the hook does not write. char writebuf[24] = ""; if (ctx.write_len > 0) { snprintf(writebuf, sizeof(writebuf), "x%d+%d:%d", ctx.write_arg, ctx.write_off, ctx.write_len); } - char item[4096]; // sitebuf is 1400 and gotbuf 288; 2048 truncated the JSON for a sites hook + char item[4096]; // sitebuf is 1400 and gotbuf 384; 2048 truncated the JSON for a sites hook snprintf(item, sizeof(item), "{\"id\":%d,\"mode\":\"%s\",\"module\":\"%s\",\"symbol\":\"%s\"," "\"address\":\"0x%llx\",\"target\":\"0x%llx\",\"original\":\"0x%llx\"," diff --git a/agent/test/got_restore.c b/agent/test/got_restore.c new file mode 100644 index 0000000..13aa038 --- /dev/null +++ b/agent/test/got_restore.c @@ -0,0 +1,50 @@ +#include "../src/hook/got.h" +#include +#include +#include +#include +#include + +// Links the actual production got.c, not a copy of its restore algorithm. +int main(void) { + const size_t size = (size_t)sysconf(_SC_PAGESIZE); + void **slot = mmap(NULL, size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + assert(slot != MAP_FAILED); + void *original = (void *)(uintptr_t)0x1000; + void *ours = (void *)(uintptr_t)0x2000; + void *other = (void *)(uintptr_t)0x3000; + *slot = ours; + assert(adh_restore_pointer_if_owned(slot, ours, original) == 1 && *slot == original); + puts("PASS owned-writable"); + *slot = other; + assert(adh_restore_pointer_if_owned(slot, ours, original) == -1 && *slot == other); + puts("PASS foreign-writable-unchanged"); + *slot = ours; + assert(mprotect(slot, size, PROT_READ) == 0); + assert(adh_restore_pointer_if_owned(slot, ours, original) == 1 && *slot == original); + char perms[8]; + adh_perms_of_addr(slot, perms, sizeof(perms)); + assert(perms[0] == 'r' && perms[1] == '-'); + puts("PASS owned-relro-protection-restored"); + assert(adh_restore_pointer_if_owned(slot, ours, original) == 1 && *slot == original); + puts("PASS already-restored-idempotent"); + assert(mprotect(slot, size, PROT_READ | PROT_WRITE) == 0); + *slot = other; + assert(mprotect(slot, size, PROT_READ) == 0); + assert(adh_restore_pointer_if_owned(slot, ours, original) == -1 && *slot == other); + adh_perms_of_addr(slot, perms, sizeof(perms)); + assert(perms[0] == 'r' && perms[1] == '-'); + puts("PASS foreign-relro-value-and-protection-unchanged"); + assert(adh_restore_pointer_if_owned(NULL, ours, original) == 0); + assert(adh_restore_pointer_if_owned((void **)((char *)slot + 1), ours, original) == 0); + puts("PASS invalid-and-misaligned-rejected"); + assert(mprotect(slot, size, PROT_NONE) == 0); + assert(adh_restore_pointer_if_owned(slot, ours, original) == 0); + puts("PASS unreadable-rejected"); + assert(munmap(slot, size) == 0); + assert(adh_restore_pointer_if_owned(slot, ours, original) == 0); + puts("PASS unmapped-rejected"); + puts("ADH_GOT_RESTORE_PASS 8"); + return 0; +} diff --git a/docs/AI_FIRST_CLOSEOUT.md b/docs/AI_FIRST_CLOSEOUT.md index 7833f1b..802bc9f 100644 --- a/docs/AI_FIRST_CLOSEOUT.md +++ b/docs/AI_FIRST_CLOSEOUT.md @@ -1,5 +1,13 @@ # ADH P0–P5 收尾索引(2026-11-17) +收尾补丁:独立 `feat/adh-completion-20261117` 分支补上 GOT 卸载所有权保护, +原生恢复夹具8/8、清理通过;详情与未重跑边界见 [NATIVE_GOT_CLOSEOUT.md](NATIVE_GOT_CLOSEOUT.md)。 +它没有解决下表的 GOT 覆盖成因,也没有推进默认部署或发布;下文 e58f2ba 仍指既有正式链验收基准。 +本次补丁回归:Agent 默认构建、Host 类型检查、Host561/561(0 skip,含配套CLI源码路径)、 +Android JVM73/73(0 skip)、原生Hook选择门禁和94项MCP registry检查均通过。 + +## 原阶段收尾记录(50b4cda) + 约定的实现与隔离验收已完成,最新代码基准为 e58f2ba(2026-11-16)。本次收尾只核对状态、补齐交付索引并执行 Host 文档回归;没有重跑真机验收、安装/重启手机或启停现有服务。 ## 交付位置 diff --git a/docs/NATIVE_GOT_CLOSEOUT.md b/docs/NATIVE_GOT_CLOSEOUT.md new file mode 100644 index 0000000..cffbc40 --- /dev/null +++ b/docs/NATIVE_GOT_CLOSEOUT.md @@ -0,0 +1,41 @@ +# GOT 卸载所有权收尾(2026-11-17) + +收尾审查发现:原生 GOT Hook 卸载先检查是否为 original,否则直接写回旧 original。 +若槽已被 runtime、人类或另一个工具改写,这会覆盖对方的新值。这里修复的是卸载的 +所有权检查,**没有定位**此前 libandroid_runtime/getpid 后续被覆盖的具体成因。 + +## 修复行为 + +- `got.c` 提供生产共用的原子 compare/exchange 恢复:当前值为本 Hook replacement 才写回 original; + 已为 original 时幂等通过;其他值拒绝且不写入。不使用“先检查再无条件写入”。 +- 保留 RELRO 原页权限。不可读、未映射、未对齐或保护操作失败,返回未确认,保留 stub。 +- `native_hook` 的 GOT 卸载冲突返回 `not-unhooked: GOT ownership lost`,保持失败状态, + 不自动重装 Hook、不重试写入、不承诺已卸载或已回收资源。 +- 活跃 GOT 状态增加 `slotOwned`(true/false/null),`verdict` 在失去当前槽时为 `ownership-lost`, + 不可读时为 `slot-unreadable`。历史 hits 保留,但不再单凭历史次数输出 fired。 + 字段描述读取时的快照,不是对其他线程后续写入的承诺。 + +## 本轮实测 + +在 aa165071(PGP110 / API35 / arm64-v8a)独立、短命的 shell 原生进程中, +`agent/test/got_restore.c` **直接链接本次生产 got.c**,8/8 通过: +可写页自有值恢复、可写页他人值不变、只读页恢复及权限恢复、已恢复幂等、 +只读页他人值及权限不变、空/未对齐地址拒绝、不可读页拒绝、已解除映射地址拒绝。 +测试程序使用合成指针数据,没有调用这些指针。 + +原始输出和报告保留于聚合工作区私有目录 `.tmp/adh-got-restore-20261117-01/`; +`cleanupVerified=true`,自己的 UUID 目录和文件已清理。没有启停 Host、修改 reverse、 +安装测试包或 Zygisk 模块、重启手机,未启停真实业务 App。 +收尾时再次比较原 scope、host.endpoint、Agent、Zygisk、daemon.apk、module.prop 六个文件, +SHA 与此前 Zygisk run-05 的原环境基线一致;原8088/8761 reverse保留,四个Host/隔离端口无监听。 + +本次 Agent 默认构建和 Host 类型检查通过;Host561/561、Android JVM73/73,均0 skip; +原生Hook选择门禁和94项MCP registry检查通过。Host回归显式指定配套adh-cli的src路径, +前两次因路径缺失跳过的1项保留日志,未当作完整通过。 +此前真实 Zygisk 6/6 和 self-load 11/11 是各自文档所列旧提交/构建的历史实测, +**没有用本次修改后的 Agent 重跑整套 Zygisk、Hook 命中或卸载 RPC 集成验收**。 +本轮原生夹具结果不替代这些未重跑项目。 + +复现:先 `bash tools/build_got_restore_fixture.sh`,再显式运行 +`node tools/verify_got_restore.ts TEST_SERIAL agent/build/adh-got-restore NEW_PRIVATE_OUTPUT`。 +仅对获准的独立测试设备执行;缺少设备/构建条件时保留未验证,不回退到业务目标。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 080d3a8..793957f 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,6 +1,11 @@ # PROGRESS — 跨会话进度看板 -2026-11-17 收尾入口:[AI_FIRST_CLOSEOUT.md](AI_FIRST_CLOSEOUT.md)。P0–P5 实现与约定隔离验收已提交,完整代码基准 e58f2ba;本次核对测试运行残留并补齐交付索引,不继续扩验或部署。分支集成/发布、默认部署、正式 capture_start 各族/LAN 撤销组合及已知 GOT 覆盖成因等仍按索引保留,未标成已完成。 +2026-11-17 收尾补丁:在独立 `feat/adh-completion-20261117` 补上 GOT 卸载的原子所有权检查, +避免覆盖 runtime/人类/其他工具的新指针;状态区分历史命中和当前槽所有权。 +原生生产恢复函数真机隔离夹具8/8、清理通过;未重跑正式 Zygisk 全链,未发布或部署。 +详情:[NATIVE_GOT_CLOSEOUT.md](NATIVE_GOT_CLOSEOUT.md)。 + +此前阶段收尾入口:[AI_FIRST_CLOSEOUT.md](AI_FIRST_CLOSEOUT.md)。P0–P5 实现与约定隔离验收已提交,正式链验收代码基准 e58f2ba;50b4cda 核对测试运行残留并补齐交付索引。分支集成/发布、默认部署、正式 capture_start 各族/LAN 撤销组合及已知 GOT 覆盖成因等仍按索引保留,未标成已完成。 > 这是"我们现在在哪"的唯一真相。每个会话开始先读它,结束前更新它。 > 详细规格见 `REQUIREMENTS.md`,路线与架构见 `DEVELOPMENT_PLAN.md`。 diff --git a/tools/MAP.md b/tools/MAP.md index c1eb4fb..453c315 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -5,6 +5,11 @@ script or touching `verify_all.sh`.** ## Shared libraries (source these, don't execute) +`build_got_restore_fixture.sh` builds a short-lived ARM64 executable linked to production `got.c`; +it never calls ADB. `verify_got_restore.ts TEST_SERIAL BUILT_BINARY NEW_PRIVATE_OUTPUT` explicitly +runs it in a UUID directory, rejects the daily device, and removes only its own executable/directory. +It does not start a Host, install an APK, change reverse mappings, flash or reboot a device. + ## P5 isolated Android acceptance (2026-11-16) `verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT` is explicit real-device acceptance with a new package, private root domain, UDS, Host ports/data and cleanup/protection checks. It never flashes a module or restarts the running service. Build `:p5sandbox` and `:daemon` with `-PadhP5Sandbox=true` and an Agent built for port 18761. `p5_isolated_host.ts` maps only the private fixture endpoints into the production dispatcher. `verify_v132_p5_stdio.sh` is the registered host-only Kotlin interoperability gate; missing offline fixture is SKIP, never real-device fallback. Details and real/unverified boundaries: [P5_ANDROID_ACCEPTANCE.md](../docs/P5_ANDROID_ACCEPTANCE.md). diff --git a/tools/build_got_restore_fixture.sh b/tools/build_got_restore_fixture.sh new file mode 100644 index 0000000..299ad1e --- /dev/null +++ b/tools/build_got_restore_fixture.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib/env.sh" +mkdir -p "$ROOT/agent/build" +CLANG="$ADH_NDK_BIN/clang$_adh_exe" +"$CLANG" --target=aarch64-linux-android26 -O2 -Wall -Wextra -Werror \ + -ffunction-sections -fdata-sections -Wl,--gc-sections \ + "$ROOT/agent/test/got_restore.c" "$ROOT/agent/src/hook/got.c" \ + -ldl -llog -o "$ROOT/agent/build/adh-got-restore" +echo 'built adh-got-restore (production GOT restore runtime fixture; no ADB)' diff --git a/tools/verify_got_restore.ts b/tools/verify_got_restore.ts new file mode 100644 index 0000000..7c5d6c4 --- /dev/null +++ b/tools/verify_got_restore.ts @@ -0,0 +1,32 @@ +// Explicit, short-lived native fixture; no Host, installed package, or Zygisk changes. +import assert from 'node:assert/strict'; +import {execFile} from 'node:child_process'; +import {promisify} from 'node:util'; +import {randomUUID} from 'node:crypto'; +import {existsSync,mkdirSync,writeFileSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +const [serial,binary,output,...extra]=process.argv.slice(2); +if(!serial||serial==='a22fecdd'||!binary||!output||extra.length) + throw new Error('usage: verify_got_restore.ts TEST_SERIAL BUILT_BINARY NEW_PRIVATE_OUTPUT; daily device refused'); +assert.ok(existsSync(binary),'built fixture missing'); +const dir=resolve(output);assert.ok(!existsSync(dir),'output must be new'); +const run=promisify(execFile),remote='/data/local/tmp/adh-got-'+randomUUID(); +const adb=async(args:string[])=>(await run('adb',['-s',serial,...args],{timeout:20000,windowsHide:true})).stdout.trim(); +const report:any={startedAt:new Date().toISOString(),serial,passed:0,cleanupVerified:false};let owned=false; +mkdirSync(dir,{recursive:true}); +try{ + assert.equal(await adb(['get-state']),'device'); + report.device={model:await adb(['shell','getprop','ro.product.model']),sdk:await adb(['shell','getprop','ro.build.version.sdk']),abi:await adb(['shell','getprop','ro.product.cpu.abi'])}; + assert.equal(report.device.abi,'arm64-v8a'); + await adb(['shell','mkdir',remote]);owned=true; + await adb(['push',resolve(binary),remote+'/verify']);await adb(['shell','chmod','700',remote+'/verify']); + const stdout=await adb(['shell',remote+'/verify']);writeFileSync(join(dir,'stdout.txt'),stdout+'\n'); + assert.match(stdout,/ADH_GOT_RESTORE_PASS 8/); + assert.equal(stdout.split(/\r?\n/).filter(s=>s.startsWith('PASS ')).length,8); + report.passed=8; +}catch(error){report.failure=(error as Error).message;process.exitCode=1;} +finally{ + try{if(owned){const files=await adb(['shell','ls','-A',remote]);assert.ok(files===''||files==='verify','unexpected fixture files; retain for inspection');await adb(['shell','rm','-f',remote+'/verify']);await adb(['shell','rmdir',remote]);}report.cleanupVerified=true;} + catch(error){report.cleanupError=(error as Error).message;process.exitCode=1;} + report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report)); +} From 2546b67e5ff63dc7900f5d18114484c0a3797847 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:23:19 +0800 Subject: [PATCH 23/24] =?UTF-8?q?test:=20=E8=A1=A5=E9=BD=90=E6=AD=A3?= =?UTF-8?q?=E5=BC=8FZygisk=E4=B8=83=E6=97=8F=E6=8D=95=E8=8E=B7=E4=B8=8ELAN?= =?UTF-8?q?=E6=8E=88=E6=9D=83=E6=92=A4=E9=94=80=E9=AA=8C=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/adh/p5sandbox/ProbeApplication.java | 17 +++++ .../java/com/adh/p5sandbox/ProbeService.java | 4 +- docs/AI_FIRST_CLOSEOUT.md | 4 ++ docs/AI_FIRST_REMAINING.md | 22 ++++++ docs/NATIVE_GOT_CLOSEOUT.md | 4 ++ docs/P5_ZYGISK_ACCEPTANCE.md | 4 ++ docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md | 70 +++++++++++++++++++ docs/PROGRESS.md | 6 ++ tools/MAP.md | 6 ++ tools/p5_zygisk_cases.ts | 55 +++++++++++++++ tools/verify_p5_zygisk.ts | 53 +++++++++----- 11 files changed, 225 insertions(+), 20 deletions(-) create mode 100644 docs/AI_FIRST_REMAINING.md create mode 100644 docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md create mode 100644 tools/p5_zygisk_cases.ts diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java index 1d62e2a..838c1ba 100644 --- a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeApplication.java @@ -12,6 +12,23 @@ public final class ProbeApplication extends Application { String maps=new String(Files.readAllBytes(new File("/proc/self/maps").toPath()),StandardCharsets.UTF_8); long before=System.nanoTime();int pid=android.system.Os.getpid();long after=System.nanoTime(); JSONObject receipt=new JSONObject().put("pid",pid).put("uid",Process.myUid()).put("beforeNs",Long.toString(before)).put("afterNs",Long.toString(after)).put("agentMemfdBeforeApplicationProbe",maps.contains("memfd:jit-cache")).put("applicationCallback",true); + File config=new File(getFilesDir(),"p5-zygisk-probes.json"); + if(config.exists()){ + JSONObject parameters=new JSONObject(new String(Files.readAllBytes(config.toPath()),StandardCharsets.UTF_8)); + String marker=parameters.getString("marker"); + if(!marker.matches("P5Z_[A-Za-z0-9_]+"))throw new IllegalArgumentException("invalid own probe marker"); + long captureBefore=System.nanoTime();JSONObject probes=ProbeService.crypto(marker); + boolean absent; + try{absent=!android.system.Os.access("/data/local/tmp/"+marker+"_system",android.system.OsConstants.F_OK);} + catch(android.system.ErrnoException e){if(e.errno!=android.system.OsConstants.ENOENT)throw e;absent=true;} + java.util.concurrent.FutureTask tls=new java.util.concurrent.FutureTask<>(()-> + new JSONObject().put("ok",ProbeService.tls(marker,parameters.getInt("tlsPort"))).put("tid",Process.myTid())); + new Thread(tls,"p5-application-tls").start(); + JSONObject tlsResult=tls.get(8,java.util.concurrent.TimeUnit.SECONDS); + probes.put("system",absent).put("tls",tlsResult.getBoolean("ok")); + receipt.put("marker",marker).put("probes",probes).put("captureBeforeNs",Long.toString(captureBefore)) + .put("captureAfterNs",Long.toString(System.nanoTime())).put("tlsTid",tlsResult.getInt("tid")).put("probesInApplicationCallback",true); + } Files.write(new File(getFilesDir(),"p5-zygisk-application.json").toPath(),receipt.toString().getBytes(StandardCharsets.UTF_8)); }catch(Exception e){throw new RuntimeException(e);}} } diff --git a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java index 78233a8..d2a76ac 100644 --- a/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java +++ b/device/p5sandbox/src/main/java/com/adh/p5sandbox/ProbeService.java @@ -21,7 +21,7 @@ public final class ProbeService extends Service { private static native int systemProbe(String path); public IBinder onBind(Intent intent){return null;} private static byte[] data(String marker,String family){return (marker+"_"+family).getBytes(StandardCharsets.UTF_8);} - private static JSONObject crypto(String marker) throws Exception { + static JSONObject crypto(String marker) throws Exception { JSONObject result=new JSONObject(); byte[] digest=MessageDigest.getInstance("SHA-256","AndroidOpenSSL").digest(data(marker,"digest"));result.put("digest",digest.length==32); Mac mac=Mac.getInstance("HmacSHA256","AndroidOpenSSL");mac.init(new SecretKeySpec(new byte[32],"HmacSHA256"));result.put("hmac",mac.doFinal(data(marker,"hmac")).length==32); @@ -29,7 +29,7 @@ private static JSONObject crypto(String marker) throws Exception { KeyPairGenerator gen=KeyPairGenerator.getInstance("EC","AndroidOpenSSL");gen.initialize(256);KeyPair pair=gen.generateKeyPair();Signature sig=Signature.getInstance("SHA256withECDSA","AndroidOpenSSL");sig.initSign(pair.getPrivate());sig.update(data(marker,"asymmetric"));byte[] signed=sig.sign();sig.initVerify(pair.getPublic());sig.update(data(marker,"asymmetric"));result.put("asymmetric",sig.verify(signed)); plain=data(marker,"aead");c=Cipher.getInstance("AES/GCM/NoPadding","AndroidOpenSSL");c.init(Cipher.ENCRYPT_MODE,key,new GCMParameterSpec(128,new byte[12]));enc=c.doFinal(plain);c.init(Cipher.DECRYPT_MODE,key,new GCMParameterSpec(128,new byte[12]));result.put("aead",Arrays.equals(plain,c.doFinal(enc)));return result; } - private static boolean tls(String marker,int port) throws Exception { + static boolean tls(String marker,int port) throws Exception { // Fixture loopback only. No external network or changes to the device trust store. TrustManager[] trust={new X509TrustManager(){public X509Certificate[] getAcceptedIssuers(){return new X509Certificate[0];}public void checkClientTrusted(X509Certificate[] c,String a){}public void checkServerTrusted(X509Certificate[] c,String a){}}}; SSLContext context=SSLContext.getInstance("TLS");context.init(null,trust,new SecureRandom()); diff --git a/docs/AI_FIRST_CLOSEOUT.md b/docs/AI_FIRST_CLOSEOUT.md index 802bc9f..d1eb099 100644 --- a/docs/AI_FIRST_CLOSEOUT.md +++ b/docs/AI_FIRST_CLOSEOUT.md @@ -1,5 +1,9 @@ # ADH P0–P5 收尾索引(2026-11-17) +后续推进:正式Zygisk原六项、capture_start七族/全部禁用、真实LAN grant撤销已在新Agent上 +完整15/15实测,清理和原环境保护通过;见[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](P5_ZYGISK_EXTENDED_ACCEPTANCE.md)。 +以下历史“正式链扩展覆盖尚未实测”条目已由这次指定探针覆盖更新,全部算法/模块组合仍未验证。 + 收尾补丁:独立 `feat/adh-completion-20261117` 分支补上 GOT 卸载所有权保护, 原生恢复夹具8/8、清理通过;详情与未重跑边界见 [NATIVE_GOT_CLOSEOUT.md](NATIVE_GOT_CLOSEOUT.md)。 它没有解决下表的 GOT 覆盖成因,也没有推进默认部署或发布;下文 e58f2ba 仍指既有正式链验收基准。 diff --git a/docs/AI_FIRST_REMAINING.md b/docs/AI_FIRST_REMAINING.md new file mode 100644 index 0000000..bda314b --- /dev/null +++ b/docs/AI_FIRST_REMAINING.md @@ -0,0 +1,22 @@ +# AI 自主分析改造:剩余工作跟踪(2026-11-17) + +用户要求继续完成剩余工作。阶段收尾不等于全部目标完成;以下按当前代码、外部运行状态和 +实际报告更新。P0–P5历史提交入口见[AI_FIRST_CLOSEOUT.md](AI_FIRST_CLOSEOUT.md)。 + +| 工作 | 当前状态 | 完成所需证据 | +| --- | --- | --- | +| 正式Zygisk扩展 | 已实测完成指定代表性范围 | 七族单启用、全部禁用、LAN grant撤销及原六项,共15/15;expanded-02清理和原环境保护通过,见[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](P5_ZYGISK_EXTENDED_ACCEPTANCE.md) | +| GOT卸载保护 | 底层恢复函数完成;状态链已复测 | 原生8/8;最新Agent全链slotOwned/首次调用通过。尚未执行失去所有权后的卸载RPC集成用例 | +| ADH与adh-cli分支集成 | 未完成 | 包含全部阶段提交的集成分支、配套CLI检查、远端PR/提交及CI结果;不得覆盖原工作区未提交修改 | +| 打包与发布 | 未完成 | 一致且递增的版本、默认产物构建、发布门禁、可下载Release/CLI包与对应提交;不发布opt-in测试APK或捕获数据 | +| 默认设备环境升级 | 未完成 | 原模块/Manager/Root状态可恢复备份;默认目录启动、身份/配对状态保留、USB/LAN共用RPC、正式缓存投递的实际结果;独立设备授权仍只适用aa165071 | +| GOT覆盖成因 | 未定位 | 实际覆盖写入方或等价强证据;不能用其他Zygisk实现源码类比就声称已定位本机Zygisk Next | +| 其他环境覆盖 | 未验证 | 第二个实际ROM/Root/架构环境的独立报告;当前仅一台API35 arm64设备,不能用JVM或同ROM多用户冒充另一环境 | +| 得物dhw纯算法 | 未交付 | 同次请求输入/输出配对、多样本逐字节对拍、独立可运行实现和已知边界;不得把工具验收或只列参数当作算法还原 | + +仍是既定产品边界:未迁移设备RPC明确unsupported;Java/inline early仍unsupported;不承诺 +init_array前或未加载模块的提前Hook。它们不能被文档换名为“已支持”,也不要求伪造不存在的验证。 +各算法/模块组合只按实际指定样本记录,代表性七族通过不外推为所有组合。 + +当前最新实现位于独立`feat/adh-completion-20261117`;原AndroidDecryptHub工作区仍在P1分支, +默认Host在本轮开始/结束均未监听。运行态会变化,下一步必须重新检查;这些不是可复用的固定环境前提。 diff --git a/docs/NATIVE_GOT_CLOSEOUT.md b/docs/NATIVE_GOT_CLOSEOUT.md index cffbc40..c63eaf6 100644 --- a/docs/NATIVE_GOT_CLOSEOUT.md +++ b/docs/NATIVE_GOT_CLOSEOUT.md @@ -1,5 +1,9 @@ # GOT 卸载所有权收尾(2026-11-17) +后续:含本补丁的Agent已通过正式Zygisk扩展15/15,包含当前GOT槽所有权与首次调用证据。 +见[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](P5_ZYGISK_EXTENDED_ACCEPTANCE.md); +本页后文“未重跑”指原收尾时点,GOT卸载冲突RPC仍未由后续全链触发。 + 收尾审查发现:原生 GOT Hook 卸载先检查是否为 original,否则直接写回旧 original。 若槽已被 runtime、人类或另一个工具改写,这会覆盖对方的新值。这里修复的是卸载的 所有权检查,**没有定位**此前 libandroid_runtime/getpid 后续被覆盖的具体成因。 diff --git a/docs/P5_ZYGISK_ACCEPTANCE.md b/docs/P5_ZYGISK_ACCEPTANCE.md index 7d32145..93228a2 100644 --- a/docs/P5_ZYGISK_ACCEPTANCE.md +++ b/docs/P5_ZYGISK_ACCEPTANCE.md @@ -1,5 +1,9 @@ # P5:真实 Zygisk 投递链隔离验收(2026-11-16) +2026-11-17 后续:最新Agent重跑原六项,并新增正式链七族捕获、全部禁用和LAN grant撤销, +最终15/15、清理与原环境保护通过,见[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](P5_ZYGISK_EXTENDED_ACCEPTANCE.md)。 +下文保留2026-11-16六项的原始范围与失败历史,不以新结果倒改旧记录。 + 最终 **6 PASS / 0 FAIL**,`cleanupVerified=true`、`originalHostAndFilesUnchanged=true`。设备为用户本轮明确授权可重启的 aa165071,PGP110 / Android 15 API35 / arm64-v8a / KernelSU,Zygisk Next 1.5.2,SELinux 保持 enforcing。使用独立 `feat/adh-p5-zygisk-e2e-20261116` worktree,基座 efe8e78。 这是**真实 Zygisk 回调、companion、Root broker、Agent 消费与命中链路**的实测;不是测试 App 主动 dlopen Agent。默认生产目录的部署/升级仍未进行。此前 self-load 沙盒结果保留于 [P5_ANDROID_ACCEPTANCE.md](P5_ANDROID_ACCEPTANCE.md)。 diff --git a/docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md b/docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md new file mode 100644 index 0000000..034b42d --- /dev/null +++ b/docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md @@ -0,0 +1,70 @@ +# P5 正式 Zygisk 扩展验收(2026-11-17) + +最终 **15 PASS / 0 FAIL**,`cleanupVerified=true`、`originalHostAndFilesUnchanged=true`。 +使用独立 `feat/adh-completion-20261117`,Agent 源码基准为0ad72ef,包含GOT卸载所有权修复。 +测试夹具和脚本为本次提交。设备仍为获准可重启的aa165071、PGP110 / API35 / arm64-v8a / +KernelSU / Zygisk Next1.5.2,SELinux enforcing。 + +正式默认命名空间的部署/升级尚未进行;本次临时模块使用同一Zygisk main.cpp、真实框架回调、 +companion、Root broker、缓存校验与Agent消费路径,状态目录/broker/Host端口独立,作用域仅测试包。 +加载和卸载各重启一次;默认生产目录六个文件SHA及原reverse映射前后一致。 +本轮开始及结束时原8088 Host均未监听,没有为满足夹具前提而启动或重启原服务。 + +## 正式捕获链的八项实测 + +每个新进程只启用一个捕获族,七族代表性探针仍全部运行;最后再全部禁用。 +cache经真实companion交付,Agent在post-specialize、start之前执行capture_start, +探针在Application.onCreate内发起,不由App加载Agent或调用early export,不做启用前warmup。 +此ROM的libjavacrypto/libssl/libjavacore已由Zygote预载;未声明未加载模块也能提前Hook。 + +| 启用族 | 代表性输入与实际事件 | 本族标记命中 | +| --- | --- | --- | +| digest | SHA-256 / EVP_DigestUpdate | 1 | +| hmac | HmacSHA256 / HMAC_Update或EVP_DigestSignUpdate | 1 | +| symmetric | AES-CBC / EVP_CipherUpdate | 1 | +| asymmetric | SHA256withECDSA / 签名原文或ECDSA_sign_digest的已计算摘要 | 1 | +| tls | 测试包→私有Root loopback TLS / SSL_write中的唯一标记 | 1 | +| aead | AES-GCM / AEAD原文 | 2 | +| system | android.system.Os.access / access唯一路径 | 1 | +| 全部禁用 | 七种探针仍全部成功 | 0,整个会话捕获数也为0 | + +每项还验证:启用族实际安装计数>0,其他族未布防;共享DigestSign符号仅在HMAC/签名需要时布防; +其他族唯一标记命中为0。命中必须属于本次session,在本次Application探针起止nanoTime窗口内, +并匹配实际执行TID。TLS在Application创建并等待的自身工作线程运行,其TID单独记录; +其他显式探针在主线程。所有会话窗口完整读取,dropped/jdropped/backlog均0,complete=true。 +这里的“0”针对禁用族的指定探针标记;不声称启用族不会捕获其他初始化流量。 +全部禁用时安装confirmed=0、回执为partial-or-failed,不把零安装包装成applied。 + +## 其余七项实测 + +- 原正式链六项重跑:投递/应用/首次GOT调用窗口命中;真实TTL到期;显式缓存撤销; + 卸载重装产生实际UID变化;仅临时模块Agent文件字节/SHA变化;Root broker不可用。 + 所有拒绝都经真实companion,新进程earlyPlan=null、native Hook数0;绑定反例前有成功正例。 +- 新增真实Wi-Fi LAN授权撤销:USB配对后,经实际TLS连接staging,缓存sourceGrant匹配该grant, + 先证明正式Zygisk命中;USB撤销grant后,已有进程同一GOT的slotOwned仍true,未自动卸载或重装; + 再冷启测试包,真实companion拒绝旧缓存,earlyPlan=null、无Hook。 + +LAN撤销验证的是未来缓存投递,不承诺撤销会回滚已经运行的进程。 +GOT正例还验证最新Agent的slotOwned=true及当前slot=replacement,不能只凭历史hits。 +GOT卸载冲突RPC仍未由本轮触发;其底层恢复函数8/8实测保留于[NATIVE_GOT_CLOSEOUT.md](NATIVE_GOT_CLOSEOUT.md)。 + +## 失败历史、清理与回归 + +首轮expanded-01前三项通过,捕获项因测试Application在主线程进行网络请求,触发 +NetworkOnMainThreadException而失败;读取自身崩溃记录确认,未归因为Agent捕获问题。 +修复为测试App自己的线程,未修改系统或业务App线程策略。首轮cleanupVerified=false还来自 +夹具把被signal终止的Host之exitCode=null误判为未退出;修复为同时检查exitCode/signalCode。 +模块/测试包已卸载,端口释放及原文件一致的事实独立核对,未倒改首轮结果。 + +清理改为各步骤分别记录失败并继续其他独立步骤,防止卸载包失败跳过自身模块清理; +nonce所有权、原Host无在线会话与原进程身份检查仍约束模块删除/重启,不靠忽略异常变绿。 +原Host可以不存在;若存在则必须可查询、无在线会话,且重启前再次核对身份。 + +最终expanded-02报告和逐族窗口证据保留在聚合工作区私有 +`.tmp/adh-p5-zygisk-expanded-02/`;失败报告保留在expanded-01,APK/so/捕获均不提交。 +回归:默认与隔离Agent构建、opt-in APK构建、Host类型检查、Host561/561(0 skip,显式CLI源码路径)、 +入口拒绝门禁通过。此前Android JVM73/73仍为相同生产Kotlin代码的实测,本轮未重跑JVM套件。 + +仍未验证:默认模块/Manager/生产RootDaemon部署与升级、其他ROM/Root/架构、真实业务App、 +全部算法/模块组合、热升级、init_array之前的保证。Java/inline early仍明确unsupported。 +此前libandroid_runtime/getpid被后续覆盖的具体成因也未由本轮定位。 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 793957f..bd02920 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,5 +1,11 @@ # PROGRESS — 跨会话进度看板 +2026-11-17 正式Zygisk扩展:最新Agent在真实companion/post-specialize链中完成七族capture_start +单族启用命中、其他族禁用不布防和全部禁用,以及真实Wi-Fi LAN grant撤销后的旧缓存拒绝; +原六项失效/GOT窗口正例也重跑,总15/15,清理/原六文件/reverse/原Host状态保护通过。 +Host561/561(0 skip)。失败首轮保留并修复测试App主线程网络及清理判定问题; +详见[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](P5_ZYGISK_EXTENDED_ACCEPTANCE.md)。发布/默认部署尚未执行。 + 2026-11-17 收尾补丁:在独立 `feat/adh-completion-20261117` 补上 GOT 卸载的原子所有权检查, 避免覆盖 runtime/人类/其他工具的新指针;状态区分历史命中和当前槽所有权。 原生生产恢复函数真机隔离夹具8/8、清理通过;未重跑正式 Zygisk 全链,未发布或部署。 diff --git a/tools/MAP.md b/tools/MAP.md index 453c315..e1670fa 100644 --- a/tools/MAP.md +++ b/tools/MAP.md @@ -12,6 +12,12 @@ It does not start a Host, install an APK, change reverse mappings, flash or rebo ## P5 isolated Android acceptance (2026-11-16) +2026-11-17: `verify_p5_zygisk.ts` + `p5_zygisk_cases.ts` also verify all seven capture families in +the first Application callback via the real Zygisk path, all-off, and real Wi-Fi grant revocation. +The original Host may be absent; an existing Host must be inspectable/idle and retain its identity. +Cleanup errors are collected per step without skipping other owned cleanup. See +[P5_ZYGISK_EXTENDED_ACCEPTANCE.md](../docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md). + `verify_p5_device.ts SERIAL TRANSPORT_ID PRIVATE_ASSETS NEW_PRIVATE_OUTPUT` is explicit real-device acceptance with a new package, private root domain, UDS, Host ports/data and cleanup/protection checks. It never flashes a module or restarts the running service. Build `:p5sandbox` and `:daemon` with `-PadhP5Sandbox=true` and an Agent built for port 18761. `p5_isolated_host.ts` maps only the private fixture endpoints into the production dispatcher. `verify_v132_p5_stdio.sh` is the registered host-only Kotlin interoperability gate; missing offline fixture is SKIP, never real-device fallback. Details and real/unverified boundaries: [P5_ANDROID_ACCEPTANCE.md](../docs/P5_ANDROID_ACCEPTANCE.md). ## Shared library reference diff --git a/tools/p5_zygisk_cases.ts b/tools/p5_zygisk_cases.ts new file mode 100644 index 0000000..5894dd2 --- /dev/null +++ b/tools/p5_zygisk_cases.ts @@ -0,0 +1,55 @@ +// Invoked only after the real Zygisk runner's device/module/namespace preflight. +import assert from 'node:assert/strict'; +import {readFileSync,writeFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {createHash} from 'node:crypto'; +const families=['digest','hmac','symmetric','asymmetric','tls','aead','system']; +const off=()=>Object.fromEntries(families.map(k=>[k,false])); +export async function zygiskExtendedCases(c:any){ + const {check,tool,deviceWrite,read,stage,launch,command,until,pause,usb,dir,nonce}=c; + const originalDigest=c.planDigest; + const tls=await deviceWrite(usb,'lan.configure',{enabled:true,address:'127.0.0.1',port:0}); + for(const family of [...families,'off'])await check('Zygisk early capture_start '+family+': Application hits and disabled-family isolation',async()=>{ + const plan={schemaVersion:1,id:'zygisk-capture-'+family,title:'Actual post-specialize '+family,package:c.pkg, + families:{...off(),...(families.includes(family)?{[family]:true}:{})}, + steps:[{id:'before-application',tool:'capture_start',arguments:{cryptoModule:'libjavacrypto.so',fileModule:'',sysModule:'libjavacore.so'}}]}; + const library=await tool('hook_plans',{action:'list'}),saved=await tool('hook_plans',{action:'put',plan,expectedLibraryRevision:library.revision},true); + assert.equal(saved.ok,true,JSON.stringify(saved));c.planDigest=saved.digest;await stage(600); + const marker='P5Z_'+family+'_'+nonce; + const result=await launch(true,{captureOnly:true,allOff:family==='off',marker,tlsPort:tls.port}); + const {receipt,session}=result;assert.equal(receipt.probesInApplicationCallback,true); + assert.equal(receipt.marker,marker);for(const key of families)assert.equal(receipt.probes[key],true,key+' probe did not succeed'); + const install=session.earlyPlan?.lastCaptureInstall;assert.ok(install,JSON.stringify(session.earlyPlan)); + const counters:any={digest:[install.digest],hmac:[install.hmac],symmetric:[install.evp,install.cipherInit,install.cipherCtxFree],asymmetric:Object.values(install.pkey),tls:[install.sslWrite,install.sslRead],aead:Object.values(install.aead),system:Object.values(install.sys)}; + for(const key of families){assert.ok(counters[key].every((v:any)=>Number.isInteger(v)),key+' counters missing');assert.equal(counters[key].some((v:number)=>v>0),key===family,key+' install mismatch');} + if(family!=='hmac'&&family!=='asymmetric'){assert.ok(install.digestSign<=0);assert.ok(Object.values(install.digestSignVerify).every((n:any)=>n<=0));} + const health=await until(async()=>{const all=JSON.parse(readFileSync(join(dir,'host/p5-capture-health.json'),'utf8'));const h=all.sessions[session.sessionId];return h&&h.ts&&h.backlog===0?h:null;},'Application capture ring fully drained'); + assert.equal(health.dropped,0);assert.equal(health.jdropped,0);assert.equal(health.complete,true);await pause(400); + const captures=await tool('live_captures',{session:session.sessionId,includeText:true,encoding:'b64',limit:1000}); + assert.equal(captures.total,captures.captures.length,'full session window required'); + const rows=captures.captures.map((r:any)=>({...r,bytes:Buffer.from(r.b64||'','base64')})); + const matches:any={digest:(r:any)=>r.func==='EVP_DigestUpdate'&&r.bytes.includes(Buffer.from(marker+'_digest')), + hmac:(r:any)=>['HMAC_Update','EVP_DigestSignUpdate'].includes(r.func)&&r.bytes.includes(Buffer.from(marker+'_hmac')), + symmetric:(r:any)=>r.func==='EVP_CipherUpdate'&&r.bytes.includes(Buffer.from(marker+'_symmetric')), + asymmetric:(r:any)=>(r.func==='ECDSA_sign_digest'&&r.bytes.includes(createHash('sha256').update(marker+'_asymmetric').digest()))||(r.func==='EVP_DSignUpdate_asym'&&r.bytes.includes(Buffer.from(marker+'_asymmetric'))), + tls:(r:any)=>r.func==='SSL_write'&&r.bytes.includes(Buffer.from(marker+'_tls')), + aead:(r:any)=>r.func.includes('AEAD')&&r.bytes.includes(Buffer.from(marker+'_aead')), + system:(r:any)=>r.func==='access'&&r.bytes.includes(Buffer.from(marker+'_system'))}; + const counts=Object.fromEntries(families.map(k=>[k,rows.filter(matches[k]).length])); + for(const key of families){const hits=rows.filter(matches[key]);assert.equal(hits.length>0,key===family,key+' marker mismatch '+JSON.stringify(counts));for(const hit of hits){assert.equal(hit.tid,key==='tls'?receipt.tlsTid:receipt.pid);assert.ok(BigInt(hit.tsNs)>=BigInt(receipt.captureBeforeNs)&&BigInt(hit.tsNs)<=BigInt(receipt.captureAfterNs),'hit outside first Application probe window');}} + if(family==='off')assert.equal(rows.length,0,'all-off must capture nothing'); + const evidence={receipt,early:session.earlyPlan,companionBytes:result.companionBytes,hitCounts:counts,health:{dropped:health.dropped,jdropped:health.jdropped,backlog:health.backlog,complete:health.complete}}; + writeFileSync(join(dir,'zygisk-family-'+family+'.json'),JSON.stringify(evidence,null,2));return evidence; + }); + c.planDigest=originalDigest; + await check('real LAN grant revoke denies companion delivery; existing process remains untouched',async()=>{ + const address=(await command(['shell','ip','-4','addr','show','wlan0'])).match(/inet (\d+\.\d+\.\d+\.\d+)/)?.[1];assert.ok(address,'real Wi-Fi address required'); + const cfg=await deviceWrite(usb,'lan.configure',{enabled:true,address,port:0}),state=await read(usb,'device.state'); + const paired=await tool('devices',{action:'pair',deviceId:usb.deviceId,connectionId:usb.connectionId,bootId:usb.bootId,daemonInstanceId:usb.daemonInstanceId,expectedDeviceRevision:state.stateRevision,permissions:['read','write','manage']},true);assert.equal(paired.ok,true,JSON.stringify(paired)); + const grant=paired.result.result,lan=await tool('devices',{action:'connect',transport:'lan',deviceId:usb.deviceId,address,port:cfg.port},true);assert.equal(lan._operation?.state,'succeeded',JSON.stringify(lan)); + const staged=await stage(600,lan);assert.equal(staged.entry.sourceGrant,grant.grantId); + const positive=await launch(true);await deviceWrite(usb,'pairings.revoke',{grantId:grant.grantId}); + const status=await tool('native_hook',{action:'status',session:positive.session.sessionId});const hook=status.status.hooks.find((h:any)=>h.id===positive.early.steps[0].hookId);assert.ok(hook);assert.equal(hook.slotOwned,true); + const rejected=await launch(false);return {tls:lan.tlsVersion,sourceGrantBound:true,existingProcessHookRetained:true,positivePid:positive.receipt.pid,...rejected}; + }); +} diff --git a/tools/verify_p5_zygisk.ts b/tools/verify_p5_zygisk.ts index eccf2d4..ddbcb9f 100644 --- a/tools/verify_p5_zygisk.ts +++ b/tools/verify_p5_zygisk.ts @@ -14,7 +14,7 @@ const run=promisify(execFile),adb=process.env.ADH_ADB_PATH||'adb'; const command=async(args:string[],timeout=15000)=>(await run(adb,['-s',serial,...args],{windowsHide:true,timeout,maxBuffer:1024*1024})).stdout.trim(); const su=(cmd:string,timeout=15000)=>command(['exec-out','su','-c',cmd],timeout); const pause=(ms:number)=>new Promise(r=>setTimeout(r,ms)); -const report:any={schemaVersion:1,mode:'real-zygisk-private-namespace',deviceRebootAuthorized:true,ownFixtureForeground:true,nonce,remote,stateRoot,moduleId,cases:[],reboots:[],unverified:['default production namespace deployment/upgrade','other ROMs/architectures','init_array-before-load and Java/inline early steps','capture_start families and LAN-grant revocation through the Zygisk chain']}; +const report:any={schemaVersion:2,mode:'real-zygisk-private-namespace',deviceRebootAuthorized:true,ownFixtureForeground:true,nonce,remote,stateRoot,moduleId,cases:[],reboots:[],unverified:['default production namespace deployment/upgrade','other ROMs/architectures','init_array-before-load and Java/inline early steps','all algorithms/module combinations beyond the named representative probes']}; let host:ReturnType|undefined,deviceChild:ReturnType|undefined,usb:any,installed=false,moduleInstalled=false,baseline:any,fixturePid:number|undefined,binding:any,planDigest:string; const base='http://127.0.0.1:18088';let sequence=0; const request=async(path:string,body?:any)=>{const response=await fetch(base+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return response.json() as Promise;}; @@ -27,20 +27,24 @@ async function until(fn:()=>Promise,label:string,budget=12000){const deadli async function check(name:string,fn:()=>Promise){console.log('RUN '+name);try{const result=await fn();report.cases.push({name,state:'pass',evidence:result??null});console.log('PASS '+name);}catch(error){report.cases.push({name,state:report.unknownOperations?.length?'unknown':'fail',error:(error as Error).message});throw error;}} const unwrap=(v:any)=>{assert.equal(v._operation?.state,'succeeded',JSON.stringify(v));return v.result.result;}; const protectedFiles='/data/adb/adh/scope.json /data/adb/adh/host.endpoint /data/adb/modules/adh/libadh_agent.so /data/adb/modules/adh/zygisk/arm64-v8a.so /data/adb/modules/adh/daemon.apk /data/adb/modules/adh/module.prop'; -async function hostIdentity(){const value=await run('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$adhConnection=Get-NetTCPConnection -LocalPort 8088 -State Listen | Select-Object -First 1; $adhProcess=Get-Process -Id $adhConnection.OwningProcess; @{pid=$adhProcess.Id;started=$adhProcess.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json -Compress"],{windowsHide:true});return JSON.parse(value.stdout);} +async function hostIdentity(){const value=await run('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$adhConnection=Get-NetTCPConnection -LocalPort 8088 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if ($null -eq $adhConnection) { 'null'; exit 0 }; $adhProcess=Get-Process -Id $adhConnection.OwningProcess -ErrorAction Stop; @{pid=$adhProcess.Id;started=$adhProcess.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json -Compress"],{windowsHide:true});return JSON.parse(value.stdout);} +async function originalHostIdle(){const identity=await hostIdentity();if(identity){const response=await fetch('http://127.0.0.1:8088/api/agents',{signal:AbortSignal.timeout(5000)});assert.equal(response.ok,true,'occupied original Host cannot be inspected');const all=await response.json() as any[];assert.ok(Array.isArray(all));assert.equal(all.filter(s=>s.online).length,0,'active original Host analysis appeared; refuse reboot');}return identity;} async function mappings(){return (await command(['reverse','--list'])).split('\n').filter(Boolean).map(line=>line.trim().split(/\s+/).slice(-2).join(' ')).sort();} async function restoreMappings(){for(const row of baseline.reverse){const [source,destination]=row.split(' ');assert.match(source,/^tcp:\d+$/);assert.match(destination,/^tcp:\d+$/);const current=(await mappings()).find(line=>line.startsWith(source+' '));if(current){assert.equal(current,row,'a mapping was replaced; never overwrite it');continue;}await command(['reverse','--no-rebind',source,destination]);}} async function reboot(label:string){ + if(baseline)assert.deepEqual(await originalHostIdle(),baseline.host,'original Host changed; refuse reboot'); const before=await su('cat /proc/sys/kernel/random/boot_id');console.log('REBOOT '+label);await command(['reboot']);await pause(2500);const deadline=Date.now()+240000;let logged=0; while(Date.now()20000){console.log('BOOT_WAIT '+label);logged=Date.now();}await pause(2000);} throw Error('device boot deadline; phone state and cleanup unconfirmed'); } -async function stage(ttl=180){const p=(await hookDevice(usb,'early-prepare')).result;binding=p.binding;return unwrap(await hookDevice(usb,'early-stage',{digest:planDigest,binding,expectedCacheRevision:p.cacheRevision,expiresAt:Math.floor(Date.now()/1000)+ttl,offline:'keep-until-expiry'},true));} -async function launch(expect:boolean){ - await command(['shell','am','force-stop',pkg]);await su(`mkdir -p /data/user/0/${pkg}/cache; chown ${binding.uid}:${binding.uid} /data/user/0/${pkg}/cache; rm -f /data/user/0/${pkg}/cache/adh_zygisk.log /data/user/0/${pkg}/files/p5-result.json /data/user/0/${pkg}/files/p5-zygisk-application.json; : > ${stateRoot}/zygisk_inject.log`); - const started=await command(['shell','am','start','-W','-n',pkg+'/.ProbeActivity']);assert.ok(!started.includes('Error'),started); +async function stage(ttl=180,peer=usb){const p=(await hookDevice(peer,'early-prepare')).result;binding=p.binding;return unwrap(await hookDevice(peer,'early-stage',{digest:planDigest,binding,expectedCacheRevision:p.cacheRevision,expiresAt:Math.floor(Date.now()/1000)+ttl,offline:'keep-until-expiry'},true));} +async function launch(expect:boolean,opts:any={}){ + await command(['shell','am','force-stop',pkg]);await su(`mkdir -p /data/user/0/${pkg}/cache /data/user/0/${pkg}/files; chown ${binding.uid}:${binding.uid} /data/user/0/${pkg}/cache /data/user/0/${pkg}/files; rm -f /data/user/0/${pkg}/cache/adh_zygisk.log /data/user/0/${pkg}/files/p5-result.json /data/user/0/${pkg}/files/p5-zygisk-application.json /data/user/0/${pkg}/files/p5-zygisk-probes.json; : > ${stateRoot}/zygisk_inject.log`); + if(opts.marker){const local=join(dir,'probe-config.json');writeFileSync(local,JSON.stringify({marker:opts.marker,tlsPort:opts.tlsPort}));await command(['push',local,remote+'/probe-config.json']);await su(`cp ${remote}/probe-config.json /data/user/0/${pkg}/files/p5-zygisk-probes.json; chown ${binding.uid}:${binding.uid} /data/user/0/${pkg}/files/p5-zygisk-probes.json; chmod 600 /data/user/0/${pkg}/files/p5-zygisk-probes.json`);} + const launchedAt=Date.now();const started=await command(['shell','am','start','-W','-n',pkg+'/.ProbeActivity']);assert.ok(!started.includes('Error'),started); + const latest=await request('/api/agents');const injected=latest.filter((s:any)=>s.package===pkg&&s.connectedAt>=launchedAt).sort((a:any,b:any)=>b.connectedAt-a.connectedAt)[0];if(injected)report.lastPid=injected.pid; const receipt=await until(async()=>{try{return JSON.parse(await su(`cat /data/user/0/${pkg}/files/p5-result.json`));}catch{return null;}},'Application receipt',18000);assert.ok(!receipt.error,JSON.stringify(receipt));assert.equal(receipt.selfLoad,false);assert.equal(receipt.applicationCallback,true);assert.equal(receipt.servicePid,receipt.pid);assert.equal(receipt.uid,binding.uid);assert.equal(receipt.agentMemfdBeforeApplicationProbe,true,'Agent must already be present at the first app callback; no self-load allowed'); report.lastPid=receipt.pid;writeFileSync(join(dir,'application-'+receipt.pid+'.json'),JSON.stringify(receipt)); const session=await until(async()=>{const all=await request('/api/agents');return all.find((s:any)=>s.online&&s.package===pkg&&s.pid===receipt.pid);},'injected Agent hello');assert.match(session.selfModule||'',/memfd:jit-cache/); @@ -48,19 +52,25 @@ async function launch(expect:boolean){ const decisions=await su('cat '+stateRoot+'/zygisk_inject.log');const appLog=await su(`cat /data/user/0/${pkg}/cache/adh_zygisk.log`).catch(()=>'');const logcat=await command(['logcat','-d','--pid',String(receipt.pid),'-s','adh-zygisk:I','*:S']); writeFileSync(join(dir,'launch-'+receipt.pid+'.json'),JSON.stringify({receipt,early:session.earlyPlan,status,decisions,appLog,logcat},null,2)); const pattern=new RegExp('early companion pkg='+pkg.replaceAll('.','\\.')+' uid='+binding.uid+' bytes=(\\d+)');const bytes=Number(pattern.exec(decisions)?.[1]);assert.ok(Number.isFinite(bytes),'real companion delivery audit missing');assert.equal(bytes>0,expect,decisions); - if(expect){assert.equal(session.earlyPlan?.state,'applied',JSON.stringify(session.earlyPlan));assert.equal(session.earlyPlan.digest,planDigest);const owned=hooks.find((h:any)=>h.id===session.earlyPlan.steps[0].hookId);assert.ok(owned);assert.equal(owned.module,'libjavacore.so');assert.equal(owned.symbol,'getpid');assert.ok(owned.hits>=1,JSON.stringify(owned));assert.equal(session.uid,binding.uid);assert.equal(owned.slotCurrent,owned.replacement,'Hook must still be installed at Application startup'); + if(expect){assert.equal(session.earlyPlan?.state,opts.captureOnly&&opts.allOff?'partial-or-failed':'applied',JSON.stringify(session.earlyPlan));assert.equal(session.earlyPlan.digest,planDigest); + assert.match(appLog+logcat,new RegExp('early post-specialize .*result='+(opts.allOff?'0':'1')+' before_agent_start=1')); + if(opts.captureOnly){assert.equal(hooks.length,0);return {receipt,session,early:session.earlyPlan,companionBytes:bytes,postLogSource:appLog?'own-app-debug-file':'logcat'};} + const owned=hooks.find((h:any)=>h.id===session.earlyPlan.steps[0].hookId);assert.ok(owned);assert.equal(owned.module,'libjavacore.so');assert.equal(owned.symbol,'getpid');assert.ok(owned.hits>=1,JSON.stringify(owned));assert.equal(session.uid,binding.uid);assert.equal(owned.slotCurrent,owned.replacement,'Hook must still be installed at Application startup');assert.equal(owned.slotOwned,true); const evidence=await until(async()=>{const list=await tool('live_captures',{session:session.sessionId,includeText:true,encoding:'b64',limit:1000});writeFileSync(join(dir,'capture-window-'+receipt.pid+'.json'),JSON.stringify(list));return list.captures?.find((r:any)=>r.func==='NATIVE_HOOK'&&r.hookId===owned.id&&BigInt(String(r.tsNs))>=BigInt(receipt.beforeNs)&&BigInt(String(r.tsNs))<=BigInt(receipt.afterNs));},'Hook event inside first Application call window'); assert.equal(evidence.tid,receipt.pid);writeFileSync(join(dir,'early-hit-'+receipt.pid+'.json'),JSON.stringify({hookId:owned.id,eventId:evidence.id,tsNs:evidence.tsNs,window:[receipt.beforeNs,receipt.afterNs],sameMainThread:true})); - assert.match(appLog+logcat,/early post-specialize .*result=1 before_agent_start=1/);return {receipt,companionBytes:bytes,early:session.earlyPlan,hits:owned.hits,firstApplicationEvent:evidence.id,postLogSource:appLog?'own-app-debug-file':'logcat'};} + assert.match(appLog+logcat,/early post-specialize .*result=1 before_agent_start=1/);return {receipt,session,companionBytes:bytes,early:session.earlyPlan,hits:owned.hits,firstApplicationEvent:evidence.id,postLogSource:appLog?'own-app-debug-file':'logcat'};} assert.equal(session.earlyPlan,null);assert.equal(hooks.length,0);return {receipt,companionBytes:bytes,early:null,hooks:0}; } try{ for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));}); assert.match(await su('id'),/uid=0\(root\)/);assert.equal(await su('getenforce'),'Enforcing');assert.equal(await command(['shell','getprop','ro.product.cpu.abi']),'arm64-v8a'); const packagePath=await command(['shell','pm','path',pkg]).catch((e:any)=>{if(e.code===1&&!String(e.stdout||'').trim())return '';throw e;});assert.equal(packagePath,'','existing test package must not be overwritten'); - const online=(await(await fetch('http://127.0.0.1:8088/api/agents')).json() as any[]).filter(s=>s.online);assert.equal(online.length,0,'new active Host analysis appeared; stop before reboot'); - const hashes=await su('sha256sum '+protectedFiles);assert.equal(hashes.split('\n').length,6);baseline={host:await hostIdentity(),hashes,reverse:await mappings()};report.before=baseline;for(const mapping of baseline.reverse)assert.match(mapping,/^tcp:\d+ tcp:\d+$/,'only existing TCP reverse mappings are supported; refuse before device mutation'); + const originalHost=await originalHostIdle(); + const hashes=await su('sha256sum '+protectedFiles);assert.equal(hashes.split('\n').length,6);baseline={host:originalHost,hashes,reverse:await mappings()};report.before=baseline;for(const mapping of baseline.reverse)assert.match(mapping,/^tcp:\d+ tcp:\d+$/,'only existing TCP reverse mappings are supported; refuse before device mutation'); assert.ok(!baseline.reverse.some((r:string)=>/^tcp:(18088|18761) /.test(r)));assert.ok(!(await su('cat /data/adb/adh/scope.json')).includes(pkg),'test package is in the original module scope'); + report.artifacts={agentSha256:createHash('sha256').update(readFileSync(join(root,'agent/build-isolated-18761/libadh_agent.so'))).digest('hex'), + daemonApkSha256:createHash('sha256').update(readFileSync(join(assets,'daemon.apk'))).digest('hex'), + sandboxApkSha256:createHash('sha256').update(readFileSync(join(assets,'sandbox-v1.apk'))).digest('hex')}; assert.match(readFileSync(join(root,'agent/build-isolated-18761/CMakeCache.txt'),'utf8'),/ADH_AGENT_CONNECT_PORT:STRING=18761/); const buildLog=await run('C:/Program Files/Git/bin/bash.exe',['-lc',`bash tools/build_p5_zygisk.sh ${nonce} '${dir.replaceAll('\\','/')}'`],{cwd:root,windowsHide:true,timeout:90000,maxBuffer:1024*1024});writeFileSync(join(dir,'companion-build.log'),buildLog.stdout+buildLog.stderr); await command(['shell','mkdir','-m','755',remote]);for(const [file,name] of [[join(assets,'daemon.apk'),'daemon.apk'],[join(assets,'sandbox-v1.apk'),'sandbox.apk'],[join(root,'agent/build-isolated-18761/libadh_agent.so'),'libadh_agent.so'],[join(dir,'companion-build/libadh.so'),'arm64-v8a.so']])await command(['push',file,remote+'/'+name]); @@ -84,10 +94,14 @@ try{ await check('real companion delivery, post-specialize apply and pre-Application GOT hit',async()=>{await stage();return launch(true);}); await check('expired cache is refused by actual companion; no Hook',async()=>{const s=await stage(3);await pause(Math.max(0,s.entry.expiresAt*1000-Date.now()+300));return launch(false);}); await check('revoked cache is refused by actual companion; no Hook',async()=>{const s=await stage();unwrap(await hookDevice(usb,'early-revoke',{deploymentId:s.entry.deploymentId,expectedCacheRevision:s.cacheRevision},true));return launch(false);}); + const {zygiskExtendedCases}=await import('./p5_zygisk_cases.ts'); + await zygiskExtendedCases({check,tool,read,deviceWrite,hookDevice,stage,launch,command,su,until,pause,usb,remote,pkg,dir,nonce, + get planDigest(){return planDigest},set planDigest(value){planDigest=value}}); await check('actual UID change rejects old cache through Zygisk',async()=>{await stage();await launch(true);const old=structuredClone(binding);await command(['shell','am','force-stop',pkg]);assert.match(await su('pm uninstall '+pkg),/Success/);assert.match(await su(`pm install ${remote}/sandbox.apk`,90000),/Success/);binding=(await hookDevice(usb,'early-prepare')).result.binding;assert.notEqual(binding.uid,old.uid);assert.equal(binding.agentSha256,old.agentSha256);return {oldUid:old.uid,newUid:binding.uid,...await launch(false)};}); await check('module Agent bytes alone change; actual FD load rejects old cache',async()=>{await stage();await launch(true);const before=structuredClone(binding);await command(['shell','am','force-stop',pkg]);const variant=Buffer.concat([readFileSync(join(root,'agent/build-isolated-18761/libadh_agent.so')),Buffer.from('\nP5-ZYGISK-REPLACEMENT\n')]);writeFileSync(join(dir,'agent-variant.so'),variant);await command(['push',join(dir,'agent-variant.so'),remote+'/agent-variant.so']);await su(`cp ${remote}/agent-variant.so ${modulePath}/libadh_agent.so`);binding=(await hookDevice(usb,'early-prepare')).result.binding;const {agentSha256:oldHash,...old}=before,{agentSha256:newHash,...fresh}=binding;assert.deepEqual(fresh,old);assert.equal(newHash,createHash('sha256').update(variant).digest('hex'));assert.notEqual(oldHash,newHash);return {onlyAgentHashChanged:true,...await launch(false)};}); await check('missing root broker fails closed through actual companion',async()=>{await stage();await launch(true);await su('touch '+remote+'/stop');await until(async()=>await su(`if [ ! -d /proc/${fixturePid} ]; then echo stopped; fi`)==='stopped','own broker stopped');return launch(false);}); }catch(error){ + if(report.lastPid)try{writeFileSync(join(dir,'failure-own-app-crash.txt'),await command(['logcat','-b','crash','-d','--pid',String(report.lastPid)]));}catch{} try{writeFileSync(join(dir,'failure-decisions.txt'),await su('cat '+stateRoot+'/zygisk_inject.log'));if(report.lastPid)writeFileSync(join(dir,'failure-logcat.txt'),await command(['logcat','-d','--pid',String(report.lastPid),'-s','adh-zygisk:I','*:S']));}catch{} if(report.lastPid)try{ const pid=String(report.lastPid);assert.match(pid,/^\d+$/);assert.ok((await su(`cat /proc/${pid}/cmdline`)).startsWith(pkg)); @@ -96,13 +110,16 @@ try{ }catch{} report.failure={message:(error as Error).message,stack:(error as Error).stack};console.error('FAIL '+(error as Error).message);process.exitCode=1;} finally{ - try{ - if(installed){await command(['shell','am','force-stop',pkg]);assert.match(await su('pm uninstall '+pkg),/Success/);} - if(host&&host.exitCode===null){host.kill();await new Promise(r=>{host!.once('exit',()=>r());setTimeout(r,3000);});} - if(deviceChild?.exitCode===null)await su('touch '+remote+'/stop').catch(()=>{}); - if(moduleInstalled){assert.equal(await su('cat '+modulePath+'/p5-owner'),nonce,'never remove an unowned module');await su('rm -rf '+modulePath);await reboot('unload isolated module');assert.equal(await su(`if [ -e ${modulePath} ]; then echo exists; fi`),'');} - if(baseline){assert.equal(await su('sha256sum '+protectedFiles),baseline.hashes);assert.deepEqual(await hostIdentity(),baseline.host);assert.deepEqual(await mappings(),baseline.reverse);report.originalHostAndFilesUnchanged=true;} - for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));});report.cleanupVerified=true; - }catch(error){report.cleanupVerified=false;report.cleanupError=(error as Error).message;process.exitCode=1;} + const errors:string[]=[]; + const cleanup=async(label:string,fn:()=>Promise)=>{try{await fn();}catch(error){errors.push(label+': '+(error as Error).message);process.exitCode=1;}}; + await cleanup('own package',async()=>{if(installed){await command(['shell','am','force-stop',pkg]);assert.match(await su('pm uninstall '+pkg),/Success/);}}); + await cleanup('own Host',async()=>{if(host&&host.exitCode===null&&host.signalCode===null){host.kill();await new Promise(r=>{host!.once('exit',()=>r());setTimeout(r,3000);});assert.ok(host.exitCode!==null||host.signalCode!==null,'own Host did not exit');}}); + await cleanup('own broker',async()=>{if(deviceChild?.exitCode===null)await su('touch '+remote+'/stop');}); + // Each step runs even if an earlier independent cleanup failed. Ownership and idle-Host + // checks still gate module removal/reboot; a failed cleanup is never reported as PASS. + await cleanup('own module',async()=>{if(moduleInstalled){assert.equal(await su('cat '+modulePath+'/p5-owner'),nonce,'never remove an unowned module');await su('rm -rf '+modulePath);await reboot('unload isolated module');assert.equal(await su(`if [ -e ${modulePath} ]; then echo exists; fi`),'');}}); + await cleanup('original scene',async()=>{if(baseline){assert.equal(await su('sha256sum '+protectedFiles),baseline.hashes);assert.deepEqual(await hostIdentity(),baseline.host);assert.deepEqual(await mappings(),baseline.reverse);report.originalHostAndFilesUnchanged=true;}}); + await cleanup('private ports',async()=>{for(const port of [18088,18761])await new Promise((yes,no)=>{const server=net.createServer();server.once('error',no);server.listen(port,'0.0.0.0',()=>server.close(()=>yes()));});}); + report.cleanupVerified=errors.length===0;if(errors.length)report.cleanupErrors=errors; if(host?.exitCode===null)host.kill();if(deviceChild?.exitCode===null)deviceChild.kill();report.completedAt=new Date().toISOString();writeFileSync(join(dir,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({passed:report.cases.filter((c:any)=>c.state==='pass').length,failure:report.failure?.message,cleanupVerified:report.cleanupVerified,hostAndFilesUnchanged:report.originalHostAndFilesUnchanged,report:join(dir,'report.json')})); } From a7e6d9240e8cf48c3621baffdf0f55bca8f65162 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:28:10 +0800 Subject: [PATCH 24/24] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E6=AD=A3?= =?UTF-8?q?=E5=BC=8FZygisk=E6=89=A9=E5=B1=95=E9=AA=8C=E6=94=B6=E5=85=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b0f52f..0efbcdf 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Android DecryptHub(ADH)是一套 Android 运行时分析工具。它把一 P5 分支将 Hook 方案和编辑器迁到 Host。MCP `hook_plans`、Python CLI `adh call/run hook_plans` 和任务工作台共用执行层。保存、暂存和实际安装分别报告,连接不自动套用旧捕获/启动默认值。迁移与兼容边界见 [P5_HOOK_PLANS.md](docs/P5_HOOK_PLANS.md)。此分支尚未部署到现有分析现场。 -P5 后续已完成真实 Android 独立沙盒的早期 GOT、过期、APK 绑定失效、LAN 授权撤销、缓存撤销和精确回滚验收,并修复早期参数与 Android 认证编码问题。详见 [实测与未验证清单](docs/P5_ANDROID_ACCEPTANCE.md);正式 Zygisk 全链仍未部署验证。 +P5 后续已完成真实 Android 独立沙盒验收,并在正式 Zygisk 回调/companion/post-specialize 的隔离命名空间中完成七族代表性捕获、全部禁用、LAN 授权撤销及 UID/Agent/过期等拒绝,共15/15。详见[正式链验收与未验证边界](docs/P5_ZYGISK_EXTENDED_ACCEPTANCE.md);默认模块/Manager/生产 RootDaemon 的部署升级仍待验证。 ## 能做什么