refactor: 将文件从子目录提升到仓库根目录

所有文件从 hello_js_reverse_skill/ 子目录移至仓库根目录,
使项目结构更清晰,便于作为 Skill 直接引用。

Made-with: Cursor
This commit is contained in:
白夜
2026-03-18 22:55:27 +08:00
parent cfd0cc919d
commit fb14cf7916
29 changed files with 0 additions and 0 deletions
+87
View File
@@ -0,0 +1,87 @@
#!/bin/bash
# 检查 JS 逆向项目所需的依赖环境
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo "=========================================="
echo " JS 逆向工程环境检查"
echo "=========================================="
echo ""
check_command() {
local cmd=$1
local name=$2
local install_hint=$3
if command -v "$cmd" &> /dev/null; then
local version=$($cmd --version 2>&1 | head -1)
echo -e " ${GREEN}✓${NC} $name: $version"
return 0
else
echo -e " ${RED}✗${NC} $name: 未安装"
if [ -n "$install_hint" ]; then
echo -e " ${YELLOW}→ 安装: $install_hint${NC}"
fi
return 1
fi
}
check_node_module() {
local module=$1
local name=$2
if node -e "require('$module')" 2>/dev/null; then
local version=$(node -e "console.log(require('$module/package.json').version)" 2>/dev/null || echo "unknown")
echo -e " ${GREEN}✓${NC} $name: v$version"
return 0
else
echo -e " ${YELLOW}○${NC} $name: 未安装(可选)"
return 1
fi
}
errors=0
echo "▸ 基础环境"
check_command "node" "Node.js" "https://nodejs.org/ 或 brew install node" || ((errors++))
check_command "npm" "npm" "随 Node.js 一起安装" || ((errors++))
echo ""
echo "▸ 浏览器"
if [ -f "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
chrome_version=$("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --version 2>/dev/null)
echo -e " ${GREEN}✓${NC} Google Chrome: $chrome_version"
elif command -v google-chrome &> /dev/null; then
chrome_version=$(google-chrome --version 2>/dev/null)
echo -e " ${GREEN}✓${NC} Google Chrome: $chrome_version"
else
echo -e " ${YELLOW}○${NC} Google Chrome: 未检测到(浏览器自动化模式需要)"
fi
echo ""
echo "▸ 全局 npm 包"
check_node_module "crypto-js" "crypto-js"
check_node_module "axios" "axios"
check_node_module "node-forge" "node-forge"
check_node_module "jsdom" "jsdom"
echo ""
echo "▸ 可选工具"
check_command "curl" "curl" "系统自带"
check_command "jq" "jq" "brew install jq"
echo ""
echo "=========================================="
if [ $errors -gt 0 ]; then
echo -e " ${RED}检查完成: $errors 个必需依赖缺失${NC}"
echo ""
echo " 快速安装缺失依赖:"
echo " npm install -g crypto-js axios node-forge"
exit 1
else
echo -e " ${GREEN}检查完成: 环境就绪${NC}"
exit 0
fi
+291
View File
@@ -0,0 +1,291 @@
/**
* 加密算法识别器
* 根据密文特征自动识别可能的加密算法
*
* 使用方式:
* node crypto-identifier.js "e10adc3949ba59abbe56e057f20f883e"
* node crypto-identifier.js --file=captured_params.json
*/
const PATTERNS = [
{
name: 'MD5',
regex: /^[0-9a-f]{32}$/i,
description: '32位十六进制字符串',
length: 32,
charset: 'hex',
verify: '对比标准 MD5 输出。如果不一致,可能是自定义 MD5(如 chrsz=16)',
},
{
name: 'MD5 (大写)',
regex: /^[0-9A-F]{32}$/,
description: '32位大写十六进制',
length: 32,
charset: 'HEX',
},
{
name: 'SHA-1',
regex: /^[0-9a-f]{40}$/i,
description: '40位十六进制字符串',
length: 40,
charset: 'hex',
},
{
name: 'SHA-256',
regex: /^[0-9a-f]{64}$/i,
description: '64位十六进制字符串',
length: 64,
charset: 'hex',
},
{
name: 'SHA-512',
regex: /^[0-9a-f]{128}$/i,
description: '128位十六进制字符串',
length: 128,
charset: 'hex',
},
{
name: 'Base64',
regex: /^[A-Za-z0-9+/]+=*$/,
description: '标准 Base64 编码',
charset: 'base64',
verify: '尝试 atob() 解码,检查结果是否有意义',
},
{
name: 'Base64url',
regex: /^[A-Za-z0-9_-]+$/,
description: 'URL安全 Base64 编码(无填充)',
charset: 'base64url',
verify: '替换 -_ 为 +/ 后尝试解码',
},
{
name: 'AES-CBC/ECB (Base64)',
regex: /^[A-Za-z0-9+/]+=*$/,
test: (s) => {
const raw = Buffer.from(s, 'base64');
return raw.length > 0 && raw.length % 16 === 0;
},
description: 'Base64 编码,解码后长度为 16 的倍数',
verify: '需要找到 key (16/24/32字节) 和 iv (16字节,CBC模式)',
},
{
name: 'AES-CBC/ECB (Hex)',
regex: /^[0-9a-f]+$/i,
test: (s) => s.length >= 32 && s.length % 32 === 0,
description: '十六进制编码,长度为 32 的倍数',
verify: '需要找到 key 和 iv',
},
{
name: 'DES-ECB/CBC (Base64)',
regex: /^[A-Za-z0-9+/]+=*$/,
test: (s) => {
const raw = Buffer.from(s, 'base64');
return raw.length > 0 && raw.length % 8 === 0 && raw.length % 16 !== 0;
},
description: 'Base64 编码,解码后长度为 8 的倍数但不是 16 的倍数',
verify: '需要找到 8 字节 key',
},
{
name: 'RSA (Base64)',
regex: /^[A-Za-z0-9+/]+=*$/,
test: (s) => {
const raw = Buffer.from(s, 'base64');
return raw.length >= 64;
},
description: '较长的 Base64 字符串(64字节以上)',
verify: '需要找到公钥/私钥',
},
{
name: 'RSA (Hex)',
regex: /^[0-9a-f]+$/i,
test: (s) => s.length >= 128,
description: '较长的十六进制字符串',
verify: '搜索 RSA、publicKey、modulus 关键词',
},
{
name: 'HMAC-SHA256',
regex: /^[0-9a-f]{64}$/i,
description: '64位十六进制(与 SHA-256 相同格式)',
verify: '搜索 HMAC、createHmac、HmacSHA256 关键词',
},
{
name: 'UUID',
regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
description: 'UUID 格式',
},
{
name: '时间戳 (秒)',
regex: /^1[0-9]{9}$/,
description: '10位数字,Unix 时间戳(秒)',
},
{
name: '时间戳 (毫秒)',
regex: /^1[0-9]{12}$/,
description: '13位数字,Unix 时间戳(毫秒)',
},
{
name: 'JWT',
regex: /^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
description: 'JSON Web Token(三段 Base64url)',
verify: '分别解码三段:Header.Payload.Signature',
},
{
name: '十六进制编码字符串',
regex: /^([0-9a-f]{2})+$/i,
test: (s) => s.length > 10 && s.length % 2 === 0,
description: '连续十六进制对',
verify: '尝试 Buffer.from(str, "hex").toString()',
},
];
function identify(ciphertext) {
const results = [];
const trimmed = ciphertext.trim();
for (const pattern of PATTERNS) {
if (pattern.regex.test(trimmed)) {
if (pattern.test && !pattern.test(trimmed)) continue;
if (pattern.length && trimmed.length !== pattern.length) continue;
results.push({
algorithm: pattern.name,
confidence: calculateConfidence(trimmed, pattern),
description: pattern.description,
verify: pattern.verify || '',
});
}
}
results.sort((a, b) => b.confidence - a.confidence);
return results;
}
function calculateConfidence(text, pattern) {
let score = 50;
if (pattern.length && text.length === pattern.length) score += 30;
if (pattern.charset === 'hex' && /^[0-9a-f]+$/i.test(text)) score += 10;
if (pattern.charset === 'base64' && text.endsWith('=')) score += 10;
if (pattern.test && pattern.test(text)) score += 20;
return Math.min(score, 95);
}
function analyzeMultiple(samples) {
const allResults = samples.map(s => ({ sample: s, matches: identify(s) }));
const lengthSet = new Set(samples.map(s => s.length));
const charsetConsistent = samples.every(s => /^[0-9a-f]+$/i.test(s)) ||
samples.every(s => /^[A-Za-z0-9+/]+=*$/.test(s));
const analysis = {
sampleCount: samples.length,
lengths: [...lengthSet],
fixedLength: lengthSet.size === 1,
charsetConsistent,
results: allResults,
};
if (analysis.fixedLength && analysis.charsetConsistent) {
analysis.recommendation = '所有样本长度相同且字符集一致,很可能是同一算法的不同输出';
} else if (!analysis.fixedLength) {
analysis.recommendation = '样本长度不一致,可能涉及变长输入或不同算法';
}
return analysis;
}
function formatReport(ciphertext) {
const results = identify(ciphertext);
let report = '';
report += `\n🔍 密文分析报告\n`;
report += `${'━'.repeat(50)}\n`;
report += `输入: ${ciphertext.substring(0, 80)}${ciphertext.length > 80 ? '...' : ''}\n`;
report += `长度: ${ciphertext.length}\n`;
report += `字符集: ${detectCharset(ciphertext)}\n`;
report += `${'━'.repeat(50)}\n`;
if (results.length === 0) {
report += `\n❌ 未识别到已知的加密模式\n`;
report += `建议:搜索 JS 源码中的加密函数名\n`;
} else {
report += `\n可能的算法(按可信度排序):\n\n`;
results.forEach((r, i) => {
report += ` ${i + 1}. ${r.algorithm} (${r.confidence}%)\n`;
report += ` 描述: ${r.description}\n`;
if (r.verify) report += ` 验证: ${r.verify}\n`;
report += `\n`;
});
}
// Base64 解码尝试
if (/^[A-Za-z0-9+/]+=*$/.test(ciphertext)) {
try {
const decoded = Buffer.from(ciphertext, 'base64');
report += `📦 Base64 解码结果:\n`;
report += ` 二进制长度: ${decoded.length} 字节\n`;
if (decoded.length % 16 === 0) report += ` ⚠ 长度是 16 的倍数(可能是 AES)\n`;
if (decoded.length % 8 === 0) report += ` ⚠ 长度是 8 的倍数(可能是 DES)\n`;
const textAttempt = decoded.toString('utf-8');
if (/^[\x20-\x7e]+$/.test(textAttempt)) {
report += ` 文本: ${textAttempt.substring(0, 100)}\n`;
} else {
report += ` 十六进制: ${decoded.toString('hex').substring(0, 100)}\n`;
}
} catch (e) {}
}
return report;
}
function detectCharset(str) {
if (/^[0-9]+$/.test(str)) return '纯数字';
if (/^[0-9a-f]+$/i.test(str)) return '十六进制';
if (/^[A-Za-z0-9+/]+=*$/.test(str)) return 'Base64';
if (/^[A-Za-z0-9_-]+$/.test(str)) return 'Base64url / 字母数字';
if (/^[\x20-\x7e]+$/.test(str)) return '可打印ASCII';
return '混合/二进制';
}
// CLI
if (require.main === module) {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('用法:');
console.log(' node crypto-identifier.js "<密文>"');
console.log(' node crypto-identifier.js --file=params.json');
console.log(' node crypto-identifier.js --compare "<样本1>" "<样本2>" ...');
process.exit(0);
}
if (args[0] === '--compare') {
const samples = args.slice(1);
const analysis = analyzeMultiple(samples);
console.log('\n📊 多样本对比分析');
console.log('━'.repeat(50));
console.log(`样本数量: ${analysis.sampleCount}`);
console.log(`长度分布: ${analysis.lengths.join(', ')}`);
console.log(`固定长度: ${analysis.fixedLength ? '是' : '否'}`);
console.log(`字符集一致: ${analysis.charsetConsistent ? '是' : '否'}`);
if (analysis.recommendation) console.log(`\n💡 ${analysis.recommendation}`);
analysis.results.forEach((r, i) => {
console.log(`\n--- 样本 ${i + 1}: ${r.sample.substring(0, 40)}... ---`);
r.matches.slice(0, 3).forEach(m => {
console.log(` ${m.algorithm} (${m.confidence}%)`);
});
});
} else if (args[0].startsWith('--file=')) {
const fs = require('fs');
const data = JSON.parse(fs.readFileSync(args[0].substring(7), 'utf-8'));
const samples = Array.isArray(data) ? data : Object.values(data);
samples.forEach((s, i) => {
console.log(formatReport(String(s)));
});
} else {
console.log(formatReport(args[0]));
}
}
module.exports = { identify, analyzeMultiple, formatReport };
+346
View File
@@ -0,0 +1,346 @@
/**
* Hook 代码生成器
* 根据逆向目标快速生成 Hook 注入代码
*
* 使用方式:
* node hook-generator.js --type=cookie
* node hook-generator.js --type=xhr --target="/api/data"
* node hook-generator.js --type=all
* node hook-generator.js --type=custom --function="encrypt" --module="CryptoJS"
*/
const HOOK_TEMPLATES = {
cookie: (options = {}) => {
const target = options.target || '';
return `(function() {
var _cookie = document.cookie || '';
Object.defineProperty(document, 'cookie', {
set: function(val) {
${target ? `if (val.indexOf('${target}') !== -1) {` : '{'}
console.log('[Hook:Cookie] Set:', val);
console.trace('[Hook:Cookie] 调用栈');
}
var parts = val.split(';');
var mainPart = parts[0];
if (_cookie) _cookie += '; ';
_cookie += mainPart;
},
get: function() { return _cookie; },
configurable: true
});
console.log('[Hook:Cookie] Cookie Hook 已注入');
})();`;
},
xhr: (options = {}) => {
const target = options.target || '';
return `(function() {
var _open = XMLHttpRequest.prototype.open;
var _send = XMLHttpRequest.prototype.send;
var _setHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.open = function(method, url) {
this.__hookMethod = method;
this.__hookUrl = url;
this.__hookHeaders = {};
return _open.apply(this, arguments);
};
XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
this.__hookHeaders[name] = value;
return _setHeader.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function(body) {
${target ? `if (this.__hookUrl && this.__hookUrl.indexOf('${target}') !== -1) {` : '{'}
console.log('[Hook:XHR] ★', this.__hookMethod, this.__hookUrl);
console.log('[Hook:XHR] Headers:', JSON.stringify(this.__hookHeaders));
console.log('[Hook:XHR] Body:', body);
console.trace('[Hook:XHR] 调用栈');
}
return _send.apply(this, arguments);
};
console.log('[Hook:XHR] XHR Hook 已注入');
})();`;
},
fetch: (options = {}) => {
const target = options.target || '';
return `(function() {
var _fetch = window.fetch;
window.fetch = function(input, init) {
var url = typeof input === 'string' ? input : (input.url || '');
${target ? `if (url.indexOf('${target}') !== -1) {` : '{'}
console.log('[Hook:Fetch] ★', url);
console.log('[Hook:Fetch] Options:', JSON.stringify(init || {}));
console.trace('[Hook:Fetch] 调用栈');
}
return _fetch.apply(this, arguments);
};
console.log('[Hook:Fetch] Fetch Hook 已注入');
})();`;
},
eval: () => {
return `(function() {
var _eval = window.eval;
window.eval = function(code) {
console.log('[Hook:eval] 代码长度:', typeof code === 'string' ? code.length : 'N/A');
if (typeof code === 'string' && code.length < 10000) {
console.log('[Hook:eval] 内容:', code.substring(0, 500));
}
return _eval.apply(this, arguments);
};
var _Function = Function;
window.Function = function() {
var body = arguments[arguments.length - 1];
console.log('[Hook:Function] body长度:', body ? body.length : 0);
if (body && body.length < 5000) {
console.log('[Hook:Function] 内容:', body.substring(0, 500));
}
return _Function.apply(this, arguments);
};
window.Function.prototype = _Function.prototype;
console.log('[Hook:eval] eval/Function Hook 已注入');
})();`;
},
json: () => {
return `(function() {
var _parse = JSON.parse;
var _stringify = JSON.stringify;
JSON.parse = function(text) {
var result = _parse.apply(this, arguments);
console.log('[Hook:JSON] parse:', typeof text === 'string' ? text.substring(0, 200) : typeof text);
return result;
};
JSON.stringify = function(obj) {
var result = _stringify.apply(this, arguments);
console.log('[Hook:JSON] stringify:', result ? result.substring(0, 200) : result);
return result;
};
console.log('[Hook:JSON] JSON Hook 已注入');
})();`;
},
base64: () => {
return `(function() {
var _atob = window.atob;
var _btoa = window.btoa;
window.atob = function(str) {
var result = _atob(str);
console.log('[Hook:Base64] atob:', str.substring(0, 80), '→', result.substring(0, 80));
return result;
};
window.btoa = function(str) {
var result = _btoa(str);
console.log('[Hook:Base64] btoa:', str.substring(0, 80), '→', result.substring(0, 80));
return result;
};
console.log('[Hook:Base64] Base64 Hook 已注入');
})();`;
},
websocket: () => {
return `(function() {
var _WS = window.WebSocket;
window.WebSocket = function(url, protocols) {
console.log('[Hook:WS] 连接:', url);
var ws = new _WS(url, protocols);
var _send = ws.send.bind(ws);
ws.send = function(data) {
console.log('[Hook:WS] 发送:', typeof data === 'string' ? data.substring(0, 200) : '[binary]');
return _send(data);
};
ws.addEventListener('message', function(e) {
console.log('[Hook:WS] 接收:', typeof e.data === 'string' ? e.data.substring(0, 200) : '[binary]');
});
return ws;
};
window.WebSocket.prototype = _WS.prototype;
console.log('[Hook:WS] WebSocket Hook 已注入');
})();`;
},
debugger_bypass: () => {
return `(function() {
var _Function = Function;
Function = function() {
var body = arguments[arguments.length - 1];
if (typeof body === 'string' && body.indexOf('debugger') !== -1) {
arguments[arguments.length - 1] = body.replace(/debugger\\s*;?/g, '');
}
return _Function.apply(this, arguments);
};
Function.prototype = _Function.prototype;
var _si = window.setInterval;
window.setInterval = function(fn, ms) {
if (typeof fn === 'function' && fn.toString().indexOf('debugger') > -1) return -1;
if (typeof fn === 'string' && fn.indexOf('debugger') > -1) return -1;
return _si.apply(this, arguments);
};
var _st = window.setTimeout;
window.setTimeout = function(fn, ms) {
if (typeof fn === 'function' && fn.toString().indexOf('debugger') > -1) return -1;
if (typeof fn === 'string' && fn.indexOf('debugger') > -1) return -1;
return _st.apply(this, arguments);
};
console.log('[Hook:AntiDebug] debugger 绕过已注入');
})();`;
},
stealth: () => {
return `(function() {
Object.defineProperty(navigator, 'webdriver', { get: function() { return undefined; }, configurable: true });
window.chrome = window.chrome || {};
window.chrome.runtime = window.chrome.runtime || {};
Object.defineProperty(navigator, 'plugins', {
get: function() {
return [
{ name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer' },
{ name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai' },
{ name: 'Native Client', filename: 'internal-nacl-plugin' }
];
}
});
Object.defineProperty(navigator, 'languages', {
get: function() { return ['zh-CN', 'zh', 'en']; }
});
var _getParameter = WebGLRenderingContext.prototype.getParameter;
WebGLRenderingContext.prototype.getParameter = function(param) {
if (param === 37445) return 'Intel Inc.';
if (param === 37446) return 'Intel Iris OpenGL Engine';
return _getParameter.apply(this, arguments);
};
console.log('[Hook:Stealth] 隐身模式已注入');
})();`;
},
custom: (options = {}) => {
const funcName = options.function || 'targetFunction';
return `(function() {
// 追踪 ${funcName} 函数
if (typeof ${funcName} !== 'undefined') {
var _orig = ${funcName};
${funcName} = function() {
console.log('[Hook:Custom] ${funcName} 调用');
console.log('[Hook:Custom] 参数:', JSON.stringify(Array.from(arguments)));
var result = _orig.apply(this, arguments);
console.log('[Hook:Custom] 返回:', JSON.stringify(result));
console.trace('[Hook:Custom] 调用栈');
return result;
};
console.log('[Hook:Custom] ${funcName} Hook 已注入');
} else {
console.warn('[Hook:Custom] ${funcName} 未定义,等待加载...');
// 使用 getter 延迟 Hook
var _origVal;
Object.defineProperty(window, '${funcName}', {
get: function() { return _origVal; },
set: function(val) {
if (typeof val === 'function') {
var _fn = val;
_origVal = function() {
console.log('[Hook:Custom] ${funcName} 调用');
console.log('[Hook:Custom] 参数:', JSON.stringify(Array.from(arguments)));
var result = _fn.apply(this, arguments);
console.log('[Hook:Custom] 返回:', JSON.stringify(result));
return result;
};
} else {
_origVal = val;
}
},
configurable: true
});
}
})();`;
},
};
function generateHook(type, options = {}) {
const generator = HOOK_TEMPLATES[type];
if (!generator) {
throw new Error(`未知的 Hook 类型: ${type}。可用类型: ${Object.keys(HOOK_TEMPLATES).join(', ')}`);
}
return generator(options);
}
function generateAllHooks(options = {}) {
const hooks = [
HOOK_TEMPLATES.debugger_bypass(),
HOOK_TEMPLATES.stealth(),
HOOK_TEMPLATES.cookie(options),
HOOK_TEMPLATES.xhr(options),
HOOK_TEMPLATES.fetch(options),
HOOK_TEMPLATES.eval(),
HOOK_TEMPLATES.base64(),
];
return hooks.join('\n\n');
}
// CLI
if (require.main === module) {
const args = process.argv.slice(2);
const options = {};
args.forEach(arg => {
if (arg.startsWith('--type=')) options.type = arg.substring(7);
else if (arg.startsWith('--target=')) options.target = arg.substring(9);
else if (arg.startsWith('--function=')) options.function = arg.substring(11);
else if (arg.startsWith('--output=')) options.output = arg.substring(9);
});
if (!options.type) {
console.log('用法: node hook-generator.js --type=<type> [options]');
console.log('');
console.log('类型:');
console.log(' cookie Cookie setter 拦截');
console.log(' xhr XMLHttpRequest 拦截');
console.log(' fetch Fetch API 拦截');
console.log(' eval eval/Function 拦截');
console.log(' json JSON.parse/stringify 拦截');
console.log(' base64 atob/btoa 拦截');
console.log(' websocket WebSocket 拦截');
console.log(' debugger_bypass debugger 反调试绕过');
console.log(' stealth 浏览器指纹隐身');
console.log(' custom 自定义函数拦截');
console.log(' all 生成所有 Hook(组合包)');
console.log('');
console.log('选项:');
console.log(' --target=<url> 目标接口路径过滤');
console.log(' --function=<name> 自定义函数名(type=custom 时)');
console.log(' --output=<file> 输出到文件');
process.exit(0);
}
let code;
if (options.type === 'all') {
code = generateAllHooks(options);
} else {
code = generateHook(options.type, options);
}
if (options.output) {
const fs = require('fs');
fs.writeFileSync(options.output, code);
console.log(`Hook 代码已保存到: ${options.output}`);
} else {
console.log(code);
}
}
module.exports = { generateHook, generateAllHooks, HOOK_TEMPLATES };
+359
View File
@@ -0,0 +1,359 @@
/**
* VM 沙箱执行器
* 用于在隔离的 Node.js 沙箱中执行从浏览器提取的 JS 代码
*
* 使用方式:
* node sandbox-runner.js <js-file> [options]
* node sandbox-runner.js code.js --url=https://target.com --extract-cookie
*/
const vm = require('vm');
const fs = require('fs');
const path = require('path');
class SandboxRunner {
constructor(options = {}) {
this.options = {
url: options.url || 'https://example.com',
userAgent: options.userAgent || 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
timeout: options.timeout || 10000,
extractCookie: options.extractCookie || false,
verbose: options.verbose || false,
...options,
};
this.cookies = {};
this.logs = [];
this.errors = [];
}
createSandbox() {
const self = this;
const urlObj = new URL(this.options.url);
const sandbox = {
window: null,
self: null,
globalThis: null,
top: null,
parent: null,
frames: null,
document: this._createDocument(),
navigator: this._createNavigator(),
location: this._createLocation(urlObj),
screen: { width: 1920, height: 1080, availWidth: 1920, availHeight: 1055, colorDepth: 24, pixelDepth: 24 },
history: { length: 1, pushState: () => {}, replaceState: () => {}, back: () => {}, forward: () => {} },
setTimeout: (fn, ms) => setTimeout(fn, Math.min(ms || 0, 5000)),
setInterval: (fn, ms) => setInterval(fn, Math.max(ms || 100, 100)),
clearTimeout, clearInterval,
requestAnimationFrame: (fn) => setTimeout(fn, 16),
cancelAnimationFrame: clearTimeout,
String, Array, Object, Math, Date, RegExp, JSON, Map, Set, WeakMap, WeakSet,
Number, Boolean, Symbol, BigInt,
parseInt, parseFloat, isNaN, isFinite, NaN, Infinity, undefined,
encodeURIComponent, decodeURIComponent, encodeURI, decodeURI,
escape, unescape,
Error, TypeError, RangeError, SyntaxError, ReferenceError, URIError, EvalError,
ArrayBuffer, Uint8Array, Uint16Array, Uint32Array, Int8Array, Int16Array, Int32Array,
Float32Array, Float64Array, DataView,
Promise, Proxy, Reflect,
TextEncoder: typeof TextEncoder !== 'undefined' ? TextEncoder : class {},
TextDecoder: typeof TextDecoder !== 'undefined' ? TextDecoder : class {},
URL: typeof URL !== 'undefined' ? URL : class {},
URLSearchParams: typeof URLSearchParams !== 'undefined' ? URLSearchParams : class {},
btoa: (str) => Buffer.from(str, 'binary').toString('base64'),
atob: (b64) => Buffer.from(b64, 'base64').toString('binary'),
console: {
log: (...args) => { self.logs.push(args.join(' ')); if (self.options.verbose) console.log('[Sandbox]', ...args); },
warn: (...args) => { self.logs.push('[WARN] ' + args.join(' ')); },
error: (...args) => { self.errors.push(args.join(' ')); if (self.options.verbose) console.error('[Sandbox Error]', ...args); },
info: (...args) => { self.logs.push('[INFO] ' + args.join(' ')); },
debug: () => {},
trace: () => {},
clear: () => {},
},
XMLHttpRequest: this._createXHR(),
fetch: async () => new Response('{}'),
Event: class Event { constructor(type) { this.type = type; } },
CustomEvent: class CustomEvent { constructor(type, opts) { this.type = type; this.detail = opts?.detail; } },
MutationObserver: class MutationObserver { observe() {} disconnect() {} },
IntersectionObserver: class IntersectionObserver { observe() {} disconnect() {} },
ResizeObserver: class ResizeObserver { observe() {} disconnect() {} },
};
sandbox.window = sandbox;
sandbox.self = sandbox;
sandbox.globalThis = sandbox;
sandbox.top = sandbox;
sandbox.parent = sandbox;
sandbox.frames = sandbox;
// Cookie 拦截
if (this.options.extractCookie) {
this._setupCookieTrap(sandbox);
}
return sandbox;
}
_createDocument() {
const createElement = (tag) => ({
tagName: tag.toUpperCase(),
style: new Proxy({}, { get: () => '', set: () => true }),
classList: { add: () => {}, remove: () => {}, contains: () => false },
setAttribute: () => {},
getAttribute: () => null,
removeAttribute: () => {},
appendChild: (child) => child,
removeChild: () => {},
insertBefore: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => true,
innerHTML: '', innerText: '', textContent: '',
src: '', href: '', id: '', className: '',
parentNode: null, parentElement: null,
childNodes: [], children: [], firstChild: null, lastChild: null,
nextSibling: null, previousSibling: null,
offsetWidth: 100, offsetHeight: 100,
getBoundingClientRect: () => ({ top: 0, left: 0, bottom: 100, right: 100, width: 100, height: 100 }),
querySelector: () => null,
querySelectorAll: () => [],
getElementsByTagName: () => [],
getElementsByClassName: () => [],
cloneNode: () => createElement(tag),
});
return {
cookie: '',
createElement,
createElementNS: (ns, tag) => createElement(tag),
createTextNode: (text) => ({ nodeType: 3, textContent: text }),
createDocumentFragment: () => ({ appendChild: () => {}, childNodes: [] }),
getElementById: () => null,
getElementsByTagName: (tag) => tag === 'script' ? [1, 2, 3] : [],
getElementsByClassName: () => [],
getElementsByName: () => [],
querySelector: () => null,
querySelectorAll: () => [],
addEventListener: () => {},
removeEventListener: () => {},
head: { appendChild: () => {} },
body: { appendChild: () => {}, innerHTML: '' },
documentElement: { style: {} },
readyState: 'complete',
title: '',
referrer: '',
domain: '',
URL: this.options.url,
characterSet: 'UTF-8',
contentType: 'text/html',
};
}
_createNavigator() {
return {
userAgent: this.options.userAgent,
appCodeName: 'Mozilla',
appName: 'Netscape',
appVersion: '5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
platform: 'MacIntel',
product: 'Gecko',
productSub: '20030107',
vendor: 'Google Inc.',
vendorSub: '',
language: 'zh-CN',
languages: ['zh-CN', 'zh', 'en'],
cookieEnabled: true,
onLine: true,
doNotTrack: null,
hardwareConcurrency: 8,
maxTouchPoints: 0,
webdriver: false,
plugins: { length: 3, item: () => null, namedItem: () => null, refresh: () => {} },
mimeTypes: { length: 4, item: () => null, namedItem: () => null },
permissions: { query: async () => ({ state: 'granted' }) },
mediaDevices: { enumerateDevices: async () => [] },
geolocation: { getCurrentPosition: () => {} },
connection: { effectiveType: '4g', downlink: 10 },
getBattery: async () => ({ charging: true, chargingTime: 0, dischargingTime: Infinity, level: 1 }),
};
}
_createLocation(urlObj) {
return {
href: urlObj.href,
protocol: urlObj.protocol,
host: urlObj.host,
hostname: urlObj.hostname,
port: urlObj.port,
pathname: urlObj.pathname,
search: urlObj.search,
hash: urlObj.hash,
origin: urlObj.origin,
assign: () => {},
replace: () => {},
reload: () => {},
toString: () => urlObj.href,
};
}
_createXHR() {
return class XMLHttpRequest {
constructor() {
this.readyState = 0;
this.status = 0;
this.statusText = '';
this.responseText = '';
this.response = '';
this.responseType = '';
this.withCredentials = false;
}
open() { this.readyState = 1; }
setRequestHeader() {}
send() {
this.readyState = 4;
this.status = 200;
this.responseText = '{}';
this.response = '{}';
if (this.onreadystatechange) this.onreadystatechange();
if (this.onload) this.onload();
}
addEventListener(e, fn) { this['on' + e] = fn; }
abort() {}
getResponseHeader() { return null; }
getAllResponseHeaders() { return ''; }
};
}
_setupCookieTrap(sandbox) {
const self = this;
const originalCookie = sandbox.document.cookie || '';
Object.defineProperty(sandbox.document, 'cookie', {
get() {
return Object.entries(self.cookies)
.map(([k, v]) => `${k}=${v}`)
.join('; ');
},
set(val) {
const mainPart = val.split(';')[0];
const eqIdx = mainPart.indexOf('=');
if (eqIdx > 0) {
const name = mainPart.substring(0, eqIdx).trim();
const value = mainPart.substring(eqIdx + 1).trim();
self.cookies[name] = value;
if (self.options.verbose) {
console.log(`[Cookie Trap] ${name}=${value}`);
}
}
},
configurable: true,
});
if (originalCookie) {
originalCookie.split(';').forEach(pair => {
const [k, ...rest] = pair.trim().split('=');
if (k) self.cookies[k.trim()] = rest.join('=');
});
}
}
run(code, filename = 'sandbox.js') {
const sandbox = this.createSandbox();
vm.createContext(sandbox);
try {
const result = vm.runInContext(code, sandbox, {
timeout: this.options.timeout,
filename,
displayErrors: true,
});
return {
success: true,
result,
cookies: { ...this.cookies },
logs: [...this.logs],
errors: [...this.errors],
sandbox,
};
} catch (e) {
return {
success: false,
error: e.message,
stack: e.stack,
cookies: { ...this.cookies },
logs: [...this.logs],
errors: [...this.errors],
};
}
}
runFile(filePath) {
const code = fs.readFileSync(filePath, 'utf-8');
return this.run(code, path.basename(filePath));
}
}
// CLI 入口
if (require.main === module) {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('用法: node sandbox-runner.js <js-file> [options]');
console.log('');
console.log('选项:');
console.log(' --url=<url> 设置 location.href');
console.log(' --extract-cookie 启用 Cookie 拦截');
console.log(' --verbose 输出详细日志');
console.log(' --timeout=<ms> 执行超时(默认 10000)');
process.exit(0);
}
const filePath = args[0];
const options = {};
args.slice(1).forEach(arg => {
if (arg === '--extract-cookie') options.extractCookie = true;
else if (arg === '--verbose') options.verbose = true;
else if (arg.startsWith('--url=')) options.url = arg.substring(6);
else if (arg.startsWith('--timeout=')) options.timeout = parseInt(arg.substring(10));
});
const runner = new SandboxRunner(options);
const result = runner.runFile(filePath);
console.log('\n========== 执行结果 ==========');
console.log('状态:', result.success ? '成功' : '失败');
if (!result.success) {
console.log('错误:', result.error);
}
if (Object.keys(result.cookies).length > 0) {
console.log('\nCookies:');
Object.entries(result.cookies).forEach(([k, v]) => {
console.log(` ${k} = ${v}`);
});
}
if (result.logs.length > 0) {
console.log('\n日志:');
result.logs.forEach(log => console.log(` ${log}`));
}
if (result.errors.length > 0) {
console.log('\n错误日志:');
result.errors.forEach(err => console.log(` ${err}`));
}
}
module.exports = { SandboxRunner };