This commit is contained in:
upload
2026-11-11 22:25:40 +08:00
commit d87848d502
325 changed files with 3894 additions and 0 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
function _typeof(o){return module.exports=_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}module.exports=_typeof;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+632
View File
@@ -0,0 +1,632 @@
// 真实浏览器环境 shim:按 SDK 实际需要铺开 navigator/screen/document/window 等
// 目标:属性做成自有可枚举属性(SDK 会用 hasOwnProperty / Object.keys 反查伪造)
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
// 环境完全由调用方传入的 profile 决定,本文件不再内置任何"默认身份"
let CUR = null; // 当前正在构建的 profile(供 makeElement/makeCanvas 这类异步路径取用)
function need(profile, k) {
if (profile == null || profile[k] === undefined || profile[k] === '') throw new Error('缺 profile.' + k);
return profile[k];
}
// 真实网络开关:默认关闭(离线);WR_NET=1 时按真实浏览器行为请求 SDK 引导接口
const NET_ON = process.env.WR_NET === '1';
const netLog = [];
function httpRequest(method, url, headers, body) {
return new Promise((resolve) => {
if (!NET_ON) { netLog.push(method + ' ' + url + ' (stubbed)'); return resolve({ status: 0, text: '' }); }
const u = new URL(url);
const lib = u.protocol === 'http:' ? require('node:http') : require('node:https');
const req = lib.request({ method, hostname: u.hostname, port: u.port || (u.protocol === 'http:' ? 80 : 443), path: u.pathname + u.search, headers }, (res) => {
let data = '';
res.on('data', (c) => { data += c; });
res.on('end', () => { netLog.push(method + ' ' + url + ' -> ' + res.statusCode + ' len=' + data.length); resolve({ status: res.statusCode, text: data }); });
});
req.on('error', (e) => { netLog.push(method + ' ' + url + ' ERR ' + e.message); resolve({ status: 0, text: '' }); });
if (body) req.write(body);
req.end();
});
}
// 方法必须挂在 prototype 上:H5guard.init 会 hook XMLHttpRequest.prototype.open/send
// 来给白名单域名自动加签(GET 拼进 url),用实例属性的话钩子挂不上、只会走手动 sign() 那条路
function makeXHR(ua) {
function XMLHttpRequest() {
this.readyState = 0; this.status = 0; this.responseText = ''; this.response = ''; this.responseType = '';
this._headers = {};
this.onreadystatechange = null; this.onload = null; this.onerror = null;
this._m = null; this._u = null;
}
XMLHttpRequest.prototype.open = function (m, u) { this._m = m; this._u = u; this.readyState = 1; if (this.onreadystatechange) this.onreadystatechange(); };
XMLHttpRequest.prototype.setRequestHeader = function (k, v) { this._headers[k] = v; };
XMLHttpRequest.prototype.getAllResponseHeaders = function () { return ''; };
XMLHttpRequest.prototype.getResponseHeader = function () { return null; };
XMLHttpRequest.prototype.addEventListener = function (t, f) { if (t === 'load') this.onload = f; if (t === 'readystatechange') this.onreadystatechange = f; };
XMLHttpRequest.prototype.send = function (body) {
const xhr = this;
httpRequest(xhr._m || 'GET', xhr._u, Object.assign({ 'user-agent': ua }, xhr._headers), body).then((r) => {
xhr.status = r.status; xhr.responseText = r.text;
xhr.response = xhr.responseType === 'json' ? (() => { try { return JSON.parse(r.text); } catch { return null; } })() : r.text;
xhr.readyState = 4;
if (xhr.onreadystatechange) xhr.onreadystatechange();
if (xhr.onload) xhr.onload();
});
};
XMLHttpRequest.prototype.abort = function () {};
return XMLHttpRequest;
}
function makeFetch(ua) {
return (u, o) => {
const url = typeof u === 'string' ? u : (u && u.url);
const method = (o && o.method) || 'GET';
return httpRequest(method, url, Object.assign({ 'user-agent': ua }, (o && o.headers) || {}), o && o.body).then((r) => ({
ok: r.status >= 200 && r.status < 300, status: r.status, headers: { get: () => null },
text: () => Promise.resolve(r.text), json: () => Promise.resolve(JSON.parse(r.text || 'null')),
}));
};
}
export function netCalls() { return netLog.slice(); }
function makeCanvas2d(canvas) {
const ctx = {
canvas, font: '10px sans-serif', textBaseline: 'alphabetic', textAlign: 'start', direction: 'ltr',
fillStyle: '#000000', strokeStyle: '#000000', globalAlpha: 1, globalCompositeOperation: 'source-over',
lineWidth: 1, lineCap: 'butt', lineJoin: 'miter', shadowBlur: 0, shadowColor: 'rgba(0, 0, 0, 0)',
imageSmoothingEnabled: true, miterLimit: 10, lineDashOffset: 0,
save() {}, restore() {}, scale() {}, rotate() {}, translate() {}, transform() {}, setTransform() {}, resetTransform() {},
beginPath() {}, closePath() {}, moveTo() {}, lineTo() {}, bezierCurveTo() {}, quadraticCurveTo() {}, arc() {}, arcTo() {}, rect() {}, ellipse() {},
fill() {}, stroke() {}, clip() {}, fillRect() {}, strokeRect() {}, clearRect() {}, drawImage() {},
fillText() {}, strokeText() {}, setLineDash() {}, getLineDash: () => [],
createLinearGradient: () => ({ addColorStop() {} }), createRadialGradient: () => ({ addColorStop() {} }),
createPattern: () => ({}), isPointInPath: () => false,
measureText(t) {
const fam = (String(ctx.font).match(/[\d.]+px\s+(.+)$/) || [])[1] || '';
const text = String(t);
let perChar = 9;
if (/monospace|Courier|Consolas|Lucida Console/i.test(fam)) perChar = 9;
else if (WIN_FONTS.has(fam)) perChar = 8.4 + (strHash(fam) % 7) * 0.1;
return { width: Math.round(perChar * text.length * 10) / 10, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2, actualBoundingBoxLeft: 0, actualBoundingBoxRight: perChar * text.length, fontBoundingBoxAscent: 9, fontBoundingBoxDescent: 2 };
},
getContextAttributes: () => ({ alpha: true, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false }),
getImageData(x, y, w, h) {
const data = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < data.length; i += 4) { data[i] = (i * 7) & 255; data[i + 1] = (i * 13) & 255; data[i + 2] = (i * 29) & 255; data[i + 3] = 255; }
return { data, width: w, height: h };
},
putImageData() {}, createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }),
};
return ctx;
}
function makeWebGL() {
const ext = { UNMASKED_VENDOR_WEBGL: 37445, UNMASKED_RENDERER_WEBGL: 37446, WEBGL_debug_renderer_info: true };
// 参数与扩展列表按真实浏览器实测镜像(GTX 1060 / NVIDIA / Chrome 153)
const params = {
7936: 'WebKit', 7937: 'WebKit WebGL', 7938: 'WebGL 1.0 (OpenGL ES 2.0 Chromium)',
35724: 'WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)',
37445: (CUR && CUR.glVendor) || '',
37446: (CUR && CUR.glRenderer) || '',
3379: 16384, 34076: 16384, 34930: 16, 35660: 16, 3386: 32767, 3413: 8, 33901: [1024, 1024], 33902: [1, 1],
34921: 16, 36347: 1024, 36348: 32, 36349: 1024, 34024: 16384, 34047: 16, 34852: 16, 34853: 8, 34854: 8,
36006: 4096, 36007: 4096, 35375: [16384, 16384], 35376: 16384, 35661: 32, 32883: 0, 33001: [1, 8192],
};
return {
canvas: { width: (CUR && CUR.screenWidth) || 0, height: (CUR && CUR.screenHeight) || 0 },
drawingBufferWidth: (CUR && CUR.screenWidth) || 0, drawingBufferHeight: (CUR && CUR.screenHeight) || 0, drawingBufferColorSpace: 'srgb', unpackColorSpace: 'srgb',
// WebGL 常量(SDK 用 gl.VERSION / gl.RENDERER 这类常量去 getParameter,缺了会拿到 undefined)
VERSION: 7938, RENDERER: 7937, VENDOR: 7936, SHADING_LANGUAGE_VERSION: 35724, MAX_TEXTURE_SIZE: 3379,
MAX_RENDERBUFFER_SIZE: 34024, MAX_VIEWPORT_DIMS: 3386, MAX_VERTEX_ATTRIBS: 34921, MAX_TEXTURE_IMAGE_UNITS: 34930,
MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660, MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661, MAX_CUBE_MAP_TEXTURE_SIZE: 34076,
MAX_FRAGMENT_UNIFORM_VECTORS: 36349, MAX_VERTEX_UNIFORM_VECTORS: 36347, MAX_VARYING_VECTORS: 36348,
DEPTH_BUFFER_BIT: 256, STENCIL_BUFFER_BIT: 1024, COLOR_BUFFER_BIT: 16384,
getExtension: (n) => (n === 'WEBGL_debug_renderer_info' ? ext : (n === 'EXT_texture_filter_anisotropic' ? { MAX_TEXTURE_MAX_ANISOTROPY_EXT: 34047 } : (n === 'WEBGL_lose_context' ? { loseContext() {}, restoreContext() {} } : {}))),
getSupportedExtensions: () => ['ANGLE_instanced_arrays', 'EXT_blend_minmax', 'EXT_clip_control', 'EXT_color_buffer_half_float', 'EXT_depth_clamp', 'EXT_disjoint_timer_query', 'EXT_float_blend', 'EXT_frag_depth', 'EXT_polygon_offset_clamp', 'EXT_shader_texture_lod', 'EXT_texture_compression_bptc', 'EXT_texture_compression_rgtc', 'EXT_texture_filter_anisotropic', 'EXT_texture_mirror_clamp_to_edge', 'EXT_sRGB', 'KHR_parallel_shader_compile', 'OES_element_index_uint', 'OES_fbo_render_mipmap', 'OES_standard_derivatives', 'OES_texture_float', 'OES_texture_float_linear', 'OES_texture_half_float', 'OES_texture_half_float_linear', 'OES_vertex_array_object', 'WEBGL_blend_func_extended', 'WEBGL_color_buffer_float', 'WEBGL_compressed_texture_s3tc', 'WEBGL_compressed_texture_s3tc_srgb', 'WEBGL_debug_renderer_info', 'WEBGL_debug_shaders', 'WEBGL_depth_texture', 'WEBGL_draw_buffers', 'WEBGL_lose_context', 'WEBGL_multi_draw', 'WEBGL_polygon_mode'],
getParameter: (p) => (p in params ? params[p] : 0),
getShaderPrecisionFormat: () => ({ rangeMin: 127, rangeMax: 127, precision: 23 }),
getContextAttributes: () => ({ alpha: true, antialias: true, depth: true, premultipliedAlpha: true, preserveDrawingBuffer: false, stencil: false }),
createBuffer: () => ({}), createTexture: () => ({}), createProgram: () => ({}), createShader: () => ({}),
getProgramParameter: () => true, getShaderParameter: () => true, getShaderInfoLog: () => '', getProgramInfoLog: () => '',
getUniformLocation: () => ({}), getAttribLocation: () => 0, getError: () => 0,
};
}
// canvas.toDataURL 返回真实浏览器同一套绘制结果的 PNG(按实测镜像,1246 字符)
const REAL_CANVAS_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAADSUlEQVR4AayXTUhUURTHzx2zD01yk2DRx8LJfUO0U4Q2RWBQm4JAwZKCFhVRFJGbMmrXZtCI3LTKICFq0SIh2iki9IEmRCVK5SbMCsum3//p6JvnvPl4M/L/33Puuefe/71n3tw3xiyVSnl80Zuytgp8K44fmNPFXBaxIhgz/fXdMGs5ada8oF5udjLsZzdzxpibcAwUzpgN3jVrv8IksBNGQQ2TdsEtsEDErOXUSmpUYa0g8WYcWcwKVIVtdGvhCig1pUr3SxHWGhJNyPFzEx0d7igWOVqzSot5Nt3swFmzRPlH8PtgMagnOaPk3wn0wIfwHxT2BIQ/EVQBRPmP6LdDbUIb+ImfDzq1xJfzUngf4QxMozYgnI4HrTahDewNDoT067czUAWF9TQX4AG4Dp6HrQUKk+rhNe0rmA81Ol0rWXqwMMuYx+uFo0UKM8Xe0IzDnNBn0kDGRuiHyj5LYD6CMNNsSE0O1uika0mogNmR+VRnz1kd/UEo16ln9dXoJ2kOZkc0Ya2lB1U2G6f/EB2FsphVWIhYai30TU0IpzYwUAfDMFWCcHgVzabPodgIQ5AYLkE4ZE0brzSb7Wb0JRR+09yGTyHQrZaYkXD4k0daOKpDhob1uaavxkCO7vGDizEeruSiV2y7OcuEJ8T0NcVkQNeoBCW8NIDwCdzrsEjo/vZPGaQzBf2QoMT0YlKJfWMIq3eZRldZgWXX/aCTSUhWJ51mCQlJQGI6oQTlMxTEkrDCOvlbnGMwD3TzDZOTFkuLSEi+xLQBUsLgE1aKfr88wBmDKv8+rN5xqoSIv5VYF2MpcobYQU80BoTR8aANqPzP6amef7HwDP4ksWsaUw7hiIjtr7Nfeefq9XqfrDuwPBiIPfvqquI3bcQOs6IEVFFRvmIS1L3cxnh5MGDOHfJK/f6S2239ljQJUFET5esFUz5B4y9piGJ1c8lA507TdkD9OsOUFVqzA1FpeAt7J/Y8Nc7dw+h2T2LLBa3ViKjWXl4zU1hh576QpJ3F6d6Ck7BYaI7mxr21WPP4qFV3jlj87GfTO9NX6uDSzk0w6SLUvwFNDF+Fj+E7qNLpTSDKV0xjymny5jinuRPkmsQqF6zBUlY1x7EU+w8AAP//KN+TZgAAAAZJREFUAwDN3O/Xd4c5tQAAAABJRU5ErkJggg==';
function makeCanvas() {
const canvas = {
width: 300, height: 150, style: {},
setAttribute() {}, appendChild() {}, addEventListener() {}, removeEventListener() {},
};
const gl = makeWebGL();
const ctx2d = makeCanvas2d(canvas);
canvas.getContext = (t) => (/webgl/i.test(t) ? gl : ctx2d);
canvas.toDataURL = () => REAL_CANVAS_PNG;
return canvas;
}
let scriptRunner = null;
let dumpHook = null;
export function setDumpHook(fn) { dumpHook = fn; }
export function setScriptRunner(fn) { scriptRunner = fn; }
function appendNode(c) { if (c && c.tagName === 'SCRIPT' && c.src) loadScript(c); return c; }
// 字体检测依赖 offsetWidth:给元素补上基于 innerHTML 的伪布局度量,让字体探测能"测出"字体
const WIN_FONTS = new Set(['Arial', 'Times New Roman', 'Courier New', 'Verdana', 'Georgia', 'Tahoma', 'Trebuchet MS', 'Comic Sans MS', 'Impact', 'Webdings', 'Wingdings', 'Segoe UI', 'Calibri', 'Cambria', 'Consolas', 'Microsoft YaHei', 'SimSun', 'SimHei', 'KaiTi', 'FangSong', 'Microsoft JhengHei', 'MS Gothic', 'Lucida Console', 'Palatino Linotype', 'Book Antiqua', 'Century Gothic', 'Gabriola', 'Candara', 'Corbel', 'Franklin Gothic Medium', 'Constantia', 'Segoe Print', 'Segoe Script', 'Sylfaen', 'Marlett', 'MS Sans Serif', 'MS Serif', 'Fixedsys', 'System', 'Terminal', 'Modern', 'Roman', 'Script', 'Small Fonts', 'Lucida Sans Unicode']);
function strHash(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return Math.abs(h); }
// 元素宽度:优先按 style.fontFamily 度量(SDK 的字体检测就是给 span 设 fontFamily 再量宽)
// 比例表按真实浏览器对 31 个候选字体的实测宽度镜像(base sans-serif=727)
const FONT_RATIO = { monospace: 468 / 727, serif: 468 / 727, 'sans-serif': 1, Arial: 648 / 727, 'Arial Black': 792 / 727, 'Arial Hebrew': 1, 'Arial MT': 1, 'Arial Narrow': 531 / 727, 'Arial Rounded MT Bold': 1, 'Arial Unicode MS': 1, Cambria: 658 / 727, 'Cambria Math': 658 / 727, 'Comic Sans MS': 619 / 727, Consolas: 515 / 727, Courier: 562 / 727, 'Courier New': 562 / 727, Georgia: 697 / 727, Helvetica: 648 / 727, 'Helvetica Neue': 1, Impact: 614 / 727, 'Microsoft YaHei': 732 / 727, 'PingFang SC': 1, 'Segoe Print': 802 / 727, 'Segoe Script': 815 / 727, 'Segoe UI': 672 / 727, 'Segoe UI Light': 636 / 727, 'Segoe UI Semibold': 694 / 727, 'Segoe UI Symbol': 672 / 727, SimHei: 468 / 727, SimSun: 468 / 727, Tahoma: 654 / 727, 'Times New Roman': 620 / 727, 'Trebuchet MS': 661 / 727, Verdana: 760 / 727 };
function measureElement(el) {
const text = String(el._html || '').replace(/<[^>]*>/g, '').replace(/&[#\w]+;/g, 'x') || 'yodaaaaaaa';
const famRaw = el.style && el.style.fontFamily ? String(el.style.fontFamily) : '';
const size = parseFloat((el.style && el.style.fontSize) || 16) || 16;
if (!famRaw) return measureHtml(el._html);
const fam = famRaw.split(',')[0].replace(/['"]/g, '').trim();
const ratio = fam in FONT_RATIO ? FONT_RATIO[fam] : 1;
return Math.round(51.93 * ratio * (size / 72) * text.length * 100) / 100;
}
function measureHtml(html) { const text = String(html).replace(/<[^>]*>/g, ' ').replace(/&#(\d+);/g, (m, d) => String.fromCharCode(Number(d))).replace(/\s+/g, ' ').trim();
const fam = (String(html).match(/font[^>]*face\s*=\s*['"]?([^'">\s]+)/i) || [])[1] || '';
if (fam === 'monospace') return Math.round(text.length * 9 * 10) / 10;
if (fam === 'sans-serif' || fam === 'serif') return Math.round(text.length * 9 * 10) / 10;
if (WIN_FONTS.has(fam)) return Math.round((8.4 + (strHash(fam) % 7) * 0.1) * text.length * 10) / 10;
return Math.round(text.length * 9 * 10) / 10;
}
// document.createElement('script') + appendChild → 真实拉取并执行,SDK 靠这个加载采集包
function loadScript(el) {
if (!el || !el.src) return;
httpRequest('GET', el.src, { 'user-agent': (CUR && CUR.ua) || '' }).then((r) => {
netLogPush('script ' + el.src + ' -> ' + r.status + ' len=' + r.text.length);
if (r.status === 200 && r.text && scriptRunner) {
try { scriptRunner(r.text, el.src); } catch (e) { netLogPush('script ERR ' + el.src + ' ' + e.message); }
}
if (el.onload) el.onload();
if (el.onreadystatechange) el.onreadystatechange();
});
}
function netLogPush(s) { netLog.push(s); if (process.env.WR_NET_VERBOSE === '1') console.error('[net] ' + s); }
function makeElement(tag) {
if (tag === 'canvas') return makeCanvas();
if (tag === 'audio' || tag === 'video') return { tagName: String(tag).toUpperCase(), canPlayType: () => 'probably', play() {}, load() {}, setAttribute() {}, style: {} };
const el = {
tagName: String(tag).toUpperCase(), style: {}, children: [],
setAttribute(k, v) { if (k === 'src') { el._src = v; loadScript(el); } },
getAttribute: () => null,
appendChild(c) { el.children.push(c); return c; },
addEventListener() {}, removeEventListener() {}, getContext: () => null, value: '',
_html: '',
get innerHTML() { return el._html; },
set innerHTML(v) { el._html = String(v); },
get textContent() { return el._html.replace(/<[^>]*>/g, ''); },
set textContent(v) { el._html = String(v); },
get offsetWidth() { return measureElement(el); },
get offsetHeight() { return el._html ? 16 : 0; },
get clientWidth() { return measureElement(el); },
get scrollWidth() { return measureElement(el); },
get clientHeight() { return el.offsetHeight; },
getBoundingClientRect() { return { width: el.offsetWidth, height: el.offsetHeight, top: 0, left: 0, right: el.offsetWidth, bottom: el.offsetHeight }; },
remove() {}, removeChild() {}, insertBefore(c) { return c; },
};
if (tag === 'script') {
Object.defineProperty(el, 'src', {
set(v) { el._src = v; loadScript(el); },
get() { return el._src || ''; },
});
}
return el;
}
// 最小内存版 IndexedDB:SDK 把指纹(dfp_h5_finger)缓存在这里,缺了它会退化成最短指纹
function makeRequest() {
const req = { result: undefined, error: null, onsuccess: null, onerror: null, readyState: 'pending' };
req._fire = (val) => { req.result = val; req.readyState = 'done'; setTimeout(() => { if (req.onsuccess) req.onsuccess({ target: req }); }, 0); };
req._fail = (e) => { req.error = e; setTimeout(() => { if (req.onerror) req.onerror({ target: req }); }, 0); };
return req;
}
function makeIndexedDB() {
const dbs = new Map();
function makeStore(map) {
return {
put(value, key) { const req = makeRequest(); map.set(key === undefined ? value.id : key, value); req._fire(key); return req; },
add(value, key) { const req = makeRequest(); map.set(key === undefined ? value.id : key, value); req._fire(key); return req; },
get(key) { const req = makeRequest(); req._fire(map.get(key)); return req; },
getAll() { const req = makeRequest(); req._fire([...map.values()]); return req; },
delete(key) { const req = makeRequest(); map.delete(key); req._fire(undefined); return req; },
clear() { const req = makeRequest(); map.clear(); req._fire(undefined); return req; },
count() { const req = makeRequest(); req._fire(map.size); return req; },
openCursor() { const req = makeRequest(); req._fire(null); return req; },
createIndex() { return {}; },
index() { return { get: () => makeRequest(), getAll: () => { const r = makeRequest(); r._fire([]); return r; }, openCursor: () => { const r = makeRequest(); r._fire(null); return r; } }; },
};
}
function makeDb(name) {
let db = dbs.get(name);
if (db) return db;
const stores = new Map();
db = {
name, version: 1, objectStoreNames: { contains: (n) => stores.has(n), length: 0 },
createObjectStore(n, opts) { const map = new Map(); stores.set(n, map); const st = makeStore(map); st.keyPath = (opts && opts.keyPath) || null; return st; },
transaction(names) {
const list = Array.isArray(names) ? names : [names];
const tx = { objectStore: (n) => { if (!stores.has(n)) stores.set(n, new Map()); return makeStore(stores.get(n)); }, oncomplete: null, onerror: null, onabort: null, mode: 'readwrite' };
setTimeout(() => { if (tx.oncomplete) tx.oncomplete(); }, 0);
return tx;
},
close() {}, deleteObjectStore(n) { stores.delete(n); },
onclose: null, onerror: null, onversionchange: null, _stores: stores,
};
dbs.set(name, db);
return db;
}
return {
open(name) {
const req = makeRequest();
const db = makeDb(name);
req.result = db;
setTimeout(() => {
if (req.onupgradeneeded) req.onupgradeneeded({ target: req });
req.readyState = 'done';
if (req.onsuccess) req.onsuccess({ target: req });
}, 0);
return req;
},
deleteDatabase(name) { const req = makeRequest(); dbs.delete(name); req._fire(undefined); return req; },
databases: () => Promise.resolve([...dbs.keys()].map((n) => ({ name: n, version: 1 }))),
};
}
// 音频指纹:OfflineAudioContext 需要正确的 oncomplete/startRendering 语义,否则 SDK 会反复重试
function makeAudioParam(v) { return { value: v, defaultValue: v, setValueAtTime() { return this; }, linearRampToValueAtTime() { return this; }, exponentialRampToValueAtTime() { return this; }, setTargetAtTime() { return this; } }; }
function makeAudioNode() { return { connect() {}, disconnect() {}, start() {}, stop() {}, channelCount: 2, numberOfInputs: 1, numberOfOutputs: 1 }; }
function makeOfflineAudioContext() {
let oacN = 0;
return function OfflineAudioContext(channels, length, sampleRate) {
const ctx = this;
if (process.env.WR_OAC_DBG === '1' && oacN++ < 5) console.error('[OAC] ctor args=', channels, length, sampleRate);
ctx.numberOfChannels = channels || 1;
ctx.length = length || 44100;
ctx.sampleRate = sampleRate || 44100;
ctx.currentTime = 0;
ctx.state = 'suspended';
ctx.destination = makeAudioNode();
ctx.oncomplete = null;
ctx.listener = {};
ctx.createOscillator = () => { const n = makeAudioNode(); n.type = 'sine'; n.frequency = makeAudioParam(1000); return n; };
ctx.createGain = () => { const n = makeAudioNode(); n.gain = makeAudioParam(1); return n; };
ctx.createDynamicsCompressor = () => { const n = makeAudioNode(); n.threshold = makeAudioParam(-24); n.knee = makeAudioParam(30); n.ratio = makeAudioParam(12); n.attack = makeAudioParam(0.003); n.release = makeAudioParam(0.25); return n; };
ctx.createAnalyser = () => { const n = makeAudioNode(); n.fftSize = 2048; n.frequencyBinCount = 1024; n.getFloatFrequencyData = () => {}; n.getByteFrequencyData = () => {}; return n; };
ctx.createBufferSource = () => makeAudioNode();
ctx.createBiquadFilter = () => { const n = makeAudioNode(); n.frequency = makeAudioParam(350); n.Q = makeAudioParam(1); n.type = 'lowpass'; return n; };
ctx.createScriptProcessor = () => makeAudioNode();
ctx.decodeAudioData = () => Promise.reject(new Error('decode error'));
ctx.resume = () => Promise.resolve();
ctx.suspend = () => Promise.resolve();
ctx.startRendering = () => {
if (process.env.WR_OAC_DBG === '1' && oacN < 8) console.error('[OAC] startRendering called');
const buf = {
numberOfChannels: ctx.numberOfChannels, length: ctx.length, sampleRate: ctx.sampleRate,
duration: ctx.length / ctx.sampleRate,
getChannelData: (c) => { const a = new Float32Array(ctx.length); for (let i = 0; i < a.length; i++) a[i] = Math.sin(i * 0.01 + c) * 0.001; return a; },
copyFromChannel() {}, copyToChannel() {},
};
ctx.state = 'closed';
return Promise.resolve(buf).then((b) => { setTimeout(() => { if (ctx.oncomplete) ctx.oncomplete({ target: ctx, renderedBuffer: b }); }, 0); return b; });
};
};
}
function makeStorage() { const m = new Map();
return {
getItem: (k) => (m.has(k) ? m.get(k) : null),
setItem: (k, v) => m.set(k, String(v)),
removeItem: (k) => m.delete(k),
clear: () => m.clear(),
key: (i) => [...m.keys()][i] ?? null,
get length() { return m.size; },
};
}
// WebRTC:SDK 会收 ICE 候选做指纹;候选按真实浏览器实测值镜像(mDNS .local)
function makeRTCPeerConnection() {
const CANDS = [
'candidate:3398552092 1 udp 2113937151 21ba7413-c3fc-4838-aa74-a2d93314734b.local 51283 typ host generation 0 ufrag QIYF network-cost 999',
'candidate:1378190728 1 udp 2113939711 04f0c44d-87bc-4da2-9f6a-1be12e4020ee.local 51284 typ host generation 0 ufrag QIYF network-cost 999',
];
return function RTCPeerConnection() {
const pc = this;
pc.localDescription = null; pc.iceGatheringState = 'new'; pc.connectionState = 'new'; pc.signalingState = 'stable';
pc.onicecandidate = null; pc.onicegatheringstatechange = null;
pc.createDataChannel = () => ({ close() {}, send() {}, addEventListener() {} });
pc.createOffer = () => Promise.resolve({ type: 'offer', sdp: 'v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=ice-ufrag:QIYF\r\na=ice-pwd:abcdefghijklmnopqrstuvwx\r\n' });
pc.setLocalDescription = (d) => {
pc.localDescription = d; pc.iceGatheringState = 'gathering';
setTimeout(() => {
for (const c of CANDS) if (pc.onicecandidate) pc.onicecandidate({ candidate: { candidate: c } });
if (pc.onicecandidate) pc.onicecandidate({ candidate: null });
pc.iceGatheringState = 'complete';
if (pc.onicegatheringstatechange) pc.onicegatheringstatechange();
}, 0);
return Promise.resolve();
};
pc.setRemoteDescription = () => Promise.resolve();
pc.createAnswer = () => Promise.resolve({ type: 'answer', sdp: '' });
pc.addIceCandidate = () => Promise.resolve();
pc.getStats = () => Promise.resolve(new Map());
pc.addEventListener = () => {}; pc.removeEventListener = () => {};
pc.close = () => {};
};
}
function makeSpeechSynthesis() {
const V = [
{ voiceURI: 'Microsoft Huihui - Chinese (Simplified, PRC)', name: 'Microsoft Huihui - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: true },
{ voiceURI: 'Microsoft Kangkang - Chinese (Simplified, PRC)', name: 'Microsoft Kangkang - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: false },
{ voiceURI: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', name: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: false },
];
return { getVoices: () => V.slice(), onvoiceschanged: null, speak() {}, cancel() {}, pause() {}, resume() {}, pending: false, speaking: false, paused: false, addEventListener() {}, removeEventListener() {} };
}
const BASE_BTOA = (s) => Buffer.from(s, 'binary').toString('base64');
function makeTextEncoder() {
return class TextEncoder {
constructor() { this.encoding = 'utf-8'; }
encode(input = '') {
const s = String(input);
if (dumpHook) { try { dumpHook(s); } catch (e) {} }
if (process.env.WR_DUMP_TE === '1' && s.length > 200) {
netLogPush('TE len=' + s.length + ' head=' + JSON.stringify(s.slice(0, 300)));
if (process.env.WR_TE_FILE && s.length > 1000) { try { require('node:fs').appendFileSync(process.env.WR_TE_FILE, s + '\n\n====\n\n'); } catch (e) { /* ignore */ } }
}
return Buffer.from(s, 'utf8');
}
encodeInto(input, dest) { const b = Buffer.from(String(input), 'utf8'); dest.set(b.subarray(0, dest.length)); return { read: input.length, written: Math.min(b.length, dest.length) }; }
};
}
// crypto:SDK 常用 getRandomValues 取 nonce、用 subtle.digest 做摘要;缺了会走降级分支
function makeCrypto() {
const nodeCrypto = require('node:crypto');
return {
getRandomValues: (arr) => { const b = nodeCrypto.randomBytes(arr.length); for (let i = 0; i < arr.length; i++) arr[i] = b[i]; return arr; },
randomUUID: () => nodeCrypto.randomUUID(),
subtle: {
digest: (alg, data) => Promise.resolve(nodeCrypto.createHash(String(alg).replace('-', '').toLowerCase()).update(Buffer.from(data)).digest().buffer),
encrypt: () => Promise.resolve(new ArrayBuffer(16)), decrypt: () => Promise.resolve(new ArrayBuffer(16)),
generateKey: () => Promise.resolve({}), importKey: () => Promise.resolve({}), exportKey: () => Promise.resolve(new ArrayBuffer(32)),
sign: () => Promise.resolve(new ArrayBuffer(32)), verify: () => Promise.resolve(true),
},
};
}
// WebAssembly 最小可用集合(SDK 会探测其存在性/能力)
function makeWebAssembly() {
return {
compile: () => Promise.resolve({}), instantiate: () => Promise.resolve({ instance: { exports: {} }, module: {} }),
validate: () => true, Module: function () {}, Instance: function () {}, Memory: function (d) { this.buffer = new ArrayBuffer((d && d.initial ? d.initial : 1) * 65536); }, Table: function () {},
};
}
// 事件系统:SDK 会注册行为采集监听(click/mousemove/visibility…),
// 只给空 addEventListener 会让行为采集永远收不到事件,bio 上报也不会触发
const eventRegistry = new Map();
let envRef = null;
function addListener(type, fn) { if (typeof fn !== 'function') return; const list = eventRegistry.get(type) || []; if (!list.includes(fn)) list.push(fn); eventRegistry.set(type, list); }
function removeListener(type, fn) { const list = eventRegistry.get(type) || []; const i = list.indexOf(fn); if (i >= 0) list.splice(i, 1); }
export function dispatchEvent(type, extra = {}) {
const tgt = (envRef && envRef.document && envRef.document.body) || { nodeName: 'BODY', tagName: 'BODY' };
const evt = Object.assign({
type, target: tgt, currentTarget: tgt, srcElement: tgt, bubbles: true, cancelable: true, defaultPrevented: false,
timeStamp: Date.now(), isTrusted: true, button: 0, buttons: 0, detail: 1, view: envRef,
composedPath: () => [tgt, envRef && envRef.document, envRef],
preventDefault() {}, stopPropagation() {}, stopImmediatePropagation() {},
}, extra);
for (const fn of [...(eventRegistry.get(type) || [])]) { try { fn(evt); } catch (e) { if (process.env.WR_EVT_DBG === '1') console.error('[evt] ' + type + ' 监听器异常: ' + (e && e.message)); } }
const on = envRef && envRef['on' + type];
if (typeof on === 'function') { try { on(evt); } catch (e) {} }
}
export function installEventTargets(s) {
const t = {
addEventListener: (ty, fn) => addListener(ty, fn),
removeEventListener: (ty, fn) => removeListener(ty, fn),
dispatchEvent: (e) => { dispatchEvent(e && e.type || 'event', e); return true; },
};
Object.assign(s, t);
for (const k of ['document', 'body', 'head', 'documentElement']) {
const o = k === 'document' ? s.document : s.document[k];
if (o && typeof o === 'object') { o.addEventListener = t.addEventListener; o.removeEventListener = t.removeEventListener; }
}
}
export function buildEnv(profile) {
CUR = profile;
const ua = need(profile, 'ua');
const language = need(profile, 'language');
const languages = need(profile, 'languages');
const chBrandsRaw = need(profile, 'chBrands');
const chPlatform = String(need(profile, 'chPlatform')).replace(/"/g, '');
const chMobile = String(need(profile, 'chMobile')).replace('?', '') === '1';
const brands = [...String(chBrandsRaw).matchAll(/"([^"]+)";v="([^"]+)"/g)].map((m) => ({ brand: m[1], version: m[2] }));
const uaFull = (brands.find((b) => /Chromium|Google Chrome|Android WebView/i.test(b.brand)) || brands[0] || {}).version || '';
const arch = profile.architecture || '';
const bitness = profile.bitness || '';
const pVer = profile.platformVersion || '';
const sw = need(profile, 'screenWidth');
const sh = need(profile, 'screenHeight');
const availHeight = need(profile, 'availHeight');
const colorDepth = need(profile, 'colorDepth');
const dpr = need(profile, 'devicePixelRatio');
const origin = need(profile, 'origin');
const originHost = new URL(origin).hostname;
const nav = {
userAgent: ua,
appVersion: ua.replace('Mozilla/', ''),
appName: 'Netscape',
appCodeName: 'Mozilla',
product: 'Gecko',
productSub: '20030107',
vendor: 'Google Inc.',
vendorSub: '',
platform: need(profile, 'platform'),
language: language,
languages: languages,
cookieEnabled: true,
onLine: true,
doNotTrack: null,
webdriver: false,
hardwareConcurrency: need(profile, 'hardwareConcurrency'),
deviceMemory: need(profile, 'deviceMemory'),
maxTouchPoints: need(profile, 'maxTouchPoints'),
pdfViewerEnabled: true,
plugins: {
length: 5, 0: { name: 'PDF Viewer', filename: 'internal-pdf-viewer' }, 1: { name: 'Chrome PDF Viewer' }, 2: { name: 'Chromium PDF Viewer' }, 3: { name: 'Microsoft Edge PDF Viewer' }, 4: { name: 'WebKit built-in PDF' },
item: (i) => null, namedItem: () => null, refresh() {},
},
mimeTypes: { length: 2, 0: { type: 'application/pdf', suffixes: 'pdf' }, 1: { type: 'text/pdf', suffixes: 'pdf' }, item: () => null, namedItem: () => null },
userAgentData: (() => { const j = { architecture: arch, bitness: bitness, brands: brands.map((b) => b.brand + '-' + b.version).join('/'), mobile: chMobile ? 'true' : 'false', model: profile.model || '', pVersion: pVer, uVersion: uaFull, platform: chPlatform }; return { brands, mobile: chMobile, platform: chPlatform, architecture: arch, bitness: bitness, model: profile.model || '', platformVersion: pVer, uaFullVersion: uaFull, fullVersionList: brands.slice(), toJSON() { return j; }, getHighEntropyValues: () => Promise.resolve(j) }; })(),
connection: { effectiveType: '4g', rtt: 50, downlink: 10, saveData: false },
javaEnabled: () => false,
sendBeacon: (u, d) => { netLogPush('beacon ' + u + (d ? ' len=' + String(d).length : '')); return true; },
vibrate: () => false,
getBattery: () => Promise.resolve({ charging: true, chargingTime: 0, dischargingTime: Infinity, level: 1, addEventListener() {}, onchargingchange: null }),
geolocation: { getCurrentPosition: (ok) => ok && ok({ coords: { latitude: 23.12, longitude: 113.28, accuracy: 20 } }), watchPosition: () => 1, clearWatch() {} },
mediaDevices: { enumerateDevices: () => Promise.resolve([{ kind: 'audioinput', deviceId: 'default', groupId: 'g', label: '' }, { kind: 'videoinput', deviceId: 'v1', groupId: 'g', label: '' }]), getUserMedia: () => Promise.reject(new Error('NotAllowedError')) },
mediaCapabilities: { decodingInfo: () => Promise.resolve({ supported: true, smooth: true, powerEfficient: true }) },
permissions: { query: () => Promise.resolve({ state: 'prompt' }) },
storage: { estimate: () => Promise.resolve({ quota: 300000000000, usage: 0 }) },
clipboard: {}, credentials: {}, serviceWorker: {},
userActivation: { isActive: true, hasBeenActive: true },
mediaSession: { metadata: null, playbackState: 'none', setActionHandler() {} },
keyboard: { getLayoutMap: () => Promise.resolve(new Map([['KeyA', 'a'], ['Enter', 'Enter']])), lock: () => Promise.resolve(), unlock() {} },
locks: { request: () => Promise.resolve() },
presentation: { defaultRequest: null, receiver: null },
bluetooth: { getAvailability: () => Promise.resolve(false) },
usb: { getDevices: () => Promise.resolve([]) },
hid: { getDevices: () => Promise.resolve([]) },
serial: { getPorts: () => Promise.resolve([]) },
registerProtocolHandler() {},
msDoNotTrack: null, oscpu: undefined, cpuClass: undefined,
requestMediaKeySystemAccess: () => Promise.resolve({}),
getUserMedia: () => Promise.reject(new Error('NotAllowedError')),
webkitGetUserMedia: () => Promise.reject(new Error('NotAllowedError')),
// 浏览器 navigator 上还有的其余属性(Chrome 153),一并铺上,避免 SDK 探测时拿到 undefined 而跳过
gpu: { requestAdapter: () => Promise.resolve(null), getPreferredCanvasFormat: () => 'bgra8unorm', wgslLanguageFeatures: new Set() },
ink: { requestPresenter: () => Promise.resolve({}) },
login: { setStatus() {}, getStatus: () => Promise.resolve({}) },
managed: { getSupportedCommands: () => Promise.resolve([]) },
protectedAudience: {}, scheduling: { isInputPending: () => false },
serial: { getPorts: () => Promise.resolve([]), requestPort: () => Promise.reject(new Error('no')) },
storageBuckets: { getDirectory: () => Promise.resolve({}) },
virtualKeyboard: { boundingRect: { x: 0, y: 0, width: 0, height: 0 }, overlaysContent: false },
wakeLock: { request: () => Promise.resolve({ release: () => Promise.resolve(), addEventListener() {} }) },
windowControlsOverlay: { visible: false, getTitlebarAreaRect: () => ({ x: 0, y: 0, width: 0, height: 0 }), addEventListener() {} },
xr: { isSessionSupported: () => Promise.resolve(false), addEventListener() {} },
devicePosture: { type: 'continuous', onchange: null },
getGamepads: () => [],
getInstalledRelatedApps: () => Promise.resolve([]),
requestMIDIAccess: () => Promise.resolve({ inputs: new Map(), outputs: new Map(), sysexEnabled: false }),
unregisterProtocolHandler() {}, setAppBadge() {}, clearAppBadge() {},
clearOriginJoinedAdInterestGroups() {}, joinAdInterestGroup() {}, leaveAdInterestGroup() {},
adAuctionComponents() {}, canLoadAdAuctionFencedFrame: () => false, createAuctionNonce: () => '', deprecatedReplaceInURN() {},
deprecatedRunAdAuctionEnforcesKAnonymity: false, deprecatedURNToURL() {}, getInterestGroupAdAuctionData: () => Promise.resolve({}),
runAdAuction: () => Promise.resolve(null), updateAdInterestGroups() {},
webkitPersistentStorage: { queryUsageAndQuota: () => {}, requestQuota: () => {} },
webkitTemporaryStorage: { queryUsageAndQuota: () => {}, requestQuota: () => {} },
};
const screen = {
width: sw, height: sh, availWidth: sw, availHeight: availHeight,
colorDepth: colorDepth, pixelDepth: colorDepth, availLeft: 0, availTop: 0,
orientation: { type: sw >= sh ? 'landscape-primary' : 'portrait-primary', angle: 0, addEventListener() {}, onchange: null },
};
const docEl = { style: {}, clientWidth: sw, clientHeight: availHeight, getBoundingClientRect: () => ({ width: sw, height: availHeight, top: 0, left: 0 }) };
const document = {
cookie: '',
documentElement: docEl, head: { appendChild: appendNode }, body: { appendChild: appendNode, style: {}, removeChild() {}, insertBefore(c) { return c; } },
referrer: need(profile, 'referrer'), title: profile.title || '', characterSet: 'UTF-8', charset: 'UTF-8',
readyState: 'complete', visibilityState: 'visible', hidden: false, hasFocus: () => true,
createElement: makeElement,
createElementNS: (ns, tag) => makeElement(tag),
getElementsByTagName: () => [], getElementsByClassName: () => [], querySelector: () => null, querySelectorAll: () => [],
getElementById: () => null,
addEventListener() {}, removeEventListener() {}, createTextNode: (t) => ({ textContent: t }), createDocumentFragment: () => ({ appendChild() {} }),
fonts: { check: () => true, add() {}, delete() {}, forEach() {}, entries: () => [][Symbol.iterator](), values: () => [][Symbol.iterator](), keys: () => [][Symbol.iterator](), size: 0, ready: Promise.resolve(), status: 'loaded', onloadingdone: null, onloadingerror: null, addEventListener() {}, removeEventListener() {} },
};
const win = {
navigator: nav, screen, document,
location: { href: origin + '/', protocol: 'https:', host: originHost, hostname: originHost, origin: origin, pathname: '/', search: '', hash: '' },
innerWidth: need(profile, 'innerWidth'), innerHeight: need(profile, 'innerHeight'), outerWidth: sw, outerHeight: sh, devicePixelRatio: dpr,
screenX: 0, screenY: 0, screenLeft: 0, screenTop: 0, scrollX: 0, scrollY: 0, pageXOffset: 0, pageYOffset: 0,
localStorage: makeStorage(), sessionStorage: makeStorage(),
indexedDB: makeIndexedDB(),
caches: { open: () => Promise.resolve({ match: () => Promise.resolve(undefined), put: () => Promise.resolve(), addAll: () => Promise.resolve() }), keys: () => Promise.resolve([]), match: () => Promise.resolve(undefined) },
performance: { now: () => Date.now() - 1000, timeOrigin: Date.now() - 1000,
timing: (() => { const base = Date.now() - 3000; const t = {}; let off = 0; for (const k of ['navigationStart','unloadEventStart','unloadEventEnd','redirectStart','redirectEnd','fetchStart','domainLookupStart','domainLookupEnd','connectStart','connectEnd','secureConnectionStart','requestStart','responseStart','responseEnd','domLoading','domInteractive','domContentLoadedEventStart','domContentLoadedEventEnd','domComplete','loadEventStart','loadEventEnd']) t[k] = base + (off += 7) + (k.length % 5); return t; })(),
navigation: { type: 0, redirectCount: 0 },
getEntriesByType: () => [], getEntriesByName: () => [], getEntries: () => [], mark() {}, measure() {}, clearMarks() {}, clearMeasures() {}, memory: { jsHeapSizeLimit: 4395630592, totalJSHeapSize: 30000000, usedJSHeapSize: 20000000 }, getEntriesByType: () => [], getEntries: () => [], mark() {}, measure() {}, clearMarks() {}, now2: () => Date.now() },
XMLHttpRequest: makeXHR(ua),
fetch: makeFetch(ua),
matchMedia: (q) => ({ matches: false, media: q, addListener() {}, removeListener() {}, addEventListener() {}, onchange: null }),
requestAnimationFrame: (cb) => setTimeout(() => cb(Date.now()), 16),
cancelAnimationFrame: (id) => clearTimeout(id),
OfflineAudioContext: makeOfflineAudioContext(),
AudioContext: function () { return new win.OfflineAudioContext(); },
WebGLRenderingContext: function () {}, Image: function () {}, Worker: function () {}, MutationObserver: function () { this.observe = () => {}; this.disconnect = () => {}; },
// 浏览器原生对象:crypto/WebAssembly/各类 Observer 缺了会让 SDK 跳过部分采集
crypto: makeCrypto(),
WebAssembly: makeWebAssembly(),
queueMicrotask: (fn) => { Promise.resolve().then(fn); },
requestIdleCallback: (fn) => setTimeout(() => fn({ didTimeout: false, timeRemaining: () => 50 }), 1),
cancelIdleCallback: (id) => clearTimeout(id),
PerformanceObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.takeRecords = () => []; },
IntersectionObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.unobserve = () => {}; this.takeRecords = () => []; },
ResizeObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.unobserve = () => {}; },
ReportingObserver: function () { this.observe = () => {}; this.disconnect = () => {}; },
BroadcastChannel: function () { this.postMessage = () => {}; this.close = () => {}; this.addEventListener = () => {}; },
MessageChannel: function () { const p = { postMessage() {}, addEventListener() {}, start() {}, close() {} }; this.port1 = p; this.port2 = p; },
CSS: { supports: () => true, escape: (s) => s },
CSSStyleDeclaration: function () {}, HTMLCanvasElement: function () {}, Event: function (t) { this.type = t; }, CustomEvent: function (t) { this.type = t; },
screen_orientation_helper: undefined,
// 能力位图(k8/k100/k101)通常来自 typeof 探测,补齐常见浏览器接口
Audio: function () {}, Blob: class {}, URL: URL, URLSearchParams: URLSearchParams, FormData: class {}, Headers: class {}, Request: class {}, Response: class {}, AbortController: class { constructor() { this.signal = {}; } abort() {} }, EventSource: function () {}, FileReader: class {}, MediaSource: function () {}, SourceBuffer: function () {}, MediaKeys: function () {}, RTCDataChannel: function () {}, RTCRtpSender: function () {}, MediaStreamTrack: function () {}, MediaStream: function () {}, Notification: function () {}, PaymentRequest: function () {}, PublicKeyCredential: function () {}, Credential: function () {}, PointerEvent: function () {}, TouchEvent: function () {}, WheelEvent: function () {}, KeyboardEvent: function () {}, DragEvent: function () {}, DataTransfer: function () {}, ClipboardEvent: function () {}, BeforeUnloadEvent: function () {}, MessageEvent: function () {}, StorageEvent: function () {}, DeviceMotionEvent: function () {}, DeviceOrientationEvent: function () {}, GamepadEvent: function () {}, MediaQueryListEvent: function () {}, TransitionEvent: function () {}, AnimationEvent: function () {}, FocusEvent: function () {}, PopStateEvent: function () {}, HashChangeEvent: function () {}, ProgressEvent: function () {}, ErrorEvent: function () {}, CloseEvent: function () {}, PageTransitionEvent: function () {}, StorageManager: function () {}, Worklet: function () {}, AudioWorkletNode: function () {}, MediaRecorder: function () {}, SpeechRecognition: function () {}, webkitSpeechRecognition: function () {}, SharedWorker: function () {}, webkitMediaSource: function () {}, webkitURL: URL, mozGetUserMedia: undefined,
speechSynthesis: makeSpeechSynthesis(),
SpeechSynthesisUtterance: function (t) { this.text = t; this.lang = ''; this.voice = null; },
RTCPeerConnection: makeRTCPeerConnection(),
webkitRTCPeerConnection: makeRTCPeerConnection(),
addEventListener() {}, removeEventListener() {}, dispatchEvent: () => true, postMessage() {},
getComputedStyle: () => ({ getPropertyValue: () => '' }),
atob: (s) => Buffer.from(s, 'base64').toString('binary'),
btoa: (s) => { if (process.env.WR_DUMP_B64 === '1') { const buf = Buffer.from(String(s), 'binary'); netLog.push('BTOA len=' + buf.length + ' hex=' + buf.slice(0, 48).toString('hex') + ' ascii=' + JSON.stringify(buf.slice(0, 120).toString('utf8'))); } return BASE_BTOA(s); },
setTimeout, clearTimeout, setInterval, clearInterval,
console: { log() {}, warn() {}, error() {}, info() {}, debug() {} },
Date, Math, JSON, Promise, parseInt, parseFloat, isNaN, encodeURIComponent, decodeURIComponent, encodeURI, decodeURI, escape, unescape,
Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, ArrayBuffer, DataView,
// 明文转字节入口:加密前 SDK 必须把明文交给 TextEncoder,钩住它就能拿到明文
TextEncoder: makeTextEncoder(),
TextDecoder, String, Number, Boolean, Array, Object, Function, Error, TypeError, RegExp, Map, Set, WeakMap, WeakSet, Symbol, Proxy, Reflect, BigInt,
};
win.self = win;
win.window = win;
win.globalThis = win;
win.top = win;
win.parent = win;
win.frames = win;
envRef = win;
installEventTargets(win);
return win;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+217
View File
@@ -0,0 +1,217 @@
// 美团小程序 mtgsig —— 纯算法实现(不加载 jsguard 包、不补环境)
// 算法来源:团购 wxde8ac0a21135c07d / wx-jsguard 2.5.0 的静态逆向,各字段均已与 bundle 逐字节对齐
//
// mtgsig 字段:
// a1 = "1.2" a2 = 毫秒时间戳(=q 里的 s)
// a3 = dfpid a4 = 见 buildA4()
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON(qn)) ) a6 = "w1.6"+base64(AES-128-CBC(gzip(9项数组)))
// a7 = appid x0 = 3 d1 = 见 buildD1()
//
// 需要外部给的(算法里算不出来):dfpid / localId / filetime / 46 项设备画像 / 出签会话上下文。
// 这些可以从一份抓包的旧 mtgsig 里解出来(见 /derive),或固定一份真机画像。
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 ----------------
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
export const A6_PREFIX = 'w1.6';
// 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) {
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 A6_PREFIX + Buffer.concat([c.update(Buffer.from(gz)), c.final()]).toString('base64');
}
export function parseA6(a6) {
const buf = Buffer.from(String(a6).slice(A6_PREFIX.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);
}
// ---------------- 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 || '';
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]))
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);x = murmur3(z, a2)
// GET 不带 body;form-POST 用原始 urlencode 串;JSON-POST 用 JSON 串
export function buildZ({ method, url, data, contentType }) {
const u = new URL(url);
const q = [...u.searchParams.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
.map(([k, v]) => k + '=' + v);
const m = String(method || 'POST').toUpperCase();
const head = m + ' ' + u.pathname + ' ' + q.join('&');
const body = data === undefined || data === null ? '' : (typeof data === 'string' ? data : JSON.stringify(data));
const tail = m === 'GET' ? '' : body;
return Buffer.concat([u8(head), u8(tail)]);
}
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;
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 };
+114
View File
@@ -0,0 +1,114 @@
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2537 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2513 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2537 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2537 预热耗时=5.7s
mtgsig 出签服务已启动: http://127.0.0.1:18094 (health: /health)
H5 READY fpLen=2513 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18094 (health: /health)
H5 READY fpLen=2537 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2537 预热耗时=3.6s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
H5 READY fpLen=2537 预热耗时=3.7s
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://127.0.0.1:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
node:internal/modules/esm/resolve:275
throw new ERR_MODULE_NOT_FOUND(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\mjz\Desktop\python\mjz\测试\AI代码\mtgsig_js\h5-pure.mjs' imported from C:\Users\jimmy\PycharmProjects\公司项目\公司项目\美团app城市搜索店铺\区域店铺搜索\搜索时店铺推荐\美团小程序拼好饭搜索\AI代码\mtgsig_js\serve.mjs
at finalizeResolution (node:internal/modules/esm/resolve:275:11)
at moduleResolve (node:internal/modules/esm/resolve:860:10)
at defaultResolve (node:internal/modules/esm/resolve:984:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:780:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:704:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:687:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:305:38)
at onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:643:36)
at TracingChannel.tracePromise (node:diagnostics_channel:344:14)
at ModuleLoader.import (node:internal/modules/esm/loader:642:21) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///C:/Users/mjz/Desktop/python/mjz/%E6%B5%8B%E8%AF%95/AI%E4%BB%A3%E7%A0%81/mtgsig_js/h5-pure.mjs'
}
Node.js v22.15.0
node:internal/modules/esm/resolve:275
throw new ERR_MODULE_NOT_FOUND(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\mjz\Desktop\python\mjz\测试\AI代码\mtgsig_js\h5-pure.mjs' imported from C:\Users\jimmy\PycharmProjects\公司项目\公司项目\美团app城市搜索店铺\区域店铺搜索\搜索时店铺推荐\美团小程序拼好饭搜索\AI代码\mtgsig_js\serve.mjs
at finalizeResolution (node:internal/modules/esm/resolve:275:11)
at moduleResolve (node:internal/modules/esm/resolve:860:10)
at defaultResolve (node:internal/modules/esm/resolve:984:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:780:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:704:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:687:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:305:38)
at onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:643:36)
at TracingChannel.tracePromise (node:diagnostics_channel:344:14)
at ModuleLoader.import (node:internal/modules/esm/loader:642:21) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///C:/Users/mjz/Desktop/python/mjz/%E6%B5%8B%E8%AF%95/AI%E4%BB%A3%E7%A0%81/mtgsig_js/h5-pure.mjs'
}
Node.js v22.15.0
node:internal/modules/esm/resolve:275
throw new ERR_MODULE_NOT_FOUND(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\mjz\Desktop\python\mjz\测试\AI代码\mtgsig_js\h5-pure.mjs' imported from C:\Users\jimmy\PycharmProjects\公司项目\公司项目\美团app城市搜索店铺\区域店铺搜索\搜索时店铺推荐\美团小程序拼好饭搜索\AI代码\mtgsig_js\serve.mjs
at finalizeResolution (node:internal/modules/esm/resolve:275:11)
at moduleResolve (node:internal/modules/esm/resolve:860:10)
at defaultResolve (node:internal/modules/esm/resolve:984:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:780:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:704:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:687:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:305:38)
at onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:643:36)
at TracingChannel.tracePromise (node:diagnostics_channel:344:14)
at ModuleLoader.import (node:internal/modules/esm/loader:642:21) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///C:/Users/mjz/Desktop/python/mjz/%E6%B5%8B%E8%AF%95/AI%E4%BB%A3%E7%A0%81/mtgsig_js/h5-pure.mjs'
}
Node.js v22.15.0
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
mtgsig 出签服务已启动: http://0.0.0.0:18092 (health: /health)
H5 READY[fe_com.sankuai.phf.h5.mp|Mozilla/5.0 (Linux; Android 12; HD1900 Build/SKQ1.211113.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/150.0.7871.189 Mobile Safari/537.36 XWEB/1500213 MMWEBSDK/20260604 MMWEBID/1670 MicroMessenger/8.0.77.3160(0x28004D3A) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 miniProgram/wxde8ac0a21135c07d|Linux armv8l|384|788|3] fpLen=2685 预热=3.6s
+411
View File
@@ -0,0 +1,411 @@
// 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 } 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';
const HERE = path.dirname(fileURLToPath(import.meta.url));
// a6 = "w1.6" + base64(AES-128-CBC(gzip(身份数组))),key/iv 来自 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(4), '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] };
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 || '';
const method = (o.method || 'POST').toUpperCase();
const contentType = o.contentType || (/^\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 反算出的 r;都没有才回退 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,
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 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 页的环境,对应测试.py 里那份 WebView 抓包。H5guard.sign 要用这套 profile。
const PHF_H5_PROFILE = {
ua: 'Mozilla/5.0 (Linux; Android 12; HD1900 Build/SKQ1.211113.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/150.0.7871.189 Mobile Safari/537.36 XWEB/1500213 MMWEBSDK/20260604 MMWEBID/1670 MicroMessenger/8.0.77.3160(0x28004D3A) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 miniProgram/wxde8ac0a21135c07d',
referrer: 'https://i.waimai.meituan.com/',
origin: 'https://i.waimai.meituan.com',
chBrands: '"Not;A=Brand";v="8", "Chromium";v="150", "Android WebView";v="150"',
chPlatform: 'Android',
chMobile: '?1',
language: 'zh-CN',
languages: ['zh-CN', 'zh', 'en-US', 'en'],
platform: 'Linux armv8l',
hardwareConcurrency: 8,
deviceMemory: 8,
maxTouchPoints: 5,
screenWidth: 384,
screenHeight: 788,
availHeight: 788,
colorDepth: 24,
devicePixelRatio: 3,
innerWidth: 384,
innerHeight: 788,
glVendor: 'Qualcomm',
glRenderer: 'Adreno (TM) 640',
appid: 'fe_com.sankuai.phf.h5.mp',
domains: ['i.waimai.meituan.com'],
};
// /sign_h5_pure:加载同目录 H5guard.js,调 H5guard.sign(),把 headers.mtgsig 返回。
async function signH5Pure(o) {
if (!o.url) throw new Error('缺 url');
const st = getH5Profile(o.profile || PHF_H5_PROFILE);
await h5WaitReady(st);
const method = String(o.method || 'POST').toUpperCase();
const signed = await signH5({
url: o.url,
data: o.data || '',
method,
mode: 'sign',
type: method,
dataType: o.dataType || 'text',
cookie: o.cookie || '',
}, st);
const mtgsig = signed && signed.mtgsig;
if (!mtgsig) throw new Error('H5guard.sign 没有返回 mtgsig');
return { mtgsig, D: null, seq: null };
}
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 = await 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)');
});
+366
View File
@@ -0,0 +1,366 @@
// 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 里解出的,没有则用真机观测到的健康值 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 只置 bit0:window 声明但为 falsy、无 globalThis.eval、WeixinJSBridge 存在
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 决定 SDK 把请求体怎么并进签名串:form 走排序键值对,JSON 走原始串
const req = { url, method, header: { 'content-type': contentType }, data };
const out = inst.signWithSiua(req);
return out.header.mtgsig;
},
close() { clearInterval(siuaTimer); },
};
}
+279
View File
@@ -0,0 +1,279 @@
{
"字段": {
"a1": "1.2",
"a2": 1793339512511,
"a3": "9v67307y25u85358y1y9zw93669w76vu8z818043u9377978462uwxz6",
"a4": "d3cb59dd6f1ca0b8dd59cbd3b8a01c6f620f9658daaf8a37",
"a5": "JSfkf+wH8axNgpy524MuRpn1YY4wB16sY3q+zxcAxMcnlHaW4d6H/s2NYVjofHAkOxoaPyBeMFvo5fF9wCb1d+Q8yCBYkPo3m/Q+tkqJp5OERZCXFqeG4iqkziDbo7UFrlxNFnX5VcTU6qqv6xruWt2XARJw6lVq9Zqrai2JYSpQFnbHg06rRF3Aa/ucyKptCZF+zfAevB0pyW44jNE1l4kGbpvqYNFQ+Tho3UvojSc0E1biIbQxoEbSG9/YF+jqyvlM2K9ABJkFgBlK2haybq82w42IRPH9h9vo+5ihfeEcU83YemzW8rMHjnIUY/OWTmb0l5c=",
"a6": "w1.6M5eQZ6Ej+qKlesiYotUiKjLSRSjW/jYxgb6YW6ckYKjkB+guB2tfhO7tS/PVKwzzvN6EMZnC71R7ypLdUSOEqZdbNQmVdeS4kc/Z2HKzhsOwHCQFw5TxvBuS9d3BRpRpZSwxYMVeAUy2NsCu+c6u4YFdlpZZ/3kxquhOSo4IZ4zZtFaBeEzbXPgJAIt82lWfs6ns2Lq1PjZ6WD7ndR/zvxLQBYw3NLDWZdS6yFlS0z3/ayZUVu/M9/R0ggltty+ort7Jti6Dj4AGel/W82QqX+FPu5o7/gFwc2jYl1mPbc2ZJU/dXf6Ie0oF3gIMon2ePrhalxHCPu6014wQB2gnATYTt1zcukw2a7+irCm43ROmXxNQHrLNMyuyfAlpULSPMps8rPIXV2kcF9K87sWMFISDARxoulGWWlY0zAuBGoL9Xp28MccUGCNjZr+Y0G0Pzw2WVKxvVWyacnyhrKsP1XHiZiMLnVYCspQh+Isci0+7YPopRuUJEQwiGoteQHyd3Glge0RoMb7An5o1dQLImEOyceWaAOYj9Cio5HjJeXR/7MrCwCTPDyMeyUi4oPwYTk+NPz/TRHj418F4fBp+5eVoY16yf7Zst3tfMr+6RIqdBZzNXrqjN6xoyx2dJGRqlxymbE5iZK/G1L5K2r+8DRI+Xl1B8cYhMkrbbBYcYxo6U9ZXBDsLxpgKmdHohrVp",
"a7": "wx92916b3adca84096",
"x0": 3,
"d1": "57e575c90db882ff7bf097966ab4e7f1"
},
"a2时间": 1793339512.511,
"a6身份": {
"gzip头": {
"mtime": 1793339513,
"os": 3
},
"system": {
"accelerometer": [
[
"-0.982",
"-0.001",
"0.004"
],
[
"-0.980",
"-0.002",
"0.001"
],
[
"-0.984",
"0.000",
"0.006"
],
[
"-0.985",
"0.002",
"0.001"
],
[
"-0.985",
"0.000",
"0.001"
],
[
"-0.983",
"0.001",
"0.004"
],
[
"-0.985",
"0.000",
"0.001"
],
[
"-0.986",
"0.001",
"0.002"
],
[
"-0.983",
"0.001",
"0.004"
],
[
"-0.985",
"0.004",
"0.003"
],
[
"-0.988",
"-0.000",
"0.004"
],
[
"-0.982",
"-0.001",
"0.004"
],
[
"-0.985",
"-0.001",
"0.004"
],
[
"-0.986",
"-0.001",
"0.003"
],
[
"-0.984",
"0.001",
"0.003"
],
[
"-0.985",
"-0.001",
"0.005"
],
[
"-0.988",
"0.001",
"0.004"
],
[
"-0.980",
"0.001",
"0.001"
],
[
"-0.983",
"0.000",
"0.004"
],
[
"-0.988",
"-0.002",
"0.001"
],
[
"-0.985",
"0.000",
"0.004"
]
],
"albumAuthorized": null,
"BatteryInfo": [
"getBatteryInfo:ok",
true,
37
],
"batteryLevel": null,
"Beacons": "[]",
"benchmarkLevel": -1,
"bluetoothEnabled": true,
"brand": "samsung",
"brightness": 0.8509804,
"cameraAuthorized": false,
"compass": [
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000",
"0.000"
],
"deviceOrientation": "portrait",
"devicePixelRatio": 3,
"enableDebug": false,
"errMsg": "getSystemInfo:ok",
"fontSizeSetting": 16,
"language": "zh_CN",
"LaunchOptionsSync": {
"path": "pages/index/index",
"scene": 1106
},
"locationAuthorized": false,
"locationEnabled": true,
"locationReducedAccuracy": null,
"microphoneAuthorized": false,
"model": "SCG17",
"networkType": "wifi",
"notificationAlertAuthorized": null,
"notificationAuthorized": false,
"notificationBadgeAuthorized": null,
"notificationSoundAuthorized": null,
"pixelRatio": 3,
"platform": "android",
"safeArea": [
0,
360,
26,
785,
360,
759
],
"screenHeight": 785,
"screenTop": null,
"screenWidth": 360,
"SDKVersion": "3.9.3",
"statusBarHeight": 26,
"system": "Android 13",
"version": "8.0.61",
"wifiEnabled": true,
"WifiInfo": null,
"windowHeight": 785,
"windowWidth": 360,
"screenRecord": null,
"isPrivacy": 1,
"hasSystemProxy": 0,
"captureRecord": "[]"
},
"ext": {
"NativeClient存在": 0,
"addEventListener存在": 0,
"getPublicLibVersion(1一致/0不一致/2空对象)": 1,
"__WeixinJSBridge存在": 0,
"NFC(1成功/2未开/3无NFC/4canIUse假)": 0
},
"app(appid)": "wx92916b3adca84096",
"dfpid": "9v67307y25u85358y1y9zw93669w76vu8z818043u9377978462uwxz6",
"filetime(USER_DATA_PATH 最后修改ms)": 1793175415990,
"fpv(jsguard版本)": "2.5.0",
"localid(时间戳+7随机大写+md5)": "1793175415990WOOQMOW60e593ce0a815b08d658526270cd17d68449",
"timestamp(秒)": 1793339513,
"sessionId": "bf348db3ceff493bbe59d7f13d0e513100"
},
"a5上下文": {
"qn": {
"b7": {
"值": 1793338367,
"含义": "会话起始秒(init 时写入)"
},
"b1": {
"值": {
"miniProgram": {
"appId": "wx92916b3adca84096",
"envVersion": "release",
"version": "7.34.0"
}
},
"含义": "getAccountInfoSync(含小程序版本)"
},
"b6": {
"值": "oV_5G45hjOMCkAHfx2KRzbzLJeuA",
"含义": "openId(账号身份)"
},
"b8": {
"值": 2,
"含义": "出签序号(同一实例自增)"
},
"b12": {
"值": "wx92916b3adca84096",
"含义": "appid"
},
"b2": {
"值": "pages/categorySkuList/index",
"含义": "当前路由 getCurrentPages().route"
},
"b9": {
"值": "22122",
"含义": "开关位图 En.join(真机健康值 22122)"
}
},
"自查": {
"r(防篡改位图)": 0,
"y[0:7]==md5(a6)前7字节": true,
"y[8:12]==a2低32位": true,
"y[12:16]==crc32(y前12字节)": true
}
},
"a4结构": {
"x=murmur3(方法+路径+query+body)": "0xd3cb59dd",
"_=murmur3(a5字符串)": "0x6f1ca0b8",
"a2低32位(=x^此行)": "0x8b5d56bf",
"结构自校验": {
"b[8:12]==LE32(x)": true,
"b[12:16]==LE32(_)": true,
"b[16:20]==LE32(x^a2低32)": true,
"b[20:24]==LE32(x^_^a2低32)": true
}
}
}
+185
View File
@@ -0,0 +1,185 @@
{
"字段": {
"a1": "1.2",
"a2": 1792843966200,
"a3": "15620x4013z9595yz764689y33y967w980u67682zy27797815zwyu1z",
"a4": "fa35428ef505b6888e4235fa88b605f576a4e697fe12e362",
"a5": "b8voZr6GzqRTFXJh+YvTS3TRBe14Svy016bTMu5i64QUKaxCEQM0Xj2/OTljmvczf1MQPQEsEHD7G9jnkf6KPKyHSMoG1VNoVDXZhNwnOnMGQGvOsEZ3vIna4h97FTEnFHK1HTvTOzXnQZvyqabjEpPjwfqi2YnICVs52axGPkhX+gSVNp2oVJCIMlzZ04Wgyhg31yVTtNoZszFJeS94QurP5TJ/USfFE7mxCMYT+BgZcblsGokL2xWcjsjGYKDIufEa86E3ZiXDv8UlytvP55yj3WlyrAcAh5rTBL018c466ey6+LJBNLhQqHx4/AKxA/S5EypaqkKqM1nHobOmCKHTR6rVjc6Ob6zd4oHDLpYQJknYEXru7VQPhxnUcJThmpghvIp6w6kAbj4s7oKEq39Rhl/2aXEhSvzm",
"a6": "w1.6fCnCSYaid3KzV7QZ7uYFj96vL1Zup+oDmh1KHpJqKZlTGnFceFiru5rNVEAFSWf+uCgXdL1gLZwjzM+Pa3epkBxX82ucIGmzMW1LFeEzS2MVNceT9zFX1df2j/+F40LlQHnch3qTGwGAZ89TZ/leFlbiyzSKXrRMiwbPyI0fPvUlNLcVRs7fp0+92Jzh+8iwCVuhdaja6BvzPikudrXvgowzPKu2ipQn+mDwfV4E8npL6ylUtOqIAt9u6gBBJ08KDDcXCzYkGXOB1Ywt+G38K/lZOGRUjAGLJr1MQvj9gKWUtGPxQKLPOKF6JZfdiT2G+fuFhqKlo9nPfcDeSQ8Hrnirt0aGVdFROkB0dZo7fadu2cWyxxNmTEdUdmqE+wW96z/PWG3BkaJ9FVQ0XRJKhnuQv/3b8yoCad9rR+7ftgxwu1a4QD51xQ1rXgbzu4qVQBppSfOfpNlE9tUfIS+WBl7h3OMc+2kZ+PZYjgd5ykC5+08MijcubaEJGsp0TefqQ9i79LDDZVFOriGsdcqrX87bGvt/ug4amL3y+d+8goRnmuXuiLQTphbCv4aAKrWzzik3/izCdWQ+/2rHqUypp9XJ7RbQ3O8PSHI1p1bTsxMRdU+wjZmdn7YkxdZgq3Ix",
"a7": "wxde8ac0a21135c07d",
"x0": 3,
"d1": "5056a6daec8f2b7cb89e436a3f2f6b50"
},
"a2时间": 1792843966.2,
"a6身份": {
"gzip头": {
"mtime": 1792843958,
"os": 3
},
"system": {
"accelerometer": [
[
"0.003",
"-0.525",
"-0.839"
],
[
"0.186",
"-0.623",
"-0.735"
]
],
"albumAuthorized": null,
"BatteryInfo": [
"getBatteryInfo:ok",
false,
99
],
"batteryLevel": null,
"Beacons": "[]",
"benchmarkLevel": -1,
"bluetoothEnabled": false,
"brand": "samsung",
"brightness": 0.51978505,
"cameraAuthorized": true,
"compass": [
"0.000",
"0.000"
],
"deviceOrientation": "portrait",
"devicePixelRatio": 2.75,
"enableDebug": false,
"errMsg": "getSystemInfo:ok",
"fontSizeSetting": 16,
"language": "zh_CN",
"LaunchOptionsSync": {
"path": "index/pages/mt/mt",
"scene": 1089
},
"locationAuthorized": true,
"locationEnabled": true,
"locationReducedAccuracy": null,
"microphoneAuthorized": false,
"model": "SM-W9026",
"networkType": "wifi",
"notificationAlertAuthorized": null,
"notificationAuthorized": true,
"notificationBadgeAuthorized": null,
"notificationSoundAuthorized": null,
"pixelRatio": 2.75,
"platform": "android",
"safeArea": [
0,
393,
0,
826,
393,
826
],
"screenHeight": 826,
"screenTop": null,
"screenWidth": 393,
"SDKVersion": "3.17.4",
"statusBarHeight": 35,
"system": "Android 11",
"version": "8.0.79",
"wifiEnabled": true,
"WifiInfo": [
"ZTE-Orbitbyte",
"e4:4e:12:af:08:68",
null,
99,
null,
null,
5240
],
"windowHeight": 826,
"windowWidth": 393,
"screenRecord": null,
"isPrivacy": 1,
"hasSystemProxy": 0,
"captureRecord": "[]"
},
"ext": {
"NativeClient存在": 0,
"addEventListener存在": 0,
"getPublicLibVersion(1一致/0不一致/2空对象)": 1,
"__WeixinJSBridge存在": 0,
"NFC(1成功/2未开/3无NFC/4canIUse假)": 0
},
"app(appid)": "wxde8ac0a21135c07d",
"dfpid": "15620x4013z9595yz764689y33y967w980u67682zy27797815zwyu1z",
"filetime(USER_DATA_PATH 最后修改ms)": 1783253528678,
"fpv(jsguard版本)": "2.5.0",
"localid(时间戳+7随机大写+md5)": "1783253528678UYUUIQU60e593ce0a815b08d658526270cd17d61761",
"timestamp(秒)": 1792843959,
"sessionId": "a44f628b0df34b8fa0120e0124c9a71f00"
},
"a5上下文": {
"qn": {
"b7": {
"值": 1792843948,
"含义": "会话起始秒(init 时写入)"
},
"b1": {
"值": {
"miniProgram": {
"appId": "wxde8ac0a21135c07d",
"envVersion": "release",
"version": "10.42.0"
}
},
"含义": "getAccountInfoSync(含小程序版本)"
},
"b6": {
"值": "oJVP50CSfX4PXW41G80sCghTSCzQ",
"含义": "openId(账号身份)"
},
"b8": {
"值": 47,
"含义": "出签序号(同一实例自增)"
},
"b12": {
"值": "wxde8ac0a21135c07d",
"含义": "appid"
},
"b2": {
"值": "sub_medicine2/medicine2/pages/wmp/drug-poi/poi",
"含义": "当前路由 getCurrentPages().route"
},
"b9": {
"值": "22132",
"含义": "开关位图 En.join(真机健康值 22122)"
},
"b11": {
"值": "25_25_0",
"含义": "定位精度串 accuracy_hacc_vacc"
},
"b10": {
"值": [
"1792843963092",
3,
600001
],
"含义": "失败上报数组(有才出现)"
}
},
"自查": {
"r(防篡改位图)": 0,
"y[0:7]==md5(a6)前7字节": true,
"y[8:12]==a2低32位": true,
"y[12:16]==crc32(y前12字节)": true
}
},
"a4结构": {
"x=murmur3(方法+路径+query+body)": "0xfa35428e",
"_=murmur3(a5字符串)": "0xf505b688",
"a2低32位(=x^此行)": "0x6dd3e6f8",
"结构自校验": {
"b[8:12]==LE32(x)": true,
"b[12:16]==LE32(_)": true,
"b[16:20]==LE32(x^a2低32)": true,
"b[20:24]==LE32(x^_^a2低32)": true
}
}
}
+184
View File
@@ -0,0 +1,184 @@
import re
import pymysql
class All_Setting():
def __init__(self,host,port,db):
self.host = host
self.port = port
self.db = db
def remove_symbols(self,text):
pattern = re.compile(r'[^\w\s]')
return pattern.sub('', text)
def get_chinese(self,text,printTxt=False):
# text = "海王星辰(广州智慧城店)"
pattern = r'[^\w\s]'
result = re.sub(pattern, '', text)
if printTxt:
print(result)
return result
def get_shoppingmalls(self,sql):
res_list = []
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
if conn:
print('ok')
cursor = conn.cursor()
res = cursor.execute(sql)
c2 = cursor.fetchall()
return c2
def write_data(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data_many(self,sql, values):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql, values)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def write_data_one(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def get(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
conn.close() # 添加连接关闭
return result
import json
import time,requests
def get_sign_meituan(url, dfpid, data):
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
print(response1.text)
mtgsig1 = response1.json()
return str(mtgsig1)
def get_sign_waimai(url, dfpid, data):
print('我是外卖mtg')
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
# "ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.request("POST", url_mtg, headers=headers, data=payload)
mtgsig = response.json()
print(mtgsig)
return str(mtgsig)
def get_Datatext(dataq):
str1 = ''
for i in dataq:
key, value = i, dataq[i]
str2 = f'{key}={value}&'
str1 = str1 + str2
data = str1[0:-1]
return data
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+90
View File
@@ -0,0 +1,90 @@
# 启动 mtgsig 出签常驻服务(幂等:已在跑就不重复起)
import os
import sys
import time
import subprocess
import requests
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
JS_DIR = os.path.join(BASE_DIR, 'mtgsig_js')
PORT = int(os.environ.get('MTGSIG_PORT', 18092))
BASE_URL = 'http://127.0.0.1:%d' % PORT
# BASE_URL = 'http://192.168.1.139:%d' % PORT
LOG_PATH = os.path.join(JS_DIR, 'serve.log')
PROXY = {'http': None, 'https': None}
def is_ready():
try:
r = requests.get(BASE_URL + '/health', timeout=3, proxies=PROXY)
return r.status_code == 200 and r.json().get('ok')
except Exception:
return False
def start():
if is_ready():
print('出签服务已在运行: %s' % BASE_URL)
return
log = open(LOG_PATH, 'a', encoding='utf-8')
flags = 0
if os.name == 'nt':
flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
subprocess.Popen(
['node', 'serve.mjs'],
cwd=JS_DIR,
stdout=log,
stderr=log,
creationflags=flags,
)
for _ in range(60):
time.sleep(1)
if is_ready():
print('出签服务已就绪: %s' % BASE_URL)
return
print('等服务起来超时,看日志: %s' % LOG_PATH)
sys.exit(1)
def find_pids_on_port():
"""按端口找出正在监听的进程号(重启用)"""
out = subprocess.run(['netstat', '-ano', '-p', 'tcp'], capture_output=True, text=True).stdout
pids = set()
for line in out.splitlines():
parts = line.split()
if len(parts) >= 5 and parts[1].endswith(':%d' % PORT) and parts[3].upper() == 'LISTENING':
pids.add(parts[4])
return pids
def stop():
"""杀掉监听该端口的出签服务(重启用)"""
pids = find_pids_on_port()
if not pids:
print('出签服务没在运行: %s' % BASE_URL)
return
for pid in pids:
subprocess.run(['taskkill', '/F', '/PID', pid], capture_output=True, text=True)
for _ in range(20):
time.sleep(0.5)
if not find_pids_on_port():
print('出签服务已停止: %s' % BASE_URL)
return
print('停止超时,端口仍被占用: %s' % BASE_URL)
sys.exit(1)
def restart():
"""重启:先杀掉旧的,再重新起一个(改了 serve.mjs 后用这个)"""
stop()
start()
if __name__ == '__main__':
mode = 'restart'
if mode == 'restart':
restart()
elif mode == 'stop':
stop()
else:
start()
+122
View File
@@ -0,0 +1,122 @@
# 美团小程序 mtgsig 出签客户端(本地补环境,不依赖浏览器/远端签名服务)
# 依赖常驻服务 mtgsig_js/serve.mjs,先跑 启动出签服务.py
import json
import urllib.parse
import requests
BASE_URL = 'http://127.0.0.1:18092'
SIGN_TIMEOUT = 60
PROXY = {'http': None, 'https': None}
def get_Datatext(dataq):
data = urllib.parse.urlencode(dataq)
return data
def check_health():
r = requests.get(BASE_URL + '/health', timeout=5, proxies=PROXY)
r.raise_for_status()
return r.json()
def derive_from_mtgsig(mtgsig):
"""从一份 mtgsig(抓包里的旧签名即可)解出会话身份:appid / dfpid / localId / filetime"""
r = requests.post(BASE_URL + '/derive', json={'mtgsig': mtgsig}, timeout=SIGN_TIMEOUT, proxies=PROXY)
r.raise_for_status()
return r.json()
def get_mtgsig(url, data, mtgsig, open_id, method, mode=None, sys=None, ext=None, r=None):
"""按 url + body 出 mtgsig(url/data/mtgsig/open_id 必传)。
mtgsig 传抓包里的旧签名,appid/dfpid/localId/filetime 会从它的 a6 里自动解出;
open_id 传请求头里的 openId(a6 里要带账号身份,缺了签名不对)。
method 默认 POST;请求体按 x-www-form-urlencoded 处理(美团小程序绝大多数接口如此)。
mode: 不传即走**纯算**(无预热、毫秒级);传 'bundle' 才用补环境跑 jsguard(每个新身份首次约 20s)。
sys/ext: 按字段名覆盖 a6 里的 system(46 项)/ext(5 项),只传要改的那几个,不传就原样。
sys 常用字段: brand/model/system/SDKVersion/version/screenWidth/screenHeight/pixelRatio/
brightness/fontSizeSetting/language/networkType/wifiEnabled/hasSystemProxy/
locationEnabled/bluetoothEnabled/deviceOrientation/LaunchOptionsSync 等(共 46 个,
完整清单见 serve.mjs 的 SYSTEM_FIELDS)
ext 字段: NativeClient / addEventListener / getPublicLibVersion / __WeixinJSBridge / NFC
仅纯算生效;字段名写错服务端会直接报错(并回可用字段名)。
同一个小程序下换任意接口都通用,只换 url + data 即可。
data 传字典时按 x-www-form-urlencoded 自动拼成 k=v&k=v;传字符串则原样使用。
"""
# if isinstance(data, dict):
# import traceback
# traceback.print_exc()
body = {'url': url, 'data': data, 'mtgsig': mtgsig, 'openId': open_id, 'method': method}
if mode:
body['mode'] = mode
if sys is not None:
body['sys'] = sys
if ext is not None:
body['ext'] = ext
if r is not None:
body['r'] = r
try:
resp = requests.post(BASE_URL + '/sign', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()['mtgsig']
def get_h5_sign(url, data, method, mode, profile, cookie='', data_type='json', type=None):
"""H5 出签(走服务里的 H5guard 补环境,非小程序 jsguard),返回整个结果 dict:
{mtgsig, url, headers, mode, a3, a6pfx}
url / data / method / mode / profile 必传(profile 缺字段服务端直接报错)。
profile = 设备/请求环境,全部来自抓包请求(没有内置默认身份):
ua, referrer, origin, chBrands(sec-ch-ua 原串), chPlatform(sec-ch-ua-platform),
chMobile(sec-ch-ua-mobile), language, languages(数组), platform, hardwareConcurrency,
deviceMemory, maxTouchPoints, screenWidth, screenHeight, availHeight, colorDepth,
devicePixelRatio, innerWidth, innerHeight, glVendor, glRenderer, appid, domains(数组)
可选: title / model / architecture / bitness / platformVersion
mode='sign':走手动 sign(),a6 前缀 h1.9 —— 外卖/买药 H5 页面自身 jquery 加签走这条。
mode='xhr':走 SDK 自己的 XHR 自动加签,a6 前缀 hs1.6 —— maf.meituan.com 这类接口要这个;
GET -> 用返回的 `url`(mtgsig 已拼进 query);POST -> 也用返回的 `url`。
cookie 可选(dfpid 走 mtgsig.a3)。服务按 profile 缓存环境,每个新 profile 首次等指纹预热。
"""
body = {'url': url, 'data': data, 'method': method, 'mode': mode, 'profile': profile,
'cookie': cookie, 'dataType': data_type, 'type': type or method}
try:
resp = requests.post(BASE_URL + '/sign_h5', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('H5 出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()
def get_h5_mtgsig(url, data, method, mode, profile, cookie='', data_type='json', type=None):
"""只要 mtgsig 值本身时用这个(= get_h5_sign(...)['mtgsig'])。"""
return get_h5_sign(url=url, data=data, method=method, mode=mode, profile=profile, cookie=cookie, data_type=data_type, type=type)['mtgsig']
def get_h5_mtgsig_pure(url, data, mtgsig, method='POST', origin_url=None, origin_data=None, cookie=''):
"""外卖 H5(h1.9) 出签—— 走服务里的 /sign_h5_pure,服务调 H5guard.sign 后返回 mtgsig。
url/data/method 是要出签的请求。data 是 form body 串,必须和实际 POST 的字节一致。
cookie 传抓包 Cookie,让 a3 跟 WEBDFPID 对齐。mtgsig 仍要传,服务用来认这是 H5 请求。
"""
body = {'url': url, 'data': data, 'mtgsig': mtgsig, 'method': method}
if origin_url is not None:
body['origin_url'] = origin_url
if origin_data is not None:
body['origin_data'] = origin_data
if cookie:
body['cookie'] = cookie
try:
resp = requests.post(BASE_URL + '/sign_h5_pure', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('H5 纯算出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()['mtgsig']
if __name__ == '__main__':
print(json.dumps(check_health(), ensure_ascii=False))
+51
View File
@@ -0,0 +1,51 @@
# 从小程序包缓存里提取签名 SDK(jsguard)到 mtgsig_js/
# 用法: python 提取jsguard.py [appid ...] 不带参数 = 提取本机所有已缓存的小程序
# 前提:该小程序在 PC 微信里被打开过(package 会缓存到 WMPF 的 applet/packages)
import os
import sys
import glob
import shutil
import tempfile
import subprocess
WECHAT_USERS = os.path.expandvars(r'%APPDATA%\Tencent\xwechat\radium\users')
UNVEILR = r'C:\Users\mjz\Downloads\unveilr.exe'
OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mtgsig_js')
def find_packages():
pkgs = {}
for appid_dir in glob.glob(os.path.join(WECHAT_USERS, '*', 'applet', 'packages', '*')):
appid = os.path.basename(appid_dir)
versions = sorted(d for d in glob.glob(os.path.join(appid_dir, '*')) if os.path.isdir(d))
if versions:
pkgs[appid] = versions[-1] # 取最大版本号
return pkgs
def extract(appid, pkg_dir):
tmp = tempfile.mkdtemp(prefix='jsg_')
try:
subprocess.run([UNVEILR, 'wx', '-o', tmp, '-d', '2', pkg_dir],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
hits = glob.glob(os.path.join(tmp, '**', 'wx-jsguard', 'dist', 'jsguard.js'), recursive=True)
if not hits:
print(' %s 里没有 jsguard(可能不是美团小程序)' % appid)
return False
dst = os.path.join(OUT_DIR, 'jsguard-%s.js' % appid)
shutil.copy(hits[0], dst)
print(' 已提取 %s -> %s (%d 字节)' % (appid, dst, os.path.getsize(dst)))
return True
finally:
shutil.rmtree(tmp, ignore_errors=True)
if __name__ == '__main__':
pkgs = find_packages()
targets = sys.argv[1:] or sorted(pkgs)
for appid in targets:
if appid not in pkgs:
print(' 跳过 %s:本机没有它的包缓存(先在 PC 微信里打开一次这个小程序)' % appid)
continue
print('处理 %s (%s)' % (appid, pkgs[appid]))
extract(appid, pkgs[appid])
File diff suppressed because one or more lines are too long
+78
View File
@@ -0,0 +1,78 @@
# 美团 mtgsig 纯算出签示例(H5 h1.9/hs1.6 + 小程序)
# 纯算:拿一份抓包 mtgsig 推会话,按新 url+data 重出签;毫秒级,不跑 SDK
# 依赖 18092 常驻服务(客户端在同目录 小程序mtgsig.py),先跑:python 启动出签服务.py
import json
import re
from urllib.parse import urlsplit, parse_qsl, urlencode
from 小程序mtgsig import get_mtgsig, get_h5_mtgsig_pure
# 抓包文件(换成你自己的)
cap_xcx = r'C:\Users\mjz\Desktop\python\8_便利店全店\headers_data\美团地址搜索_20260603\1780484974177\1780484974177_美团地址搜索\request.json' # 小程序 w1.6
cap_h19 = r'C:\Users\mjz\Desktop\python\8_便利店全店\headers_data\店铺详情20261012\1789376979325KUSKGKOe67dcc3e61b3db1bf3f9e3b1c7aaaa883268\美团-买药接口\美团-买药接口' # H5 h1.9,mtgsig 在 header
cap_hs16 = r'C:\Users\mjz\Desktop\python\8_便利店全店\headers_data\店铺资质20261014\1789969535481QOGEWOKe67dcc3e61b3db1bf3f9e3b1c7aaaa887742\qualification\qualification' # H5 hs1.6,mtgsig 在 url query
def read_packet(path):
# 抓包 -> headers / url / data / method / 旧 mtgsig
cap = json.load(open(path, encoding='utf-8'))
headers = cap['headers']
url = cap['url']
method = cap['method']
data = cap['data']
if isinstance(data, dict):
data = urlencode(data) # dict -> 表单串
if 'mtgsig' in headers:
mtgsig = headers['mtgsig'] # 页面 ajax:在 header
else:
mtgsig = dict(parse_qsl(urlsplit(url).query, keep_blank_values=True))['mtgsig'] # 小程序 xhr:在 url query
return headers, url, data, method, mtgsig
def replace_data(data, change):
# 改表单参数:替换指定 key,其余原样保留
for k, v in change.items():
pattern = r'(^|&)' + k + r'=[^&]*'
if re.search(pattern, data):
data = re.sub(pattern, lambda m: m.group(1) + k + '=' + v, data)
else:
data = data + '&' + k + '=' + v
return data
def get_xcx_mtgsig(cap_path, data2=None):
# 小程序(jsguard) 出签;openId 取不到就留空(服务会退回 a6 里的身份)
headers, url, data, method, mtgsig = read_packet(cap_path)
if data2 is None:
data2 = data
if 'openId' in headers:
open_id = headers['openId']
else:
open_id = ''
return get_mtgsig(url=url, data=data2, mtgsig=mtgsig, open_id=open_id, method=method)
def get_h5_mtgsig(cap_path, data2=None):
# H5 出签(h1.9 / hs1.6 同一入口);原 url/data 当 origin 传进去(derive 只认原始包)
headers, url, data, method, mtgsig = read_packet(cap_path)
if data2 is None:
data2 = data
return get_h5_mtgsig_pure(url=url, data=data2, mtgsig=mtgsig, method=method, origin_url=url, origin_data=data)
if __name__ == '__main__':
# 1) 小程序:直接出一版
sig = get_xcx_mtgsig(cap_xcx)
print('小程序:', json.loads(sig)['a6'][:6], sig)
# 2) H5 h1.9:改坐标再出签
headers, url, data, method, mtgsig = read_packet(cap_h19)
data2 = replace_data(data, {'wm_longitude': '113310000', 'wm_latitude': '23140000'})
sig = get_h5_mtgsig(cap_h19, data2)
print('H5 h1.9:', json.loads(sig)['a6'][:6], sig)
# 3) H5 hs1.6:改坐标再出签;这份包 mtgsig 拼进 url query 时要整体编码:'mtgsig=' + quote(sig, safe='')
headers, url, data, method, mtgsig = read_packet(cap_hs16)
data2 = replace_data(data, {'wm_longitude': '113310000', 'wm_latitude': '23140000'})
sig = get_h5_mtgsig(cap_hs16, data2)
print('H5 hs1.6:', json.loads(sig)['a6'][:6], sig)
+237
View File
@@ -0,0 +1,237 @@
# 解析一份 mtgsig:把 a6/a5/a4 里的身份、设备画像、检测点全部解出来(自用,不依赖出签服务)
#
# 用法:把 __main__ 里的 text 换成要解的 mtgsig(本体,或含 "mtgsig" 字段的整段抓包 JSON),
# 直接 python 解密mtgsig.py,结果打印并写成 mtgsig解密值.json
#
# 返回/打印一个 dict:身份(a6) / 出签上下文(a5 的 qn) / 检测点(防篡改位图 r、开关位、ext、gzip 头…)
import base64
import hashlib
import json
import os
import sys
import zlib
from binascii import hexlify
import newsetting as ten
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
from Crypto.Cipher import AES
def get_header_rows():
"""取未处理的模板包(id / json_data / current_count)"""
sql = f'''
select id, json_data, current_count from waima_coupon_list_headers where id = {id_}
'''
rows = tent.get_shoppingmalls(sql)
print('未处理模板包 %d 条' % len(rows))
return rows
A6_KEY = b'z7Jut6Ywr2Pe5Nhx'
A6_IV = b'0807060504030201'
A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5'
# a6 里 system 数组的 46 项顺序(= jsguard 的 vt.system)
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 项
EXT_FIELDS = ['NativeClient存在', 'addEventListener存在', 'getPublicLibVersion(1一致/0不一致/2空对象)',
'__WeixinJSBridge存在', 'NFC(1成功/2未开/3无NFC/4canIUse假)']
# a5 里 qn 的含义
QN_FIELDS = {
'b1': 'getAccountInfoSync(含小程序版本)',
'b2': '当前路由 getCurrentPages().route',
'b6': 'openId(账号身份)',
'b7': '会话起始秒(init 时写入)',
'b8': '出签序号(同一实例自增)',
'b9': '开关位图 En.join(真机健康值 22122)',
'b10': '失败上报数组(有才出现)',
'b11': '定位精度串 accuracy_hacc_vacc',
'b12': 'appid',
}
A6_FIELDS = ['app(appid)', 'dfpid', 'filetime(USER_DATA_PATH 最后修改ms)', 'fpv(jsguard版本)',
'localid(时间戳+7随机大写+md5)', 'system(46项设备画像)', 'timestamp(秒)',
'ext(5项能力探测)', 'sessionId']
def b64_alpha(s):
"""a5 用的自定义字母表 base64 解码(= 号直接跳过)"""
buf = 0
nb = 0
out = bytearray()
for ch in s:
v = A5_ALPHA.find(ch)
if v < 0:
continue
buf = (buf << 6) | v
nb += 6
if nb >= 8:
nb -= 8
out.append((buf >> nb) & 0xFF)
return bytes(out)
def rc4_twist(key, data):
"""与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)"""
s = list(range(256))
j = 0
for i in range(256):
j = (j + s[i] + key[i % len(key)] + 31) % 256
s[i], s[j] = s[j], s[i]
out = bytearray()
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
out.append(ch ^ s[(s[i] + s[j]) % 256])
return bytes(out)
def crc32_twist(b):
"""jsguard 的 crc32 变体:反射多项式 0xEDB88320、初值全 1、末异或 306674911(=0x12477CDF,不是标准的 0xFFFFFFFF)"""
crc = 0xFFFFFFFF
for ch in b:
crc ^= ch
for _ in range(8):
crc = (crc >> 1) ^ (0xEDB88320 if crc & 1 else 0)
return (crc ^ 306674911) & 0xFFFFFFFF
def aes_cbc_dec(data):
return AES.new(A6_KEY, AES.MODE_CBC, A6_IV).decrypt(data)
def gunzip(data):
"""只解第一个 gzip 成员:AES 解出来的尾部是填充字节,gzip.decompress 会把它当成第二个成员而报错"""
return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
def parse_a6(a6):
"""解 a6 -> 9 项数组 + gzip 头"""
if not str(a6).startswith('w1.'):
raise ValueError('a6 前缀是 %r,不是小程序 jsguard(w1.x);H5 的 mtgsig(h1.9/hs1.6) 本脚本解不了' % str(a6)[:4])
raw = aes_cbc_dec(base64.b64decode(a6[4:]))
arr = json.loads(gunzip(raw).decode('utf-8'))
system = {}
for i, name in enumerate(SYSTEM_FIELDS):
v = arr[5][i] if i < len(arr[5]) else None
if name in ('LaunchOptionsSync', 'StorageInfo') and isinstance(v, str) and v.startswith('{'):
try:
v = json.loads(v) # 原来是 JSON 串,解出来更好看
except Exception:
pass
system[name] = v
ext = {}
for i, name in enumerate(EXT_FIELDS):
ext[name] = arr[7][i] if i < len(arr[7]) else None
out = {
'gzip头': {'mtime': int.from_bytes(raw[4:8], 'little'), 'os': raw[9]},
'system': system,
'ext': ext,
}
for i, name in enumerate(A6_FIELDS):
if name.startswith('system') or name.startswith('ext'):
continue
out[name] = arr[i]
return out
def parse_a5(a5, a2, a6):
"""解 a5 -> y(16B) 结构 + qn;并回算防篡改位图 r"""
w = b64_alpha(a5)
y, ct = w[:16], w[16:]
qn = json.loads(rc4_twist(y, ct).decode('utf-8'))
l = (a2 & 0xFFFFFFFF).to_bytes(4, 'big')
checks = {
'r(防篡改位图)': y[7] ^ (crc32_twist(l) & 0xFF), # 真机 appservice = 1
'y[0:7]==md5(a6)前7字节': hexlify(y[:7]).decode() ==
hashlib.md5(a6.encode('utf-8') + l).hexdigest()[:14],
'y[8:12]==a2低32位': int.from_bytes(y[8:12], 'big') == (a2 & 0xFFFFFFFF),
'y[12:16]==crc32(y前12字节)': int.from_bytes(y[12:16], 'big') == crc32_twist(y[:12]),
}
qn_named = {}
for k, v in qn.items():
qn_named[k] = {'值': v, '含义': QN_FIELDS.get(k, '?')}
return {'qn': qn_named, '自查': checks}
def parse_a4(a4):
"""解 a4:拆成 x / _ 及两个 XOR 项,验证结构"""
b = bytes.fromhex(a4)
x = int.from_bytes(b[0:4], 'big')
under = int.from_bytes(b[4:8], 'big')
low = int.from_bytes(b[16:20], 'little') ^ x # = a2 低32位
return {
'x=murmur3(方法+路径+query+body)': hex(x),
'_=murmur3(a5字符串)': hex(under),
'a2低32位(=x^此行)': hex(low),
'结构自校验': {
'b[8:12]==LE32(x)': int.from_bytes(b[8:12], 'little') == x,
'b[12:16]==LE32(_)': int.from_bytes(b[12:16], 'little') == under,
'b[16:20]==LE32(x^a2低32)': int.from_bytes(b[16:20], 'little') == (x ^ low),
'b[20:24]==LE32(x^_^a2低32)': int.from_bytes(b[20:24], 'little') == (x ^ under ^ low),
},
}
def parse_mtgsig(mtgsig):
"""入口:传 mtgsig 的 JSON 字符串,返回 dict"""
if isinstance(mtgsig, str):
mtgsig = json.loads(mtgsig)
a2 = mtgsig['a2']
out = {
'字段': dict(mtgsig), # a1 a2 a3 a4 a5 a6 a7 x0 d1 原样留一份
'a2时间': a2 / 1000,
}
try:
out['a6身份'] = parse_a6(mtgsig['a6'])
except Exception as e:
out['a6身份'] = '解失败: %s' % e
try:
out['a5上下文'] = parse_a5(mtgsig['a5'], a2, mtgsig['a6'])
except Exception as e:
out['a5上下文'] = '解失败: %s' % e
try:
out['a4结构'] = parse_a4(mtgsig['a4'])
except Exception as e:
out['a4结构'] = '解失败: %s' % e
return out
def _pick_mtgsig(raw):
"""从输入里抠出 mtgsig:本体 / 含 mtgsig 字段的抓包 JSON / 文件路径"""
raw = raw.strip()
if os.path.exists(raw):
raw = open(raw, encoding='utf-8').read().strip()
try:
obj = json.loads(raw)
except Exception:
return raw # 不是 JSON,当成本体
if isinstance(obj, dict):
if 'mtgsig' in obj:
return json.dumps(obj['mtgsig']) if not isinstance(obj['mtgsig'], str) else obj['mtgsig']
if 'headers' in obj and 'mtgsig' in obj['headers']: # 整段抓包
return obj['headers']['mtgsig']
return raw
if __name__ == '__main__':
id_=13
header_rows = get_header_rows()
text = header_rows[0][1]
text = '{"a1":"1.2","a2":1793339512511,"a3":"9v67307y25u85358y1y9zw93669w76vu8z818043u9377978462uwxz6","a4":"d3cb59dd6f1ca0b8dd59cbd3b8a01c6f620f9658daaf8a37","a5":"JSfkf+wH8axNgpy524MuRpn1YY4wB16sY3q+zxcAxMcnlHaW4d6H/s2NYVjofHAkOxoaPyBeMFvo5fF9wCb1d+Q8yCBYkPo3m/Q+tkqJp5OERZCXFqeG4iqkziDbo7UFrlxNFnX5VcTU6qqv6xruWt2XARJw6lVq9Zqrai2JYSpQFnbHg06rRF3Aa/ucyKptCZF+zfAevB0pyW44jNE1l4kGbpvqYNFQ+Tho3UvojSc0E1biIbQxoEbSG9/YF+jqyvlM2K9ABJkFgBlK2haybq82w42IRPH9h9vo+5ihfeEcU83YemzW8rMHjnIUY/OWTmb0l5c=","a6":"w1.6M5eQZ6Ej+qKlesiYotUiKjLSRSjW/jYxgb6YW6ckYKjkB+guB2tfhO7tS/PVKwzzvN6EMZnC71R7ypLdUSOEqZdbNQmVdeS4kc/Z2HKzhsOwHCQFw5TxvBuS9d3BRpRpZSwxYMVeAUy2NsCu+c6u4YFdlpZZ/3kxquhOSo4IZ4zZtFaBeEzbXPgJAIt82lWfs6ns2Lq1PjZ6WD7ndR/zvxLQBYw3NLDWZdS6yFlS0z3/ayZUVu/M9/R0ggltty+ort7Jti6Dj4AGel/W82QqX+FPu5o7/gFwc2jYl1mPbc2ZJU/dXf6Ie0oF3gIMon2ePrhalxHCPu6014wQB2gnATYTt1zcukw2a7+irCm43ROmXxNQHrLNMyuyfAlpULSPMps8rPIXV2kcF9K87sWMFISDARxoulGWWlY0zAuBGoL9Xp28MccUGCNjZr+Y0G0Pzw2WVKxvVWyacnyhrKsP1XHiZiMLnVYCspQh+Isci0+7YPopRuUJEQwiGoteQHyd3Glge0RoMb7An5o1dQLImEOyceWaAOYj9Cio5HjJeXR/7MrCwCTPDyMeyUi4oPwYTk+NPz/TRHj418F4fBp+5eVoY16yf7Zst3tfMr+6RIqdBZzNXrqjN6xoyx2dJGRqlxymbE5iZK/G1L5K2r+8DRI+Xl1B8cYhMkrbbBYcYxo6U9ZXBDsLxpgKmdHohrVp","a7":"wx92916b3adca84096","x0":3,"d1":"57e575c90db882ff7bf097966ab4e7f1"}'
# input(645)
# with open(r'C:\Users\mjz\Desktop\python\10月\店铺详情\mtgsig.txt','r',encoding='utf-8') as f:
# text = f.read()
result = parse_mtgsig(_pick_mtgsig(text))
out = json.dumps(result, ensure_ascii=False, indent=2)
with open('mtgsig解密值.json', 'w', encoding='utf-8') as f:
f.write(out)
print(out)
View File
Binary file not shown.
+144
View File
@@ -0,0 +1,144 @@
import re
import pymysql
class All_Setting():
def __init__(self,host,port,db):
self.host = host
self.port = port
self.db = db
def remove_symbols(self,text):
pattern = re.compile(r'[^\w\s]')
return pattern.sub('', text)
def get_chinese(self,text,printTxt=False):
# text = "海王星辰(广州智慧城店)"
pattern = r'[^\w\s]'
result = re.sub(pattern, '', text)
if printTxt:
print(result)
return result
def get_shoppingmalls(self,sql):
res_list = []
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
if conn:
print('ok')
cursor = conn.cursor()
res = cursor.execute(sql)
c2 = cursor.fetchall()
return c2
def write_data(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql,data)
conn.commit()
cursor.close()
def update_data(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
def write_data_one(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql,data)
conn.commit()
cursor.close()
import json
import time,requests
def get_sign_meituan(url, dfpid, data):
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
print(response1.text)
mtgsig1 = response1.json()
return str(mtgsig1)
def get_sign_waimai(url, dfpid, data):
print('我是外卖mtg')
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
# "ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.request("POST", url_mtg, headers=headers, data=payload)
mtgsig = response.json()
print(mtgsig)
return str(mtgsig)
def get_Datatext(dataq):
str1 = ''
for i in dataq:
key, value = i, dataq[i]
str2 = f'{key}={value}&'
str1 = str1 + str2
data = str1[0:-1]
return data
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"code":0,"msg":"","data":"{\"pageCode\":\"poiInfoPage\",\"module_list\":[{\"dataType\":0,\"moduleId\":\"poi_instore_recommend\",\"json_data\":{\"code\":514001101,\"content\":\"商品列表为空\"},\"module_id\":\"poi_instore_recommend\"},{\"dataType\":0,\"moduleId\":\"poi_page_base_info\",\"json_data\":{\"id\":0,\"poiIdStr\":\"DJ0Ss1qhW87Yg1YFx5VotQI\",\"name\":\"蜜雪冰城•现磨咖啡(长子营店)\",\"picUrl\":\"https://p0.meituan.net/waimaipoi/cccb8df6444c421e0b6c71519cc7bb8f1365016.png\",\"address\":\"北京市大兴区长子营镇上长子村\",\"phoneList\":[\"15890333185\",\"13716778635\"],\"poiQualifyInfo\":{\"show\":true,\"content\":\"商家资质档案\",\"url\":\"https://i.waimai.meituan.com/c/foods_safe_doc/index.html\",\"unionPoi\":false},\"bulletin\":\"亲亲看这里哦!如果收到餐品有任何漏放餐具、餐品错误、或破损撒漏等问题不要着急不要生气,请立刻打电话给我们,我们会马上解决ଘ(੭ˊ꒳ˋ)੭✧联系我们将真诚为您服务!感谢您的支持!比心心️~!\",\"deliveryTimeTip\":\"90分钟\",\"latitude\":39685356,\"longitude\":116593187,\"distance\":\"2616.3km\",\"poiInfoLabelList\":[{\"tagType\":0,\"text\":\"亮厨商家\",\"iconUrl\":\"https://p0.meituan.net/phfimage/44685112da815f5d17e01437ee212c0922881.png\",\"priority\":0,\"label\":\"phf_bright_kitchen_label\",\"labelType\":0,\"displayArea\":1,\"type\":0,\"jumpUrl\":\"https://market.waimai.meituan.com/gd2/wm/2UBHzb?tenant=gundam&isMultiTab=true&bs=0000\",\"iconWidth\":0,\"iconHeight\":0}],\"backgroundUrl\":\"https://p0.meituan.net/phfimage/891589d1343369a5de66b30f65b9392d18870.png\"},\"module_id\":\"poi_page_base_info\"},{\"dataType\":0,\"moduleId\":\"poi_page_service_insurance\",\"json_data\":{\"deliveryType\":0,\"deliverTip\":\"由美团提供配送服务\",\"shippingTime\":\"09:20-22:00\",\"poiLabels\":[{\"tagType\":2,\"text\":\"商家赠送拼单宝,拼单必成单\",\"iconUrl\":\"https://p0.meituan.net/phfimage/51fecff1b8fd5b2b73a2281689c429974262.png\",\"textColor\":\"#222426\",\"backgroundColor\":\"\",\"backgroundUrl\":\"\",\"borderColor\":\"\",\"priority\":60,\"label\":\"phf_group_order_insurance_tag\",\"labelType\":0,\"displayArea\":-1,\"type\":2,\"extraMap\":{\"link\":\"https://market.waimai.meituan.com/gundam/9mxVP0Rv/index.html?knb_enable_plugins=waimaiQueryPlugin001&knb_offline=false&knb_request=true&knb_standard=true&knb_uid=k1004103100d949e973519d2dd2d0e61&tenant=gundam&knb_no_title_bar=true&gundam_id=9mxVP0Rv&bs=0000&new_loc=true\",\"iDesc\":\"商家赠送拼单宝,发起拼单后9分钟内必成单\"},\"iconWidth\":0,\"iconHeight\":0}]},\"module_id\":\"poi_page_service_insurance\"},{\"dataType\":0,\"moduleId\":\"poi_page_real_shot\",\"json_data\":{\"envPicList\":[{\"id\":14940522,\"picTypeDesc\":\"门面\",\"ctime\":\"2026-07-23\",\"tab\":\"facade\",\"url\":\"https://p0.meituan.net/imageenhance/7d152c4f711b936aad514384eca37f92178408.jpg\"}]},\"module_id\":\"poi_page_real_shot\"}],\"json_data\":{\"shareInfo\":{\"title\":\"【美团拼好饭】亮厨商家蜜雪冰城•现磨咖啡(长子营店),快来选购吧\",\"iconUrl\":\"https://p1.meituan.net/phfimage/0d89cb3101e62c9117874f3bc7f196ac535034.png\"},\"expMap\":{\"brightKitchenAddLiveCondition\":\"true\",\"productInstoreOptimizeCondition\":\"true\",\"brightKitchenPerceptionOptimizationV2\":\"true\"}}}"}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"code":0,"msg":"","data":"{\"pageCode\":\"poiInfoPage\",\"module_list\":[{\"dataType\":0,\"moduleId\":\"poi_instore_recommend\",\"json_data\":{\"code\":514001101,\"content\":\"商品列表为空\"},\"module_id\":\"poi_instore_recommend\"},{\"dataType\":0,\"moduleId\":\"poi_page_base_info\",\"json_data\":{\"id\":0,\"poiIdStr\":\"uChsFiccc37phig5ES3oOwI\",\"name\":\"蜜雪冰城•现磨咖啡(南大红门店)\",\"picUrl\":\"https://p0.meituan.net/waimaipoi/9251ab884033133afe731a1536224b591459462.png\",\"address\":\"北京市大兴区青云店镇南大红门村京福路25号01室\",\"phoneList\":[\"18612663505\"],\"poiQualifyInfo\":{\"show\":true,\"content\":\"商家资质档案\",\"url\":\"https://i.waimai.meituan.com/c/foods_safe_doc/index.html\",\"unionPoi\":false},\"bulletin\":\"亲亲看这里哦!如果收到餐品有任何漏放餐具、餐品错误、或破损撒漏等问题不要着急不要生气,请立刻打电话给我们,我们会马上解决ଘ(੭ˊ꒳ˋ)੭✧联系我们将真诚为您服务!感谢您的支持!比心心️~!\",\"deliveryTimeTip\":\"7200分钟\",\"latitude\":39723288,\"longitude\":116464864,\"distance\":\"2619.4km\",\"poiInfoLabelList\":[{\"tagType\":0,\"text\":\"亮厨商家\",\"iconUrl\":\"https://p0.meituan.net/phfimage/44685112da815f5d17e01437ee212c0922881.png\",\"priority\":0,\"label\":\"phf_bright_kitchen_label\",\"labelType\":0,\"displayArea\":1,\"type\":0,\"jumpUrl\":\"https://market.waimai.meituan.com/gd2/wm/2UBHzb?tenant=gundam&isMultiTab=true&bs=0000\",\"iconWidth\":0,\"iconHeight\":0}],\"backgroundUrl\":\"https://p0.meituan.net/phfimage/891589d1343369a5de66b30f65b9392d18870.png\"},\"module_id\":\"poi_page_base_info\"},{\"dataType\":0,\"moduleId\":\"poi_page_service_insurance\",\"json_data\":{\"deliveryType\":0,\"deliverTip\":\"由美团提供配送服务\",\"shippingTime\":\"10:00-22:30\",\"poiLabels\":[{\"tagType\":2,\"text\":\"商家赠送拼单宝,拼单必成单\",\"iconUrl\":\"https://p0.meituan.net/phfimage/51fecff1b8fd5b2b73a2281689c429974262.png\",\"textColor\":\"#222426\",\"backgroundColor\":\"\",\"backgroundUrl\":\"\",\"borderColor\":\"\",\"priority\":60,\"label\":\"phf_group_order_insurance_tag\",\"labelType\":0,\"displayArea\":-1,\"type\":2,\"extraMap\":{\"link\":\"https://market.waimai.meituan.com/gundam/9mxVP0Rv/index.html?knb_enable_plugins=waimaiQueryPlugin001&knb_offline=false&knb_request=true&knb_standard=true&knb_uid=k1004103100d949e973519d2dd2d0e61&tenant=gundam&knb_no_title_bar=true&gundam_id=9mxVP0Rv&bs=0000&new_loc=true\",\"iDesc\":\"商家赠送拼单宝,发起拼单后9分钟内必成单\"},\"iconWidth\":0,\"iconHeight\":0},{\"tagType\":0,\"text\":\"商家已提供食品安全保障\",\"iconUrl\":\"https://p0.meituan.net/phfimage/a5d407c246881c66bf463eb8ee1440483338.png\",\"textColor\":\"#222426\",\"backgroundColor\":\"\",\"backgroundUrl\":\"\",\"borderColor\":\"\",\"priority\":195,\"label\":\"wm_poi_service\",\"labelType\":0,\"displayArea\":-1,\"type\":0,\"extraMap\":{\"link\":\"https://www.jchunuo.com/fe/operation/view/insurance-tying/new-terms/index.html?insurance_source=kano&authType=passport&wmpoiId=-100&insuranceType=87&businessId=45&poi_id_str=uChsFiccc37phig5ES3oOwI\",\"experimental_group\":\"true\",\"list_type\":\"7\",\"list_priority\":\"15\",\"iDesc\":\"商家为您投保放心吃-食品安全险, 饮食安全有保障(详情以下单页面显示为准)\"},\"iconWidth\":0,\"iconHeight\":0}]},\"module_id\":\"poi_page_service_insurance\"},{\"dataType\":0,\"moduleId\":\"poi_page_real_shot\",\"json_data\":{\"envPicList\":[{\"id\":15019582,\"picTypeDesc\":\"门面\",\"ctime\":\"2026-07-23\",\"tab\":\"facade\",\"url\":\"https://p0.meituan.net/imageenhance/83798a40f6e27b32ecfabfd480086fa7219489.jpg\"}]},\"module_id\":\"poi_page_real_shot\"}],\"json_data\":{\"shareInfo\":{\"title\":\"【美团拼好饭】亮厨商家蜜雪冰城•现磨咖啡(南大红门店),快来选购吧\",\"iconUrl\":\"https://p1.meituan.net/phfimage/0d89cb3101e62c9117874f3bc7f196ac535034.png\"},\"expMap\":{\"brightKitchenAddLiveCondition\":\"true\",\"productInstoreOptimizeCondition\":\"true\",\"brightKitchenPerceptionOptimizationV2\":\"true\"}}}"}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"code":50000003,"msg":"非拼好饭商家","data":null}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"code":0,"msg":"","data":"{\"pageCode\":\"poiInfoPage\",\"module_list\":[{\"dataType\":0,\"moduleId\":\"poi_instore_recommend\",\"json_data\":{\"code\":514001101,\"content\":\"商品列表为空\"},\"module_id\":\"poi_instore_recommend\"},{\"dataType\":0,\"moduleId\":\"poi_page_base_info\",\"json_data\":{\"id\":0,\"poiIdStr\":\"UlLr4GB3M4A0lBL_i4IkDwI\",\"name\":\"蜜雪冰城•现磨咖啡(马昌营地铁站店)\",\"picUrl\":\"https://p0.meituan.net/waimaipoi/9251ab884033133afe731a1536224b591459462.png\",\"address\":\"北京市平谷区马昌营镇南定福东路180号院4号楼1层4-1\",\"phoneList\":[\"15321926027\"],\"poiQualifyInfo\":{\"show\":true,\"content\":\"商家资质档案\",\"url\":\"https://i.waimai.meituan.com/c/foods_safe_doc/index.html\",\"unionPoi\":false},\"bulletin\":\"亲亲看这里哦!如果收到餐品有任何漏放餐具、餐品错误、或破损撒漏等问题不要着急不要生气,请立刻打电话给我们,我们会马上解决ଘ(੭ˊ꒳ˋ)੭✧联系我们将真诚为您服务!感谢您的支持!比心心️~!\",\"deliveryTimeTip\":\"90分钟\",\"latitude\":40141984,\"longitude\":117023512,\"distance\":\"2696.3km\",\"poiInfoLabelList\":[{\"tagType\":0,\"text\":\"亮厨商家\",\"iconUrl\":\"https://p0.meituan.net/phfimage/44685112da815f5d17e01437ee212c0922881.png\",\"priority\":0,\"label\":\"phf_bright_kitchen_label\",\"labelType\":0,\"displayArea\":1,\"type\":0,\"jumpUrl\":\"https://market.waimai.meituan.com/gd2/wm/2UBHzb?tenant=gundam&isMultiTab=true&bs=0000\",\"iconWidth\":0,\"iconHeight\":0}],\"backgroundUrl\":\"https://p0.meituan.net/phfimage/891589d1343369a5de66b30f65b9392d18870.png\"},\"module_id\":\"poi_page_base_info\"},{\"dataType\":0,\"moduleId\":\"poi_page_service_insurance\",\"json_data\":{\"deliveryType\":1,\"deliverTip\":\"由美团提供配送服务\",\"shippingTime\":\"09:30-21:30\",\"poiLabels\":[{\"tagType\":2,\"text\":\"商家赠送拼单宝,拼单必成单\",\"iconUrl\":\"https://p0.meituan.net/phfimage/51fecff1b8fd5b2b73a2281689c429974262.png\",\"textColor\":\"#222426\",\"backgroundColor\":\"\",\"backgroundUrl\":\"\",\"borderColor\":\"\",\"priority\":60,\"label\":\"phf_group_order_insurance_tag\",\"labelType\":0,\"displayArea\":-1,\"type\":2,\"extraMap\":{\"link\":\"https://market.waimai.meituan.com/gundam/9mxVP0Rv/index.html?knb_enable_plugins=waimaiQueryPlugin001&knb_offline=false&knb_request=true&knb_standard=true&knb_uid=k1004103100d949e973519d2dd2d0e61&tenant=gundam&knb_no_title_bar=true&gundam_id=9mxVP0Rv&bs=0000&new_loc=true\",\"iDesc\":\"商家赠送拼单宝,发起拼单后9分钟内必成单\"},\"iconWidth\":0,\"iconHeight\":0},{\"tagType\":0,\"text\":\"商家已提供食品安全保障\",\"iconUrl\":\"https://p0.meituan.net/phfimage/a5d407c246881c66bf463eb8ee1440483338.png\",\"textColor\":\"#222426\",\"backgroundColor\":\"\",\"backgroundUrl\":\"\",\"borderColor\":\"\",\"priority\":195,\"label\":\"wm_poi_service\",\"labelType\":0,\"displayArea\":-1,\"type\":0,\"extraMap\":{\"link\":\"https://www.jchunuo.com/fe/operation/view/insurance-tying/new-terms/index.html?insurance_source=kano&authType=passport&wmpoiId=-100&insuranceType=87&businessId=45&poi_id_str=UlLr4GB3M4A0lBL_i4IkDwI\",\"experimental_group\":\"true\",\"list_type\":\"7\",\"list_priority\":\"15\",\"iDesc\":\"商家为您投保放心吃-食品安全险, 饮食安全有保障(详情以下单页面显示为准)\"},\"iconWidth\":0,\"iconHeight\":0}]},\"module_id\":\"poi_page_service_insurance\"},{\"dataType\":0,\"moduleId\":\"poi_page_real_shot\",\"json_data\":{\"envPicList\":[{\"id\":15305809,\"picTypeDesc\":\"门面\",\"ctime\":\"2026-07-23\",\"tab\":\"facade\",\"url\":\"https://p1.meituan.net/imageenhance/437c1d735f051ef37fb7c041c020572b193133.jpg\"}]},\"module_id\":\"poi_page_real_shot\"}],\"json_data\":{\"shareInfo\":{\"title\":\"【美团拼好饭】亮厨商家蜜雪冰城•现磨咖啡(马昌营地铁站店),快来选购吧\",\"iconUrl\":\"https://p1.meituan.net/phfimage/0d89cb3101e62c9117874f3bc7f196ac535034.png\"},\"expMap\":{\"brightKitchenAddLiveCondition\":\"true\",\"productInstoreOptimizeCondition\":\"true\",\"brightKitchenPerceptionOptimizationV2\":\"true\"}}}"}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More