@causyne/agent 1.20.15 → 1.20.17

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.
@@ -0,0 +1,791 @@
1
+ // Sovereign Reverse Engineering & Binary Inspection Capability.
2
+ //
3
+ // Native Causyne Agent reverse engineering suite backed by the headless sovereign
4
+ // engine substrate with zero-dependency static analysis fallbacks.
5
+ //
6
+ // Compliant with Causyne progressive disclosure (toolPacks.ts) and DTOC
7
+ // token-guarding offload (toolOutputStore.ts).
8
+
9
+ import fs from 'node:fs';
10
+ import fsp from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import { execFile } from 'node:child_process';
13
+ import util from 'node:util';
14
+ import { resolveUserPath } from '../utils/paths.js';
15
+ import { ToolOutputStore, defaultToolOutputStore } from './toolOutputStore.js';
16
+ import { isAutonomousToolContext } from '../approvalPolicy.js';
17
+ import { sovereignReverseHarness } from '../engines/reverseHarness.js';
18
+
19
+ const execFileAsync = util.promisify(execFile);
20
+
21
+ // ─────────────────────────────────────────────────────────────────────────────
22
+ // TYPES & INTERFACES
23
+ // ─────────────────────────────────────────────────────────────────────────────
24
+
25
+ export type ReverseEngineeringAction =
26
+ | 'inspect'
27
+ | 'decompile'
28
+ | 'unpack'
29
+ | 'deobfuscate'
30
+ | 'trace'
31
+ | 'status'
32
+ | 'engine_tool'
33
+ | 'list_tools';
34
+
35
+ export interface BinaryMitigations {
36
+ pie?: boolean | undefined;
37
+ nx?: boolean | undefined;
38
+ canary?: boolean | undefined;
39
+ relro?: 'none' | 'partial' | 'full' | undefined;
40
+ aslr?: boolean | undefined;
41
+ codeSigned?: boolean | undefined;
42
+ }
43
+
44
+ export interface BinaryInspectionResult {
45
+ filePath: string;
46
+ format: 'Mach-O' | 'ELF' | 'PE/COFF' | 'ASAR' | 'APK/ZIP' | 'WebAssembly' | 'DEX' | 'Unknown';
47
+ architecture?: string | undefined;
48
+ byteOrder?: 'little-endian' | 'big-endian' | undefined;
49
+ is64Bit?: boolean | undefined;
50
+ fileType?: string | undefined;
51
+ entryPoint?: string | undefined;
52
+ sections?: string[] | undefined;
53
+ importedLibraries?: string[] | undefined;
54
+ exportedSymbols?: string[] | undefined;
55
+ mitigations?: BinaryMitigations | undefined;
56
+ metadata?: Record<string, unknown> | undefined;
57
+ }
58
+
59
+ export interface ReverseEngineeringParams {
60
+ action: ReverseEngineeringAction;
61
+ filePath?: string | undefined;
62
+ target?: string | undefined;
63
+ outputDir?: string | undefined;
64
+ functionName?: string | undefined;
65
+ address?: string | undefined;
66
+ engine?: 'auto' | 'ghidra' | 'rizin' | 'hopper' | 'native' | undefined;
67
+ detail?: 'summary' | 'symbols' | 'headers' | 'mitigations' | 'full' | undefined;
68
+ listOnly?: boolean | undefined;
69
+ script?: string | undefined;
70
+ toolName?: string | undefined;
71
+ toolArgs?: Record<string, unknown> | undefined;
72
+ }
73
+
74
+ // ─────────────────────────────────────────────────────────────────────────────
75
+ // NATIVE BINARY PARSERS (Pure Node.js Zero-Dependency Fallback)
76
+ // ─────────────────────────────────────────────────────────────────────────────
77
+
78
+ function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
79
+ const magic = buffer.readUInt32BE(0);
80
+ const is64 = magic === 0xfeedfacf || magic === 0xcffaedfe;
81
+ const isLe = magic === 0xfeedfacf || magic === 0xfeedface;
82
+ const isFat = magic === 0xcafebabe || magic === 0xbebafeca;
83
+
84
+ if (isFat) {
85
+ let architecture = 'Universal FAT (Mach-O)';
86
+ const nfat_arch = buffer.readUInt32BE(4);
87
+ if (buffer.length >= 8 + nfat_arch * 20) {
88
+ for (let i = 0; i < nfat_arch; i++) {
89
+ const offset = 8 + i * 20;
90
+ const cputype = buffer.readInt32BE(offset);
91
+ const sliceOffset = buffer.readUInt32BE(offset + 8);
92
+ const sliceSize = buffer.readUInt32BE(offset + 12);
93
+ if (sliceOffset + 8 <= buffer.length) {
94
+ const sliceBuf = buffer.subarray(sliceOffset, Math.min(sliceOffset + sliceSize, buffer.length));
95
+ if (sliceBuf.length >= 8) {
96
+ const inner = parseMachO(sliceBuf);
97
+ return {
98
+ format: 'Mach-O',
99
+ architecture: `Universal FAT (slice: ${inner.architecture || 'unknown'}, cputype: ${cputype})`,
100
+ is64Bit: inner.is64Bit ?? true,
101
+ byteOrder: inner.byteOrder ?? 'little-endian',
102
+ fileType: inner.fileType ?? 'Mach-O Universal Binary',
103
+ mitigations: inner.mitigations ?? { pie: true, nx: true, aslr: true, codeSigned: true }
104
+ };
105
+ }
106
+ }
107
+ }
108
+ }
109
+ return {
110
+ format: 'Mach-O',
111
+ architecture,
112
+ is64Bit: true,
113
+ byteOrder: 'big-endian',
114
+ fileType: 'Mach-O Universal Binary',
115
+ mitigations: { pie: true, nx: true, aslr: true, codeSigned: true }
116
+ };
117
+ }
118
+
119
+ const cputype = isLe ? buffer.readInt32LE(4) : buffer.readInt32BE(4);
120
+ let architecture = 'unknown';
121
+ if (cputype === 0x01000007) architecture = 'x86_64';
122
+ else if (cputype === 0x0100000c) architecture = 'arm64';
123
+ else if (cputype === 7) architecture = 'i386';
124
+ else if (cputype === 12) architecture = 'arm';
125
+
126
+ const filetypeInt = isLe ? buffer.readUInt32LE(12) : buffer.readUInt32BE(12);
127
+ let fileType = 'Mach-O Binary';
128
+ if (filetypeInt === 2) fileType = 'Executable (MH_EXECUTE)';
129
+ else if (filetypeInt === 6) fileType = 'Shared Library (MH_DYLIB)';
130
+ else if (filetypeInt === 8) fileType = 'Bundle (MH_BUNDLE)';
131
+
132
+ const flags = isLe ? buffer.readUInt32LE(24) : buffer.readUInt32BE(24);
133
+ const pie = (flags & 0x200000) !== 0; // MH_PIE
134
+
135
+ return {
136
+ format: 'Mach-O',
137
+ architecture,
138
+ is64Bit: is64,
139
+ byteOrder: isLe ? 'little-endian' : 'big-endian',
140
+ fileType,
141
+ mitigations: {
142
+ pie,
143
+ nx: true,
144
+ aslr: pie,
145
+ codeSigned: true
146
+ }
147
+ };
148
+ }
149
+
150
+ function parseElf(buffer: Buffer): Partial<BinaryInspectionResult> {
151
+ const is64 = buffer[4] === 2;
152
+ const isLe = buffer[5] === 1;
153
+
154
+ const readU16 = (off: number) => isLe ? buffer.readUInt16LE(off) : buffer.readUInt16BE(off);
155
+ const readU32 = (off: number) => isLe ? buffer.readUInt32LE(off) : buffer.readUInt32BE(off);
156
+
157
+ const eType = readU16(16);
158
+ let fileType = 'ELF Binary';
159
+ let pie = false;
160
+ if (eType === 2) {
161
+ fileType = 'Executable (ET_EXEC)';
162
+ pie = false;
163
+ } else if (eType === 3) {
164
+ fileType = 'Shared Object / Dynamic Library (ET_DYN)';
165
+ pie = true;
166
+ }
167
+
168
+ const eMachine = readU16(18);
169
+ let architecture = 'unknown';
170
+ if (eMachine === 0x3e) architecture = 'x86_64';
171
+ else if (eMachine === 0xb7) architecture = 'aarch64 (ARM64)';
172
+ else if (eMachine === 0x03) architecture = 'i386';
173
+ else if (eMachine === 0x28) architecture = 'ARM (32-bit)';
174
+ else if (eMachine === 0xf3) architecture = 'RISC-V';
175
+
176
+ return {
177
+ format: 'ELF',
178
+ architecture,
179
+ is64Bit: is64,
180
+ byteOrder: isLe ? 'little-endian' : 'big-endian',
181
+ fileType,
182
+ mitigations: {
183
+ pie,
184
+ nx: true,
185
+ relro: pie ? 'full' : 'partial'
186
+ }
187
+ };
188
+ }
189
+
190
+ function parsePE(buffer: Buffer): Partial<BinaryInspectionResult> {
191
+ if (buffer.length < 64) return { format: 'PE/COFF' };
192
+ const peOffset = buffer.readUInt32LE(0x3c);
193
+ if (peOffset + 24 > buffer.length) return { format: 'PE/COFF' };
194
+
195
+ const peSig = buffer.toString('utf8', peOffset, peOffset + 4);
196
+ if (peSig !== 'PE\0\0') return { format: 'PE/COFF' };
197
+
198
+ const machine = buffer.readUInt16LE(peOffset + 4);
199
+ let architecture = 'unknown';
200
+ if (machine === 0x8664) architecture = 'x86_64 (AMD64)';
201
+ else if (machine === 0xaa64) architecture = 'ARM64';
202
+ else if (machine === 0x14c) architecture = 'i386 (x86)';
203
+
204
+ const optHeaderOffset = peOffset + 24;
205
+ let is64 = false;
206
+ let pie = false;
207
+ let nx = false;
208
+
209
+ if (optHeaderOffset + 72 <= buffer.length) {
210
+ const magic = buffer.readUInt16LE(optHeaderOffset);
211
+ is64 = magic === 0x20b; // PE32+
212
+
213
+ const dllCharOffset = optHeaderOffset + 70;
214
+ if (dllCharOffset + 2 <= buffer.length) {
215
+ const dllCharacteristics = buffer.readUInt16LE(dllCharOffset);
216
+ pie = (dllCharacteristics & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
217
+ nx = (dllCharacteristics & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
218
+ }
219
+ }
220
+
221
+ return {
222
+ format: 'PE/COFF',
223
+ architecture,
224
+ is64Bit: is64,
225
+ byteOrder: 'little-endian',
226
+ fileType: 'Windows Portable Executable',
227
+ mitigations: {
228
+ pie,
229
+ nx,
230
+ aslr: pie
231
+ }
232
+ };
233
+ }
234
+
235
+ // ─────────────────────────────────────────────────────────────────────────────
236
+ // ASAR BUNDLE PARSER (Electron Container Zero-Dependency Unpack)
237
+ // ─────────────────────────────────────────────────────────────────────────────
238
+
239
+ interface AsarFileEntry {
240
+ size: number;
241
+ offset: number;
242
+ executable?: boolean;
243
+ }
244
+
245
+ interface AsarDirectory {
246
+ files: Record<string, AsarDirectory | AsarFileEntry>;
247
+ }
248
+
249
+ function parseAsarHeader(buffer: Buffer): { headerSize: number; header: AsarDirectory } | null {
250
+ if (buffer.length < 16) return null;
251
+ const magic = buffer.readUInt32LE(0);
252
+ if (magic !== 4) return null;
253
+
254
+ const headerSize = buffer.readUInt32LE(12);
255
+ if (16 + headerSize > buffer.length) return null;
256
+
257
+ try {
258
+ const headerJson = buffer.toString('utf8', 16, 16 + headerSize);
259
+ const header = JSON.parse(headerJson) as AsarDirectory;
260
+ return { headerSize: 16 + headerSize, header };
261
+ } catch {
262
+ return null;
263
+ }
264
+ }
265
+
266
+ function listAsarFiles(dir: AsarDirectory, prefix = ''): { path: string; size: number }[] {
267
+ const list: { path: string; size: number }[] = [];
268
+ if (!dir || !dir.files) return list;
269
+
270
+ for (const [name, entry] of Object.entries(dir.files)) {
271
+ const fullPath = prefix ? `${prefix}/${name}` : name;
272
+ if ('files' in entry && entry.files) {
273
+ list.push(...listAsarFiles(entry, fullPath));
274
+ } else if ('size' in entry && typeof entry.size === 'number') {
275
+ list.push({ path: fullPath, size: entry.size });
276
+ }
277
+ }
278
+ return list;
279
+ }
280
+
281
+ // ─────────────────────────────────────────────────────────────────────────────
282
+ // JAVASCRIPT / BUNDLE SCRIPT DEOBFUSCATOR
283
+ // ─────────────────────────────────────────────────────────────────────────────
284
+
285
+ async function deobfuscateScript(filePath: string): Promise<{
286
+ sourcemapDetected: boolean;
287
+ extractedRoutes: string[];
288
+ summary: string;
289
+ }> {
290
+ const code = await fsp.readFile(filePath, 'utf8');
291
+ const sourcemapDetected = /\/\/# sourceMappingURL=/i.test(code) || /\/\*# sourceMappingURL=/i.test(code);
292
+
293
+ const urlMatches = code.match(/https?:\/\/[a-zA-Z0-9./?=_%&:-]+/g) || [];
294
+ const routeMatches = code.match(/['"`]\/(?:api|v[0-9]|auth|users|admin|graphql)[a-zA-Z0-9/_-]*['"`]/g) || [];
295
+ const cleanedRoutes = routeMatches.map(r => r.slice(1, -1));
296
+ const uniqueEndpoints = Array.from(new Set([...urlMatches, ...cleanedRoutes]));
297
+
298
+ const lines = code.split('\n').length;
299
+ const summary = `Script Analysis: ${lines} lines, ${code.length} characters. Sourcemap: ${sourcemapDetected ? 'Present' : 'None'}. Harvested ${uniqueEndpoints.length} endpoints.`;
300
+
301
+ return {
302
+ sourcemapDetected,
303
+ extractedRoutes: uniqueEndpoints.slice(0, 50),
304
+ summary
305
+ };
306
+ }
307
+
308
+ // ─────────────────────────────────────────────────────────────────────────────
309
+ // CANONICAL TOOL DEFINITION
310
+ // ─────────────────────────────────────────────────────────────────────────────
311
+
312
+ export const reverseEngineering = {
313
+ schema: {
314
+ name: 'reverse_engineering',
315
+ description: 'Sovereign reverse engineering, binary triage, decompilation, bundle unpacking, and runtime tracing suite backed by headless MCP engine substrate.',
316
+ parameters: {
317
+ type: 'object',
318
+ properties: {
319
+ action: {
320
+ type: 'string',
321
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools'],
322
+ description: 'Reverse engineering action to perform.'
323
+ },
324
+ filePath: {
325
+ type: 'string',
326
+ description: 'Absolute or workspace-relative path to target binary, bundle, or script.'
327
+ },
328
+ target: {
329
+ type: 'string',
330
+ description: 'Process name, function symbol, or bundle resource identifier.'
331
+ },
332
+ outputDir: {
333
+ type: 'string',
334
+ description: 'Target extraction directory for bundle unpacking.'
335
+ },
336
+ functionName: {
337
+ type: 'string',
338
+ description: 'Specific function symbol to decompile or disassemble.'
339
+ },
340
+ address: {
341
+ type: 'string',
342
+ description: 'Hexadecimal memory address (e.g. "0x100003fa0") to inspect or decompile.'
343
+ },
344
+ engine: {
345
+ type: 'string',
346
+ enum: ['auto', 'ghidra', 'rizin', 'hopper', 'native'],
347
+ description: 'Decompiler engine preference (default: auto).'
348
+ },
349
+ detail: {
350
+ type: 'string',
351
+ enum: ['summary', 'symbols', 'headers', 'mitigations', 'full'],
352
+ description: 'Level of analytical detail.'
353
+ },
354
+ listOnly: {
355
+ type: 'boolean',
356
+ description: 'When unpacking, list container manifest contents without extracting files to disk.'
357
+ },
358
+ script: {
359
+ type: 'string',
360
+ description: 'Custom instrumentation or tracer hook script.'
361
+ },
362
+ toolName: {
363
+ type: 'string',
364
+ description: 'Specific engine tool name to execute when action is "engine_tool".'
365
+ },
366
+ toolArgs: {
367
+ type: 'object',
368
+ description: 'Arguments payload for engine_tool.'
369
+ }
370
+ },
371
+ required: ['action']
372
+ }
373
+ },
374
+
375
+ async execute(args: Record<string, unknown>, context: { workspaceDir?: string; sessionId?: string; signal?: AbortSignal } = {}): Promise<Record<string, unknown>> {
376
+ const action = String(args['action'] || 'status') as ReverseEngineeringAction;
377
+ const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
378
+ const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
379
+ const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
380
+ const address = typeof args['address'] === 'string' ? args['address'] : undefined;
381
+ const engine = typeof args['engine'] === 'string' ? args['engine'] as 'auto' | 'ghidra' | 'rizin' | 'hopper' | 'native' : 'auto';
382
+ const detail = typeof args['detail'] === 'string' ? args['detail'] as 'summary' | 'symbols' | 'headers' | 'mitigations' | 'full' : 'summary';
383
+ const listOnly = Boolean(args['listOnly']);
384
+ const workspaceDir = context.workspaceDir || process.cwd();
385
+ const sessionId = context.sessionId || 're_session';
386
+ const outputStore = defaultToolOutputStore;
387
+ const callId = `re_${Date.now()}`;
388
+
389
+ // ── ACTION: STATUS ────────────────────────────────────────────────────
390
+ if (action === 'status') {
391
+ const engines: Record<string, boolean> = {};
392
+ const checkCmd = async (cmd: string): Promise<boolean> => {
393
+ try {
394
+ await execFileAsync('which', [cmd]);
395
+ return true;
396
+ } catch {
397
+ return false;
398
+ }
399
+ };
400
+
401
+ engines['otool'] = await checkCmd('otool');
402
+ engines['objdump'] = await checkCmd('objdump');
403
+ engines['nm'] = await checkCmd('nm');
404
+ engines['file'] = await checkCmd('file');
405
+ engines['ghidra'] = await checkCmd('analyzeHeadless');
406
+ engines['rizin'] = await checkCmd('rizin');
407
+ engines['frida'] = await checkCmd('frida');
408
+
409
+ const engineAvailable = await sovereignReverseHarness.isAvailable();
410
+ const toolList = engineAvailable ? await sovereignReverseHarness.listTools() : [];
411
+
412
+ return {
413
+ success: true,
414
+ action: 'status',
415
+ platform: process.platform,
416
+ architecture: process.arch,
417
+ engineAvailable,
418
+ specializedEngineToolsCount: toolList.length,
419
+ installedEngines: engines,
420
+ capabilities: [
421
+ 'Mach-O Universal / FAT & 64-bit triage',
422
+ 'ELF executable & shared object parsing',
423
+ 'PE/COFF Windows binary mitigation checks',
424
+ 'Electron ASAR pickle header inspection & extraction',
425
+ 'JavaScript sourcemap recovery and route harvesting',
426
+ 'Dynamic runtime tracing and API observation',
427
+ 'Headless MCP engine with 229 specialized reverse engineering tools'
428
+ ]
429
+ };
430
+ }
431
+
432
+ // ── ACTION: LIST_TOOLS ────────────────────────────────────────────────
433
+ if (action === 'list_tools') {
434
+ const tools = await sovereignReverseHarness.listTools();
435
+ return {
436
+ success: true,
437
+ action: 'list_tools',
438
+ totalTools: tools.length,
439
+ tools
440
+ };
441
+ }
442
+
443
+ // ── ACTION: ENGINE_TOOL ───────────────────────────────────────────────
444
+ if (action === 'engine_tool') {
445
+ const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : '';
446
+ if (!toolName) {
447
+ return { success: false, error: 'toolName parameter is required for action "engine_tool".' };
448
+ }
449
+ const toolArgs = (args['toolArgs'] && typeof args['toolArgs'] === 'object')
450
+ ? (args['toolArgs'] as Record<string, unknown>)
451
+ : {};
452
+
453
+ const res = await sovereignReverseHarness.callEngineTool(toolName, toolArgs, context.signal);
454
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
455
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_${toolName}`, textOutput);
456
+
457
+ return {
458
+ success: res.success,
459
+ action: 'engine_tool',
460
+ toolName,
461
+ preview: stored.contentForModel,
462
+ isTruncated: stored.isTruncated,
463
+ diskPath: stored.diskPath,
464
+ error: res.error
465
+ };
466
+ }
467
+
468
+ // Require filePath for inspect, decompile, unpack, deobfuscate
469
+ if (!rawPath && action !== 'trace') {
470
+ return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
471
+ }
472
+
473
+ const resolvedFile = rawPath ? resolveUserPath(rawPath) : '';
474
+ if (resolvedFile && !fs.existsSync(resolvedFile)) {
475
+ return { success: false, error: `File not found: ${resolvedFile}` };
476
+ }
477
+
478
+ // ── ACTION: INSPECT ───────────────────────────────────────────────────
479
+ if (action === 'inspect') {
480
+ try {
481
+ let engineText = '';
482
+ try {
483
+ const engineRes = await sovereignReverseHarness.inspectBinary(resolvedFile, context.signal);
484
+ if (engineRes.success && engineRes.output) {
485
+ engineText = engineRes.output;
486
+ }
487
+ } catch {
488
+ // Fall back gracefully to native parsing
489
+ }
490
+
491
+ const stats = await fsp.stat(resolvedFile);
492
+ const fd = await fsp.open(resolvedFile, 'r');
493
+ const headerBuf = Buffer.alloc(Math.min(8192, stats.size));
494
+ await fd.read(headerBuf, 0, headerBuf.length, 0);
495
+ await fd.close();
496
+
497
+ let result: BinaryInspectionResult = {
498
+ filePath: resolvedFile,
499
+ format: 'Unknown'
500
+ };
501
+
502
+ const magic32Be = headerBuf.length >= 4 ? headerBuf.readUInt32BE(0) : 0;
503
+ const magic32Le = headerBuf.length >= 4 ? headerBuf.readUInt32LE(0) : 0;
504
+
505
+ if (
506
+ magic32Be === 0xfeedface || magic32Be === 0xfeedfacf ||
507
+ magic32Le === 0xfeedface || magic32Le === 0xfeedfacf ||
508
+ magic32Be === 0xcafebabe || magic32Be === 0xbebafeca
509
+ ) {
510
+ result = { ...result, ...parseMachO(headerBuf) } as BinaryInspectionResult;
511
+ } else if (headerBuf[0] === 0x7f && headerBuf[1] === 0x45 && headerBuf[2] === 0x4c && headerBuf[3] === 0x46) {
512
+ result = { ...result, ...parseElf(headerBuf) } as BinaryInspectionResult;
513
+ } else if (headerBuf[0] === 0x4d && headerBuf[1] === 0x5a) {
514
+ result = { ...result, ...parsePE(headerBuf) } as BinaryInspectionResult;
515
+ } else if (headerBuf[0] === 0x00 && headerBuf[1] === 0x61 && headerBuf[2] === 0x73 && headerBuf[3] === 0x6d) {
516
+ result.format = 'WebAssembly';
517
+ result.architecture = 'wasm32 / wasm64';
518
+ } else if (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) {
519
+ result.format = 'APK/ZIP';
520
+ result.fileType = 'Compressed Archive / Package';
521
+ } else {
522
+ const asar = parseAsarHeader(headerBuf);
523
+ if (asar) {
524
+ result.format = 'ASAR';
525
+ result.fileType = 'Electron Archive';
526
+ const files = listAsarFiles(asar.header);
527
+ result.metadata = { totalFiles: files.length, sampleFiles: files.slice(0, 10).map(f => f.path) };
528
+ }
529
+ }
530
+
531
+ if (engineText) {
532
+ result.metadata = { ...(result.metadata ?? {}), engineAnalysis: engineText };
533
+ }
534
+
535
+ if (detail === 'symbols' || detail === 'full') {
536
+ try {
537
+ const nmRes = await execFileAsync('nm', ['-gU', resolvedFile], { timeout: 10000, maxBuffer: 5 * 1024 * 1024 });
538
+ const symbols = nmRes.stdout.split('\n').filter(Boolean).slice(0, 100);
539
+ result.exportedSymbols = symbols;
540
+ } catch {
541
+ // nm not available or stripped binary
542
+ }
543
+ }
544
+
545
+ const rawJson = JSON.stringify(result, null, 2);
546
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_inspect`, rawJson);
547
+
548
+ return {
549
+ success: true,
550
+ action: 'inspect',
551
+ format: result.format,
552
+ architecture: result.architecture || 'unknown',
553
+ mitigations: result.mitigations,
554
+ preview: stored.contentForModel,
555
+ isTruncated: stored.isTruncated,
556
+ diskPath: stored.diskPath
557
+ };
558
+ } catch (err: unknown) {
559
+ return { success: false, error: `Inspection failed: ${err instanceof Error ? err.message : String(err)}` };
560
+ }
561
+ }
562
+
563
+ // ── ACTION: DECOMPILE ─────────────────────────────────────────────────
564
+ if (action === 'decompile') {
565
+ try {
566
+ let disassemblyText = '';
567
+
568
+ // 1. Try sovereign engine decompilation
569
+ try {
570
+ const engineRes = await sovereignReverseHarness.decompile(resolvedFile, functionName, address, context.signal);
571
+ if (engineRes.success && engineRes.output) {
572
+ disassemblyText = engineRes.output;
573
+ }
574
+ } catch {
575
+ // Fall back gracefully
576
+ }
577
+
578
+ // 2. Fallbacks if engine output is empty
579
+ if (!disassemblyText && engine === 'rizin') {
580
+ try {
581
+ const args = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
582
+ const rzRes = await execFileAsync('rizin', args, { timeout: 30000 });
583
+ disassemblyText = rzRes.stdout;
584
+ } catch (e: unknown) {
585
+ disassemblyText = `[Rizin failed: ${e instanceof Error ? e.message : String(e)}]`;
586
+ }
587
+ }
588
+
589
+ if (!disassemblyText && process.platform === 'darwin') {
590
+ try {
591
+ const otoolArgs = ['-tvV'];
592
+ if (functionName) otoolArgs.push('-p', functionName);
593
+ otoolArgs.push(resolvedFile);
594
+ const res = await execFileAsync('otool', otoolArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
595
+ disassemblyText = res.stdout;
596
+ } catch {
597
+ // fallback to objdump
598
+ }
599
+ }
600
+
601
+ if (!disassemblyText) {
602
+ try {
603
+ const objdumpArgs = ['--disassemble'];
604
+ if (functionName) objdumpArgs.push(`--disassemble=${functionName}`);
605
+ objdumpArgs.push(resolvedFile);
606
+ const res = await execFileAsync('objdump', objdumpArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
607
+ disassemblyText = res.stdout;
608
+ } catch {
609
+ disassemblyText = `Decompiler not available on system for ${path.basename(resolvedFile)}. Install Ghidra or Rizin for advanced decompilation.`;
610
+ }
611
+ }
612
+
613
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_decompile`, disassemblyText);
614
+
615
+ return {
616
+ success: true,
617
+ action: 'decompile',
618
+ target: functionName || address || 'entry',
619
+ preview: stored.contentForModel,
620
+ totalLines: stored.totalLines,
621
+ isTruncated: stored.isTruncated,
622
+ diskPath: stored.diskPath
623
+ };
624
+ } catch (err: unknown) {
625
+ return { success: false, error: `Decompilation error: ${err instanceof Error ? err.message : String(err)}` };
626
+ }
627
+ }
628
+
629
+ // ── ACTION: UNPACK ────────────────────────────────────────────────────
630
+ if (action === 'unpack') {
631
+ try {
632
+ const dest = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_unpacked`);
633
+
634
+ // Try sovereign engine bundle unpacker first
635
+ try {
636
+ const engineRes = await sovereignReverseHarness.unpackBundle(resolvedFile, dest, context.signal);
637
+ if (engineRes.success && engineRes.output) {
638
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_unpack`, engineRes.output);
639
+ return {
640
+ success: true,
641
+ action: 'unpack',
642
+ destination: dest,
643
+ preview: stored.contentForModel,
644
+ isTruncated: stored.isTruncated,
645
+ diskPath: stored.diskPath
646
+ };
647
+ }
648
+ } catch {
649
+ // Fall back gracefully
650
+ }
651
+
652
+ const fileBuf = await fsp.readFile(resolvedFile);
653
+ const asar = parseAsarHeader(fileBuf);
654
+
655
+ if (asar) {
656
+ const files = listAsarFiles(asar.header);
657
+ if (listOnly) {
658
+ return {
659
+ success: true,
660
+ action: 'unpack',
661
+ format: 'ASAR',
662
+ totalFiles: files.length,
663
+ files: files.slice(0, 100),
664
+ message: `Listed ${files.length} files in ASAR archive.`
665
+ };
666
+ }
667
+
668
+ await fsp.mkdir(dest, { recursive: true });
669
+ const baseOffset = asar.headerSize;
670
+ let extractedCount = 0;
671
+
672
+ const extractEntry = async (entry: AsarDirectory | AsarFileEntry, currPath: string) => {
673
+ if ('files' in entry && entry.files) {
674
+ await fsp.mkdir(currPath, { recursive: true });
675
+ for (const [name, child] of Object.entries(entry.files)) {
676
+ await extractEntry(child, path.join(currPath, name));
677
+ }
678
+ } else if ('size' in entry && typeof entry.offset !== 'undefined') {
679
+ const fileOffset = baseOffset + parseInt(String(entry.offset), 10);
680
+ const fileData = fileBuf.subarray(fileOffset, fileOffset + entry.size);
681
+ await fsp.writeFile(currPath, fileData);
682
+ extractedCount++;
683
+ }
684
+ };
685
+
686
+ await extractEntry(asar.header, dest);
687
+ return {
688
+ success: true,
689
+ action: 'unpack',
690
+ format: 'ASAR',
691
+ extractedFiles: extractedCount,
692
+ destination: dest,
693
+ message: `Successfully unpacked ${extractedCount} files from ASAR archive to ${dest}.`
694
+ };
695
+ }
696
+
697
+ try {
698
+ if (listOnly) {
699
+ const listRes = await execFileAsync('unzip', ['-l', resolvedFile]);
700
+ return { success: true, action: 'unpack', listOnly: true, contents: listRes.stdout.split('\n').slice(0, 50) };
701
+ }
702
+ await fsp.mkdir(dest, { recursive: true });
703
+ await execFileAsync('unzip', ['-q', '-o', resolvedFile, '-d', dest]);
704
+ return {
705
+ success: true,
706
+ action: 'unpack',
707
+ destination: dest,
708
+ message: `Successfully extracted package to ${dest}.`
709
+ };
710
+ } catch (unzipErr: unknown) {
711
+ return { success: false, error: `Unpack failed: ${unzipErr instanceof Error ? unzipErr.message : String(unzipErr)}` };
712
+ }
713
+ } catch (err: unknown) {
714
+ return { success: false, error: `Unpack error: ${err instanceof Error ? err.message : String(err)}` };
715
+ }
716
+ }
717
+
718
+ // ── ACTION: DEOBFUSCATE ───────────────────────────────────────────────
719
+ if (action === 'deobfuscate') {
720
+ try {
721
+ const res = await deobfuscateScript(resolvedFile);
722
+ let engineText = '';
723
+ try {
724
+ const engineRes = await sovereignReverseHarness.deobfuscateScript(resolvedFile, context.signal);
725
+ if (engineRes.success && engineRes.output) {
726
+ engineText = engineRes.output;
727
+ }
728
+ } catch {
729
+ // Fall back gracefully
730
+ }
731
+
732
+ return {
733
+ success: true,
734
+ action: 'deobfuscate',
735
+ filePath: resolvedFile,
736
+ sourcemapDetected: res.sourcemapDetected,
737
+ extractedRoutes: res.extractedRoutes,
738
+ summary: res.summary,
739
+ ...(engineText ? { engineAnalysis: engineText } : {})
740
+ };
741
+ } catch (err: unknown) {
742
+ return { success: false, error: `Deobfuscation error: ${err instanceof Error ? err.message : String(err)}` };
743
+ }
744
+ }
745
+
746
+ // ── ACTION: TRACE ─────────────────────────────────────────────────────
747
+ if (action === 'trace') {
748
+ const target = typeof args['target'] === 'string' ? args['target'] : path.basename(resolvedFile || 'process');
749
+ const script = typeof args['script'] === 'string' ? args['script'] : undefined;
750
+
751
+ try {
752
+ const engineRes = await sovereignReverseHarness.traceRuntime(target, script ? { script } : {}, context.signal);
753
+ if (engineRes.success && engineRes.output) {
754
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_trace`, engineRes.output);
755
+ return {
756
+ success: true,
757
+ action: 'trace',
758
+ target,
759
+ preview: stored.contentForModel,
760
+ isTruncated: stored.isTruncated,
761
+ diskPath: stored.diskPath
762
+ };
763
+ }
764
+ } catch {
765
+ // Fall back to hook template
766
+ }
767
+
768
+ const hookTemplate = `// Sovereign Runtime Hook for ${target}\n` +
769
+ `console.log("[*] Attaching hook to ${target}...");\n` +
770
+ `if (Process.platform === 'darwin') {\n` +
771
+ ` const resolver = new ApiResolver('module');\n` +
772
+ ` const matches = resolver.enumerateMatches('exports:*!*open*');\n` +
773
+ ` matches.slice(0, 5).forEach(m => {\n` +
774
+ ` Interceptor.attach(m.address, {\n` +
775
+ ` onEnter(args) { console.log("[+] Hook hit: " + m.name); }\n` +
776
+ ` });\n` +
777
+ ` });\n` +
778
+ `}\n`;
779
+
780
+ return {
781
+ success: true,
782
+ action: 'trace',
783
+ target,
784
+ hookScript: hookTemplate,
785
+ message: `Generated sovereign runtime hook template for ${target}.`
786
+ };
787
+ }
788
+
789
+ return { success: false, error: `Unknown action: "${action}".` };
790
+ }
791
+ };