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