Files

367 lines
20 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// wx-jsguard 本地出签器:在 Node 的 vm 上下文里补 wx 环境跑美团小程序 jsguard,产出 mtgsig
// 纯本地,不依赖小程序运行时、不依赖远端签名服务(SDK 自身会走 msp.meituan.com 的指纹登记)
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';
// 每个小程序必须有自己的签名 SDK:jsguard-<appid>.js(用 提取jsguard.py 生成),不做降级
const HERE = path.dirname(fileURLToPath(import.meta.url));
export function resolveSdk(appid) {
if (process.env.WR_SDK) return process.env.WR_SDK;
if (appid) {
const p = path.join(HERE, 'jsguard-' + appid + '.js');
if (fs.existsSync(p)) return p;
}
const have = fs.readdirSync(HERE).filter((f) => /^jsguard-.+\.js$/.test(f)).map((f) => f.slice(8, -3));
throw new Error('未适配该小程序(appid=' + (appid || '未知') + ')。已适配: ' + (have.join(', ') || '无') +
';先跑 `python 提取jsguard.py ' + (appid || '<appid>') + '`');
}
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON.stringify(qn)) ),用来读回本次请求的上下文
const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
export function b64alpha(s) {
let buf = 0, nb = 0;
const out = [];
for (const ch of s) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v;
nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 多加 +31)
export function rc4Twist(key, data) {
const S = [];
for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
// 解出 a5 里带的 qn(请求上下文:路由/开关位/定位精度等)
export function decodeQn(a5) {
const w = b64alpha(String(a5));
return JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
}
const LOG = process.env.WR_LOG === '1';
const SYSTEM_INFO = {
brand: 'microsoft', model: 'microsoft', system: 'Windows 10 x64', platform: 'windows',
version: '4.1.12.24', SDKVersion: '3.17.3', language: 'zh_CN',
screenWidth: 414, screenHeight: 780, windowWidth: 414, windowHeight: 780,
pixelRatio: 1, devicePixelRatio: 1, statusBarHeight: 20,
benchmarkLevel: -1, bluetoothEnabled: false, wifiEnabled: true, locationEnabled: true,
enableDebug: false, errMsg: 'getSystemInfo:ok',
safeArea: { left: 0, right: 414, top: 0, bottom: 780, width: 414, height: 780 },
};
// 从旧 mtgsig 的 a6 system 数组还原真机设备画像(字段顺序 = jsguard 的 DFP 顺序)
function deviceFromSys(S) {
if (!Array.isArray(S) || S.length < 45) return null;
const at = (i, d) => (S[i] === undefined || S[i] === null ? d : S[i]);
const opt = (i, k, o) => (at(i, null) === null ? o : { ...o, [k]: at(i) });
let lo = {};
try { lo = JSON.parse(at(17, '{}')); } catch (e) {}
const sa = Array.isArray(at(30, null)) ? at(30) : null;
const bi = Array.isArray(at(2, null)) ? at(2) : null;
let sys = {
brand: at(7, 'microsoft'), model: at(22, 'microsoft'), system: at(36, 'Windows 10 x64'), platform: at(29, 'windows'),
version: at(37, '10.38.3'), SDKVersion: at(34, '3.17.3'), language: at(16, 'zh_CN'),
fontSizeSetting: at(15, undefined), screenWidth: at(33, 414), screenHeight: at(31, 780),
windowWidth: at(41, 414), windowHeight: at(40, 780), pixelRatio: at(28, 1), devicePixelRatio: at(12, 1),
statusBarHeight: at(35, 20), benchmarkLevel: at(5, -1), bluetoothEnabled: at(6, false),
wifiEnabled: at(38, true), locationEnabled: at(19, true), enableDebug: at(13, false),
errMsg: at(14, 'getSystemInfo:ok'),
};
sys = opt(11, 'deviceOrientation', sys);
sys = opt(32, 'screenTop', sys);
sys = opt(1, 'albumAuthorized', sys);
sys = opt(9, 'cameraAuthorized', sys);
sys = opt(18, 'locationAuthorized', sys);
sys = opt(21, 'microphoneAuthorized', sys);
sys = opt(25, 'notificationAuthorized', sys);
sys = opt(20, 'locationReducedAccuracy', sys);
if (sa) sys.safeArea = { left: sa[0], right: sa[1], top: sa[2], bottom: sa[3], width: sa[4], height: sa[5] };
return {
sys,
launchOptions: { path: lo.path || 'pages/index/index', scene: lo.scene === undefined ? 1256 : lo.scene, query: {}, referrerInfo: {}, isSticky: false },
networkType: at(23, 'wifi'),
hasSystemProxy: at(44, -1),
brightness: at(8, 0.5),
battery: bi ? { errMsg: bi[0] || 'getBatteryInfo:ok', isCharging: !!bi[1], level: bi[2] } : { errMsg: 'getBatteryInfo:ok', isCharging: true, level: 100 },
beaconsOk: typeof at(4, null) === 'string',
};
}
const SUCCESS = (o) => ({ errMsg: 'ok', ...o });
// 真机 USER_DATA_PATH 目录的 lastModifiedTime(毫秒),影响 a6 里的 filetime/localid
const FILE_MTIME = Number(process.env.WR_MTIME || 1787118064811);
const STORE = new Map();
function buildWx(log, cfg) {
const appid = cfg.appid;
const D = cfg.sys ? deviceFromSys(cfg.sys) : null;
const SI = D ? D.sys : SYSTEM_INFO;
const appVersion = cfg.appVersion || SI.version;
const launchPath = cfg.launchPath || (D ? D.launchOptions.path : 'pages/index/index');
const mtime = cfg.mtime || FILE_MTIME;
const track = cfg.track; // 统计 et 上报(ops.meituan.com)在途/完成
const mk = (name, impl) => function (...a) {
log.push(name);
if (LOG) console.error('[wx] ' + name + '(' + a.map((x) => (typeof x === 'function' ? 'fn' : JSON.stringify(x))).join(', ') + ')');
if (impl) return impl.apply(this, a);
};
return {
getSystemInfoSync: mk('getSystemInfoSync', () => SI),
getSystemInfo: mk('getSystemInfo', (o) => { if (o && o.success) o.success(SUCCESS(SI)); if (o && o.complete) o.complete(SUCCESS(SI)); }),
getDeviceInfo: mk('getDeviceInfo', () => SI),
getWindowInfo: mk('getWindowInfo', () => ({ pixelRatio: SI.pixelRatio, screenWidth: SI.screenWidth, screenHeight: SI.screenHeight, windowWidth: SI.windowWidth, windowHeight: SI.windowHeight, statusBarHeight: SI.statusBarHeight, safeArea: SI.safeArea })),
getAppBaseInfo: mk('getAppBaseInfo', () => ({ SDKVersion: SI.SDKVersion, language: SI.language, version: appVersion, platform: SI.platform, theme: 'light', enableDebug: SI.enableDebug })),
getAppAuthorizeSetting: mk('getAppAuthorizeSetting', () => ({ albumAuthorized: 'authorized', cameraAuthorized: 'authorized', locationAuthorized: 'authorized', microphoneAuthorized: 'authorized', notificationAuthorized: 'authorized' })),
getSetting: mk('getSetting', (o) => { if (o && o.success) o.success(SUCCESS({ authSetting: {}, subscriptionsSetting: {} })); }),
getPublicLibVersion: mk('getPublicLibVersion', () => (cfg.ext && cfg.ext[2] === 1 ? { system: SI.platform } : {})),
getNetworkType: mk('getNetworkType', (o) => { if (o && o.success) o.success(SUCCESS({ networkType: D ? D.networkType : 'wifi', hasSystemProxy: D ? D.hasSystemProxy === 1 : false })); }),
getScreenBrightness: mk('getScreenBrightness', (o) => { if (o && o.success) o.success(SUCCESS({ value: D ? D.brightness : 0.5 })); }),
getBatteryInfoSync: mk('getBatteryInfoSync', () => (D ? D.battery : { errMsg: 'getBatteryInfo:ok', level: 100, isCharging: true })),
getBatteryInfo: mk('getBatteryInfo', (o) => { const r = D ? D.battery : { errMsg: 'getBatteryInfo:ok', level: 100, isCharging: true }; if (o && o.success) o.success(r); if (o && o.complete) o.complete(r); }),
getScreenRecordingState: mk('getScreenRecordingState', (o) => { if (o && o.fail) o.fail({ errMsg: 'getScreenRecordingState:fail' }); if (o && o.complete) o.complete({ errMsg: 'getScreenRecordingState:fail' }); }),
getLocalIPAddress: mk('getLocalIPAddress', (o) => { if (o && o.success) o.success(SUCCESS({ localip: '192.168.1.100' })); }),
getStorageInfo: mk('getStorageInfo', (o) => { if (o && o.success) o.success(SUCCESS({ keys: ['a'], currentSize: 1, limitSize: 10240 })); }),
getStorageInfoSync: mk('getStorageInfoSync', () => ({ keys: ['a'], currentSize: 1, limitSize: 10240 })),
getStorageSync: mk('getStorageSync', (k) => {
if (cfg.seedDfp && k === '40a10de2') return { id: { ...cfg.seedDfp } };
return STORE.has(k) ? STORE.get(k) : '';
}),
setStorageSync: mk('setStorageSync', (k, v) => { STORE.set(k, v); }),
setStorage: mk('setStorage', (o) => { if (o && o.key !== undefined) STORE.set(o.key, o.data); if (o && o.success) o.success({ errMsg: 'setStorage:ok' }); }),
getBeacons: mk('getBeacons', (o) => {
if (D && D.beaconsOk) { if (o && o.success) o.success(SUCCESS({ beacons: [] })); return; }
if (o && o.fail) o.fail({ errMsg: 'getBeacons:fail' }); if (o && o.complete) o.complete({ errMsg: 'getBeacons:fail' });
}),
getSelectedTextRange: mk('getSelectedTextRange', (o) => { if (o && o.success) o.success(SUCCESS({ start: 0, end: 0 })); }),
getLaunchOptionsSync: mk('getLaunchOptionsSync', () => (D ? D.launchOptions : { path: launchPath, scene: 1256, query: {}, referrerInfo: {}, isSticky: false })),
getLocation: mk('getLocation', (o) => { if (o && o.success) o.success(SUCCESS({ latitude: 23.129, longitude: 113.264, accuracy: 65, horizontalAccuracy: 65, verticalAccuracy: 65 })); }),
startWifi: mk('startWifi', (o) => { if (o && o.success) o.success(SUCCESS({})); }),
getConnectedWifi: mk('getConnectedWifi', (o) => { if (o && o.error) o.error({ errMsg: 'not connected' }); }),
getWifiList: mk('getWifiList', () => undefined),
onGetWifiList: mk('onGetWifiList', () => undefined),
// NFC 一项影响指纹里的 ext 数组:真机 Android 有 NFC 且 startDiscovery 失败(=0),Windows 无该 API(=4)
canIUse: mk('canIUse', (n) => !(n === 'getNFCAdapter' && (cfg.ext ? cfg.ext[4] : 4) === 4)),
getNFCAdapter: mk('getNFCAdapter', () => {
const nfc = cfg.ext ? cfg.ext[4] : 4;
return {
startDiscovery: (o) => { if (nfc === 1) { if (o && o.success) o.success({}); } else if (o && o.fail) o.fail({ errCode: nfc === 3 ? 13000 : nfc === 2 ? 13001 : 0 }); },
stopDiscovery: (o) => { if (o && o.success) o.success({}); },
};
}),
getPrivacySetting: mk('getPrivacySetting', (o) => { if (o && o.success) o.success(SUCCESS({ needAuthorization: false, privacyContractName: '《小程序隐私保护指引》' })); }),
getAccountInfoSync: mk('getAccountInfoSync', () => ({ miniProgram: { appId: appid, envVersion: 'release', version: appVersion } })),
getUserCryptoManager: mk('getUserCryptoManager', () => ({
getLatestUserKey: mk('getLatestUserKey', (o) => {
const k = { encryptKey: '0123456789abcdef', iv: 'abcdef0123456789', version: 1, expireTime: Math.floor(Date.now() / 1000) + 86400 };
if (o && o.success) o.success(SUCCESS(k));
return k;
}),
getRandomValues: mk('getRandomValues', (o) => { if (o && o.success) o.success(SUCCESS({ randomValues: new Uint8Array(16) })); }),
})),
getFileSystemManager: mk('getFileSystemManager', () => ({ statSync: mk('statSync', () => ({ lastModifiedTime: mtime, lastAccessedTime: mtime, size: 4096, mode: 33188, isDirectory: () => true, isFile: () => false })) })),
env: { USER_DATA_PATH: 'wxfile://usr' },
onAppHide: mk('onAppHide', () => undefined),
onAppShow: mk('onAppShow', () => undefined),
onUserCaptureScreen: mk('onUserCaptureScreen', () => undefined),
offUserCaptureScreen: mk('offUserCaptureScreen', () => undefined),
onAccelerometerChange: mk('onAccelerometerChange', () => undefined),
startAccelerometer: mk('startAccelerometer', () => undefined),
onCompassChange: mk('onCompassChange', () => undefined),
startCompass: mk('startCompass', () => undefined),
request: mk('request', (o) => {
let url = o.url;
const method = (o.method || 'GET').toUpperCase();
const headers = o.header || {};
let body;
if (o.data !== undefined) {
if (method === 'GET' || method === 'HEAD') {
const qs = typeof o.data === 'string' ? o.data : Object.entries(o.data).map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v)).join('&');
if (qs) url += (url.includes('?') ? '&' : '?') + qs;
} else {
body = typeof o.data === 'string' ? o.data : JSON.stringify(o.data);
}
}
// 微信默认:对象 body -> application/json,字符串 -> x-www-form-urlencoded
const hdrs = { ...headers };
if (!Object.keys(hdrs).some((k) => k.toLowerCase() === 'content-type')) {
hdrs['content-type'] = (o.data !== undefined && typeof o.data !== 'string') ? 'application/json' : 'application/x-www-form-urlencoded';
}
const isEt = url.includes('ops.meituan.com');
if (isEt && track) { track.inFlight++; track.seen = true; }
fetch(url, { method, headers: hdrs, body })
.then(async (r) => {
const text = await r.text();
let data; try { data = JSON.parse(text); } catch (e) { data = text; }
const res = { statusCode: r.status, data, header: Object.fromEntries(r.headers) };
if (LOG) console.error('[net] ' + method + ' ' + url + ' -> ' + r.status + ' ' + text.slice(0, 300));
if (o.success) o.success(res);
if (o.complete) o.complete(res);
if (isEt && track) track.inFlight--;
})
.catch((e) => {
const res = { errMsg: 'request:fail ' + (e && e.message) };
if (LOG) console.error('[net] ' + method + ' ' + url + ' -> FAIL ' + (e && e.message));
if (o.fail) o.fail(res);
if (o.complete) o.complete(res);
if (isEt && track) track.inFlight--;
});
}),
};
}
function patchSdk(src, switchDigits) {
// 被吞掉的出签异常打出来
src = src.replace(
/catch\(e\)\{try\{Qe&&Qe\[c\(39\)\]\(a\(616\),e\)\}catch\(e\)\{\}\}/,
"catch(e){try{console.error('CALCMTGSIG_ERR',e&&(e.stack||e.message||String(e)))}catch(_e){}}"
);
// 开关位串(qn.b9):优先旧 mtgsig 解出的 b9;没有才兜底 22122(五位串随环境变,勿当成固定健康值)
src = src.replace(/(\{su:0,fm:0,fp:0,sig:0\},[A-Za-z_$][\w$]*=)\[0,0,0,0,0\]/, '$1[' + switchDigits.split('').join(',') + ']');
return src;
}
function makeLoader(context, sdkPath, switchDigits) {
const cache = new Map();
const ROOT = path.dirname(sdkPath).replace(/[\\/]npm[\\/].*$/, '');
function load(file) {
const abs = path.resolve(file);
if (cache.has(abs)) return cache.get(abs).exports;
let src = fs.readFileSync(abs, 'utf8');
if (abs === path.resolve(sdkPath)) src = patchSdk(src, switchDigits);
const mod = { exports: {} };
cache.set(abs, mod);
const dir = path.dirname(abs);
const req = (spec) => {
// @babel/runtime/helpers/* 统一从 SDK 所在项目的根目录取
const babel = spec.match(/@babel\/runtime\/helpers\/([\w.-]+)/);
if (babel) return load(path.join(ROOT, '@babel', 'runtime', 'helpers', babel[1] + '.js'));
if (spec.startsWith('.') || path.isAbsolute(spec)) {
let p = path.resolve(dir, spec);
if (!p.endsWith('.js')) { if (fs.existsSync(p + '.js')) p = p + '.js'; else if (fs.existsSync(path.join(p, 'index.js'))) p = path.join(p, 'index.js'); }
return load(p);
}
throw new Error('external require: ' + spec);
};
// 文件名里带 app-service:SDK 的防篡改位图会检查 Error.stack 里是否有 'app-service'/'appservice'
const fn = vm.runInContext('(function(module, exports, require, __filename, __dirname){' + src + '\n})', context, { filename: 'app-service/' + path.basename(abs) });
fn(mod, mod.exports, req, abs, dir);
return mod.exports;
}
return load;
}
export async function createSigner(opts = {}) {
const appid = opts.appid || 'wxde8ac0a21135c07d';
const sdkPath = opts.sdk || resolveSdk(appid);
const calls = [];
// et 上报(ops.meituan.com)在途计数:没落定就出签,qn.b9 会停在中间态 → 判可疑
const track = { inFlight: 0, seen: false };
const sandbox = {
console, setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask,
fetch, Buffer, TextEncoder, TextDecoder, URL, URLSearchParams, crypto: globalThis.crypto,
wx: buildWx(calls, { appid, appVersion: opts.appVersion, launchPath: opts.launchPath, sys: opts.sys, ext: opts.ext, seedDfp: opts.seedDfp, mtime: opts.mtime, track }),
__wxConfig: { config: { debug: false }, platform: 'windows' },
getCurrentPages: () => (opts.route ? [{ route: opts.route, options: {}, __origin_route__: opts.route }] : []),
navigator: undefined,
};
// ext[1]=addEventListener 是否存在(真机 Android appservice 没有)
if (!opts.ext || opts.ext[1] === 1) sandbox.addEventListener = () => undefined;
sandbox.globalThis = sandbox;
sandbox.self = sandbox;
// appservice 上下文:反篡改位图 r 随环境变(真机 appservice 常见反算 r=0,勿写死为 1)
if (opts.noWindow) { /* 完全不声明 window */ }
else if ('windowValue' in opts) sandbox.window = opts.windowValue;
else sandbox.window = undefined;
sandbox.eval = opts.keepEval ? sandbox.eval : undefined;
if (opts.weixinJSBridge !== false) {
sandbox.WeixinJSBridge = (opts.weixinJSBridge && opts.weixinJSBridge !== true) ? opts.weixinJSBridge : {};
}
sandbox.document = undefined;
// 冻结时间(拿抓包逐字节校验用):让 Date.now()/new Date 返回固定毫秒
if (opts.nowMs) {
const Real = Date;
const FIXED = opts.nowMs;
function FixedDate(...a) { return a.length ? new Real(...a) : new Real(FIXED); }
FixedDate.now = () => FIXED;
FixedDate.parse = Real.parse;
FixedDate.UTC = Real.UTC;
FixedDate.prototype = Real.prototype;
sandbox.Date = FixedDate;
}
const context = vm.createContext(sandbox);
const switchDigits = /^\d{5}$/.test(opts.switchState || '') ? opts.switchState : '22122';
const jsguard = makeLoader(context, sdkPath, switchDigits)(sdkPath);
let inst = null;
const initAt = Date.now();
try {
inst = await Promise.race([
jsguard.init({ appid, env: 'prod' }),
new Promise((_, rej) => setTimeout(() => rej(new Error('init timeout')), opts.initWaitMs || 8000)),
]);
} catch (e) {
inst = jsguard.initSync({ appid, env: 'prod' });
}
const siuaTimer = setInterval(() => { try { inst.finger.i(); } catch (e) {} }, 10000);
// 账号/会话身份要在 SDK 刷新指纹(a6) 之前注入,否则这一轮 a6 里带不上
if (opts.openId) { try { inst.finger.o(opts.openId); } catch (e) {} }
if (opts.unionId) { try { inst.finger.u(opts.unionId); } catch (e) {} }
if (opts.mchId) { try { inst.finger.m(opts.mchId); } catch (e) {} }
if (opts.sessionId) { try { inst.finger.ss(opts.sessionId); } catch (e) {} }
// 定位精度串(qn.b11,形如 "30_30_0"):真机会带,缺了也可疑
if (opts.loc) {
const [acc, hacc, vacc] = String(opts.loc).split('_').map(Number);
try { inst.finger.l({ accuracy: acc, horizontalAccuracy: hacc, verticalAccuracy: vacc }); } catch (e) {}
}
if (opts.settleMs !== 0) {
// SDK 的 a6 每 10s 刷一次;身份注入后必须过一轮才会带进 a6
const need = 10500 - (Date.now() - initAt);
if (need > 0) await new Promise((r) => setTimeout(r, need));
// et 上报也是 10s 周期:等它跑完并静默一段时间,开关位 b9 才回到健康值
const maxMs = opts.settleWaitMs || 30000;
const t0 = Date.now();
let drainedAt = 0;
while (Date.now() - t0 < maxMs) {
await new Promise((r) => setTimeout(r, 500));
if (track.seen && track.inFlight === 0) { if (!drainedAt) drainedAt = Date.now(); }
if (!track.seen && Date.now() - t0 > 8000) break;
if (drainedAt && Date.now() - drainedAt > (opts.settleTailMs || 9000)) break;
}
}
return {
appid,
guard: inst,
calls,
fingerId: () => { try { return inst.finger.i(); } catch (e) { return ''; } },
dfpid: () => { try { return inst.finger.d(); } catch (e) { return ''; } },
sign({ url, method = 'POST', data = '', contentType = 'application/x-www-form-urlencoded' }) {
// content-type 只影响对象 body:json 走 JSON.stringify,表单走插入顺序的 encodeURIComponent。字符串 body 原样进签名串
const req = { url, method, header: { 'content-type': contentType }, data };
const out = inst.signWithSiua(req);
return out.header.mtgsig;
},
close() { clearInterval(siuaTimer); },
};
}