// mtgsig 出签服务(常驻):小程序 jsguard(纯算/补环境)+ 外卖 H5guard // 启动: node serve.mjs 端口默认 18092(MTGSIG_PORT 可改) // 接口: GET /health -> {ok,ready,h5Profiles,port,uptimeSec} // POST /sign {url,data,mtgsig,openId,method,mode,sys?,ext?} 小程序签名(sys/ext 按字段名覆盖 a6 的 system/ext,仅纯算生效) // POST /sign_h5 {url,data,method,mode,type,dataType,profile,cookie?} 外卖/买药 H5 签名(H5guard 补环境;profile=设备环境,缺字段报错) // POST /sign_h5_pure {url,data,mtgsig,method,origin_url?,origin_data?} H5(h1.9) 纯算出签(不跑 SDK,毫秒级) // POST /derive {mtgsig} 解出小程序签名身份 import http from 'node:http'; import crypto from 'node:crypto'; import zlib from 'node:zlib'; import fs from 'node:fs'; import path from 'node:path'; import vm from 'node:vm'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { createSigner } from './signer.mjs'; import * as P from './pure.mjs'; import { buildEnv as buildH5Env, setScriptRunner as setH5ScriptRunner } from './h5-env.mjs'; // H5(h1.9) 纯算(不加载 H5guard):从一份 mtgsig 推会话,再按 url+body 出签 const H5P = await import(pathToFileURL('C:/Users/mjz/Desktop/python/mjz/测试/AI代码/mtgsig_js/h5-pure.mjs').href); // a6 = "w1.6" + base64(AES-128-CBC(gzip(身份数组))),key/iv 在已测 w1.6 样本上与 jsguard 一致(其它版本需再验) const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx'); const A6_IV = Buffer.from('0807060504030201'); // a5 = 自定义base64( y(16B) ‖ RC4_y(JSON.stringify(qn)) ),qn 是本次请求的上下文 const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5'; 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) 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; } // 从一份 mtgsig(最好是抓包里的旧签名)解出会话身份 + 请求上下文 function deriveFromMtgsig(mtgsig) { const p = typeof mtgsig === 'string' ? JSON.parse(mtgsig) : mtgsig; const buf = Buffer.from(String(p.a6).slice(P.a6PrefixOf(p.a6).length), 'base64'); const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV); const arr = JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8')); const out = { appid: arr[0], dfpid: p.a3, localId: arr[4], filetime: arr[2], fpv: arr[3], sys: arr[5], ext: arr[7], sessionId: arr[8], a6Prefix: P.a6PrefixOf(p.a6) }; try { // a6 的 system 数组里带着真机的启动页路径(LaunchOptionsSync),直接复用 const lp = (arr[5] || []).find((v) => typeof v === 'string' && v.startsWith('{"path"')); if (lp) out.launchPath = JSON.parse(lp).path; } catch (e) {} try { const w = b64alpha(String(p.a5)); const qn = JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8')); out.route = qn.b2 || ''; out.switchState = qn.b9 || ''; out.loc = qn.b11 || ''; out.openId = qn.b6 || ''; out.appVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.version) || ''; out.envVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.envVersion) || ''; if (Array.isArray(qn.b10) && qn.b10.length) out.failReports = qn.b10; // 防篡改位图 r 同样能从包里反算:y[7] = r ^ crc32(BE32(a2低32)) const y = w.slice(0, 16); out.r = y[7] ^ (P.crc32(P.be4(p.a2 >>> 0)) & 255); } catch (e) { /* 旧签名拿不到上下文就算了 */ } return out; } // a6 里 system 数组的 46 项顺序(= jsguard vt.system),按字段名覆盖时靠它映射到下标 const SYSTEM_FIELDS = [ 'accelerometer', 'albumAuthorized', 'BatteryInfo', 'batteryLevel', 'Beacons', 'benchmarkLevel', 'bluetoothEnabled', 'brand', 'brightness', 'cameraAuthorized', 'compass', 'deviceOrientation', 'devicePixelRatio', 'enableDebug', 'errMsg', 'fontSizeSetting', 'language', 'LaunchOptionsSync', 'locationAuthorized', 'locationEnabled', 'locationReducedAccuracy', 'microphoneAuthorized', 'model', 'networkType', 'notificationAlertAuthorized', 'notificationAuthorized', 'notificationBadgeAuthorized', 'notificationSoundAuthorized', 'pixelRatio', 'platform', 'safeArea', 'screenHeight', 'screenTop', 'screenWidth', 'SDKVersion', 'statusBarHeight', 'system', 'version', 'wifiEnabled', 'WifiInfo', 'windowHeight', 'windowWidth', 'screenRecord', 'isPrivacy', 'hasSystemProxy', 'captureRecord', ]; // a6 里 ext 数组的 5 项 const EXT_FIELDS = ['NativeClient', 'addEventListener', 'getPublicLibVersion', '__WeixinJSBridge', 'NFC']; // 按字段名把 override 覆盖到 base 数组(override 不传/空 = 原样返回;字段名不在清单里直接报错) function applyNamed(base, order, override, label) { if (!override) return base; const out = Array.isArray(base) ? base.slice() : []; for (const k of Object.keys(override)) { const i = order.indexOf(k); if (i < 0) throw new Error('未知的 ' + label + ' 字段: ' + k + '(可用字段: ' + order.join(', ') + ')'); out[i] = override[k]; } return out; } const PORT = Number(process.env.MTGSIG_PORT || 18092); const HOST = '0.0.0.0'; // 每个 (appid|dfpid) 一个出签实例(含 jsguard init 与 dfp 登记),首次调用会等几秒 const cache = new Map(); const startedAt = Date.now(); async function getSigner(id, openId) { const key = id.appid + '|' + id.dfpid; if (cache.has(key)) return cache.get(key); const p = createSigner({ appid: id.appid, openId: openId || '', mtime: Number(id.filetime), route: id.route || '', launchPath: id.launchPath || '', appVersion: id.appVersion || '', loc: id.loc || '', switchState: id.switchState || '', sessionId: id.sessionId || '', sys: id.sys, ext: id.ext, seedDfp: { dfpId: String(id.dfpid), localId: String(id.localId), timestamp: Number(id.filetime) }, }); cache.set(key, p); try { return await p; } catch (e) { cache.delete(key); throw e; } } function readBody(req) { return new Promise((resolve) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => resolve(b)); }); } async function handleSign(o) { if (!o.url) throw new Error('缺 url'); if (o.data === undefined) throw new Error('缺 data'); if (!o.mtgsig) throw new Error('缺 mtgsig(用它解出 appid/dfpid/localId/filetime)'); const id = deriveFromMtgsig(o.mtgsig); const openId = o.openId || id.openId; if (!openId) throw new Error('缺 openId(a6 里要带账号身份;旧 mtgsig 的 qn.b6 有的话也能自动取)'); const data = o.data == null ? '' : o.data; const method = (o.method || 'POST').toUpperCase(); // 字符串看首字符;对象没标 type 时按表单(和 get_mtgsig 的字典约定一致)。显式 contentType 优先 const contentType = o.contentType || (typeof data === 'string' && /^\s*[{[]/.test(data) ? 'application/json' : 'application/x-www-form-urlencoded'); // 默认走纯算(无 init、无预热);要旧的补环境路径就显式传 mode: 'bundle' const mode = String(o.mode || 'pure').toLowerCase(); if (mode === 'pure') { const mtgsig = signPure(id, openId, { url: o.url, data, method, contentType, sys: o.sys, ext: o.ext, r: o.r }); const p = JSON.parse(mtgsig); return { mtgsig, mode, a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length }; } const s = await getSigner(id, openId); const mtgsig = s.sign({ url: o.url, data, method, contentType }); const p = JSON.parse(mtgsig); return { mtgsig, mode: 'bundle', a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length }; } // 纯算模式:不加载 jsguard、不 init,因此没有那 20s 预热,换新包即出即用 const pureState = new Map(); // appid|dfpid -> { seq, initSec } function signPure(id, openId, { url, data, method, contentType, sys, ext, r }) { const key = id.appid + '|' + id.dfpid; let st = pureState.get(key); if (!st) { st = { seq: 1, initSec: Math.floor(Date.now() / 1000) }; pureState.set(key, st); } else st.seq += 1; // 防篡改位图:优先调用方 r,否则用旧包 a5 反算 id.r;仅都无时才回退 1(真机常见为 0,回退 1 可能错签) const bitmapR = r === undefined || r === null ? (id.r === undefined ? 1 : id.r) : Number(r); const a2 = Date.now(); const a6 = P.buildA6FromParts({ appid: id.appid, dfpid: id.dfpid, filetime: id.filetime, fpv: id.fpv || '2.5.0', localid: id.localId, sessionId: id.sessionId, a6Prefix: id.a6Prefix, sys: applyNamed(id.sys, SYSTEM_FIELDS, sys, 'system'), ext: applyNamed(id.ext, EXT_FIELDS, ext, 'ext'), timestamp: Math.ceil(a2 / 1000), }); return P.sign({ method, url, data, contentType, identity: { appid: id.appid, dfpid: id.dfpid, a6, a2 }, runtime: { openId, route: id.route, appVersion: id.appVersion, envVersion: id.envVersion, loc: id.loc, switchState: id.switchState, failReports: id.failReports, r: bitmapR }, initSec: st.initSec, seq: st.seq, }); } // ---------- H5guard(外卖/买药 H5,浏览器环境 shim) ---------- // 每个 profile(设备/身份)一套独立 vm + H5guard;环境全部由 profile 决定,不再有内置默认身份 const HERE = path.dirname(fileURLToPath(import.meta.url)); const H5_PKG = fs.readFileSync(path.join(HERE, 'package-v1.js'), 'utf8'); const H5_SDK = fs.readFileSync(path.join(HERE, 'H5guard.js'), 'utf8'); const h5Profiles = new Map(); // profileKey -> { env, ready, fpLen } function h5ProfileKey(p) { return [p.appid, p.ua, p.platform, p.screenWidth, p.screenHeight, p.devicePixelRatio].join('|'); } function getH5Profile(profile) { if (!profile || !profile.appid || !profile.domains) throw new Error('profile 缺 appid 或 domains'); const key = h5ProfileKey(profile); let st = h5Profiles.get(key); if (st) return st; const env = buildH5Env(profile); const ctx = vm.createContext(env); setH5ScriptRunner((code, name) => vm.runInContext(code, ctx, { filename: name })); vm.runInContext(H5_PKG, ctx, { filename: 'package-v1.js' }); vm.runInContext(H5_SDK, ctx, { filename: 'H5guard.js' }); st = { key, env, ready: false, fpLen: 0 }; h5Profiles.set(key, st); try { env.H5guard.init({ appid: profile.appid, xhrHook: true, domains: profile.domains, geo: false, yodaEnv: undefined }); } catch (e) { /* 已发起后台初始化 */ } const t0 = Date.now(); let last = -1; let stable = 0; const iv = setInterval(() => { let len = -1; try { len = String(env.H5guard.getfp()).length; } catch (e) { len = -1; } if (len > 0 && len === last) stable++; else stable = 0; last = len; const el = Date.now() - t0; if ((el >= 3500 && stable >= 2) || el >= 20000) { clearInterval(iv); st.fpLen = Math.max(0, len); st.ready = true; console.log('H5 READY[' + key + '] fpLen=' + st.fpLen + ' 预热=' + (el / 1000).toFixed(1) + 's'); } }, 250); return st; } function h5WaitReady(st) { if (st.ready) return Promise.resolve(); return new Promise((res) => { const iv = setInterval(() => { if (st.ready) { clearInterval(iv); res(); } }, 200); }); } let h5Queue = Promise.resolve(); // 串行化,避免并发互相干扰 SDK 状态 // 路径一:手动 H5guard.sign() -> a6 前缀 h1.9(外卖/买药 H5 页面自身加签走的这条) function signH5Api(o, st) { return (async () => { const env = st.env; if (o.cookie !== undefined) env.document.cookie = String(o.cookie || ''); const t = await env.H5guard.sign({ cache: false, dataType: o.dataType, url: o.url, type: String(o.type).toUpperCase(), data: o.data, method: String(o.method).toUpperCase(), }); return { mtgsig: t.headers.mtgsig, url: o.url, headers: {}, mode: 'sign' }; })(); } // 路径二:走 H5guard 自己装的 XHR 钩子(signType 2)-> a6 前缀 hs1.6 // 白名单域名来自 init 的 domains(profile.domains):GET 把 mtgsig 拼进 url、POST 塞 header function signH5Xhr(o, st) { return new Promise((resolve, reject) => { try { const env = st.env; if (o.cookie !== undefined) env.document.cookie = String(o.cookie || ''); const method = String(o.method).toUpperCase(); const xhr = new env.XMLHttpRequest(); xhr.open(method, o.url, true); if (o.contentType) xhr.setRequestHeader('content-type', o.contentType); if (o.headers) for (const k of Object.keys(o.headers)) xhr.setRequestHeader(k, o.headers[k]); xhr.send(o.data); const t0 = Date.now(); const iv = setInterval(() => { const g = xhr.guardReq || {}; const u = String(g.url || ''); const hs = g.headers || {}; let mtgsig = null; const m = u.match(/mtgsig=([^&]+)/); if (m) mtgsig = decodeURIComponent(m[1]); else if (hs.mtgsig) mtgsig = String(hs.mtgsig); if (mtgsig) { clearInterval(iv); resolve({ mtgsig, url: u || o.url, headers: hs, mode: 'xhr' }); return; } if (Date.now() - t0 > 15000) { clearInterval(iv); reject(new Error('H5 XHR 出签超时(域名可能不在 domains 白名单,或请求没被 SDK 钩到)')); } }, 50); } catch (e) { reject(e); } }); } function signH5(o, st) { const mode = String(o.mode).toLowerCase(); if (mode !== 'sign' && mode !== 'xhr') throw new Error('mode 非法(只能 sign 或 xhr): ' + JSON.stringify(o.mode)); const run = h5Queue.then(() => (mode === 'sign' ? signH5Api(o, st) : signH5Xhr(o, st))); h5Queue = run.then(() => {}, () => {}); // 单次失败不毒化后续请求 return run; } // H5(h1.9) 纯算:用一份抓包 mtgsig 推会话(origin_url/origin_data 要和那份包一致,默认同 url/data), // 再按新 url/data 出签;同一个 dfpid(a3) 的 seq 自增(qn[2] 服务端会核对) const h5PureSeq = new Map(); // a3(dfpid) -> seq function signH5Pure(o) { const data = o.data || ''; const method = (o.method || 'POST').toUpperCase(); const mtg = typeof o.mtgsig === 'string' ? JSON.parse(o.mtgsig) : o.mtgsig; const snap = H5P.deriveFromMtgsig(mtg, { url: o.origin_url || o.url, data: o.origin_data === undefined ? data : o.origin_data, method, }); const key = String(mtg.a3); const seq = h5PureSeq.has(key) ? h5PureSeq.get(key) + 1 : snap.seq + 1; h5PureSeq.set(key, seq); const a2 = o.a2 || Date.now(); const sig = H5P.sign(snap, { url: o.url, data, method, a2, seq }); return { mtgsig: JSON.stringify(sig), D: snap.D, seq }; } const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://' + HOST); const send = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(obj)); }; try { if (req.method === 'GET' && u.pathname === '/health') { return send(200, { ok: true, port: PORT, uptimeSec: Math.round((Date.now() - startedAt) / 1000), ready: true, h5Profiles: [...h5Profiles.values()].map((s) => ({ key: s.key, ready: s.ready, fpLen: s.fpLen })), identities: [...cache.keys()] }); } if (u.pathname === '/sign_h5') { let o = {}; if (req.method === 'POST') { const raw = await readBody(req); o = raw ? JSON.parse(raw) : {}; } else { o = Object.fromEntries(u.searchParams.entries()); } for (const k of ['url', 'data', 'method', 'mode', 'type', 'dataType', 'profile']) { if (o[k] === undefined) return send(400, { error: '缺 ' + k }); } const st = getH5Profile(o.profile); // 按 profile 建/取一套环境(profile 缺字段会报错) await h5WaitReady(st); // 该 profile 首次会等指纹预热(最多 20s) const r = await signH5(o, st); const m = JSON.parse(r.mtgsig); return send(200, { mtgsig: r.mtgsig, url: r.url, headers: r.headers, mode: r.mode, a3: m.a3, a6pfx: String(m.a6).slice(0, 5) }); } if (u.pathname === '/sign_h5_pure') { let o = {}; if (req.method === 'POST') { const raw = await readBody(req); o = raw ? JSON.parse(raw) : {}; } else { o = Object.fromEntries(u.searchParams.entries()); } if (!o.url) return send(400, { error: '缺 url' }); if (!o.mtgsig) return send(400, { error: '缺 mtgsig(用它推会话:a5 的 qn / a8 的 A / d1 的 pool2)' }); const r = signH5Pure(o); const m = JSON.parse(r.mtgsig); return send(200, { mtgsig: r.mtgsig, mode: 'h5-pure', a3: m.a3, a6pfx: String(m.a6).slice(0, 5), D: r.D, seq: r.seq }); } if (u.pathname === '/derive') { let mtgsig; if (req.method === 'POST') { const raw = await readBody(req); mtgsig = (raw ? JSON.parse(raw) : {}).mtgsig; } else mtgsig = u.searchParams.get('mtgsig') || ''; return send(200, deriveFromMtgsig(mtgsig)); } if (u.pathname === '/sign') { let o = {}; if (req.method === 'POST') { const raw = await readBody(req); o = raw ? JSON.parse(raw) : {}; } else { o = Object.fromEntries(u.searchParams.entries()); } const r = await handleSign(o); return send(200, r); } send(404, { error: 'not found' }); } catch (e) { send(500, { error: e && (e.message || String(e)) }); } }); server.on('error', (e) => { if (e && e.code === 'EADDRINUSE') { console.error('端口 ' + PORT + ' 已被占用,先停掉旧服务或改 MTGSIG_PORT'); process.exit(1); } console.error(e); process.exit(1); }); server.listen(PORT, HOST, () => { console.log('mtgsig 出签服务已启动: http://' + HOST + ':' + PORT + ' (health: /health)'); });