Files

283 lines
13 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.
// 美团小程序 mtgsig —— 纯算法实现(不加载 jsguard 包、不补环境)
// 算法来源:wxde8ac0a21135c07d / wx-jsguard 2.5.0 静态逆向;在 flows 抓包上 a4/d1/a5 结构与公式已对齐
//
// mtgsig 字段:
// a1 = "1.2" a2 = 毫秒时间戳(=q 里的 s)
// a3 = dfpid a4 = 见 buildA4()
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON(qn)) ) a6 = "w1.x"+base64(AES-128-CBC(gzip(9项数组)))(当前纯写 w1.6)
// a7 = appid x0 = 3 d1 = 见 buildD1()
//
// 需要外部给的(算法里算不出来):dfpid / localId / filetime / 46 项设备画像 / 出签会话上下文。
// 须从一份抓包旧 mtgsig 解出(解密mtgsig.py 或 serve /derive);含 b9 开关串、反算 r、qn.b7/b8 等。
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import { gzipSync } from './gzip-mini.mjs';
// ---------------- 基础算法 ----------------
// 与 jsguard 里的 ge() 等价的 MurmurHash3_x86_32(results 为有符号 Int32,用时 >>>0)
export function murmur3(bytes, seed) {
const e = bytes, n0 = e.length;
const mul = (x) => (1540483477 * (x & 65535) + ((1540483477 * (x >>> 16) & 65535) << 16)) >>> 0;
let n = n0, t = ((seed | 0) ^ n0) >>> 0, c = 0;
while (n >= 4) {
let r = ((e[c] & 255) | ((e[c + 1] & 255) << 8) | ((e[c + 2] & 255) << 16) | ((e[c + 3] & 255) << 24)) >>> 0;
r = mul(r);
r = mul((r ^ (r >>> 24)) >>> 0);
t = (mul(t) ^ r) >>> 0;
n -= 4; c += 4;
}
switch (n) {
case 3: t = (t ^ ((e[c + 2] & 255) << 16)) >>> 0;
case 2: t = (t ^ ((e[c + 1] & 255) << 8)) >>> 0;
case 1: t = mul((t ^ (e[c] & 255)) >>> 0);
}
t = (t ^ (t >>> 13)) >>> 0;
t = mul(t);
return (((t ^ (t >>> 15)) >>> 0) ^ 1540483477) >>> 0;
}
// jsguard 的 crc32 变体:反射多项式 0xEDB88320,初值 0xFFFFFFFF,末异或 306674911(即 0x12477CDF,不是标准的 0xFFFFFFFF)
const CRC_TABLE = (() => {
const t = [];
for (let r = 0; r < 256; r++) { let v = r; for (let k = 0; k < 8; k++) v = v & 1 ? (v >>> 1) ^ 3988292384 : v >>> 1; t[r] = v >>> 0; }
return t;
})();
export function crc32(bytes) {
let r = -1;
for (let i = 0; i < bytes.length; i++) r = CRC_TABLE[(r ^ bytes[i]) & 255] ^ (r >>> 8);
return ((306674911 ^ r) >>> 0);
}
// 自定义字母表的标准 base64(带 = 填充)
export const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
export function b64alphaEncode(buf) {
let out = '';
for (let i = 0; i < buf.length; i += 3) {
const n = (buf[i] << 16) | ((buf[i + 1] || 0) << 8) | (buf[i + 2] || 0);
out += A5_ALPHA[(n >> 18) & 63] + A5_ALPHA[(n >> 12) & 63];
out += i + 1 < buf.length ? A5_ALPHA[(n >> 6) & 63] : '=';
out += i + 2 < buf.length ? A5_ALPHA[n & 63] : '=';
}
return out;
}
export function b64alpha(s) {
let buf = 0, nb = 0; const out = [];
for (const ch of String(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;
}
const be4 = (v) => Buffer.from([(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]);
const le4 = (v) => Buffer.from([v & 255, (v >>> 8) & 255, (v >>> 16) & 255, (v >>> 24) & 255]);
const u8 = (s) => Buffer.from(s, 'utf8');
const md5 = (b) => crypto.createHash('md5').update(b).digest();
const md5hex = (b) => md5(b).toString('hex');
const md5ints = (b) => { const x = md5(b); return [0, 1, 2, 3].map((i) => (x[i * 4] | x[i * 4 + 1] << 8 | x[i * 4 + 2] << 16 | x[i * 4 + 3] << 24) >>> 0); };
const hexInts = (a) => a.map((v) => le4(v).toString('hex')).join('');
// ---------------- a6 ----------------
// key/iv:w1.4(快驴 fpv 1.8.0)和 w1.6 都能用这套解开;换更大版本仍要再对一次样本
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
// 出签默认前缀。从旧包重出时用旧 a6 的前缀(w1.4 / w1.6),不要写死成 w1.6
export const A6_PREFIX = 'w1.6';
// 次版本号只取一位。\d+ 会把 base64 开头的数字吃进前缀,密文长度对不齐 16,AES 报 wrong final block length
export function a6PrefixOf(a6) {
const m = String(a6 || '').match(/^(w\d+\.\d)/);
return m ? m[1] : A6_PREFIX;
}
// arr = [app, dfpid, filetime, fpv, localid, system(46项), timestamp, ext(5项), sessionId]
// 用 jsguard 自带那套 gzip(gzip-mini.mjs 搬运版)而不是 zlib:zlib 压出来的流与真机不同,
// 搬过来的实现已实测与 jsguard 的 gzipSync 逐字节一致(含 MTIME=当前秒、OS=3 的头)。
export function buildA6(arr, mtimeSec, prefix) {
const sec = mtimeSec === undefined ? Math.floor(Date.now() / 1000) : mtimeSec;
const gz = gzipSync(u8(JSON.stringify(arr)), { mtime: sec * 1000 });
const c = crypto.createCipheriv('aes-128-cbc', A6_KEY, A6_IV);
return (prefix || A6_PREFIX) + Buffer.concat([c.update(Buffer.from(gz)), c.final()]).toString('base64');
}
export function parseA6(a6) {
const buf = Buffer.from(String(a6).slice(a6PrefixOf(a6).length), 'base64');
const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV);
return JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8'));
}
// 由零件直接拼 a6(不传 timestamp 时用当前秒)
export function buildA6FromParts(o) {
const ts = o.timestamp === undefined ? Math.ceil(Date.now() / 1000) : o.timestamp;
return buildA6([
o.appid, o.dfpid, o.filetime, o.fpv, o.localid, o.sys, ts, o.ext, o.sessionId,
], ts, o.a6Prefix || A6_PREFIX);
}
// ---------------- qn(a5 里 RC4 的载荷,键的插入顺序要跟 SDK 一致)----------------
// b7 秒级时间(init 时写入) / b1 getAccountInfoSync / b6 openId / b8 出签序号
// b12 appid / b11 定位精度串 / b2 当前路由 / b9 开关位图 / b10 失败上报(有才写)
export function buildQn(o) {
const qn = {};
qn.b7 = o.initSec;
qn.b1 = { miniProgram: { appId: o.appid, envVersion: o.envVersion || 'release', version: o.appVersion } };
if (o.openId) qn.b6 = o.openId;
qn.b8 = o.seq;
qn.b12 = o.appid;
qn.b2 = o.route || '';
// b9:五位开关串,随环境变;22122 只是无旧包时的兜底,应优先用抓包 qn.b9
qn.b9 = o.switchState || '22122';
if (o.loc) qn.b11 = o.loc; // 实测 b11 排在最后(不是赋值顺序)
if (o.failReports && o.failReports.length) qn.b10 = o.failReports;
return qn;
}
export function decodeQn(a5) {
const w = b64alpha(a5);
return JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
}
// ---------------- a5 ----------------
// y = md5(utf8(a6) ‖ BE32(low32(a2)))[0:7] ‖ [255&(r^crc32(l))] ‖ l ‖ BE32(crc32(y[0:12]))
// r 默认 1 仅防忘传;真机 appservice 常见反算为 0,须用 y[7]^crc32(BE32(a2低32)) 从旧包取
export function buildA5(a6, a2, qn, r = 1) {
const l = be4(a2 >>> 0);
const v = md5hex(Buffer.concat([u8(a6), l]));
const y = Buffer.from(v.slice(0, 14), 'hex'); // 7 字节
return (() => {
const buf = Buffer.alloc(16);
y.copy(buf, 0);
buf[7] = (r ^ crc32(l)) & 255;
l.copy(buf, 8);
be4(crc32(buf.slice(0, 12))).copy(buf, 12);
return b64alphaEncode(Buffer.concat([buf, rc4Twist(buf, u8(JSON.stringify(qn)))]));
})();
}
// ---------------- a4 / d1 ----------------
// z = utf8("METHOD path 规范化query") ‖ utf8(body前16200字节);x = murmur3(z, a2)
// query:按 & 切开,+ 当空格,decode 后再用 fe(encodeURIComponent 再编码 !'()*)重编码,按 [key, value] 排序。
// 不看接口路径。url 里如果已经带着 mtgsig,会算进去;重出签前先把这个参数从 url 去掉。
// body:GET/HEAD 不带。字符串原样(调用方已经编好的表单/JSON 都走这条)。
// 对象 + content-type 含 json → JSON.stringify。
// 其它对象 → 按插入顺序做 encodeURIComponent(不排序、不编码 !'()*),这是表单对象。
// 非 GET 的 body 只取前 16200 字节参与哈希,发出去的 body 本身不要截。
const BODY_LIMIT = 16200;
// query 用。比 encodeURIComponent 多编码 ! ' ( ) *
export function feQuery(s) {
return encodeURIComponent(s).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
}
function decComponent(s) {
const t = String(s).replace(/\+/g, ' ');
try { return decodeURIComponent(t); } catch (e) { return t; }
}
function parsePairs(q) {
const out = [];
for (const part of String(q || '').split('&')) {
if (!part) continue;
const i = part.indexOf('=');
if (i < 0) out.push([part, '']);
else out.push([part.slice(0, i), part.slice(i + 1)]);
}
return out;
}
export function canonQuery(url) {
const u = new URL(url);
const raw = u.search.startsWith('?') ? u.search.slice(1) : '';
const ps = parsePairs(raw).map(([k, v]) => [feQuery(decComponent(k)), feQuery(decComponent(v))]);
ps.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
return { pathname: u.pathname, query: ps.map(([k, v]) => k + '=' + v).join('&') };
}
// 表单对象的 value 编码,和 query 的 fe 不是同一套
function formEncode(data) {
const parts = [];
for (const k of Object.keys(data)) {
const v = data[k];
parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(v == null ? '' : String(v)));
}
return parts.join('&');
}
export function canonBody(method, data, contentType) {
const m = String(method || 'POST').toUpperCase();
if (m === 'GET' || m === 'HEAD') return '';
if (data === undefined || data === null) return '';
let body;
if (typeof data === 'string') body = data;
else {
const ct = String(contentType || '').toLowerCase();
body = ct.includes('json') ? JSON.stringify(data) : formEncode(data);
}
return body.length > BODY_LIMIT ? body.slice(0, BODY_LIMIT) : body;
}
export function buildZ({ method, url, data, contentType }) {
const m = String(method || 'POST').toUpperCase();
const q = canonQuery(url);
const head = m + ' ' + q.pathname + ' ' + q.query;
return Buffer.concat([u8(head), u8(canonBody(m, data, contentType))]);
}
export const buildX = (z, a2) => murmur3(z, a2) >>> 0;
// a5 里的 `_`:对 a5 字符串本身取 murmur3
export const buildUnderscore = (a5, a2) => murmur3(u8(a5), a2) >>> 0;
// a4 = hex( BE32(x) ‖ BE32(_) ‖ LE32(x) ‖ LE32(_) ‖ LE32(x^s32) ‖ LE32(x^_^s32) )
export function buildA4(x, under, a2) {
const s32 = a2 >>> 0;
return Buffer.concat([be4(x), be4(under), le4(x), le4(under), le4(x ^ s32), le4(x ^ under ^ s32)]).toString('hex');
}
// d1 = hexLE( B ),B 由 md5(M) 的 4 个 int 经异或混淆得到
export function buildD1({ a1, a2, a3, a4, under, a6, a7, x0 = 3 }) {
const s32 = a2 >>> 0;
const v = md5hex(Buffer.concat([u8(a6), be4(s32)]));
const M = String(a1) + String(a2) + String(a3) + String(a4) + String(under) + v + String(a7);
const B = md5ints(u8(M));
const u = under >>> 0, f = u;
const j = ((s32 << x0) | (s32 << (32 - x0))) >>> 0;
B[0] = (B[0] ^ j) >>> 0; B[1] = (B[1] ^ f) >>> 0; B[2] = (B[2] ^ f ^ j) >>> 0; B[3] = (B[3] ^ B[0]) >>> 0;
return hexInts(B);
}
// ---------------- 主入口 ----------------
// identity: { appid, dfpid, a6, a2 } —— a6/a2 可与 a5 复用;runtime: { route, openId, appVersion, switchState, loc, initSec, seq, r }
export function sign({ method = 'POST', url, data = '', contentType, identity, runtime, seq, initSec }) {
const a2 = identity.a2 || Date.now();
const a6 = identity.a6;
// 未传 r 时默认 1 易错;出签应传 runtime.r(从旧 mtgsig 反算)
const r = runtime.r === undefined ? 1 : runtime.r;
const qn = buildQn({
appid: identity.appid, openId: runtime.openId, route: runtime.route,
appVersion: runtime.appVersion, envVersion: runtime.envVersion, loc: runtime.loc, switchState: runtime.switchState,
initSec: initSec || Math.floor(a2 / 1000), seq: seq || 1, failReports: runtime.failReports,
});
const a5 = buildA5(a6, a2, qn, r);
const x = buildX(buildZ({ method, url, data, contentType }), a2);
const under = buildUnderscore(a5, a2);
const a1 = '1.2';
const a4 = buildA4(x, under, a2);
const d1 = buildD1({ a1, a2, a3: identity.dfpid, a4, under, a6, a7: identity.appid });
return JSON.stringify({ a1, a2, a3: identity.dfpid, a4, a5, a6, a7: identity.appid, x0: 3, d1 });
}
export { be4, le4, u8, md5ints, hexInts };