-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyze_qauth.js
More file actions
510 lines (430 loc) Β· 19.2 KB
/
Copy pathanalyze_qauth.js
File metadata and controls
510 lines (430 loc) Β· 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// @ts-check
const traverse = require('@babel/traverse').default;
const parser = require('@babel/parser');
/**
* exposeRootFunctions: Add window assignments immediately after each root function declaration
*
* @param {string} sourceCode - Original source code
* @param {Object} stats - Analysis statistics containing root functions
* @returns {string} - Modified source code with window assignments inserted after function declarations
*/
function exposeRootFunctions(sourceCode, stats) {
if (!stats || !stats.rootFunctions) {
console.log('No root functions found to expose');
return sourceCode;
}
const ast = parser.parse(sourceCode, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
locations: true,
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
});
const rootFunctionNames = Object.keys(stats.rootFunctions);
console.log(`\nπ Exposing ${rootFunctionNames.length} root functions to window...`);
// Collect all insertion points with their positions
const insertions = [];
traverse(ast, {
FunctionDeclaration(path) {
const funcName = path.node.id ? path.node.id.name : null;
if (funcName && rootFunctionNames.includes(funcName)) {
const funcEnd = path.node.end;
const windowAssignment = `\nwindow.__${funcName} = ${funcName};`;
insertions.push({
position: funcEnd,
code: windowAssignment,
funcName: funcName,
});
console.log(
`β Found function declaration: ${funcName} at line ${path.node.loc?.start.line || 'unknown'}`
);
console.log(`π Will insert: window.__${funcName} = ${funcName}; after position ${funcEnd}`);
}
},
});
if (insertions.length === 0) {
console.log('No function declarations found to expose');
return sourceCode;
}
// Sort insertions by position in reverse order (so we insert from end to beginning)
// This prevents position shifts from affecting subsequent insertions
insertions.sort((a, b) => b.position - a.position);
let modifiedSource = sourceCode;
// Insert window assignments after each function declaration
insertions.forEach((insertion) => {
const beforeInsertion = modifiedSource.substring(0, insertion.position);
const afterInsertion = modifiedSource.substring(insertion.position);
modifiedSource = beforeInsertion + insertion.code + afterInsertion;
console.log(`β
Inserted window assignment for ${insertion.funcName}`);
});
console.log(
`\nπ Successfully added ${insertions.length} window assignments immediately after function declarations`
);
return modifiedSource;
}
/**
* analyzeAndExpose: Complete workflow - analyze code and generate exposed version
*
* @param {string} sourceCode - Original source code
* @returns {Object} - { originalResults, exposedSourceCode, stats }
*/
function analyzeAndExpose(sourceCode) {
console.log('π Starting analysis and exposure process...\n');
// Step 1: Analyze the original code
const analysisResult = analyzeSourceCode(sourceCode);
if (!analysisResult.results || analysisResult.results.length === 0) {
console.log('β No function calls found to analyze');
return {
originalResults: [],
exposedSourceCode: sourceCode,
stats: null,
};
}
// Step 2: Generate exposed version
const exposedSourceCode = exposeRootFunctions(sourceCode, analysisResult.stats);
// Step 3: Return comprehensive results
return {
originalResults: analysisResult.results,
exposedSourceCode: exposedSourceCode,
stats: analysisResult.stats,
};
}
/**
* findAssignmentInScope: Look for assignment expressions in the scope that assign to the given variable
*
* @param {string} varName - Variable name to search for
* @param {Scope} scope - The scope to search in
* @param {Set<string>} visited - Visited bindings to prevent infinite loops
* @param {boolean} debug - Enable detailed debugging output
* @returns {Object} - { found: boolean, rightName: string|null, assignmentPath: NodePath|null }
*/
function findAssignmentInScope(varName, scope, visited, debug = false) {
if (debug) console.log(` π Searching for assignments to "${varName}" in scope...`);
let foundAssignment = null;
// Search through ALL paths in the scope, not just references
scope.path.traverse({
AssignmentExpression(path) {
const left = path.node.left;
const right = path.node.right;
if (debug) {
console.log(
` π Found assignment: ${left.type} = ${right.type} at ${
path.node.loc ? `${path.node.loc.start.line}:${path.node.loc.start.column}` : 'unknown'
}`
);
}
// Check if left side matches our variable name
if (left.type === 'Identifier' && left.name === varName && right.type === 'Identifier') {
if (debug) console.log(` β Found matching assignment: ${varName} = ${right.name}`);
foundAssignment = {
found: true,
rightName: right.name,
assignmentPath: path,
};
// Stop traversal once found
path.stop();
}
},
});
if (debug && !foundAssignment) {
console.log(` β No assignments found for "${varName}" using traverse method`);
}
return foundAssignment || { found: false, rightName: null, assignmentPath: null };
}
/**
* resolveIdentifier: Enhanced version - Track identifier through scope chain to find root function definition
*
* @param {string} name - The identifier name to resolve
* @param {NodePath} startPath - The starting path for scope lookup
* @param {Set<string>} visited - Prevent circular references using unique binding identifiers
* @param {boolean} debug - Enable detailed debugging output
* @returns {Object} - { rootName: String|null, chain: Array<String>, finalDeclaration: NodePath|null }
*/
function resolveIdentifier(name, startPath, visited = new Set(), debug = false) {
const chain = [];
let currentName = name;
let currentPath = startPath;
if (debug) console.log(`\nπ DEBUG: Starting resolution for "${name}"`);
while (true) {
// Find binding in current scope
const binding = currentPath.scope.getBinding(currentName);
if (!binding) {
if (debug) console.log(` β No binding found for "${currentName}"`);
chain.push(`${currentName} (no binding found)`);
return { rootName: null, chain, finalDeclaration: null };
}
if (debug) {
console.log(` β Found binding for "${currentName}"`);
console.log(` Binding kind: ${binding.kind}`);
console.log(` Declaration type: ${binding.path.node.type}`);
console.log(
` Declaration location: ${
binding.path.node.loc
? `${binding.path.node.loc.start.line}:${binding.path.node.loc.start.column}`
: 'unknown'
}`
);
}
// Create unique identifier for this binding using path position + name + scope level
const bindingId = `${binding.path.node.start}-${binding.path.node.end}-${currentName}-${binding.scope.uid}`;
// Check for circular reference using unique binding identifier
if (visited.has(bindingId)) {
if (debug) console.log(` π Circular reference detected for "${currentName}"`);
chain.push(`${currentName} (circular reference detected)`);
return { rootName: null, chain, finalDeclaration: null };
}
visited.add(bindingId);
chain.push(currentName);
const declPath = binding.path;
// Case 1: Direct function declaration - function name() {}
if (declPath.isFunctionDeclaration()) {
const funcName = declPath.node.id ? declPath.node.id.name : '(anonymous function)';
if (debug) console.log(` π― Found function declaration: "${funcName}"`);
return { rootName: funcName, chain, finalDeclaration: declPath };
}
// Case 2: Variable declaration - var/let/const name = ...
if (declPath.isVariableDeclarator()) {
const init = declPath.node.init;
if (debug) {
console.log(` π Variable declarator for "${declPath.node.id.name}"`);
console.log(` Has initializer: ${!!init}`);
if (init) console.log(` Initializer type: ${init.type}`);
}
if (!init) {
if (debug) console.log(` π No initializer, searching for assignments...`);
// No initializer in declaration, look for assignments in the scope
const assignmentResult = findAssignmentInScope(currentName, binding.scope, visited, debug);
if (assignmentResult.found) {
if (debug) console.log(` β Found assignment: ${currentName} = ${assignmentResult.rightName}`);
chain.push(`(found assignment: ${currentName} = ${assignmentResult.rightName})`);
currentName = assignmentResult.rightName;
currentPath = assignmentResult.assignmentPath;
continue;
} else {
if (debug) console.log(` β No assignment found for "${currentName}"`);
chain.push('(no initializer and no assignment found)');
return { rootName: null, chain, finalDeclaration: null };
}
}
// 2a: var name = identifier (alias)
if (init.type === 'Identifier') {
if (debug) console.log(` β‘οΈ Following alias: ${currentName} -> ${init.name}`);
currentName = init.name;
// Important: Update scope lookup starting point
currentPath = declPath.parentPath;
continue;
}
// 2b: var name = function() {} (function expression)
if (init.type === 'FunctionExpression' || init.type === 'ArrowFunctionExpression') {
const varName = declPath.node.id ? declPath.node.id.name : currentName;
if (debug) console.log(` π― Found function expression assigned to: "${varName}"`);
return { rootName: varName, chain, finalDeclaration: declPath };
}
// 2c: var name = someComplexExpression
if (debug) console.log(` β οΈ Complex expression assignment: ${init.type}`);
chain.push('(complex expression assignment)');
return { rootName: null, chain, finalDeclaration: declPath };
}
// Case 3: Assignment expression - name = ...
if (declPath.isAssignmentExpression()) {
const right = declPath.node.right;
if (debug) {
console.log(` π Assignment expression`);
console.log(` Right side type: ${right.type}`);
}
if (right.type === 'Identifier') {
if (debug) console.log(` β‘οΈ Following assignment: ${currentName} -> ${right.name}`);
currentName = right.name;
currentPath = declPath.parentPath;
continue;
}
if (right.type === 'FunctionExpression' || right.type === 'ArrowFunctionExpression') {
// For assignments, use left-hand side name as function name
const leftName = declPath.node.left.type === 'Identifier' ? declPath.node.left.name : currentName;
if (debug) console.log(` π― Found function expression in assignment: "${leftName}"`);
return { rootName: leftName, chain, finalDeclaration: declPath };
}
}
// Case 4: Function parameter
if (declPath.isParameter()) {
if (debug) console.log(` π Function parameter: ${currentName}`);
chain.push('(function parameter)');
return { rootName: null, chain, finalDeclaration: declPath };
}
// Case 5: Import declaration
if (declPath.isImportSpecifier() || declPath.isImportDefaultSpecifier()) {
if (debug) console.log(` π¦ Import declaration: ${currentName}`);
chain.push('(import declaration)');
return { rootName: null, chain, finalDeclaration: declPath };
}
// Other cases
if (debug) console.log(` β Unhandled declaration type: ${declPath.node.type}`);
chain.push(`(unhandled declaration type: ${declPath.node.type})`);
return { rootName: null, chain, finalDeclaration: declPath };
}
}
/**
* findAndResolveCalls: Find all matching call expressions and resolve them
*/
function findAndResolveCalls(ast) {
const results = [];
traverse(ast, {
CallExpression(path) {
const node = path.node;
// Must have exactly two arguments
if (node.arguments.length !== 2) return;
const [arg0, arg1] = node.arguments;
// First argument must be number, second must be string
if (arg0.type !== 'NumericLiteral' || arg1.type !== 'StringLiteral') {
return;
}
// Callee must be identifier
if (node.callee.type !== 'Identifier') return;
const calleeName = node.callee.name;
const numValue = arg0.value;
const strValue = arg1.value;
// Get location info
const loc = node.loc ? `${node.loc.start.line}:${node.loc.start.column}` : 'unknown location';
// Resolve identifier to root function (enable debug for unresolved calls)
const shouldDebug = !results.some((r) => r.calleeName === calleeName && r.resolved);
const resolution = resolveIdentifier(calleeName, path, new Set(), shouldDebug);
const result = {
location: loc,
calleeName,
rootName: resolution.rootName,
chain: resolution.chain,
arguments: { number: numValue, string: strValue },
resolved: !!resolution.rootName,
};
results.push(result);
// Print result
console.log(`\n=== Call Analysis ===`);
console.log(`Location: [${loc}]`);
console.log(`Call: ${calleeName}(${numValue}, "${strValue}")`);
console.log(`Alias chain: ${resolution.chain.join(' β ')}`);
if (resolution.rootName) {
console.log(`β Resolution SUCCESS: Root function is "${resolution.rootName}"`);
} else {
console.log(`β Resolution FAILED: Cannot find root function`);
}
},
});
return results;
}
/**
* Main function to analyze source code
*/
function analyzeSourceCode(sourceCode) {
try {
const ast = parser.parse(sourceCode, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
locations: true,
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
});
console.log('Starting source code analysis...\n');
const results = findAndResolveCalls(ast);
// Generate final statistics
const stats = generateStatistics(results);
printFinalStatistics(stats);
return { results, stats };
} catch (error) {
console.error('Error parsing code:', error.message);
return { results: [], stats: null };
}
}
/**
* Generate detailed statistics from analysis results
*/
function generateStatistics(results) {
const totalCalls = results.length;
const resolvedCalls = results.filter((r) => r.resolved);
const unresolvedCalls = results.filter((r) => !r.resolved);
// Group by root functions
const rootFunctions = {};
resolvedCalls.forEach((result) => {
const rootName = result.rootName;
if (!rootFunctions[rootName]) {
rootFunctions[rootName] = [];
}
rootFunctions[rootName].push(result);
});
// Group unresolved calls by their immediate caller name
const unresolvedCallers = {};
unresolvedCalls.forEach((result) => {
const callerName = result.calleeName;
if (!unresolvedCallers[callerName]) {
unresolvedCallers[callerName] = [];
}
unresolvedCallers[callerName].push(result);
});
return {
totalCalls,
resolvedCount: resolvedCalls.length,
unresolvedCount: unresolvedCalls.length,
rootFunctions,
unresolvedCallers,
uniqueRootFunctions: Object.keys(rootFunctions).length,
};
}
/**
* Print comprehensive final statistics
*/
function printFinalStatistics(stats) {
if (!stats) return;
console.log('\n'.repeat(2));
console.log('='.repeat(60));
console.log(' FINAL STATISTICS');
console.log('='.repeat(60));
// Overall summary
console.log(`\nOVERALL SUMMARY:`);
console.log(`β’ Total function calls found: ${stats.totalCalls}`);
console.log(`β’ Successfully resolved: ${stats.resolvedCount}`);
console.log(`β’ Failed to resolve: ${stats.unresolvedCount}`);
console.log(`β’ Success rate: ${((stats.resolvedCount / stats.totalCalls) * 100).toFixed(1)}%`);
// Root functions found
console.log(`\nROOT FUNCTIONS DISCOVERED: ${stats.uniqueRootFunctions} unique functions`);
console.log('-'.repeat(40));
Object.entries(stats.rootFunctions).forEach(([rootFunc, calls]) => {
console.log(`\nπ Root Function: "${rootFunc}"`);
console.log(` ββ Called ${calls.length} times through these aliases:`);
calls.forEach((call) => {
const chainStr = call.chain.length > 1 ? ` (chain: ${call.chain.join(' β ')})` : '';
console.log(
` β’ ${call.calleeName}(${call.arguments.number}, "${call.arguments.string}") at ${call.location}${chainStr}`
);
});
});
// Unresolved calls
if (stats.unresolvedCount > 0) {
console.log(`\nβ UNRESOLVED CALLS: ${stats.unresolvedCount} calls`);
console.log('-'.repeat(40));
Object.entries(stats.unresolvedCallers).forEach(([callerName, calls]) => {
console.log(`\nπ Caller: "${callerName}" (${calls.length} unresolved calls)`);
calls.forEach((call) => {
console.log(
` ββ ${call.calleeName}(${call.arguments.number}, "${call.arguments.string}") at ${call.location}`
);
console.log(` Chain: ${call.chain.join(' β ')}`);
});
});
}
console.log('\n' + '='.repeat(60));
}
/**
* Helper function: Batch analysis with grouping
*/
function batchAnalyze(sourceCode) {
return analyzeSourceCode(sourceCode);
}
module.exports = {
resolveIdentifier,
findAndResolveCalls,
analyzeSourceCode,
batchAnalyze,
generateStatistics,
printFinalStatistics,
exposeRootFunctions,
analyzeAndExpose,
};