upload hotel shelf and area search

This commit is contained in:
mjz
2026-12-05 17:56:43 +08:00
commit 0640568feb
19 changed files with 5171 additions and 0 deletions
@@ -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
@@ -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
+282
View File
@@ -0,0 +1,282 @@
// 美团小程序 mtgsig —— 纯算法实现(不加载 jsguard 包、不补环境)
// 算法来源:wxde8ac0a21135c07d / wx-jsguard 2.5.0 静态逆向;在 flows 抓包上 a4/d1/a5 结构与公式已对齐
//
// mtgsig 字段:
// a1 = "1.2" a2 = 毫秒时间戳(=q 里的 s)
// a3 = dfpid a4 = 见 buildA4()
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON(qn)) ) a6 = "w1.x"+base64(AES-128-CBC(gzip(9项数组)))(当前纯写 w1.6)
// a7 = appid x0 = 3 d1 = 见 buildD1()
//
// 需要外部给的(算法里算不出来):dfpid / localId / filetime / 46 项设备画像 / 出签会话上下文。
// 须从一份抓包旧 mtgsig 解出(解密mtgsig.py 或 serve /derive);含 b9 开关串、反算 r、qn.b7/b8 等。
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import { gzipSync } from './gzip-mini.mjs';
// ---------------- 基础算法 ----------------
// 与 jsguard 里的 ge() 等价的 MurmurHash3_x86_32(results 为有符号 Int32,用时 >>>0)
export function murmur3(bytes, seed) {
const e = bytes, n0 = e.length;
const mul = (x) => (1540483477 * (x & 65535) + ((1540483477 * (x >>> 16) & 65535) << 16)) >>> 0;
let n = n0, t = ((seed | 0) ^ n0) >>> 0, c = 0;
while (n >= 4) {
let r = ((e[c] & 255) | ((e[c + 1] & 255) << 8) | ((e[c + 2] & 255) << 16) | ((e[c + 3] & 255) << 24)) >>> 0;
r = mul(r);
r = mul((r ^ (r >>> 24)) >>> 0);
t = (mul(t) ^ r) >>> 0;
n -= 4; c += 4;
}
switch (n) {
case 3: t = (t ^ ((e[c + 2] & 255) << 16)) >>> 0;
case 2: t = (t ^ ((e[c + 1] & 255) << 8)) >>> 0;
case 1: t = mul((t ^ (e[c] & 255)) >>> 0);
}
t = (t ^ (t >>> 13)) >>> 0;
t = mul(t);
return (((t ^ (t >>> 15)) >>> 0) ^ 1540483477) >>> 0;
}
// jsguard 的 crc32 变体:反射多项式 0xEDB88320,初值 0xFFFFFFFF,末异或 306674911(即 0x12477CDF,不是标准的 0xFFFFFFFF)
const CRC_TABLE = (() => {
const t = [];
for (let r = 0; r < 256; r++) { let v = r; for (let k = 0; k < 8; k++) v = v & 1 ? (v >>> 1) ^ 3988292384 : v >>> 1; t[r] = v >>> 0; }
return t;
})();
export function crc32(bytes) {
let r = -1;
for (let i = 0; i < bytes.length; i++) r = CRC_TABLE[(r ^ bytes[i]) & 255] ^ (r >>> 8);
return ((306674911 ^ r) >>> 0);
}
// 自定义字母表的标准 base64(带 = 填充)
export const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
export function b64alphaEncode(buf) {
let out = '';
for (let i = 0; i < buf.length; i += 3) {
const n = (buf[i] << 16) | ((buf[i + 1] || 0) << 8) | (buf[i + 2] || 0);
out += A5_ALPHA[(n >> 18) & 63] + A5_ALPHA[(n >> 12) & 63];
out += i + 1 < buf.length ? A5_ALPHA[(n >> 6) & 63] : '=';
out += i + 2 < buf.length ? A5_ALPHA[n & 63] : '=';
}
return out;
}
export function b64alpha(s) {
let buf = 0, nb = 0; const out = [];
for (const ch of String(s)) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v; nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)
export function rc4Twist(key, data) {
const S = []; for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
const be4 = (v) => Buffer.from([(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]);
const le4 = (v) => Buffer.from([v & 255, (v >>> 8) & 255, (v >>> 16) & 255, (v >>> 24) & 255]);
const u8 = (s) => Buffer.from(s, 'utf8');
const md5 = (b) => crypto.createHash('md5').update(b).digest();
const md5hex = (b) => md5(b).toString('hex');
const md5ints = (b) => { const x = md5(b); return [0, 1, 2, 3].map((i) => (x[i * 4] | x[i * 4 + 1] << 8 | x[i * 4 + 2] << 16 | x[i * 4 + 3] << 24) >>> 0); };
const hexInts = (a) => a.map((v) => le4(v).toString('hex')).join('');
// ---------------- a6 ----------------
// key/iv:w1.4(快驴 fpv 1.8.0)和 w1.6 都能用这套解开;换更大版本仍要再对一次样本
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
// 出签默认前缀。从旧包重出时用旧 a6 的前缀(w1.4 / w1.6),不要写死成 w1.6
export const A6_PREFIX = 'w1.6';
// 次版本号只取一位。\d+ 会把 base64 开头的数字吃进前缀,密文长度对不齐 16,AES 报 wrong final block length
export function a6PrefixOf(a6) {
const m = String(a6 || '').match(/^(w\d+\.\d)/);
return m ? m[1] : A6_PREFIX;
}
// arr = [app, dfpid, filetime, fpv, localid, system(46项), timestamp, ext(5项), sessionId]
// 用 jsguard 自带那套 gzip(gzip-mini.mjs 搬运版)而不是 zlib:zlib 压出来的流与真机不同,
// 搬过来的实现已实测与 jsguard 的 gzipSync 逐字节一致(含 MTIME=当前秒、OS=3 的头)。
export function buildA6(arr, mtimeSec, prefix) {
const sec = mtimeSec === undefined ? Math.floor(Date.now() / 1000) : mtimeSec;
const gz = gzipSync(u8(JSON.stringify(arr)), { mtime: sec * 1000 });
const c = crypto.createCipheriv('aes-128-cbc', A6_KEY, A6_IV);
return (prefix || A6_PREFIX) + Buffer.concat([c.update(Buffer.from(gz)), c.final()]).toString('base64');
}
export function parseA6(a6) {
const buf = Buffer.from(String(a6).slice(a6PrefixOf(a6).length), 'base64');
const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV);
return JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8'));
}
// 由零件直接拼 a6(不传 timestamp 时用当前秒)
export function buildA6FromParts(o) {
const ts = o.timestamp === undefined ? Math.ceil(Date.now() / 1000) : o.timestamp;
return buildA6([
o.appid, o.dfpid, o.filetime, o.fpv, o.localid, o.sys, ts, o.ext, o.sessionId,
], ts, o.a6Prefix || A6_PREFIX);
}
// ---------------- qn(a5 里 RC4 的载荷,键的插入顺序要跟 SDK 一致)----------------
// b7 秒级时间(init 时写入) / b1 getAccountInfoSync / b6 openId / b8 出签序号
// b12 appid / b11 定位精度串 / b2 当前路由 / b9 开关位图 / b10 失败上报(有才写)
export function buildQn(o) {
const qn = {};
qn.b7 = o.initSec;
qn.b1 = { miniProgram: { appId: o.appid, envVersion: o.envVersion || 'release', version: o.appVersion } };
if (o.openId) qn.b6 = o.openId;
qn.b8 = o.seq;
qn.b12 = o.appid;
qn.b2 = o.route || '';
// b9:五位开关串,随环境变;22122 只是无旧包时的兜底,应优先用抓包 qn.b9
qn.b9 = o.switchState || '22122';
if (o.loc) qn.b11 = o.loc; // 实测 b11 排在最后(不是赋值顺序)
if (o.failReports && o.failReports.length) qn.b10 = o.failReports;
return qn;
}
export function decodeQn(a5) {
const w = b64alpha(a5);
return JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
}
// ---------------- a5 ----------------
// y = md5(utf8(a6) ‖ BE32(low32(a2)))[0:7] ‖ [255&(r^crc32(l))] ‖ l ‖ BE32(crc32(y[0:12]))
// r 默认 1 仅防忘传;真机 appservice 常见反算为 0,须用 y[7]^crc32(BE32(a2低32)) 从旧包取
export function buildA5(a6, a2, qn, r = 1) {
const l = be4(a2 >>> 0);
const v = md5hex(Buffer.concat([u8(a6), l]));
const y = Buffer.from(v.slice(0, 14), 'hex'); // 7 字节
return (() => {
const buf = Buffer.alloc(16);
y.copy(buf, 0);
buf[7] = (r ^ crc32(l)) & 255;
l.copy(buf, 8);
be4(crc32(buf.slice(0, 12))).copy(buf, 12);
return b64alphaEncode(Buffer.concat([buf, rc4Twist(buf, u8(JSON.stringify(qn)))]));
})();
}
// ---------------- a4 / d1 ----------------
// z = utf8("METHOD path 规范化query") ‖ utf8(body前16200字节);x = murmur3(z, a2)
// query:按 & 切开,+ 当空格,decode 后再用 fe(encodeURIComponent 再编码 !'()*)重编码,按 [key, value] 排序。
// 不看接口路径。url 里如果已经带着 mtgsig,会算进去;重出签前先把这个参数从 url 去掉。
// body:GET/HEAD 不带。字符串原样(调用方已经编好的表单/JSON 都走这条)。
// 对象 + content-type 含 json → JSON.stringify。
// 其它对象 → 按插入顺序做 encodeURIComponent(不排序、不编码 !'()*),这是表单对象。
// 非 GET 的 body 只取前 16200 字节参与哈希,发出去的 body 本身不要截。
const BODY_LIMIT = 16200;
// query 用。比 encodeURIComponent 多编码 ! ' ( ) *
export function feQuery(s) {
return encodeURIComponent(s).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
}
function decComponent(s) {
const t = String(s).replace(/\+/g, ' ');
try { return decodeURIComponent(t); } catch (e) { return t; }
}
function parsePairs(q) {
const out = [];
for (const part of String(q || '').split('&')) {
if (!part) continue;
const i = part.indexOf('=');
if (i < 0) out.push([part, '']);
else out.push([part.slice(0, i), part.slice(i + 1)]);
}
return out;
}
export function canonQuery(url) {
const u = new URL(url);
const raw = u.search.startsWith('?') ? u.search.slice(1) : '';
const ps = parsePairs(raw).map(([k, v]) => [feQuery(decComponent(k)), feQuery(decComponent(v))]);
ps.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
return { pathname: u.pathname, query: ps.map(([k, v]) => k + '=' + v).join('&') };
}
// 表单对象的 value 编码,和 query 的 fe 不是同一套
function formEncode(data) {
const parts = [];
for (const k of Object.keys(data)) {
const v = data[k];
parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(v == null ? '' : String(v)));
}
return parts.join('&');
}
export function canonBody(method, data, contentType) {
const m = String(method || 'POST').toUpperCase();
if (m === 'GET' || m === 'HEAD') return '';
if (data === undefined || data === null) return '';
let body;
if (typeof data === 'string') body = data;
else {
const ct = String(contentType || '').toLowerCase();
body = ct.includes('json') ? JSON.stringify(data) : formEncode(data);
}
return body.length > BODY_LIMIT ? body.slice(0, BODY_LIMIT) : body;
}
export function buildZ({ method, url, data, contentType }) {
const m = String(method || 'POST').toUpperCase();
const q = canonQuery(url);
const head = m + ' ' + q.pathname + ' ' + q.query;
return Buffer.concat([u8(head), u8(canonBody(m, data, contentType))]);
}
export const buildX = (z, a2) => murmur3(z, a2) >>> 0;
// a5 里的 `_`:对 a5 字符串本身取 murmur3
export const buildUnderscore = (a5, a2) => murmur3(u8(a5), a2) >>> 0;
// a4 = hex( BE32(x) ‖ BE32(_) ‖ LE32(x) ‖ LE32(_) ‖ LE32(x^s32) ‖ LE32(x^_^s32) )
export function buildA4(x, under, a2) {
const s32 = a2 >>> 0;
return Buffer.concat([be4(x), be4(under), le4(x), le4(under), le4(x ^ s32), le4(x ^ under ^ s32)]).toString('hex');
}
// d1 = hexLE( B ),B 由 md5(M) 的 4 个 int 经异或混淆得到
export function buildD1({ a1, a2, a3, a4, under, a6, a7, x0 = 3 }) {
const s32 = a2 >>> 0;
const v = md5hex(Buffer.concat([u8(a6), be4(s32)]));
const M = String(a1) + String(a2) + String(a3) + String(a4) + String(under) + v + String(a7);
const B = md5ints(u8(M));
const u = under >>> 0, f = u;
const j = ((s32 << x0) | (s32 << (32 - x0))) >>> 0;
B[0] = (B[0] ^ j) >>> 0; B[1] = (B[1] ^ f) >>> 0; B[2] = (B[2] ^ f ^ j) >>> 0; B[3] = (B[3] ^ B[0]) >>> 0;
return hexInts(B);
}
// ---------------- 主入口 ----------------
// identity: { appid, dfpid, a6, a2 } —— a6/a2 可与 a5 复用;runtime: { route, openId, appVersion, switchState, loc, initSec, seq, r }
export function sign({ method = 'POST', url, data = '', contentType, identity, runtime, seq, initSec }) {
const a2 = identity.a2 || Date.now();
const a6 = identity.a6;
// 未传 r 时默认 1 易错;出签应传 runtime.r(从旧 mtgsig 反算)
const r = runtime.r === undefined ? 1 : runtime.r;
const qn = buildQn({
appid: identity.appid, openId: runtime.openId, route: runtime.route,
appVersion: runtime.appVersion, envVersion: runtime.envVersion, loc: runtime.loc, switchState: runtime.switchState,
initSec: initSec || Math.floor(a2 / 1000), seq: seq || 1, failReports: runtime.failReports,
});
const a5 = buildA5(a6, a2, qn, r);
const x = buildX(buildZ({ method, url, data, contentType }), a2);
const under = buildUnderscore(a5, a2);
const a1 = '1.2';
const a4 = buildA4(x, under, a2);
const d1 = buildD1({ a1, a2, a3: identity.dfpid, a4, under, a6, a7: identity.appid });
return JSON.stringify({ a1, a2, a3: identity.dfpid, a4, a5, a6, a7: identity.appid, x0: 3, d1 });
}
export { be4, le4, u8, md5ints, hexInts };
@@ -0,0 +1,387 @@
// mtgsig 出签服务(常驻):小程序 jsguard(纯算/补环境)+ 外卖 H5guard
// 启动: node serve.mjs 端口默认 18092(MTGSIG_PORT 可改)
// 接口: GET /health -> {ok,ready,h5Profiles,port,uptimeSec}
// POST /sign {url,data,mtgsig,openId,method,mode,sys?,ext?} 小程序签名(sys/ext 按字段名覆盖 a6 的 system/ext,仅纯算生效)
// POST /sign_h5 {url,data,method,mode,type,dataType,profile,cookie?} 外卖/买药 H5 签名(H5guard 补环境;profile=设备环境,缺字段报错)
// POST /sign_h5_pure {url,data,mtgsig,method,origin_url?,origin_data?} H5(h1.9) 纯算出签(不跑 SDK,毫秒级)
// POST /derive {mtgsig} 解出小程序签名身份
import http from 'node:http';
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createSigner } from './signer.mjs';
import * as P from './pure.mjs';
import { buildEnv as buildH5Env, setScriptRunner as setH5ScriptRunner } from './h5-env.mjs';
// H5(h1.9) 纯算(不加载 H5guard):从一份 mtgsig 推会话,再按 url+body 出签
const H5P = await import(pathToFileURL('C:/Users/mjz/Desktop/python/mjz/测试/AI代码/mtgsig_js/h5-pure.mjs').href);
// a6 = "w1.6" + base64(AES-128-CBC(gzip(身份数组))),key/iv 在已测 w1.6 样本上与 jsguard 一致(其它版本需再验)
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON.stringify(qn)) ),qn 是本次请求的上下文
const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
function b64alpha(s) {
let buf = 0, nb = 0;
const out = [];
for (const ch of s) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v;
nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)
function rc4Twist(key, data) {
const S = [];
for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
// 从一份 mtgsig(最好是抓包里的旧签名)解出会话身份 + 请求上下文
function deriveFromMtgsig(mtgsig) {
const p = typeof mtgsig === 'string' ? JSON.parse(mtgsig) : mtgsig;
const buf = Buffer.from(String(p.a6).slice(P.a6PrefixOf(p.a6).length), 'base64');
const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV);
const arr = JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8'));
const out = { appid: arr[0], dfpid: p.a3, localId: arr[4], filetime: arr[2], fpv: arr[3], sys: arr[5], ext: arr[7], sessionId: arr[8], a6Prefix: P.a6PrefixOf(p.a6) };
try {
// a6 的 system 数组里带着真机的启动页路径(LaunchOptionsSync),直接复用
const lp = (arr[5] || []).find((v) => typeof v === 'string' && v.startsWith('{"path"'));
if (lp) out.launchPath = JSON.parse(lp).path;
} catch (e) {}
try {
const w = b64alpha(String(p.a5));
const qn = JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
out.route = qn.b2 || '';
out.switchState = qn.b9 || '';
out.loc = qn.b11 || '';
out.openId = qn.b6 || '';
out.appVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.version) || '';
out.envVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.envVersion) || '';
if (Array.isArray(qn.b10) && qn.b10.length) out.failReports = qn.b10;
// 防篡改位图 r 同样能从包里反算:y[7] = r ^ crc32(BE32(a2低32))
const y = w.slice(0, 16);
out.r = y[7] ^ (P.crc32(P.be4(p.a2 >>> 0)) & 255);
} catch (e) { /* 旧签名拿不到上下文就算了 */ }
return out;
}
// a6 里 system 数组的 46 项顺序(= jsguard vt.system),按字段名覆盖时靠它映射到下标
const SYSTEM_FIELDS = [
'accelerometer', 'albumAuthorized', 'BatteryInfo', 'batteryLevel', 'Beacons', 'benchmarkLevel',
'bluetoothEnabled', 'brand', 'brightness', 'cameraAuthorized', 'compass', 'deviceOrientation',
'devicePixelRatio', 'enableDebug', 'errMsg', 'fontSizeSetting', 'language', 'LaunchOptionsSync',
'locationAuthorized', 'locationEnabled', 'locationReducedAccuracy', 'microphoneAuthorized', 'model',
'networkType', 'notificationAlertAuthorized', 'notificationAuthorized', 'notificationBadgeAuthorized',
'notificationSoundAuthorized', 'pixelRatio', 'platform', 'safeArea', 'screenHeight', 'screenTop',
'screenWidth', 'SDKVersion', 'statusBarHeight', 'system', 'version', 'wifiEnabled', 'WifiInfo',
'windowHeight', 'windowWidth', 'screenRecord', 'isPrivacy', 'hasSystemProxy', 'captureRecord',
];
// a6 里 ext 数组的 5 项
const EXT_FIELDS = ['NativeClient', 'addEventListener', 'getPublicLibVersion', '__WeixinJSBridge', 'NFC'];
// 按字段名把 override 覆盖到 base 数组(override 不传/空 = 原样返回;字段名不在清单里直接报错)
function applyNamed(base, order, override, label) {
if (!override) return base;
const out = Array.isArray(base) ? base.slice() : [];
for (const k of Object.keys(override)) {
const i = order.indexOf(k);
if (i < 0) throw new Error('未知的 ' + label + ' 字段: ' + k + '(可用字段: ' + order.join(', ') + ')');
out[i] = override[k];
}
return out;
}
const PORT = Number(process.env.MTGSIG_PORT || 18092);
const HOST = '0.0.0.0';
// 每个 (appid|dfpid) 一个出签实例(含 jsguard init 与 dfp 登记),首次调用会等几秒
const cache = new Map();
const startedAt = Date.now();
async function getSigner(id, openId) {
const key = id.appid + '|' + id.dfpid;
if (cache.has(key)) return cache.get(key);
const p = createSigner({
appid: id.appid,
openId: openId || '',
mtime: Number(id.filetime),
route: id.route || '',
launchPath: id.launchPath || '',
appVersion: id.appVersion || '',
loc: id.loc || '',
switchState: id.switchState || '',
sessionId: id.sessionId || '',
sys: id.sys,
ext: id.ext,
seedDfp: { dfpId: String(id.dfpid), localId: String(id.localId), timestamp: Number(id.filetime) },
});
cache.set(key, p);
try { return await p; } catch (e) { cache.delete(key); throw e; }
}
function readBody(req) {
return new Promise((resolve) => {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => resolve(b));
});
}
async function handleSign(o) {
if (!o.url) throw new Error('缺 url');
if (o.data === undefined) throw new Error('缺 data');
if (!o.mtgsig) throw new Error('缺 mtgsig(用它解出 appid/dfpid/localId/filetime)');
const id = deriveFromMtgsig(o.mtgsig);
const openId = o.openId || id.openId;
if (!openId) throw new Error('缺 openId(a6 里要带账号身份;旧 mtgsig 的 qn.b6 有的话也能自动取)');
const data = o.data == null ? '' : o.data;
const method = (o.method || 'POST').toUpperCase();
// 字符串看首字符;对象没标 type 时按表单(和 get_mtgsig 的字典约定一致)。显式 contentType 优先
const contentType = o.contentType || (typeof data === 'string' && /^\s*[{[]/.test(data) ? 'application/json' : 'application/x-www-form-urlencoded');
// 默认走纯算(无 init、无预热);要旧的补环境路径就显式传 mode: 'bundle'
const mode = String(o.mode || 'pure').toLowerCase();
if (mode === 'pure') {
const mtgsig = signPure(id, openId, { url: o.url, data, method, contentType, sys: o.sys, ext: o.ext, r: o.r });
const p = JSON.parse(mtgsig);
return { mtgsig, mode, a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length };
}
const s = await getSigner(id, openId);
const mtgsig = s.sign({ url: o.url, data, method, contentType });
const p = JSON.parse(mtgsig);
return { mtgsig, mode: 'bundle', a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length };
}
// 纯算模式:不加载 jsguard、不 init,因此没有那 20s 预热,换新包即出即用
const pureState = new Map(); // appid|dfpid -> { seq, initSec }
function signPure(id, openId, { url, data, method, contentType, sys, ext, r }) {
const key = id.appid + '|' + id.dfpid;
let st = pureState.get(key);
if (!st) { st = { seq: 1, initSec: Math.floor(Date.now() / 1000) }; pureState.set(key, st); } else st.seq += 1;
// 防篡改位图:优先调用方 r,否则用旧包 a5 反算 id.r;仅都无时才回退 1(真机常见为 0,回退 1 可能错签)
const bitmapR = r === undefined || r === null ? (id.r === undefined ? 1 : id.r) : Number(r);
const a2 = Date.now();
const a6 = P.buildA6FromParts({
appid: id.appid, dfpid: id.dfpid, filetime: id.filetime, fpv: id.fpv || '2.5.0',
localid: id.localId, sessionId: id.sessionId, a6Prefix: id.a6Prefix,
sys: applyNamed(id.sys, SYSTEM_FIELDS, sys, 'system'),
ext: applyNamed(id.ext, EXT_FIELDS, ext, 'ext'),
timestamp: Math.ceil(a2 / 1000),
});
return P.sign({
method, url, data, contentType,
identity: { appid: id.appid, dfpid: id.dfpid, a6, a2 },
runtime: { openId, route: id.route, appVersion: id.appVersion, envVersion: id.envVersion, loc: id.loc, switchState: id.switchState, failReports: id.failReports, r: bitmapR },
initSec: st.initSec, seq: st.seq,
});
}
// ---------- H5guard(外卖/买药 H5,浏览器环境 shim) ----------
// 每个 profile(设备/身份)一套独立 vm + H5guard;环境全部由 profile 决定,不再有内置默认身份
const HERE = path.dirname(fileURLToPath(import.meta.url));
const H5_PKG = fs.readFileSync(path.join(HERE, 'package-v1.js'), 'utf8');
const H5_SDK = fs.readFileSync(path.join(HERE, 'H5guard.js'), 'utf8');
const h5Profiles = new Map(); // profileKey -> { env, ready, fpLen }
function h5ProfileKey(p) {
return [p.appid, p.ua, p.platform, p.screenWidth, p.screenHeight, p.devicePixelRatio].join('|');
}
function getH5Profile(profile) {
if (!profile || !profile.appid || !profile.domains) throw new Error('profile 缺 appid 或 domains');
const key = h5ProfileKey(profile);
let st = h5Profiles.get(key);
if (st) return st;
const env = buildH5Env(profile);
const ctx = vm.createContext(env);
setH5ScriptRunner((code, name) => vm.runInContext(code, ctx, { filename: name }));
vm.runInContext(H5_PKG, ctx, { filename: 'package-v1.js' });
vm.runInContext(H5_SDK, ctx, { filename: 'H5guard.js' });
st = { key, env, ready: false, fpLen: 0 };
h5Profiles.set(key, st);
try { env.H5guard.init({ appid: profile.appid, xhrHook: true, domains: profile.domains, geo: false, yodaEnv: undefined }); } catch (e) { /* 已发起后台初始化 */ }
const t0 = Date.now(); let last = -1; let stable = 0;
const iv = setInterval(() => {
let len = -1;
try { len = String(env.H5guard.getfp()).length; } catch (e) { len = -1; }
if (len > 0 && len === last) stable++; else stable = 0;
last = len;
const el = Date.now() - t0;
if ((el >= 3500 && stable >= 2) || el >= 20000) {
clearInterval(iv);
st.fpLen = Math.max(0, len);
st.ready = true;
console.log('H5 READY[' + key + '] fpLen=' + st.fpLen + ' 预热=' + (el / 1000).toFixed(1) + 's');
}
}, 250);
return st;
}
function h5WaitReady(st) {
if (st.ready) return Promise.resolve();
return new Promise((res) => { const iv = setInterval(() => { if (st.ready) { clearInterval(iv); res(); } }, 200); });
}
let h5Queue = Promise.resolve(); // 串行化,避免并发互相干扰 SDK 状态
// 路径一:手动 H5guard.sign() -> a6 前缀 h1.9(外卖/买药 H5 页面自身加签走的这条)
function signH5Api(o, st) {
return (async () => {
const env = st.env;
if (o.cookie !== undefined) env.document.cookie = String(o.cookie || '');
const t = await env.H5guard.sign({
cache: false,
dataType: o.dataType,
url: o.url,
type: String(o.type).toUpperCase(),
data: o.data,
method: String(o.method).toUpperCase(),
});
return { mtgsig: t.headers.mtgsig, url: o.url, headers: {}, mode: 'sign' };
})();
}
// 路径二:走 H5guard 自己装的 XHR 钩子(signType 2)-> a6 前缀 hs1.6
// 白名单域名来自 init 的 domains(profile.domains):GET 把 mtgsig 拼进 url、POST 塞 header
function signH5Xhr(o, st) {
return new Promise((resolve, reject) => {
try {
const env = st.env;
if (o.cookie !== undefined) env.document.cookie = String(o.cookie || '');
const method = String(o.method).toUpperCase();
const xhr = new env.XMLHttpRequest();
xhr.open(method, o.url, true);
if (o.contentType) xhr.setRequestHeader('content-type', o.contentType);
if (o.headers) for (const k of Object.keys(o.headers)) xhr.setRequestHeader(k, o.headers[k]);
xhr.send(o.data);
const t0 = Date.now();
const iv = setInterval(() => {
const g = xhr.guardReq || {};
const u = String(g.url || '');
const hs = g.headers || {};
let mtgsig = null;
const m = u.match(/mtgsig=([^&]+)/);
if (m) mtgsig = decodeURIComponent(m[1]);
else if (hs.mtgsig) mtgsig = String(hs.mtgsig);
if (mtgsig) { clearInterval(iv); resolve({ mtgsig, url: u || o.url, headers: hs, mode: 'xhr' }); return; }
if (Date.now() - t0 > 15000) { clearInterval(iv); reject(new Error('H5 XHR 出签超时(域名可能不在 domains 白名单,或请求没被 SDK 钩到)')); }
}, 50);
} catch (e) { reject(e); }
});
}
function signH5(o, st) {
const mode = String(o.mode).toLowerCase();
if (mode !== 'sign' && mode !== 'xhr') throw new Error('mode 非法(只能 sign 或 xhr): ' + JSON.stringify(o.mode));
const run = h5Queue.then(() => (mode === 'sign' ? signH5Api(o, st) : signH5Xhr(o, st)));
h5Queue = run.then(() => {}, () => {}); // 单次失败不毒化后续请求
return run;
}
// H5(h1.9) 纯算:用一份抓包 mtgsig 推会话(origin_url/origin_data 要和那份包一致,默认同 url/data),
// 再按新 url/data 出签;同一个 dfpid(a3) 的 seq 自增(qn[2] 服务端会核对)
const h5PureSeq = new Map(); // a3(dfpid) -> seq
function signH5Pure(o) {
const data = o.data || '';
const method = (o.method || 'POST').toUpperCase();
const mtg = typeof o.mtgsig === 'string' ? JSON.parse(o.mtgsig) : o.mtgsig;
const snap = H5P.deriveFromMtgsig(mtg, {
url: o.origin_url || o.url,
data: o.origin_data === undefined ? data : o.origin_data,
method,
});
const key = String(mtg.a3);
const seq = h5PureSeq.has(key) ? h5PureSeq.get(key) + 1 : snap.seq + 1;
h5PureSeq.set(key, seq);
const a2 = o.a2 || Date.now();
const sig = H5P.sign(snap, { url: o.url, data, method, a2, seq });
return { mtgsig: JSON.stringify(sig), D: snap.D, seq };
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://' + HOST);
const send = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(obj)); };
try {
if (req.method === 'GET' && u.pathname === '/health') {
return send(200, { ok: true, port: PORT, uptimeSec: Math.round((Date.now() - startedAt) / 1000), ready: true, h5Profiles: [...h5Profiles.values()].map((s) => ({ key: s.key, ready: s.ready, fpLen: s.fpLen })), identities: [...cache.keys()] });
}
if (u.pathname === '/sign_h5') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
for (const k of ['url', 'data', 'method', 'mode', 'type', 'dataType', 'profile']) {
if (o[k] === undefined) return send(400, { error: '缺 ' + k });
}
const st = getH5Profile(o.profile); // 按 profile 建/取一套环境(profile 缺字段会报错)
await h5WaitReady(st); // 该 profile 首次会等指纹预热(最多 20s)
const r = await signH5(o, st);
const m = JSON.parse(r.mtgsig);
return send(200, { mtgsig: r.mtgsig, url: r.url, headers: r.headers, mode: r.mode, a3: m.a3, a6pfx: String(m.a6).slice(0, 5) });
}
if (u.pathname === '/sign_h5_pure') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
if (!o.url) return send(400, { error: '缺 url' });
if (!o.mtgsig) return send(400, { error: '缺 mtgsig(用它推会话:a5 的 qn / a8 的 A / d1 的 pool2)' });
const r = signH5Pure(o);
const m = JSON.parse(r.mtgsig);
return send(200, { mtgsig: r.mtgsig, mode: 'h5-pure', a3: m.a3, a6pfx: String(m.a6).slice(0, 5), D: r.D, seq: r.seq });
}
if (u.pathname === '/derive') {
let mtgsig;
if (req.method === 'POST') { const raw = await readBody(req); mtgsig = (raw ? JSON.parse(raw) : {}).mtgsig; }
else mtgsig = u.searchParams.get('mtgsig') || '';
return send(200, deriveFromMtgsig(mtgsig));
}
if (u.pathname === '/sign') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
const r = await handleSign(o);
return send(200, r);
}
send(404, { error: 'not found' });
} catch (e) {
send(500, { error: e && (e.message || String(e)) });
}
});
server.on('error', (e) => {
if (e && e.code === 'EADDRINUSE') { console.error('端口 ' + PORT + ' 已被占用,先停掉旧服务或改 MTGSIG_PORT'); process.exit(1); }
console.error(e);
process.exit(1);
});
server.listen(PORT, HOST, () => {
console.log('mtgsig 出签服务已启动: http://' + HOST + ':' + PORT + ' (health: /health)');
});
@@ -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 解出的 b9;没有才兜底 22122(五位串随环境变,勿当成固定健康值)
src = src.replace(/(\{su:0,fm:0,fp:0,sig:0\},[A-Za-z_$][\w$]*=)\[0,0,0,0,0\]/, '$1[' + switchDigits.split('').join(',') + ']');
return src;
}
function makeLoader(context, sdkPath, switchDigits) {
const cache = new Map();
const ROOT = path.dirname(sdkPath).replace(/[\\/]npm[\\/].*$/, '');
function load(file) {
const abs = path.resolve(file);
if (cache.has(abs)) return cache.get(abs).exports;
let src = fs.readFileSync(abs, 'utf8');
if (abs === path.resolve(sdkPath)) src = patchSdk(src, switchDigits);
const mod = { exports: {} };
cache.set(abs, mod);
const dir = path.dirname(abs);
const req = (spec) => {
// @babel/runtime/helpers/* 统一从 SDK 所在项目的根目录取
const babel = spec.match(/@babel\/runtime\/helpers\/([\w.-]+)/);
if (babel) return load(path.join(ROOT, '@babel', 'runtime', 'helpers', babel[1] + '.js'));
if (spec.startsWith('.') || path.isAbsolute(spec)) {
let p = path.resolve(dir, spec);
if (!p.endsWith('.js')) { if (fs.existsSync(p + '.js')) p = p + '.js'; else if (fs.existsSync(path.join(p, 'index.js'))) p = path.join(p, 'index.js'); }
return load(p);
}
throw new Error('external require: ' + spec);
};
// 文件名里带 app-service:SDK 的防篡改位图会检查 Error.stack 里是否有 'app-service'/'appservice'
const fn = vm.runInContext('(function(module, exports, require, __filename, __dirname){' + src + '\n})', context, { filename: 'app-service/' + path.basename(abs) });
fn(mod, mod.exports, req, abs, dir);
return mod.exports;
}
return load;
}
export async function createSigner(opts = {}) {
const appid = opts.appid || 'wxde8ac0a21135c07d';
const sdkPath = opts.sdk || resolveSdk(appid);
const calls = [];
// et 上报(ops.meituan.com)在途计数:没落定就出签,qn.b9 会停在中间态 → 判可疑
const track = { inFlight: 0, seen: false };
const sandbox = {
console, setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask,
fetch, Buffer, TextEncoder, TextDecoder, URL, URLSearchParams, crypto: globalThis.crypto,
wx: buildWx(calls, { appid, appVersion: opts.appVersion, launchPath: opts.launchPath, sys: opts.sys, ext: opts.ext, seedDfp: opts.seedDfp, mtime: opts.mtime, track }),
__wxConfig: { config: { debug: false }, platform: 'windows' },
getCurrentPages: () => (opts.route ? [{ route: opts.route, options: {}, __origin_route__: opts.route }] : []),
navigator: undefined,
};
// ext[1]=addEventListener 是否存在(真机 Android appservice 没有)
if (!opts.ext || opts.ext[1] === 1) sandbox.addEventListener = () => undefined;
sandbox.globalThis = sandbox;
sandbox.self = sandbox;
// appservice 上下文:反篡改位图 r 随环境变(真机 appservice 常见反算 r=0,勿写死为 1)
if (opts.noWindow) { /* 完全不声明 window */ }
else if ('windowValue' in opts) sandbox.window = opts.windowValue;
else sandbox.window = undefined;
sandbox.eval = opts.keepEval ? sandbox.eval : undefined;
if (opts.weixinJSBridge !== false) {
sandbox.WeixinJSBridge = (opts.weixinJSBridge && opts.weixinJSBridge !== true) ? opts.weixinJSBridge : {};
}
sandbox.document = undefined;
// 冻结时间(拿抓包逐字节校验用):让 Date.now()/new Date 返回固定毫秒
if (opts.nowMs) {
const Real = Date;
const FIXED = opts.nowMs;
function FixedDate(...a) { return a.length ? new Real(...a) : new Real(FIXED); }
FixedDate.now = () => FIXED;
FixedDate.parse = Real.parse;
FixedDate.UTC = Real.UTC;
FixedDate.prototype = Real.prototype;
sandbox.Date = FixedDate;
}
const context = vm.createContext(sandbox);
const switchDigits = /^\d{5}$/.test(opts.switchState || '') ? opts.switchState : '22122';
const jsguard = makeLoader(context, sdkPath, switchDigits)(sdkPath);
let inst = null;
const initAt = Date.now();
try {
inst = await Promise.race([
jsguard.init({ appid, env: 'prod' }),
new Promise((_, rej) => setTimeout(() => rej(new Error('init timeout')), opts.initWaitMs || 8000)),
]);
} catch (e) {
inst = jsguard.initSync({ appid, env: 'prod' });
}
const siuaTimer = setInterval(() => { try { inst.finger.i(); } catch (e) {} }, 10000);
// 账号/会话身份要在 SDK 刷新指纹(a6) 之前注入,否则这一轮 a6 里带不上
if (opts.openId) { try { inst.finger.o(opts.openId); } catch (e) {} }
if (opts.unionId) { try { inst.finger.u(opts.unionId); } catch (e) {} }
if (opts.mchId) { try { inst.finger.m(opts.mchId); } catch (e) {} }
if (opts.sessionId) { try { inst.finger.ss(opts.sessionId); } catch (e) {} }
// 定位精度串(qn.b11,形如 "30_30_0"):真机会带,缺了也可疑
if (opts.loc) {
const [acc, hacc, vacc] = String(opts.loc).split('_').map(Number);
try { inst.finger.l({ accuracy: acc, horizontalAccuracy: hacc, verticalAccuracy: vacc }); } catch (e) {}
}
if (opts.settleMs !== 0) {
// SDK 的 a6 每 10s 刷一次;身份注入后必须过一轮才会带进 a6
const need = 10500 - (Date.now() - initAt);
if (need > 0) await new Promise((r) => setTimeout(r, need));
// et 上报也是 10s 周期:等它跑完并静默一段时间,开关位 b9 才回到健康值
const maxMs = opts.settleWaitMs || 30000;
const t0 = Date.now();
let drainedAt = 0;
while (Date.now() - t0 < maxMs) {
await new Promise((r) => setTimeout(r, 500));
if (track.seen && track.inFlight === 0) { if (!drainedAt) drainedAt = Date.now(); }
if (!track.seen && Date.now() - t0 > 8000) break;
if (drainedAt && Date.now() - drainedAt > (opts.settleTailMs || 9000)) break;
}
}
return {
appid,
guard: inst,
calls,
fingerId: () => { try { return inst.finger.i(); } catch (e) { return ''; } },
dfpid: () => { try { return inst.finger.d(); } catch (e) { return ''; } },
sign({ url, method = 'POST', data = '', contentType = 'application/x-www-form-urlencoded' }) {
// content-type 只影响对象 body:json 走 JSON.stringify,表单走插入顺序的 encodeURIComponent。字符串 body 原样进签名串
const req = { url, method, header: { 'content-type': contentType }, data };
const out = inst.signWithSiua(req);
return out.header.mtgsig;
},
close() { clearInterval(siuaTimer); },
};
}