@causyne/agent 1.20.19 → 1.20.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/causyne.js +7 -1
- package/package.json +1 -1
- package/src/agentLoop.js +36 -100
- package/src/agentLoop.ts +35 -101
- package/src/autoUpdate.js +251 -183
- package/src/autoUpdate.ts +360 -0
- package/src/engines/reverseHarness.js +25 -3
- package/src/engines/reverseHarness.ts +30 -3
- package/src/providers/antigravity.js +17 -17
- package/src/providers/antigravity.ts +16 -16
- package/src/smartToolsUse.js +26 -3
- package/src/smartToolsUse.ts +29 -3
- package/src/tools/reverseEngineering.js +464 -24
- package/src/tools/reverseEngineering.ts +473 -25
- package/src/utils/cli_ui.d.ts +19 -0
- package/src/providers/budgetEnforcer.js +0 -136
- package/src/providers/budgetEnforcer.ts +0 -143
package/src/smartToolsUse.ts
CHANGED
|
@@ -176,9 +176,13 @@ const EXPLICIT_WEB_ENGINEERING_PATTERN =
|
|
|
176
176
|
const EXPLICIT_GAME_DEV_PATTERN =
|
|
177
177
|
/(?:\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)[\s\S]*(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b|\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
|
|
178
178
|
|
|
179
|
-
// Explicit
|
|
179
|
+
// Explicit reverse engineering and binary analysis intent
|
|
180
|
+
const EXPLICIT_REVERSE_ENGINEERING_PATTERN =
|
|
181
|
+
/\b(reverse[-_ ]?engineering|decompile|disassemble|disasm|apk|aab|dex|radare|rizin|ghidra|jadx|apktool|mach-o|elf binary|portable executable|\.apk\b|\.aab\b|\.dex\b|\.so\b|\.dylib\b|\.wasm\b|\.asar\b)\b/i;
|
|
182
|
+
|
|
183
|
+
// Explicit software and systems engineering intent (backend, APIs, refactoring, algorithms, testing, architecture, CLI tools, Android/mobile)
|
|
180
184
|
const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN =
|
|
181
|
-
/(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|engineer|benchmark|profile|audit)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream)\b|\b(?:python|rust|golang|c\+\+|cpp|java|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes)\b)/i;
|
|
185
|
+
/(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android)\b)/i;
|
|
182
186
|
|
|
183
187
|
/**
|
|
184
188
|
* Select tools to preload based on prompt intent. This is never an allowlist:
|
|
@@ -193,7 +197,29 @@ export function determineToolScope(
|
|
|
193
197
|
return { toolScope: null, archetype: 'empty', suppressedPacks: [] };
|
|
194
198
|
}
|
|
195
199
|
|
|
196
|
-
// 1.
|
|
200
|
+
// 1. Reverse engineering & binary analysis intent
|
|
201
|
+
if (EXPLICIT_REVERSE_ENGINEERING_PATTERN.test(text)) {
|
|
202
|
+
const tools = new Set([
|
|
203
|
+
'reverse_engineering',
|
|
204
|
+
'fs_read',
|
|
205
|
+
'fs_write',
|
|
206
|
+
'fs_edit',
|
|
207
|
+
'fs_list',
|
|
208
|
+
'fs_search',
|
|
209
|
+
'sysRun',
|
|
210
|
+
'view_image',
|
|
211
|
+
'update_plan',
|
|
212
|
+
'tool_search'
|
|
213
|
+
]);
|
|
214
|
+
return {
|
|
215
|
+
toolScope: tools,
|
|
216
|
+
archetype: 'reverse_engineering',
|
|
217
|
+
suppressedPacks: ['media', 'game', 'web'],
|
|
218
|
+
reason: 'Reverse engineering intent prioritizes binary triage, decompilation, filesystem exploration, and terminal verification; suppresses creative packs.'
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// 2. Desktop personalization (e.g. wallpaper / desktop background)
|
|
197
223
|
if (DESKTOP_PERSONALIZATION_PATTERN.test(text)) {
|
|
198
224
|
const tools = new Set([
|
|
199
225
|
'sysRun',
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import fs from 'node:fs';
|
|
9
9
|
import fsp from 'node:fs/promises';
|
|
10
10
|
import path from 'node:path';
|
|
11
|
+
import zlib from 'node:zlib';
|
|
11
12
|
import { execFile } from 'node:child_process';
|
|
12
13
|
import util from 'node:util';
|
|
13
14
|
import { resolveUserPath } from '../utils/paths.js';
|
|
@@ -228,6 +229,428 @@ async function deobfuscateScript(filePath) {
|
|
|
228
229
|
};
|
|
229
230
|
}
|
|
230
231
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
232
|
+
// DALVIK EXECUTABLE (DEX) ZERO-DEPENDENCY PARSER
|
|
233
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
234
|
+
function parseDex(buffer) {
|
|
235
|
+
if (buffer.length < 112)
|
|
236
|
+
return { format: 'DEX' };
|
|
237
|
+
const magic = buffer.toString('utf8', 0, 8);
|
|
238
|
+
if (!magic.startsWith('dex\n'))
|
|
239
|
+
return { format: 'DEX' };
|
|
240
|
+
const endianTag = buffer.readUInt32LE(40);
|
|
241
|
+
const isLe = endianTag === 0x12345678;
|
|
242
|
+
const readU32 = (off) => isLe ? buffer.readUInt32LE(off) : buffer.readUInt32BE(off);
|
|
243
|
+
const fileSize = readU32(32);
|
|
244
|
+
const headerSize = readU32(36);
|
|
245
|
+
const stringIdsSize = readU32(56);
|
|
246
|
+
const typeIdsSize = readU32(64);
|
|
247
|
+
const protoIdsSize = readU32(72);
|
|
248
|
+
const fieldIdsSize = readU32(80);
|
|
249
|
+
const methodIdsSize = readU32(88);
|
|
250
|
+
const classDefsSize = readU32(96);
|
|
251
|
+
return {
|
|
252
|
+
format: 'DEX',
|
|
253
|
+
architecture: 'Dalvik / ART Bytecode',
|
|
254
|
+
is64Bit: false,
|
|
255
|
+
byteOrder: isLe ? 'little-endian' : 'big-endian',
|
|
256
|
+
fileType: 'Dalvik Executable (DEX)',
|
|
257
|
+
metadata: {
|
|
258
|
+
dexMagic: magic.trim(),
|
|
259
|
+
fileSize,
|
|
260
|
+
headerSize,
|
|
261
|
+
classDefinitionsCount: classDefsSize,
|
|
262
|
+
methodIdsCount: methodIdsSize,
|
|
263
|
+
fieldIdsCount: fieldIdsSize,
|
|
264
|
+
typeIdsCount: typeIdsSize,
|
|
265
|
+
stringIdsCount: stringIdsSize
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
270
|
+
// ANDROID SDK AAPT DISCOVERY & BADGING PARSER
|
|
271
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
272
|
+
function findAaptExecutable() {
|
|
273
|
+
const home = process.env.HOME || '';
|
|
274
|
+
const searchDirs = [
|
|
275
|
+
path.join(home, 'Library/Android/sdk/build-tools'),
|
|
276
|
+
path.join(home, 'Android/Sdk/build-tools'),
|
|
277
|
+
'/opt/android-sdk/build-tools'
|
|
278
|
+
];
|
|
279
|
+
if (process.env.ANDROID_HOME) {
|
|
280
|
+
searchDirs.unshift(path.join(process.env.ANDROID_HOME, 'build-tools'));
|
|
281
|
+
}
|
|
282
|
+
if (process.env.ANDROID_SDK_ROOT) {
|
|
283
|
+
searchDirs.unshift(path.join(process.env.ANDROID_SDK_ROOT, 'build-tools'));
|
|
284
|
+
}
|
|
285
|
+
for (const dir of searchDirs) {
|
|
286
|
+
if (fs.existsSync(dir)) {
|
|
287
|
+
try {
|
|
288
|
+
const versions = fs.readdirSync(dir).sort().reverse();
|
|
289
|
+
for (const v of versions) {
|
|
290
|
+
const aaptPath = path.join(dir, v, 'aapt');
|
|
291
|
+
if (fs.existsSync(aaptPath))
|
|
292
|
+
return aaptPath;
|
|
293
|
+
const aapt2Path = path.join(dir, v, 'aapt2');
|
|
294
|
+
if (fs.existsSync(aapt2Path))
|
|
295
|
+
return aapt2Path;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
// safe continuation
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
async function parseApkBadging(aaptPath, apkPath) {
|
|
306
|
+
try {
|
|
307
|
+
const res = await execFileAsync(aaptPath, ['dump', 'badging', apkPath], {
|
|
308
|
+
timeout: 20000,
|
|
309
|
+
maxBuffer: 25 * 1024 * 1024
|
|
310
|
+
});
|
|
311
|
+
const stdout = res.stdout;
|
|
312
|
+
const pkgMatch = stdout.match(/package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'/);
|
|
313
|
+
const sdkMatch = stdout.match(/sdkVersion:'([^']+)'/);
|
|
314
|
+
const targetSdkMatch = stdout.match(/targetSdkVersion:'([^']+)'/);
|
|
315
|
+
const labelMatch = stdout.match(/application-label:'([^']+)'/);
|
|
316
|
+
const launchMatch = stdout.match(/launchable-activity: name='([^']+)'/);
|
|
317
|
+
const permissions = [...stdout.matchAll(/uses-permission: name='([^']+)'/g)].map(m => m[1]);
|
|
318
|
+
const nativeCodes = [...stdout.matchAll(/native-code: '([^']+)'/g)].map(m => m[1]);
|
|
319
|
+
const features = [...stdout.matchAll(/uses-feature: name='([^']+)'/g)].map(m => m[1]);
|
|
320
|
+
return {
|
|
321
|
+
packageName: pkgMatch?.[1],
|
|
322
|
+
versionCode: pkgMatch?.[2],
|
|
323
|
+
versionName: pkgMatch?.[3],
|
|
324
|
+
minSdkVersion: sdkMatch?.[1],
|
|
325
|
+
targetSdkVersion: targetSdkMatch?.[1],
|
|
326
|
+
applicationLabel: labelMatch?.[1],
|
|
327
|
+
launchableActivity: launchMatch?.[1],
|
|
328
|
+
nativeArchitectures: nativeCodes.length > 0 ? nativeCodes : undefined,
|
|
329
|
+
permissionsCount: permissions.length,
|
|
330
|
+
permissions: permissions.slice(0, 100),
|
|
331
|
+
featuresCount: features.length,
|
|
332
|
+
features: features.slice(0, 30)
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
340
|
+
// BINARY XML (AXML) STRING POOL & COMPONENT EXTRACTOR
|
|
341
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
342
|
+
function parseAxmlStrings(buf) {
|
|
343
|
+
if (buf.length < 36)
|
|
344
|
+
return [];
|
|
345
|
+
const chunkType = buf.readUInt16LE(8);
|
|
346
|
+
if (chunkType !== 0x0001)
|
|
347
|
+
return []; // RES_STRING_POOL_TYPE
|
|
348
|
+
const stringCount = buf.readUInt32LE(16);
|
|
349
|
+
const flags = buf.readUInt32LE(24);
|
|
350
|
+
const isUtf8 = (flags & (1 << 8)) !== 0;
|
|
351
|
+
const stringsStart = 8 + buf.readUInt32LE(28);
|
|
352
|
+
const strings = [];
|
|
353
|
+
for (let i = 0; i < stringCount; i++) {
|
|
354
|
+
const offPos = 36 + i * 4;
|
|
355
|
+
if (offPos + 4 > buf.length)
|
|
356
|
+
break;
|
|
357
|
+
const strOffset = stringsStart + buf.readUInt32LE(offPos);
|
|
358
|
+
if (strOffset >= buf.length)
|
|
359
|
+
continue;
|
|
360
|
+
try {
|
|
361
|
+
if (isUtf8) {
|
|
362
|
+
let off = strOffset;
|
|
363
|
+
const b0 = buf[off];
|
|
364
|
+
if (b0 === undefined)
|
|
365
|
+
continue;
|
|
366
|
+
if ((b0 & 0x80) !== 0)
|
|
367
|
+
off += 2;
|
|
368
|
+
else
|
|
369
|
+
off += 1;
|
|
370
|
+
if (off >= buf.length)
|
|
371
|
+
continue;
|
|
372
|
+
const b1 = buf[off];
|
|
373
|
+
if (b1 === undefined)
|
|
374
|
+
continue;
|
|
375
|
+
let byteLen = b1;
|
|
376
|
+
if ((byteLen & 0x80) !== 0) {
|
|
377
|
+
const b2 = buf[off + 1];
|
|
378
|
+
if (b2 === undefined)
|
|
379
|
+
continue;
|
|
380
|
+
byteLen = ((byteLen & 0x7f) << 8) | b2;
|
|
381
|
+
off += 2;
|
|
382
|
+
}
|
|
383
|
+
else {
|
|
384
|
+
off += 1;
|
|
385
|
+
}
|
|
386
|
+
if (off + byteLen <= buf.length) {
|
|
387
|
+
strings.push(buf.toString('utf8', off, off + byteLen));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
let off = strOffset;
|
|
392
|
+
let len = buf.readUInt16LE(off);
|
|
393
|
+
if ((len & 0x8000) !== 0) {
|
|
394
|
+
len = ((len & 0x7fff) << 16) | buf.readUInt16LE(off + 2);
|
|
395
|
+
off += 4;
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
off += 2;
|
|
399
|
+
}
|
|
400
|
+
if (off + len * 2 <= buf.length) {
|
|
401
|
+
strings.push(buf.toString('utf16le', off, off + len * 2));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
// safe ignore individual string decode error
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return strings;
|
|
410
|
+
}
|
|
411
|
+
async function inspectApkZipAndManifest(apkPath) {
|
|
412
|
+
let fd = null;
|
|
413
|
+
try {
|
|
414
|
+
const stat = await fsp.stat(apkPath);
|
|
415
|
+
fd = await fsp.open(apkPath, 'r');
|
|
416
|
+
const endSize = Math.min(65536, stat.size);
|
|
417
|
+
const endBuf = Buffer.alloc(endSize);
|
|
418
|
+
await fd.read(endBuf, 0, endSize, stat.size - endSize);
|
|
419
|
+
let eocdOffset = -1;
|
|
420
|
+
for (let i = endBuf.length - 22; i >= 0; i--) {
|
|
421
|
+
if (endBuf.readUInt32LE(i) === 0x06054b50) {
|
|
422
|
+
eocdOffset = stat.size - endSize + i;
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (eocdOffset === -1) {
|
|
427
|
+
return { format: 'APK/ZIP', fileType: 'Android Application Package (APK)' };
|
|
428
|
+
}
|
|
429
|
+
const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
|
|
430
|
+
const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
|
|
431
|
+
const cdBuf = Buffer.alloc(cdSize);
|
|
432
|
+
await fd.read(cdBuf, 0, cdSize, cdOffset);
|
|
433
|
+
let ptr = 0;
|
|
434
|
+
let manifestEntry = null;
|
|
435
|
+
const dexFiles = [];
|
|
436
|
+
let totalDexUncompressed = 0;
|
|
437
|
+
const nativeLibs = [];
|
|
438
|
+
const abis = new Set();
|
|
439
|
+
const frameworks = new Set();
|
|
440
|
+
while (ptr + 46 <= cdBuf.length) {
|
|
441
|
+
if (cdBuf.readUInt32LE(ptr) !== 0x02014b50)
|
|
442
|
+
break;
|
|
443
|
+
const method = cdBuf.readUInt16LE(ptr + 10);
|
|
444
|
+
const compSize = cdBuf.readUInt32LE(ptr + 20);
|
|
445
|
+
const uncompSize = cdBuf.readUInt32LE(ptr + 24);
|
|
446
|
+
const nameLen = cdBuf.readUInt16LE(ptr + 28);
|
|
447
|
+
const extraLen = cdBuf.readUInt16LE(ptr + 30);
|
|
448
|
+
const commentLen = cdBuf.readUInt16LE(ptr + 32);
|
|
449
|
+
const localHeaderOffset = cdBuf.readUInt32LE(ptr + 42);
|
|
450
|
+
const name = cdBuf.toString('utf8', ptr + 46, ptr + 46 + nameLen);
|
|
451
|
+
if (name === 'AndroidManifest.xml') {
|
|
452
|
+
manifestEntry = { name, method, compSize, uncompSize, localHeaderOffset };
|
|
453
|
+
}
|
|
454
|
+
else if (name.endsWith('.dex')) {
|
|
455
|
+
dexFiles.push(name);
|
|
456
|
+
totalDexUncompressed += uncompSize;
|
|
457
|
+
}
|
|
458
|
+
else if (name.startsWith('lib/')) {
|
|
459
|
+
nativeLibs.push(name);
|
|
460
|
+
const parts = name.split('/');
|
|
461
|
+
const abiName = parts[1];
|
|
462
|
+
if (parts.length > 2 && abiName)
|
|
463
|
+
abis.add(abiName);
|
|
464
|
+
if (name.includes('libflutter.so') || name.includes('libapp.so'))
|
|
465
|
+
frameworks.add('Flutter');
|
|
466
|
+
if (name.includes('libreactnativejni.so') || name.includes('libhermes.so'))
|
|
467
|
+
frameworks.add('React Native');
|
|
468
|
+
if (name.includes('libunity.so'))
|
|
469
|
+
frameworks.add('Unity');
|
|
470
|
+
if (name.includes('libkwopdf.so') || name.includes('libksoedit.so'))
|
|
471
|
+
frameworks.add('Kingsoft Office Native C++ Engine');
|
|
472
|
+
if (name.includes('libUE4.so') || name.includes('libUnreal.so'))
|
|
473
|
+
frameworks.add('Unreal Engine');
|
|
474
|
+
if (name.includes('libcocos2djs.so'))
|
|
475
|
+
frameworks.add('Cocos2d-x');
|
|
476
|
+
}
|
|
477
|
+
ptr += 46 + nameLen + extraLen + commentLen;
|
|
478
|
+
}
|
|
479
|
+
let manifestStrings = [];
|
|
480
|
+
if (manifestEntry) {
|
|
481
|
+
const localHdr = Buffer.alloc(30);
|
|
482
|
+
await fd.read(localHdr, 0, 30, manifestEntry.localHeaderOffset);
|
|
483
|
+
const fnLen = localHdr.readUInt16LE(26);
|
|
484
|
+
const extraLen = localHdr.readUInt16LE(28);
|
|
485
|
+
const dataOffset = manifestEntry.localHeaderOffset + 30 + fnLen + extraLen;
|
|
486
|
+
const compData = Buffer.alloc(manifestEntry.compSize);
|
|
487
|
+
await fd.read(compData, 0, manifestEntry.compSize, dataOffset);
|
|
488
|
+
const xmlBuf = manifestEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
|
|
489
|
+
manifestStrings = parseAxmlStrings(xmlBuf);
|
|
490
|
+
}
|
|
491
|
+
const permissions = manifestStrings.filter(s => s.includes('permission.') || s.startsWith('android.permission'));
|
|
492
|
+
const activities = manifestStrings.filter(s => s.endsWith('Activity') || s.includes('Activity$'));
|
|
493
|
+
const services = manifestStrings.filter(s => s.endsWith('Service') || s.includes('Service$') || s.startsWith(':'));
|
|
494
|
+
const receivers = manifestStrings.filter(s => s.endsWith('Receiver') || s.includes('Receiver$'));
|
|
495
|
+
const providers = manifestStrings.filter(s => s.endsWith('Provider') || s.includes('Provider$'));
|
|
496
|
+
// Discover package name candidate from strings
|
|
497
|
+
const pkgCandidate = manifestStrings.find(s => s.includes('.') && !s.includes('/') && !s.startsWith('android.') && !s.startsWith('androidx.') && s.split('.').length >= 3 && !s.includes('Activity') && !s.includes('Service'));
|
|
498
|
+
const primaryAbi = Array.from(abis)[0] || 'arm64-v8a';
|
|
499
|
+
let badging = null;
|
|
500
|
+
const aaptPath = findAaptExecutable();
|
|
501
|
+
if (aaptPath) {
|
|
502
|
+
badging = await parseApkBadging(aaptPath, apkPath);
|
|
503
|
+
}
|
|
504
|
+
const metadata = {
|
|
505
|
+
packageName: badging?.packageName || pkgCandidate,
|
|
506
|
+
versionCode: badging?.versionCode,
|
|
507
|
+
versionName: badging?.versionName,
|
|
508
|
+
minSdkVersion: badging?.minSdkVersion,
|
|
509
|
+
targetSdkVersion: badging?.targetSdkVersion,
|
|
510
|
+
applicationLabel: badging?.applicationLabel,
|
|
511
|
+
launchableActivity: badging?.launchableActivity,
|
|
512
|
+
dexFileCount: dexFiles.length,
|
|
513
|
+
dexFiles: dexFiles.slice(0, 15),
|
|
514
|
+
totalDexSizeMb: (totalDexUncompressed / (1024 * 1024)).toFixed(1),
|
|
515
|
+
nativeArchitectures: badging?.nativeArchitectures || Array.from(abis),
|
|
516
|
+
nativeLibraryCount: nativeLibs.length,
|
|
517
|
+
sampleNativeLibraries: nativeLibs.slice(0, 10),
|
|
518
|
+
detectedFrameworks: Array.from(frameworks),
|
|
519
|
+
permissionsCount: badging?.permissionsCount || permissions.length,
|
|
520
|
+
permissions: badging?.permissions || permissions.slice(0, 50),
|
|
521
|
+
activitiesCount: activities.length,
|
|
522
|
+
sampleActivities: activities.slice(0, 10),
|
|
523
|
+
servicesCount: services.length,
|
|
524
|
+
sampleServices: services.slice(0, 10),
|
|
525
|
+
receiversCount: receivers.length,
|
|
526
|
+
providersCount: providers.length
|
|
527
|
+
};
|
|
528
|
+
return {
|
|
529
|
+
format: 'APK/ZIP',
|
|
530
|
+
architecture: primaryAbi,
|
|
531
|
+
is64Bit: primaryAbi.includes('64'),
|
|
532
|
+
byteOrder: 'little-endian',
|
|
533
|
+
fileType: 'Android Application Package (APK)',
|
|
534
|
+
metadata
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
finally {
|
|
538
|
+
if (fd)
|
|
539
|
+
await fd.close();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
543
|
+
// SEARCH CLASSES DIRECTLY IN APK DEX & MANIFEST
|
|
544
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
545
|
+
async function searchClassesInApk(apkPath, query) {
|
|
546
|
+
let fd = null;
|
|
547
|
+
const matches = new Set();
|
|
548
|
+
let totalInspected = 0;
|
|
549
|
+
const qLower = query.toLowerCase();
|
|
550
|
+
try {
|
|
551
|
+
const stat = await fsp.stat(apkPath);
|
|
552
|
+
fd = await fsp.open(apkPath, 'r');
|
|
553
|
+
const endSize = Math.min(65536, stat.size);
|
|
554
|
+
const endBuf = Buffer.alloc(endSize);
|
|
555
|
+
await fd.read(endBuf, 0, endSize, stat.size - endSize);
|
|
556
|
+
let eocdOffset = -1;
|
|
557
|
+
for (let i = endBuf.length - 22; i >= 0; i--) {
|
|
558
|
+
if (endBuf.readUInt32LE(i) === 0x06054b50) {
|
|
559
|
+
eocdOffset = stat.size - endSize + i;
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (eocdOffset === -1)
|
|
564
|
+
return { matchedClasses: [], totalInspected: 0 };
|
|
565
|
+
const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
|
|
566
|
+
const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
|
|
567
|
+
const cdBuf = Buffer.alloc(cdSize);
|
|
568
|
+
await fd.read(cdBuf, 0, cdSize, cdOffset);
|
|
569
|
+
let ptr = 0;
|
|
570
|
+
const dexEntries = [];
|
|
571
|
+
while (ptr + 46 <= cdBuf.length) {
|
|
572
|
+
if (cdBuf.readUInt32LE(ptr) !== 0x02014b50)
|
|
573
|
+
break;
|
|
574
|
+
const method = cdBuf.readUInt16LE(ptr + 10);
|
|
575
|
+
const compSize = cdBuf.readUInt32LE(ptr + 20);
|
|
576
|
+
const uncompSize = cdBuf.readUInt32LE(ptr + 24);
|
|
577
|
+
const nameLen = cdBuf.readUInt16LE(ptr + 28);
|
|
578
|
+
const extraLen = cdBuf.readUInt16LE(ptr + 30);
|
|
579
|
+
const commentLen = cdBuf.readUInt16LE(ptr + 32);
|
|
580
|
+
const localHeaderOffset = cdBuf.readUInt32LE(ptr + 42);
|
|
581
|
+
const name = cdBuf.toString('utf8', ptr + 46, ptr + 46 + nameLen);
|
|
582
|
+
if (name.endsWith('.dex')) {
|
|
583
|
+
dexEntries.push({ name, method, compSize, uncompSize, localHeaderOffset });
|
|
584
|
+
}
|
|
585
|
+
ptr += 46 + nameLen + extraLen + commentLen;
|
|
586
|
+
}
|
|
587
|
+
for (const dexEntry of dexEntries.slice(0, 5)) {
|
|
588
|
+
try {
|
|
589
|
+
const localHdr = Buffer.alloc(30);
|
|
590
|
+
await fd.read(localHdr, 0, 30, dexEntry.localHeaderOffset);
|
|
591
|
+
const fnLen = localHdr.readUInt16LE(26);
|
|
592
|
+
const extraLen = localHdr.readUInt16LE(28);
|
|
593
|
+
const dataOffset = dexEntry.localHeaderOffset + 30 + fnLen + extraLen;
|
|
594
|
+
const compData = Buffer.alloc(dexEntry.compSize);
|
|
595
|
+
await fd.read(compData, 0, dexEntry.compSize, dataOffset);
|
|
596
|
+
const dexBuf = dexEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
|
|
597
|
+
if (dexBuf.length >= 112 && dexBuf.toString('utf8', 0, 4) === 'dex\n') {
|
|
598
|
+
const stringIdsOff = dexBuf.readUInt32LE(60);
|
|
599
|
+
const typeIdsOff = dexBuf.readUInt32LE(68);
|
|
600
|
+
const classDefsSize = dexBuf.readUInt32LE(96);
|
|
601
|
+
const classDefsOff = dexBuf.readUInt32LE(100);
|
|
602
|
+
totalInspected += classDefsSize;
|
|
603
|
+
for (let i = 0; i < classDefsSize; i++) {
|
|
604
|
+
const classDefOffset = classDefsOff + i * 32;
|
|
605
|
+
if (classDefOffset + 4 > dexBuf.length)
|
|
606
|
+
break;
|
|
607
|
+
const classIdx = dexBuf.readUInt32LE(classDefOffset);
|
|
608
|
+
const typeOff = typeIdsOff + classIdx * 4;
|
|
609
|
+
if (typeOff + 4 > dexBuf.length)
|
|
610
|
+
continue;
|
|
611
|
+
const descriptorIdx = dexBuf.readUInt32LE(typeOff);
|
|
612
|
+
const strOffPos = stringIdsOff + descriptorIdx * 4;
|
|
613
|
+
if (strOffPos + 4 > dexBuf.length)
|
|
614
|
+
continue;
|
|
615
|
+
const stringDataOff = dexBuf.readUInt32LE(strOffPos);
|
|
616
|
+
let off = stringDataOff;
|
|
617
|
+
while (off < dexBuf.length) {
|
|
618
|
+
const b = dexBuf[off];
|
|
619
|
+
if (b === undefined || (b & 0x80) === 0)
|
|
620
|
+
break;
|
|
621
|
+
off++;
|
|
622
|
+
}
|
|
623
|
+
off++;
|
|
624
|
+
let end = off;
|
|
625
|
+
while (end < dexBuf.length && dexBuf[end] !== 0)
|
|
626
|
+
end++;
|
|
627
|
+
const rawDesc = dexBuf.toString('utf8', off, end);
|
|
628
|
+
if (!qLower || rawDesc.toLowerCase().includes(qLower)) {
|
|
629
|
+
const cleanName = rawDesc.replace(/^L/, '').replace(/;$/, '').replace(/\//g, '.');
|
|
630
|
+
matches.add(cleanName);
|
|
631
|
+
if (matches.size >= 100)
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
// continue
|
|
639
|
+
}
|
|
640
|
+
if (matches.size >= 100)
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
finally {
|
|
645
|
+
if (fd)
|
|
646
|
+
await fd.close();
|
|
647
|
+
}
|
|
648
|
+
return {
|
|
649
|
+
matchedClasses: Array.from(matches),
|
|
650
|
+
totalInspected
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
231
654
|
// CANONICAL TOOL DEFINITION
|
|
232
655
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
233
656
|
export const reverseEngineering = {
|
|
@@ -414,8 +837,20 @@ export const reverseEngineering = {
|
|
|
414
837
|
}
|
|
415
838
|
// ── ACTION: DECODE_RESOURCES ──────────────────────────────────────────
|
|
416
839
|
if (action === 'decode_resources') {
|
|
417
|
-
|
|
418
|
-
|
|
840
|
+
let res = await sovereignReverseHarness.decodeAndroidResources(resolvedFile, outputDir, context.signal);
|
|
841
|
+
let textOutput = '';
|
|
842
|
+
if (res.success && res.output && !res.output.includes('apktool launcher was not found')) {
|
|
843
|
+
textOutput = res.output;
|
|
844
|
+
}
|
|
845
|
+
else {
|
|
846
|
+
const targetDir = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_resources`);
|
|
847
|
+
await fsp.mkdir(targetDir, { recursive: true });
|
|
848
|
+
const apkInfo = await inspectApkZipAndManifest(resolvedFile);
|
|
849
|
+
const manifestSummaryPath = path.join(targetDir, 'manifest_summary.json');
|
|
850
|
+
await fsp.writeFile(manifestSummaryPath, JSON.stringify(apkInfo.metadata || {}, null, 2), 'utf8');
|
|
851
|
+
textOutput = `Extracted Android package architecture to ${targetDir}:\n- Manifest summary: ${manifestSummaryPath}\n- Package: ${apkInfo.metadata?.packageName || 'unknown'}\n- Activities: ${apkInfo.metadata?.activitiesCount || 0}\n- Services: ${apkInfo.metadata?.servicesCount || 0}\n- Permissions: ${apkInfo.metadata?.permissionsCount || 0}`;
|
|
852
|
+
res = { success: true, toolName: 'decode_resources', output: textOutput, source: 'fallback' };
|
|
853
|
+
}
|
|
419
854
|
const stored = outputStore.processToolOutput(sessionId, `${callId}_decode_resources`, textOutput);
|
|
420
855
|
return {
|
|
421
856
|
success: res.success,
|
|
@@ -430,8 +865,21 @@ export const reverseEngineering = {
|
|
|
430
865
|
// ── ACTION: SEARCH_CLASSES ───────────────────────────────────────────
|
|
431
866
|
if (action === 'search_classes') {
|
|
432
867
|
const query = String(args['query'] || '');
|
|
433
|
-
|
|
434
|
-
|
|
868
|
+
let res = await sovereignReverseHarness.searchAndroidClasses(resolvedFile, query, context.signal);
|
|
869
|
+
let textOutput = '';
|
|
870
|
+
if (res.success && res.output && !res.output.includes('capability_unavailable') && !res.output.includes('REA_JADX_MCP_JAR')) {
|
|
871
|
+
textOutput = res.output;
|
|
872
|
+
}
|
|
873
|
+
else {
|
|
874
|
+
const nativeSearch = await searchClassesInApk(resolvedFile, query);
|
|
875
|
+
textOutput = JSON.stringify({
|
|
876
|
+
query,
|
|
877
|
+
totalInspectedDexClasses: nativeSearch.totalInspected,
|
|
878
|
+
matchedClassesCount: nativeSearch.matchedClasses.length,
|
|
879
|
+
matchedClasses: nativeSearch.matchedClasses
|
|
880
|
+
}, null, 2);
|
|
881
|
+
res = { success: true, toolName: 'search_classes', output: textOutput, source: 'fallback' };
|
|
882
|
+
}
|
|
435
883
|
const stored = outputStore.processToolOutput(sessionId, `${callId}_search_classes`, textOutput);
|
|
436
884
|
return {
|
|
437
885
|
success: res.success,
|
|
@@ -483,6 +931,11 @@ export const reverseEngineering = {
|
|
|
483
931
|
};
|
|
484
932
|
const magic32Be = headerBuf.length >= 4 ? headerBuf.readUInt32BE(0) : 0;
|
|
485
933
|
const magic32Le = headerBuf.length >= 4 ? headerBuf.readUInt32LE(0) : 0;
|
|
934
|
+
const isDex = (headerBuf.length >= 4 && headerBuf[0] === 0x64 && headerBuf[1] === 0x65 && headerBuf[2] === 0x78 && headerBuf[3] === 0x0a)
|
|
935
|
+
|| resolvedFile.toLowerCase().endsWith('.dex');
|
|
936
|
+
const isApkOrZip = (headerBuf.length >= 4 && headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04)
|
|
937
|
+
|| resolvedFile.toLowerCase().endsWith('.apk')
|
|
938
|
+
|| resolvedFile.toLowerCase().endsWith('.aab');
|
|
486
939
|
if (magic32Be === 0xfeedface || magic32Be === 0xfeedfacf ||
|
|
487
940
|
magic32Le === 0xfeedface || magic32Le === 0xfeedfacf ||
|
|
488
941
|
magic32Be === 0xcafebabe || magic32Be === 0xbebafeca) {
|
|
@@ -498,26 +951,12 @@ export const reverseEngineering = {
|
|
|
498
951
|
result.format = 'WebAssembly';
|
|
499
952
|
result.architecture = 'wasm32 / wasm64';
|
|
500
953
|
}
|
|
501
|
-
else if (
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
const lines = unzipList.stdout.split('\n');
|
|
508
|
-
const dexFiles = lines.filter(l => l.includes('.dex')).map(l => l.trim().split(/\s+/).pop());
|
|
509
|
-
const hasManifest = lines.some(l => l.includes('AndroidManifest.xml'));
|
|
510
|
-
const nativeLibs = lines.filter(l => l.includes('lib/')).slice(0, 15).map(l => l.trim().split(/\s+/).pop());
|
|
511
|
-
result.metadata = {
|
|
512
|
-
dexFiles,
|
|
513
|
-
hasManifest,
|
|
514
|
-
totalEntries: lines.length,
|
|
515
|
-
sampleNativeLibraries: nativeLibs
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
catch {
|
|
519
|
-
// unzip fallback
|
|
520
|
-
}
|
|
954
|
+
else if (isDex) {
|
|
955
|
+
result = { ...result, ...parseDex(headerBuf) };
|
|
956
|
+
}
|
|
957
|
+
else if (isApkOrZip) {
|
|
958
|
+
const apkResult = await inspectApkZipAndManifest(resolvedFile);
|
|
959
|
+
result = { ...result, ...apkResult };
|
|
521
960
|
}
|
|
522
961
|
else {
|
|
523
962
|
const asar = parseAsarHeader(headerBuf);
|
|
@@ -548,6 +987,7 @@ export const reverseEngineering = {
|
|
|
548
987
|
action: 'inspect',
|
|
549
988
|
format: result.format,
|
|
550
989
|
architecture: result.architecture || 'unknown',
|
|
990
|
+
metadata: result.metadata,
|
|
551
991
|
mitigations: result.mitigations,
|
|
552
992
|
preview: stored.contentForModel,
|
|
553
993
|
isTruncated: stored.isTruncated,
|