upload hotel shelf and area search
This commit is contained in:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user