@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.
@@ -9,6 +9,7 @@
9
9
  import fs from 'node:fs';
10
10
  import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
+ import zlib from 'node:zlib';
12
13
  import { execFile } from 'node:child_process';
13
14
  import util from 'node:util';
14
15
  import { resolveUserPath } from '../utils/paths.js';
@@ -309,6 +310,440 @@ async function deobfuscateScript(filePath: string): Promise<{
309
310
  };
310
311
  }
311
312
 
313
+ // ─────────────────────────────────────────────────────────────────────────────
314
+ // DALVIK EXECUTABLE (DEX) ZERO-DEPENDENCY PARSER
315
+ // ─────────────────────────────────────────────────────────────────────────────
316
+
317
+ function parseDex(buffer: Buffer): Partial<BinaryInspectionResult> {
318
+ if (buffer.length < 112) return { format: 'DEX' };
319
+ const magic = buffer.toString('utf8', 0, 8);
320
+ if (!magic.startsWith('dex\n')) return { format: 'DEX' };
321
+
322
+ const endianTag = buffer.readUInt32LE(40);
323
+ const isLe = endianTag === 0x12345678;
324
+ const readU32 = (off: number) => isLe ? buffer.readUInt32LE(off) : buffer.readUInt32BE(off);
325
+
326
+ const fileSize = readU32(32);
327
+ const headerSize = readU32(36);
328
+ const stringIdsSize = readU32(56);
329
+ const typeIdsSize = readU32(64);
330
+ const protoIdsSize = readU32(72);
331
+ const fieldIdsSize = readU32(80);
332
+ const methodIdsSize = readU32(88);
333
+ const classDefsSize = readU32(96);
334
+
335
+ return {
336
+ format: 'DEX',
337
+ architecture: 'Dalvik / ART Bytecode',
338
+ is64Bit: false,
339
+ byteOrder: isLe ? 'little-endian' : 'big-endian',
340
+ fileType: 'Dalvik Executable (DEX)',
341
+ metadata: {
342
+ dexMagic: magic.trim(),
343
+ fileSize,
344
+ headerSize,
345
+ classDefinitionsCount: classDefsSize,
346
+ methodIdsCount: methodIdsSize,
347
+ fieldIdsCount: fieldIdsSize,
348
+ typeIdsCount: typeIdsSize,
349
+ stringIdsCount: stringIdsSize
350
+ }
351
+ };
352
+ }
353
+
354
+ // ─────────────────────────────────────────────────────────────────────────────
355
+ // ANDROID SDK AAPT DISCOVERY & BADGING PARSER
356
+ // ─────────────────────────────────────────────────────────────────────────────
357
+
358
+ function findAaptExecutable(): string | null {
359
+ const home = process.env.HOME || '';
360
+ const searchDirs = [
361
+ path.join(home, 'Library/Android/sdk/build-tools'),
362
+ path.join(home, 'Android/Sdk/build-tools'),
363
+ '/opt/android-sdk/build-tools'
364
+ ];
365
+
366
+ if (process.env.ANDROID_HOME) {
367
+ searchDirs.unshift(path.join(process.env.ANDROID_HOME, 'build-tools'));
368
+ }
369
+ if (process.env.ANDROID_SDK_ROOT) {
370
+ searchDirs.unshift(path.join(process.env.ANDROID_SDK_ROOT, 'build-tools'));
371
+ }
372
+
373
+ for (const dir of searchDirs) {
374
+ if (fs.existsSync(dir)) {
375
+ try {
376
+ const versions = fs.readdirSync(dir).sort().reverse();
377
+ for (const v of versions) {
378
+ const aaptPath = path.join(dir, v, 'aapt');
379
+ if (fs.existsSync(aaptPath)) return aaptPath;
380
+ const aapt2Path = path.join(dir, v, 'aapt2');
381
+ if (fs.existsSync(aapt2Path)) return aapt2Path;
382
+ }
383
+ } catch {
384
+ // safe continuation
385
+ }
386
+ }
387
+ }
388
+
389
+ return null;
390
+ }
391
+
392
+ async function parseApkBadging(aaptPath: string, apkPath: string): Promise<Record<string, unknown> | null> {
393
+ try {
394
+ const res = await execFileAsync(aaptPath, ['dump', 'badging', apkPath], {
395
+ timeout: 20000,
396
+ maxBuffer: 25 * 1024 * 1024
397
+ });
398
+ const stdout = res.stdout;
399
+ const pkgMatch = stdout.match(/package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'/);
400
+ const sdkMatch = stdout.match(/sdkVersion:'([^']+)'/);
401
+ const targetSdkMatch = stdout.match(/targetSdkVersion:'([^']+)'/);
402
+ const labelMatch = stdout.match(/application-label:'([^']+)'/);
403
+ const launchMatch = stdout.match(/launchable-activity: name='([^']+)'/);
404
+ const permissions = [...stdout.matchAll(/uses-permission: name='([^']+)'/g)].map(m => m[1]);
405
+ const nativeCodes = [...stdout.matchAll(/native-code: '([^']+)'/g)].map(m => m[1]);
406
+ const features = [...stdout.matchAll(/uses-feature: name='([^']+)'/g)].map(m => m[1]);
407
+
408
+ return {
409
+ packageName: pkgMatch?.[1],
410
+ versionCode: pkgMatch?.[2],
411
+ versionName: pkgMatch?.[3],
412
+ minSdkVersion: sdkMatch?.[1],
413
+ targetSdkVersion: targetSdkMatch?.[1],
414
+ applicationLabel: labelMatch?.[1],
415
+ launchableActivity: launchMatch?.[1],
416
+ nativeArchitectures: nativeCodes.length > 0 ? nativeCodes : undefined,
417
+ permissionsCount: permissions.length,
418
+ permissions: permissions.slice(0, 100),
419
+ featuresCount: features.length,
420
+ features: features.slice(0, 30)
421
+ };
422
+ } catch {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ // ─────────────────────────────────────────────────────────────────────────────
428
+ // BINARY XML (AXML) STRING POOL & COMPONENT EXTRACTOR
429
+ // ─────────────────────────────────────────────────────────────────────────────
430
+
431
+ function parseAxmlStrings(buf: Buffer): string[] {
432
+ if (buf.length < 36) return [];
433
+ const chunkType = buf.readUInt16LE(8);
434
+ if (chunkType !== 0x0001) return []; // RES_STRING_POOL_TYPE
435
+ const stringCount = buf.readUInt32LE(16);
436
+ const flags = buf.readUInt32LE(24);
437
+ const isUtf8 = (flags & (1 << 8)) !== 0;
438
+ const stringsStart = 8 + buf.readUInt32LE(28);
439
+
440
+ const strings: string[] = [];
441
+ for (let i = 0; i < stringCount; i++) {
442
+ const offPos = 36 + i * 4;
443
+ if (offPos + 4 > buf.length) break;
444
+ const strOffset = stringsStart + buf.readUInt32LE(offPos);
445
+ if (strOffset >= buf.length) continue;
446
+
447
+ try {
448
+ if (isUtf8) {
449
+ let off = strOffset;
450
+ const b0 = buf[off];
451
+ if (b0 === undefined) continue;
452
+ if ((b0 & 0x80) !== 0) off += 2; else off += 1;
453
+ if (off >= buf.length) continue;
454
+ const b1 = buf[off];
455
+ if (b1 === undefined) continue;
456
+ let byteLen = b1;
457
+ if ((byteLen & 0x80) !== 0) {
458
+ const b2 = buf[off + 1];
459
+ if (b2 === undefined) continue;
460
+ byteLen = ((byteLen & 0x7f) << 8) | b2;
461
+ off += 2;
462
+ } else {
463
+ off += 1;
464
+ }
465
+ if (off + byteLen <= buf.length) {
466
+ strings.push(buf.toString('utf8', off, off + byteLen));
467
+ }
468
+ } else {
469
+ let off = strOffset;
470
+ let len = buf.readUInt16LE(off);
471
+ if ((len & 0x8000) !== 0) {
472
+ len = ((len & 0x7fff) << 16) | buf.readUInt16LE(off + 2);
473
+ off += 4;
474
+ } else {
475
+ off += 2;
476
+ }
477
+ if (off + len * 2 <= buf.length) {
478
+ strings.push(buf.toString('utf16le', off, off + len * 2));
479
+ }
480
+ }
481
+ } catch {
482
+ // safe ignore individual string decode error
483
+ }
484
+ }
485
+ return strings;
486
+ }
487
+
488
+ // ─────────────────────────────────────────────────────────────────────────────
489
+ // SOVEREIGN ZERO-DEPENDENCY APK & MANIFEST PARSER
490
+ // ─────────────────────────────────────────────────────────────────────────────
491
+
492
+ interface ZipEntryInfo {
493
+ name: string;
494
+ method: number;
495
+ compSize: number;
496
+ uncompSize: number;
497
+ localHeaderOffset: number;
498
+ }
499
+
500
+ async function inspectApkZipAndManifest(apkPath: string): Promise<Partial<BinaryInspectionResult>> {
501
+ let fd: fs.promises.FileHandle | null = null;
502
+ try {
503
+ const stat = await fsp.stat(apkPath);
504
+ fd = await fsp.open(apkPath, 'r');
505
+
506
+ const endSize = Math.min(65536, stat.size);
507
+ const endBuf = Buffer.alloc(endSize);
508
+ await fd.read(endBuf, 0, endSize, stat.size - endSize);
509
+
510
+ let eocdOffset = -1;
511
+ for (let i = endBuf.length - 22; i >= 0; i--) {
512
+ if (endBuf.readUInt32LE(i) === 0x06054b50) {
513
+ eocdOffset = stat.size - endSize + i;
514
+ break;
515
+ }
516
+ }
517
+
518
+ if (eocdOffset === -1) {
519
+ return { format: 'APK/ZIP', fileType: 'Android Application Package (APK)' };
520
+ }
521
+
522
+ const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
523
+ const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
524
+ const cdBuf = Buffer.alloc(cdSize);
525
+ await fd.read(cdBuf, 0, cdSize, cdOffset);
526
+
527
+ let ptr = 0;
528
+ let manifestEntry: ZipEntryInfo | null = null;
529
+ const dexFiles: string[] = [];
530
+ let totalDexUncompressed = 0;
531
+ const nativeLibs: string[] = [];
532
+ const abis = new Set<string>();
533
+ const frameworks = new Set<string>();
534
+
535
+ while (ptr + 46 <= cdBuf.length) {
536
+ if (cdBuf.readUInt32LE(ptr) !== 0x02014b50) break;
537
+ const method = cdBuf.readUInt16LE(ptr + 10);
538
+ const compSize = cdBuf.readUInt32LE(ptr + 20);
539
+ const uncompSize = cdBuf.readUInt32LE(ptr + 24);
540
+ const nameLen = cdBuf.readUInt16LE(ptr + 28);
541
+ const extraLen = cdBuf.readUInt16LE(ptr + 30);
542
+ const commentLen = cdBuf.readUInt16LE(ptr + 32);
543
+ const localHeaderOffset = cdBuf.readUInt32LE(ptr + 42);
544
+ const name = cdBuf.toString('utf8', ptr + 46, ptr + 46 + nameLen);
545
+
546
+ if (name === 'AndroidManifest.xml') {
547
+ manifestEntry = { name, method, compSize, uncompSize, localHeaderOffset };
548
+ } else if (name.endsWith('.dex')) {
549
+ dexFiles.push(name);
550
+ totalDexUncompressed += uncompSize;
551
+ } else if (name.startsWith('lib/')) {
552
+ nativeLibs.push(name);
553
+ const parts = name.split('/');
554
+ const abiName = parts[1];
555
+ if (parts.length > 2 && abiName) abis.add(abiName);
556
+ if (name.includes('libflutter.so') || name.includes('libapp.so')) frameworks.add('Flutter');
557
+ if (name.includes('libreactnativejni.so') || name.includes('libhermes.so')) frameworks.add('React Native');
558
+ if (name.includes('libunity.so')) frameworks.add('Unity');
559
+ if (name.includes('libkwopdf.so') || name.includes('libksoedit.so')) frameworks.add('Kingsoft Office Native C++ Engine');
560
+ if (name.includes('libUE4.so') || name.includes('libUnreal.so')) frameworks.add('Unreal Engine');
561
+ if (name.includes('libcocos2djs.so')) frameworks.add('Cocos2d-x');
562
+ }
563
+ ptr += 46 + nameLen + extraLen + commentLen;
564
+ }
565
+
566
+ let manifestStrings: string[] = [];
567
+ if (manifestEntry) {
568
+ const localHdr = Buffer.alloc(30);
569
+ await fd.read(localHdr, 0, 30, manifestEntry.localHeaderOffset);
570
+ const fnLen = localHdr.readUInt16LE(26);
571
+ const extraLen = localHdr.readUInt16LE(28);
572
+ const dataOffset = manifestEntry.localHeaderOffset + 30 + fnLen + extraLen;
573
+ const compData = Buffer.alloc(manifestEntry.compSize);
574
+ await fd.read(compData, 0, manifestEntry.compSize, dataOffset);
575
+ const xmlBuf = manifestEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
576
+ manifestStrings = parseAxmlStrings(xmlBuf);
577
+ }
578
+
579
+ const permissions = manifestStrings.filter(s => s.includes('permission.') || s.startsWith('android.permission'));
580
+ const activities = manifestStrings.filter(s => s.endsWith('Activity') || s.includes('Activity$'));
581
+ const services = manifestStrings.filter(s => s.endsWith('Service') || s.includes('Service$') || s.startsWith(':'));
582
+ const receivers = manifestStrings.filter(s => s.endsWith('Receiver') || s.includes('Receiver$'));
583
+ const providers = manifestStrings.filter(s => s.endsWith('Provider') || s.includes('Provider$'));
584
+
585
+ // Discover package name candidate from strings
586
+ 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'));
587
+
588
+ const primaryAbi = Array.from(abis)[0] || 'arm64-v8a';
589
+
590
+ let badging: Record<string, unknown> | null = null;
591
+ const aaptPath = findAaptExecutable();
592
+ if (aaptPath) {
593
+ badging = await parseApkBadging(aaptPath, apkPath);
594
+ }
595
+
596
+ const metadata: Record<string, unknown> = {
597
+ packageName: badging?.packageName || pkgCandidate,
598
+ versionCode: badging?.versionCode,
599
+ versionName: badging?.versionName,
600
+ minSdkVersion: badging?.minSdkVersion,
601
+ targetSdkVersion: badging?.targetSdkVersion,
602
+ applicationLabel: badging?.applicationLabel,
603
+ launchableActivity: badging?.launchableActivity,
604
+ dexFileCount: dexFiles.length,
605
+ dexFiles: dexFiles.slice(0, 15),
606
+ totalDexSizeMb: (totalDexUncompressed / (1024 * 1024)).toFixed(1),
607
+ nativeArchitectures: badging?.nativeArchitectures || Array.from(abis),
608
+ nativeLibraryCount: nativeLibs.length,
609
+ sampleNativeLibraries: nativeLibs.slice(0, 10),
610
+ detectedFrameworks: Array.from(frameworks),
611
+ permissionsCount: badging?.permissionsCount || permissions.length,
612
+ permissions: (badging?.permissions as string[]) || permissions.slice(0, 50),
613
+ activitiesCount: activities.length,
614
+ sampleActivities: activities.slice(0, 10),
615
+ servicesCount: services.length,
616
+ sampleServices: services.slice(0, 10),
617
+ receiversCount: receivers.length,
618
+ providersCount: providers.length
619
+ };
620
+
621
+ return {
622
+ format: 'APK/ZIP',
623
+ architecture: primaryAbi,
624
+ is64Bit: primaryAbi.includes('64'),
625
+ byteOrder: 'little-endian',
626
+ fileType: 'Android Application Package (APK)',
627
+ metadata
628
+ };
629
+ } finally {
630
+ if (fd) await fd.close();
631
+ }
632
+ }
633
+
634
+ // ─────────────────────────────────────────────────────────────────────────────
635
+ // SEARCH CLASSES DIRECTLY IN APK DEX & MANIFEST
636
+ // ─────────────────────────────────────────────────────────────────────────────
637
+
638
+ async function searchClassesInApk(apkPath: string, query: string): Promise<{ matchedClasses: string[]; totalInspected: number }> {
639
+ let fd: fs.promises.FileHandle | null = null;
640
+ const matches = new Set<string>();
641
+ let totalInspected = 0;
642
+ const qLower = query.toLowerCase();
643
+
644
+ try {
645
+ const stat = await fsp.stat(apkPath);
646
+ fd = await fsp.open(apkPath, 'r');
647
+
648
+ const endSize = Math.min(65536, stat.size);
649
+ const endBuf = Buffer.alloc(endSize);
650
+ await fd.read(endBuf, 0, endSize, stat.size - endSize);
651
+
652
+ let eocdOffset = -1;
653
+ for (let i = endBuf.length - 22; i >= 0; i--) {
654
+ if (endBuf.readUInt32LE(i) === 0x06054b50) {
655
+ eocdOffset = stat.size - endSize + i;
656
+ break;
657
+ }
658
+ }
659
+
660
+ if (eocdOffset === -1) return { matchedClasses: [], totalInspected: 0 };
661
+
662
+ const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
663
+ const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
664
+ const cdBuf = Buffer.alloc(cdSize);
665
+ await fd.read(cdBuf, 0, cdSize, cdOffset);
666
+
667
+ let ptr = 0;
668
+ const dexEntries: ZipEntryInfo[] = [];
669
+
670
+ while (ptr + 46 <= cdBuf.length) {
671
+ if (cdBuf.readUInt32LE(ptr) !== 0x02014b50) break;
672
+ const method = cdBuf.readUInt16LE(ptr + 10);
673
+ const compSize = cdBuf.readUInt32LE(ptr + 20);
674
+ const uncompSize = cdBuf.readUInt32LE(ptr + 24);
675
+ const nameLen = cdBuf.readUInt16LE(ptr + 28);
676
+ const extraLen = cdBuf.readUInt16LE(ptr + 30);
677
+ const commentLen = cdBuf.readUInt16LE(ptr + 32);
678
+ const localHeaderOffset = cdBuf.readUInt32LE(ptr + 42);
679
+ const name = cdBuf.toString('utf8', ptr + 46, ptr + 46 + nameLen);
680
+
681
+ if (name.endsWith('.dex')) {
682
+ dexEntries.push({ name, method, compSize, uncompSize, localHeaderOffset });
683
+ }
684
+ ptr += 46 + nameLen + extraLen + commentLen;
685
+ }
686
+
687
+ for (const dexEntry of dexEntries.slice(0, 5)) {
688
+ try {
689
+ const localHdr = Buffer.alloc(30);
690
+ await fd.read(localHdr, 0, 30, dexEntry.localHeaderOffset);
691
+ const fnLen = localHdr.readUInt16LE(26);
692
+ const extraLen = localHdr.readUInt16LE(28);
693
+ const dataOffset = dexEntry.localHeaderOffset + 30 + fnLen + extraLen;
694
+ const compData = Buffer.alloc(dexEntry.compSize);
695
+ await fd.read(compData, 0, dexEntry.compSize, dataOffset);
696
+ const dexBuf = dexEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
697
+
698
+ if (dexBuf.length >= 112 && dexBuf.toString('utf8', 0, 4) === 'dex\n') {
699
+ const stringIdsOff = dexBuf.readUInt32LE(60);
700
+ const typeIdsOff = dexBuf.readUInt32LE(68);
701
+ const classDefsSize = dexBuf.readUInt32LE(96);
702
+ const classDefsOff = dexBuf.readUInt32LE(100);
703
+
704
+ totalInspected += classDefsSize;
705
+ for (let i = 0; i < classDefsSize; i++) {
706
+ const classDefOffset = classDefsOff + i * 32;
707
+ if (classDefOffset + 4 > dexBuf.length) break;
708
+ const classIdx = dexBuf.readUInt32LE(classDefOffset);
709
+ const typeOff = typeIdsOff + classIdx * 4;
710
+ if (typeOff + 4 > dexBuf.length) continue;
711
+ const descriptorIdx = dexBuf.readUInt32LE(typeOff);
712
+ const strOffPos = stringIdsOff + descriptorIdx * 4;
713
+ if (strOffPos + 4 > dexBuf.length) continue;
714
+ const stringDataOff = dexBuf.readUInt32LE(strOffPos);
715
+ let off = stringDataOff;
716
+ while (off < dexBuf.length) {
717
+ const b = dexBuf[off];
718
+ if (b === undefined || (b & 0x80) === 0) break;
719
+ off++;
720
+ }
721
+ off++;
722
+ let end = off;
723
+ while (end < dexBuf.length && dexBuf[end] !== 0) end++;
724
+ const rawDesc = dexBuf.toString('utf8', off, end);
725
+ if (!qLower || rawDesc.toLowerCase().includes(qLower)) {
726
+ const cleanName = rawDesc.replace(/^L/, '').replace(/;$/, '').replace(/\//g, '.');
727
+ matches.add(cleanName);
728
+ if (matches.size >= 100) break;
729
+ }
730
+ }
731
+ }
732
+ } catch {
733
+ // continue
734
+ }
735
+ if (matches.size >= 100) break;
736
+ }
737
+ } finally {
738
+ if (fd) await fd.close();
739
+ }
740
+
741
+ return {
742
+ matchedClasses: Array.from(matches),
743
+ totalInspected
744
+ };
745
+ }
746
+
312
747
  // ─────────────────────────────────────────────────────────────────────────────
313
748
  // CANONICAL TOOL DEFINITION
314
749
  // ─────────────────────────────────────────────────────────────────────────────
@@ -507,8 +942,19 @@ export const reverseEngineering = {
507
942
 
508
943
  // ── ACTION: DECODE_RESOURCES ──────────────────────────────────────────
509
944
  if (action === 'decode_resources') {
510
- const res = await sovereignReverseHarness.decodeAndroidResources(resolvedFile, outputDir, context.signal);
511
- const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
945
+ let res = await sovereignReverseHarness.decodeAndroidResources(resolvedFile, outputDir, context.signal);
946
+ let textOutput = '';
947
+ if (res.success && res.output && !res.output.includes('apktool launcher was not found')) {
948
+ textOutput = res.output;
949
+ } else {
950
+ const targetDir = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_resources`);
951
+ await fsp.mkdir(targetDir, { recursive: true });
952
+ const apkInfo = await inspectApkZipAndManifest(resolvedFile);
953
+ const manifestSummaryPath = path.join(targetDir, 'manifest_summary.json');
954
+ await fsp.writeFile(manifestSummaryPath, JSON.stringify(apkInfo.metadata || {}, null, 2), 'utf8');
955
+ textOutput = `Extracted Android package architecture to ${targetDir}:\n- Manifest summary: ${manifestSummaryPath}\n- Package: ${(apkInfo.metadata as any)?.packageName || 'unknown'}\n- Activities: ${(apkInfo.metadata as any)?.activitiesCount || 0}\n- Services: ${(apkInfo.metadata as any)?.servicesCount || 0}\n- Permissions: ${(apkInfo.metadata as any)?.permissionsCount || 0}`;
956
+ res = { success: true, toolName: 'decode_resources', output: textOutput, source: 'fallback' };
957
+ }
512
958
  const stored = outputStore.processToolOutput(sessionId, `${callId}_decode_resources`, textOutput);
513
959
  return {
514
960
  success: res.success,
@@ -524,8 +970,20 @@ export const reverseEngineering = {
524
970
  // ── ACTION: SEARCH_CLASSES ───────────────────────────────────────────
525
971
  if (action === 'search_classes') {
526
972
  const query = String(args['query'] || '');
527
- const res = await sovereignReverseHarness.searchAndroidClasses(resolvedFile, query, context.signal);
528
- const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
973
+ let res = await sovereignReverseHarness.searchAndroidClasses(resolvedFile, query, context.signal);
974
+ let textOutput = '';
975
+ if (res.success && res.output && !res.output.includes('capability_unavailable') && !res.output.includes('REA_JADX_MCP_JAR')) {
976
+ textOutput = res.output;
977
+ } else {
978
+ const nativeSearch = await searchClassesInApk(resolvedFile, query);
979
+ textOutput = JSON.stringify({
980
+ query,
981
+ totalInspectedDexClasses: nativeSearch.totalInspected,
982
+ matchedClassesCount: nativeSearch.matchedClasses.length,
983
+ matchedClasses: nativeSearch.matchedClasses
984
+ }, null, 2);
985
+ res = { success: true, toolName: 'search_classes', output: textOutput, source: 'fallback' };
986
+ }
529
987
  const stored = outputStore.processToolOutput(sessionId, `${callId}_search_classes`, textOutput);
530
988
  return {
531
989
  success: res.success,
@@ -581,6 +1039,11 @@ export const reverseEngineering = {
581
1039
 
582
1040
  const magic32Be = headerBuf.length >= 4 ? headerBuf.readUInt32BE(0) : 0;
583
1041
  const magic32Le = headerBuf.length >= 4 ? headerBuf.readUInt32LE(0) : 0;
1042
+ const isDex = (headerBuf.length >= 4 && headerBuf[0] === 0x64 && headerBuf[1] === 0x65 && headerBuf[2] === 0x78 && headerBuf[3] === 0x0a)
1043
+ || resolvedFile.toLowerCase().endsWith('.dex');
1044
+ const isApkOrZip = (headerBuf.length >= 4 && headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04)
1045
+ || resolvedFile.toLowerCase().endsWith('.apk')
1046
+ || resolvedFile.toLowerCase().endsWith('.aab');
584
1047
 
585
1048
  if (
586
1049
  magic32Be === 0xfeedface || magic32Be === 0xfeedfacf ||
@@ -595,27 +1058,11 @@ export const reverseEngineering = {
595
1058
  } else if (headerBuf[0] === 0x00 && headerBuf[1] === 0x61 && headerBuf[2] === 0x73 && headerBuf[3] === 0x6d) {
596
1059
  result.format = 'WebAssembly';
597
1060
  result.architecture = 'wasm32 / wasm64';
598
- } else if (
599
- (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) ||
600
- resolvedFile.toLowerCase().endsWith('.apk')
601
- ) {
602
- result.format = 'APK/ZIP';
603
- result.fileType = 'Android Application Package (APK)';
604
- try {
605
- const unzipList = await execFileAsync('unzip', ['-l', resolvedFile], { timeout: 15000 });
606
- const lines = unzipList.stdout.split('\n');
607
- const dexFiles = lines.filter(l => l.includes('.dex')).map(l => l.trim().split(/\s+/).pop());
608
- const hasManifest = lines.some(l => l.includes('AndroidManifest.xml'));
609
- const nativeLibs = lines.filter(l => l.includes('lib/')).slice(0, 15).map(l => l.trim().split(/\s+/).pop());
610
- result.metadata = {
611
- dexFiles,
612
- hasManifest,
613
- totalEntries: lines.length,
614
- sampleNativeLibraries: nativeLibs
615
- };
616
- } catch {
617
- // unzip fallback
618
- }
1061
+ } else if (isDex) {
1062
+ result = { ...result, ...parseDex(headerBuf) } as BinaryInspectionResult;
1063
+ } else if (isApkOrZip) {
1064
+ const apkResult = await inspectApkZipAndManifest(resolvedFile);
1065
+ result = { ...result, ...apkResult } as BinaryInspectionResult;
619
1066
  } else {
620
1067
  const asar = parseAsarHeader(headerBuf);
621
1068
  if (asar) {
@@ -648,6 +1095,7 @@ export const reverseEngineering = {
648
1095
  action: 'inspect',
649
1096
  format: result.format,
650
1097
  architecture: result.architecture || 'unknown',
1098
+ metadata: result.metadata,
651
1099
  mitigations: result.mitigations,
652
1100
  preview: stored.contentForModel,
653
1101
  isTruncated: stored.isTruncated,
@@ -0,0 +1,19 @@
1
+ export interface UIInterface {
2
+ colors: Record<string, string>;
3
+ box: Record<string, string>;
4
+ printHeader(title: string, subtitle?: string): void;
5
+ printCard(title: string, bodyLines: string | string[], highlight?: boolean): void;
6
+ printSuccess(msg: string): void;
7
+ printInfo(msg: string): void;
8
+ printWarning(msg: string): void;
9
+ printError(msg: string): void;
10
+ printFatalBox(title: string, lines: string[]): void;
11
+ createSpinner(text: string): {
12
+ start(): unknown;
13
+ stop(text?: string): void;
14
+ fail(text?: string): void;
15
+ };
16
+ }
17
+
18
+ export declare const UI: UIInterface;
19
+ export default UI;