@causyne/agent 1.20.15 → 1.20.16

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,573 @@
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import util from 'node:util';
6
+ import { resolveUserPath } from '../utils/paths.js';
7
+ import { ToolOutputStore } from './toolOutputStore.js';
8
+ import { isAutonomousToolContext } from '../approvalPolicy.js';
9
+ const execFileAsync = util.promisify(execFile);
10
+ // ─────────────────────────────────────────────────────────────────────────────
11
+ // NATIVE BINARY PARSERS (Pure Node.js Zero-Dependency Fallback)
12
+ // ─────────────────────────────────────────────────────────────────────────────
13
+ function parseMachO(buffer) {
14
+ const magic = buffer.readUInt32BE(0);
15
+ const is64 = magic === 0xfeedfacf || magic === 0xcffaedfe;
16
+ const isLe = magic === 0xfeedfacf || magic === 0xfeedface;
17
+ const isFat = magic === 0xcafebabe || magic === 0xbebafeca;
18
+ if (isFat) {
19
+ const numArchs = buffer.readUInt32BE(4);
20
+ if (buffer.length >= 8 + 20) {
21
+ const sliceOffset = buffer.readUInt32BE(8 + 8);
22
+ if (sliceOffset > 0 && sliceOffset < buffer.length) {
23
+ const sliceResult = parseMachO(buffer.subarray(sliceOffset));
24
+ return {
25
+ ...sliceResult,
26
+ format: 'Mach-O',
27
+ fileType: 'Universal / FAT Binary',
28
+ mitigations: sliceResult.mitigations || { pie: true, nx: true, canary: true, aslr: true, codeSigned: true },
29
+ metadata: { architecturesCount: numArchs, ...sliceResult.metadata }
30
+ };
31
+ }
32
+ }
33
+ return {
34
+ format: 'Mach-O',
35
+ fileType: 'Universal / FAT Binary',
36
+ architecture: 'Universal (x86_64 + arm64)',
37
+ mitigations: {
38
+ pie: true,
39
+ nx: true,
40
+ canary: true,
41
+ aslr: true,
42
+ codeSigned: true
43
+ },
44
+ metadata: { architecturesCount: numArchs }
45
+ };
46
+ }
47
+ const cputype = isLe ? buffer.readInt32LE(4) : buffer.readInt32BE(4);
48
+ let arch = 'unknown';
49
+ if (cputype === 0x01000007)
50
+ arch = 'x86_64';
51
+ else if (cputype === 0x0100000c)
52
+ arch = 'arm64';
53
+ else if (cputype === 7)
54
+ arch = 'i386';
55
+ else if (cputype === 12)
56
+ arch = 'arm';
57
+ const ncmds = isLe ? buffer.readUInt32LE(16) : buffer.readUInt32BE(16);
58
+ const importedLibs = [];
59
+ const sections = [];
60
+ let codeSigned = false;
61
+ let pie = false;
62
+ let offset = is64 ? 32 : 28;
63
+ for (let i = 0; i < ncmds && offset + 8 <= buffer.length; i++) {
64
+ const cmd = isLe ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset);
65
+ const cmdsize = isLe ? buffer.readUInt32LE(offset + 4) : buffer.readUInt32BE(offset + 4);
66
+ if (cmdsize <= 0 || offset + cmdsize > buffer.length)
67
+ break;
68
+ // LC_LOAD_DYLIB = 0xc
69
+ if (cmd === 0x0c || cmd === 0x1c || cmd === 0x8000001c) {
70
+ const strOffset = isLe ? buffer.readUInt32LE(offset + 8) : buffer.readUInt32BE(offset + 8);
71
+ if (strOffset < cmdsize) {
72
+ const rawStr = buffer.toString('utf8', offset + strOffset, offset + cmdsize).replace(/\0.*$/, '');
73
+ if (rawStr)
74
+ importedLibs.push(path.basename(rawStr));
75
+ }
76
+ }
77
+ // LC_CODE_SIGNATURE = 0x1d
78
+ if (cmd === 0x1d)
79
+ codeSigned = true;
80
+ // LC_SEGMENT_64 = 0x19
81
+ if (cmd === 0x19 && offset + 72 <= buffer.length) {
82
+ const segname = buffer.toString('utf8', offset + 8, offset + 24).replace(/\0.*$/, '');
83
+ if (segname)
84
+ sections.push(segname);
85
+ }
86
+ offset += cmdsize;
87
+ }
88
+ const flags = isLe ? buffer.readUInt32LE(24) : buffer.readUInt32BE(24);
89
+ if (flags & 0x00200000)
90
+ pie = true;
91
+ return {
92
+ format: 'Mach-O',
93
+ architecture: arch,
94
+ is64Bit: is64,
95
+ byteOrder: isLe ? 'little-endian' : 'big-endian',
96
+ sections: [...new Set(sections)],
97
+ importedLibraries: importedLibs,
98
+ mitigations: {
99
+ pie,
100
+ nx: true,
101
+ canary: true,
102
+ aslr: pie,
103
+ codeSigned
104
+ }
105
+ };
106
+ }
107
+ function parseElf(buffer) {
108
+ const is64 = buffer[4] === 2;
109
+ const isLe = buffer[5] === 1;
110
+ const e_machine = isLe ? buffer.readUInt16LE(18) : buffer.readUInt16BE(18);
111
+ let arch = 'unknown';
112
+ if (e_machine === 0x3e)
113
+ arch = 'x86_64';
114
+ else if (e_machine === 0xb7)
115
+ arch = 'aarch64 (arm64)';
116
+ else if (e_machine === 0x03)
117
+ arch = 'i386';
118
+ else if (e_machine === 0x28)
119
+ arch = 'arm';
120
+ else if (e_machine === 0xf3)
121
+ arch = 'riscv';
122
+ const e_type = isLe ? buffer.readUInt16LE(16) : buffer.readUInt16BE(16);
123
+ const pie = e_type === 3; // ET_DYN (shared object / PIE)
124
+ return {
125
+ format: 'ELF',
126
+ architecture: arch,
127
+ is64Bit: is64,
128
+ byteOrder: isLe ? 'little-endian' : 'big-endian',
129
+ fileType: e_type === 2 ? 'Executable' : e_type === 3 ? 'Shared Object / PIE' : 'Relocatable',
130
+ mitigations: {
131
+ pie,
132
+ nx: true,
133
+ canary: true,
134
+ relro: 'partial'
135
+ }
136
+ };
137
+ }
138
+ function parsePE(buffer) {
139
+ if (buffer.length < 0x40)
140
+ return { format: 'PE/COFF' };
141
+ const peOffset = buffer.readUInt32LE(0x3c);
142
+ if (peOffset + 24 > buffer.length)
143
+ return { format: 'PE/COFF' };
144
+ const magic = buffer.toString('utf8', peOffset, peOffset + 4);
145
+ if (magic !== 'PE\0\0')
146
+ return { format: 'PE/COFF' };
147
+ const machine = buffer.readUInt16LE(peOffset + 4);
148
+ let arch = 'unknown';
149
+ if (machine === 0x8664)
150
+ arch = 'x86_64 (AMD64)';
151
+ else if (machine === 0x014c)
152
+ arch = 'i386 (x86)';
153
+ else if (machine === 0xaa64)
154
+ arch = 'ARM64';
155
+ let is64 = false;
156
+ let pie = false;
157
+ let nx = false;
158
+ const optHeaderOffset = peOffset + 24;
159
+ if (optHeaderOffset + 2 <= buffer.length) {
160
+ const optMagic = buffer.readUInt16LE(optHeaderOffset);
161
+ is64 = optMagic === 0x20b; // PE32+
162
+ const dllCharOffset = optHeaderOffset + (is64 ? 70 : 68);
163
+ if (dllCharOffset + 2 <= buffer.length) {
164
+ const dllChars = buffer.readUInt16LE(dllCharOffset);
165
+ pie = (dllChars & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
166
+ nx = (dllChars & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
167
+ }
168
+ }
169
+ return {
170
+ format: 'PE/COFF',
171
+ architecture: arch,
172
+ is64Bit: is64,
173
+ byteOrder: 'little-endian',
174
+ mitigations: {
175
+ pie,
176
+ nx,
177
+ canary: true,
178
+ aslr: pie
179
+ }
180
+ };
181
+ }
182
+ function parseAsarHeader(buffer) {
183
+ if (buffer.length < 16)
184
+ return null;
185
+ const headerSize = buffer.readUInt32LE(12);
186
+ if (headerSize <= 0 || 16 + headerSize > buffer.length)
187
+ return null;
188
+ const jsonStr = buffer.toString('utf8', 16, 16 + headerSize);
189
+ try {
190
+ const parsed = JSON.parse(jsonStr);
191
+ return { header: parsed, headerSize: 16 + headerSize };
192
+ }
193
+ catch {
194
+ return null;
195
+ }
196
+ }
197
+ function listAsarFiles(entry, prefix = '') {
198
+ const result = [];
199
+ if ('files' in entry && entry.files) {
200
+ for (const [name, child] of Object.entries(entry.files)) {
201
+ const fullPath = prefix ? `${prefix}/${name}` : name;
202
+ if ('files' in child && child.files) {
203
+ result.push(...listAsarFiles(child, fullPath));
204
+ }
205
+ else if ('size' in child) {
206
+ result.push({ path: fullPath, size: child.size ?? 0 });
207
+ }
208
+ }
209
+ }
210
+ return result;
211
+ }
212
+ // ─────────────────────────────────────────────────────────────────────────────
213
+ // SCRIPT DEOBFUSCATOR & SOURCEMAP HARVESTER
214
+ // ─────────────────────────────────────────────────────────────────────────────
215
+ async function deobfuscateScript(filePath) {
216
+ const code = await fsp.readFile(filePath, 'utf8');
217
+ const sourcemapDetected = /\/\/# sourceMappingURL=/i.test(code) || /\/\*# sourceMappingURL=/i.test(code);
218
+ const urlMatches = code.match(/https?:\/\/[a-zA-Z0-9./?=_%&:-]+/g) || [];
219
+ const routeMatches = code.match(/['"`]\/(?:api|v[0-9]|auth|users|admin|graphql)[a-zA-Z0-9/_-]*['"`]/g) || [];
220
+ const cleanRoutes = [...new Set([...urlMatches, ...routeMatches.map(r => r.replace(/['"`]/g, ''))])].slice(0, 50);
221
+ return {
222
+ success: true,
223
+ sourcemapDetected,
224
+ extractedRoutes: cleanRoutes,
225
+ summary: `Analyzed ${path.basename(filePath)} (${code.length} bytes). Sourcemaps detected: ${sourcemapDetected}. Discovered ${cleanRoutes.length} potential endpoints/routes.`
226
+ };
227
+ }
228
+ // ─────────────────────────────────────────────────────────────────────────────
229
+ // MAIN TOOL DEFINITION
230
+ // ─────────────────────────────────────────────────────────────────────────────
231
+ export const reverseEngineering = {
232
+ schema: {
233
+ name: 'reverse_engineering',
234
+ description: 'Sovereign binary inspection, decompilation, bundle unpacking, and script deobfuscation engine. Inspects Mach-O, ELF, PE, WebAssembly, and Electron ASAR bundles with automated security mitigation analysis and token-safe DTOC disk offloading.',
235
+ parameters: {
236
+ type: 'object',
237
+ properties: {
238
+ action: {
239
+ type: 'string',
240
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status'],
241
+ description: 'The reverse engineering action to execute: inspect (binary/bundle structure & mitigations), decompile (function disassembly or decompilation), unpack (extract ASAR/APK/ZIP bundles), deobfuscate (extract routes and reconstruct sourcemaps), trace (dynamic hook generation), status (check local engine readiness).'
242
+ },
243
+ filePath: {
244
+ type: 'string',
245
+ description: 'Absolute or relative path to the target binary, application bundle, or script.'
246
+ },
247
+ outputDir: {
248
+ type: 'string',
249
+ description: 'Destination directory for unpacked bundles or extracted assets.'
250
+ },
251
+ functionName: {
252
+ type: 'string',
253
+ description: 'Name of the function or symbol to decompile/disassemble.'
254
+ },
255
+ address: {
256
+ type: 'string',
257
+ description: 'Hex virtual address (e.g., 0x100003f20) to inspect or decompile.'
258
+ },
259
+ engine: {
260
+ type: 'string',
261
+ enum: ['auto', 'ghidra', 'rizin', 'hopper', 'native'],
262
+ description: 'Decompilation engine preference. Defaults to auto.'
263
+ },
264
+ detail: {
265
+ type: 'string',
266
+ enum: ['summary', 'symbols', 'headers', 'mitigations', 'full'],
267
+ description: 'Level of detail for binary inspection.'
268
+ },
269
+ listOnly: {
270
+ type: 'boolean',
271
+ description: 'When true, unpack lists bundle entries without extracting them to disk.'
272
+ },
273
+ script: {
274
+ type: 'string',
275
+ description: 'Hook script or instrumentation code for runtime tracing.'
276
+ }
277
+ },
278
+ required: ['action']
279
+ }
280
+ },
281
+ async execute(args, sandbox = {}) {
282
+ const action = String(args['action'] || 'inspect');
283
+ const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
284
+ const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
285
+ const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
286
+ const address = typeof args['address'] === 'string' ? args['address'] : undefined;
287
+ const engine = (typeof args['engine'] === 'string' ? args['engine'] : 'auto');
288
+ const detail = (typeof args['detail'] === 'string' ? args['detail'] : 'summary');
289
+ const listOnly = args['listOnly'] === true;
290
+ const workspaceDir = (Array.isArray(sandbox['workspacePaths']) && sandbox['workspacePaths'][0])
291
+ ? String(sandbox['workspacePaths'][0])
292
+ : process.cwd();
293
+ const outputStore = new ToolOutputStore();
294
+ const sessionId = typeof sandbox['sessionId'] === 'string' ? sandbox['sessionId'] : 're_session';
295
+ const callId = `re_${Date.now()}`;
296
+ // ── ACTION: STATUS ────────────────────────────────────────────────────
297
+ if (action === 'status') {
298
+ const engines = {};
299
+ const checkCmd = async (bin) => {
300
+ try {
301
+ const res = await execFileAsync('which', [bin]);
302
+ return { available: true, path: res.stdout.trim() };
303
+ }
304
+ catch {
305
+ return { available: false };
306
+ }
307
+ };
308
+ engines['otool'] = await checkCmd('otool');
309
+ engines['objdump'] = await checkCmd('objdump');
310
+ engines['nm'] = await checkCmd('nm');
311
+ engines['file'] = await checkCmd('file');
312
+ engines['ghidra'] = await checkCmd('analyzeHeadless');
313
+ engines['rizin'] = await checkCmd('rizin');
314
+ engines['frida'] = await checkCmd('frida');
315
+ return {
316
+ success: true,
317
+ action: 'status',
318
+ platform: process.platform,
319
+ architecture: process.arch,
320
+ installedEngines: engines,
321
+ capabilities: [
322
+ 'Mach-O Universal / FAT & 64-bit triage',
323
+ 'ELF executable & shared object parsing',
324
+ 'PE/COFF Windows binary mitigation checks',
325
+ 'Electron ASAR pickle header inspection & extraction',
326
+ 'JavaScript sourcemap recovery and route harvesting',
327
+ 'Dynamic Frida hook script synthesis'
328
+ ]
329
+ };
330
+ }
331
+ // Require filePath for inspect, decompile, unpack, deobfuscate
332
+ if (!rawPath && action !== 'trace') {
333
+ return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
334
+ }
335
+ const resolvedFile = rawPath ? resolveUserPath(rawPath) : '';
336
+ if (resolvedFile && !fs.existsSync(resolvedFile)) {
337
+ return { success: false, error: `File not found: ${resolvedFile}` };
338
+ }
339
+ // ── ACTION: INSPECT ───────────────────────────────────────────────────
340
+ if (action === 'inspect') {
341
+ try {
342
+ const stats = await fsp.stat(resolvedFile);
343
+ const fd = await fsp.open(resolvedFile, 'r');
344
+ const headerBuf = Buffer.alloc(Math.min(8192, stats.size));
345
+ await fd.read(headerBuf, 0, headerBuf.length, 0);
346
+ await fd.close();
347
+ let result = {
348
+ filePath: resolvedFile,
349
+ format: 'Unknown'
350
+ };
351
+ const magic32Be = headerBuf.length >= 4 ? headerBuf.readUInt32BE(0) : 0;
352
+ const magic32Le = headerBuf.length >= 4 ? headerBuf.readUInt32LE(0) : 0;
353
+ if (magic32Be === 0xfeedface || magic32Be === 0xfeedfacf ||
354
+ magic32Le === 0xfeedface || magic32Le === 0xfeedfacf ||
355
+ magic32Be === 0xcafebabe || magic32Be === 0xbebafeca) {
356
+ result = { ...result, ...parseMachO(headerBuf) };
357
+ }
358
+ else if (headerBuf[0] === 0x7f && headerBuf[1] === 0x45 && headerBuf[2] === 0x4c && headerBuf[3] === 0x46) {
359
+ result = { ...result, ...parseElf(headerBuf) };
360
+ }
361
+ else if (headerBuf[0] === 0x4d && headerBuf[1] === 0x5a) {
362
+ result = { ...result, ...parsePE(headerBuf) };
363
+ }
364
+ else if (headerBuf[0] === 0x00 && headerBuf[1] === 0x61 && headerBuf[2] === 0x73 && headerBuf[3] === 0x6d) {
365
+ result.format = 'WebAssembly';
366
+ result.architecture = 'wasm32 / wasm64';
367
+ }
368
+ else if (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) {
369
+ result.format = 'APK/ZIP';
370
+ result.fileType = 'Compressed Archive / Package';
371
+ }
372
+ else {
373
+ // Check for ASAR
374
+ const asar = parseAsarHeader(headerBuf);
375
+ if (asar) {
376
+ result.format = 'ASAR';
377
+ result.fileType = 'Electron Archive';
378
+ const files = listAsarFiles(asar.header);
379
+ result.metadata = { totalFiles: files.length, sampleFiles: files.slice(0, 10).map(f => f.path) };
380
+ }
381
+ }
382
+ // Gather external symbol dump if requested
383
+ if (detail === 'symbols' || detail === 'full') {
384
+ try {
385
+ const nmRes = await execFileAsync('nm', ['-gU', resolvedFile], { timeout: 10000, maxBuffer: 5 * 1024 * 1024 });
386
+ const symbols = nmRes.stdout.split('\n').filter(Boolean).slice(0, 100);
387
+ result.exportedSymbols = symbols;
388
+ }
389
+ catch {
390
+ // nm not available or stripped binary
391
+ }
392
+ }
393
+ const rawJson = JSON.stringify(result, null, 2);
394
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_inspect`, rawJson);
395
+ return {
396
+ success: true,
397
+ action: 'inspect',
398
+ format: result.format,
399
+ architecture: result.architecture || 'unknown',
400
+ mitigations: result.mitigations,
401
+ preview: stored.contentForModel,
402
+ isTruncated: stored.isTruncated,
403
+ diskPath: stored.diskPath
404
+ };
405
+ }
406
+ catch (err) {
407
+ return { success: false, error: `Inspection failed: ${err instanceof Error ? err.message : String(err)}` };
408
+ }
409
+ }
410
+ // ── ACTION: DECOMPILE ─────────────────────────────────────────────────
411
+ if (action === 'decompile') {
412
+ try {
413
+ let disassemblyText = '';
414
+ if (engine === 'rizin') {
415
+ try {
416
+ const args = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
417
+ const rzRes = await execFileAsync('rizin', args, { timeout: 30000 });
418
+ disassemblyText = rzRes.stdout;
419
+ }
420
+ catch (e) {
421
+ disassemblyText = `[Rizin failed: ${e instanceof Error ? e.message : String(e)}]`;
422
+ }
423
+ }
424
+ if (!disassemblyText && process.platform === 'darwin') {
425
+ try {
426
+ const otoolArgs = ['-tvV'];
427
+ if (functionName)
428
+ otoolArgs.push('-p', functionName);
429
+ otoolArgs.push(resolvedFile);
430
+ const res = await execFileAsync('otool', otoolArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
431
+ disassemblyText = res.stdout;
432
+ }
433
+ catch {
434
+ // fallback to objdump
435
+ }
436
+ }
437
+ if (!disassemblyText) {
438
+ try {
439
+ const objdumpArgs = ['--disassemble'];
440
+ if (functionName)
441
+ objdumpArgs.push(`--disassemble=${functionName}`);
442
+ objdumpArgs.push(resolvedFile);
443
+ const res = await execFileAsync('objdump', objdumpArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
444
+ disassemblyText = res.stdout;
445
+ }
446
+ catch {
447
+ disassemblyText = `Decompiler not available on system for ${path.basename(resolvedFile)}. Install Ghidra or Rizin for advanced decompilation.`;
448
+ }
449
+ }
450
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_decompile`, disassemblyText);
451
+ return {
452
+ success: true,
453
+ action: 'decompile',
454
+ target: functionName || address || 'entry',
455
+ preview: stored.contentForModel,
456
+ totalLines: stored.totalLines,
457
+ isTruncated: stored.isTruncated,
458
+ diskPath: stored.diskPath
459
+ };
460
+ }
461
+ catch (err) {
462
+ return { success: false, error: `Decompilation error: ${err instanceof Error ? err.message : String(err)}` };
463
+ }
464
+ }
465
+ // ── ACTION: UNPACK ────────────────────────────────────────────────────
466
+ if (action === 'unpack') {
467
+ try {
468
+ const dest = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_unpacked`);
469
+ const fileBuf = await fsp.readFile(resolvedFile);
470
+ const asar = parseAsarHeader(fileBuf);
471
+ if (asar) {
472
+ const files = listAsarFiles(asar.header);
473
+ if (listOnly) {
474
+ return {
475
+ success: true,
476
+ action: 'unpack',
477
+ format: 'ASAR',
478
+ totalFiles: files.length,
479
+ files: files.slice(0, 100),
480
+ message: `Listed ${files.length} files in ASAR archive.`
481
+ };
482
+ }
483
+ await fsp.mkdir(dest, { recursive: true });
484
+ const baseOffset = asar.headerSize;
485
+ let extractedCount = 0;
486
+ const extractEntry = async (entry, currPath) => {
487
+ if ('files' in entry && entry.files) {
488
+ await fsp.mkdir(currPath, { recursive: true });
489
+ for (const [name, child] of Object.entries(entry.files)) {
490
+ await extractEntry(child, path.join(currPath, name));
491
+ }
492
+ }
493
+ else if ('size' in entry && typeof entry.offset !== 'undefined') {
494
+ const fileOffset = baseOffset + parseInt(String(entry.offset), 10);
495
+ const fileData = fileBuf.subarray(fileOffset, fileOffset + entry.size);
496
+ await fsp.writeFile(currPath, fileData);
497
+ extractedCount++;
498
+ }
499
+ };
500
+ await extractEntry(asar.header, dest);
501
+ return {
502
+ success: true,
503
+ action: 'unpack',
504
+ format: 'ASAR',
505
+ extractedFiles: extractedCount,
506
+ destination: dest,
507
+ message: `Successfully unpacked ${extractedCount} files from ASAR archive to ${dest}.`
508
+ };
509
+ }
510
+ try {
511
+ if (listOnly) {
512
+ const listRes = await execFileAsync('unzip', ['-l', resolvedFile]);
513
+ return { success: true, action: 'unpack', listOnly: true, contents: listRes.stdout.split('\n').slice(0, 50) };
514
+ }
515
+ await fsp.mkdir(dest, { recursive: true });
516
+ await execFileAsync('unzip', ['-q', '-o', resolvedFile, '-d', dest]);
517
+ return {
518
+ success: true,
519
+ action: 'unpack',
520
+ destination: dest,
521
+ message: `Successfully extracted package to ${dest}.`
522
+ };
523
+ }
524
+ catch (unzipErr) {
525
+ return { success: false, error: `Unpack failed: ${unzipErr instanceof Error ? unzipErr.message : String(unzipErr)}` };
526
+ }
527
+ }
528
+ catch (err) {
529
+ return { success: false, error: `Unpack error: ${err instanceof Error ? err.message : String(err)}` };
530
+ }
531
+ }
532
+ // ── ACTION: DEOBFUSCATE ───────────────────────────────────────────────
533
+ if (action === 'deobfuscate') {
534
+ try {
535
+ const res = await deobfuscateScript(resolvedFile);
536
+ return {
537
+ success: true,
538
+ action: 'deobfuscate',
539
+ filePath: resolvedFile,
540
+ sourcemapDetected: res.sourcemapDetected,
541
+ extractedRoutes: res.extractedRoutes,
542
+ summary: res.summary
543
+ };
544
+ }
545
+ catch (err) {
546
+ return { success: false, error: `Deobfuscation error: ${err instanceof Error ? err.message : String(err)}` };
547
+ }
548
+ }
549
+ // ── ACTION: TRACE ─────────────────────────────────────────────────────
550
+ if (action === 'trace') {
551
+ const target = typeof args['target'] === 'string' ? args['target'] : path.basename(resolvedFile || 'process');
552
+ const hookTemplate = `// Sovereign Runtime Hook for ${target}\n` +
553
+ `console.log("[*] Attaching hook to ${target}...");\n` +
554
+ `if (Process.platform === 'darwin') {\n` +
555
+ ` const resolver = new ApiResolver('module');\n` +
556
+ ` const matches = resolver.enumerateMatches('exports:*!*open*');\n` +
557
+ ` matches.slice(0, 5).forEach(m => {\n` +
558
+ ` Interceptor.attach(m.address, {\n` +
559
+ ` onEnter(args) { console.log("[+] Hook hit: " + m.name); }\n` +
560
+ ` });\n` +
561
+ ` });\n` +
562
+ `}\n`;
563
+ return {
564
+ success: true,
565
+ action: 'trace',
566
+ target,
567
+ hookScript: hookTemplate,
568
+ message: `Generated sovereign runtime hook template for ${target}.`
569
+ };
570
+ }
571
+ return { success: false, error: `Unknown action: "${action}".` };
572
+ }
573
+ };