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