280 lines
8.2 KiB
JavaScript
280 lines
8.2 KiB
JavaScript
// 极简 Chrome DevTools Protocol 客户端。
|
|
// 零依赖:只用 Node 22+ 内置的全局 WebSocket 和 fetch。
|
|
// 作用:让真实的、已登录的 Chrome 自己去请求小红书,我们只在旁边"抄"它的网络响应。
|
|
// 这样完全不需要逆向 x-s 签名,也不容易被判定为爬虫。
|
|
|
|
import { spawn } from 'node:child_process';
|
|
import { existsSync } from 'node:fs';
|
|
import path from 'node:path';
|
|
|
|
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
const CHROME_CANDIDATES = [
|
|
process.env.CHROME_PATH,
|
|
'C:/Program Files/Google/Chrome/Application/chrome.exe',
|
|
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
|
|
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google/Chrome/Application/chrome.exe'),
|
|
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
|
|
'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
|
|
].filter(Boolean);
|
|
|
|
export function findBrowser() {
|
|
for (const p of CHROME_CANDIDATES) if (existsSync(p)) return p;
|
|
throw new Error('没找到 Chrome/Edge,请用环境变量 CHROME_PATH 指定浏览器 exe 路径');
|
|
}
|
|
|
|
async function httpJson(url, timeoutMs = 3000) {
|
|
const ac = new AbortController();
|
|
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
try {
|
|
const r = await fetch(url, { signal: ac.signal });
|
|
if (!r.ok) throw new Error(String(r.status));
|
|
return await r.json();
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
export async function browserVersion(port) {
|
|
return httpJson(`http://127.0.0.1:${port}/json/version`);
|
|
}
|
|
|
|
/**
|
|
* 确保有一个带 remote-debugging-port 的浏览器在跑。
|
|
* 用独立的 user-data-dir:既不影响你日常的 Chrome,也能把登录态存下来复用。
|
|
*/
|
|
export async function ensureBrowser({
|
|
port = 9222,
|
|
profileDir,
|
|
headless = false,
|
|
startUrl = 'about:blank',
|
|
executable,
|
|
} = {}) {
|
|
try {
|
|
const version = await browserVersion(port);
|
|
return { reused: true, version };
|
|
} catch {
|
|
/* 没在跑,继续启动 */
|
|
}
|
|
|
|
const exe = executable || findBrowser();
|
|
const args = [
|
|
`--remote-debugging-port=${port}`,
|
|
`--user-data-dir=${profileDir}`,
|
|
'--no-first-run',
|
|
'--no-default-browser-check',
|
|
'--disable-blink-features=AutomationControlled',
|
|
'--disable-features=Translate,MediaRouter',
|
|
startUrl,
|
|
];
|
|
if (headless) args.unshift('--headless=new', '--disable-gpu');
|
|
|
|
const child = spawn(exe, args, { detached: true, stdio: 'ignore' });
|
|
child.unref();
|
|
|
|
const deadline = Date.now() + 30000;
|
|
while (Date.now() < deadline) {
|
|
try {
|
|
return { reused: false, version: await browserVersion(port) };
|
|
} catch {
|
|
await sleep(400);
|
|
}
|
|
}
|
|
throw new Error(`浏览器启动超时:端口 ${port} 无响应`);
|
|
}
|
|
|
|
export async function listTargets(port) {
|
|
return httpJson(`http://127.0.0.1:${port}/json`);
|
|
}
|
|
|
|
export async function pageTarget(port) {
|
|
const list = await listTargets(port);
|
|
return list.find((t) => t.type === 'page') || null;
|
|
}
|
|
|
|
export class CDP {
|
|
#ws;
|
|
#nextId = 0;
|
|
#pending = new Map();
|
|
#handlers = new Map();
|
|
|
|
constructor(ws) {
|
|
this.#ws = ws;
|
|
ws.addEventListener('message', (e) => this.#onMessage(e.data));
|
|
ws.addEventListener('close', () => {
|
|
for (const { reject } of this.#pending.values()) reject(new Error('WebSocket 已关闭'));
|
|
this.#pending.clear();
|
|
});
|
|
}
|
|
|
|
static connect(url, timeoutMs = 15000) {
|
|
return new Promise((resolve, reject) => {
|
|
const ws = new WebSocket(url);
|
|
const timer = setTimeout(() => reject(new Error('连接 CDP 超时')), timeoutMs);
|
|
ws.addEventListener('open', () => {
|
|
clearTimeout(timer);
|
|
resolve(new CDP(ws));
|
|
});
|
|
ws.addEventListener('error', () => {
|
|
clearTimeout(timer);
|
|
reject(new Error('连接 CDP 失败'));
|
|
});
|
|
});
|
|
}
|
|
|
|
send(method, params = {}) {
|
|
const id = ++this.#nextId;
|
|
this.#ws.send(JSON.stringify({ id, method, params }));
|
|
return new Promise((resolve, reject) => {
|
|
this.#pending.set(id, { resolve, reject });
|
|
});
|
|
}
|
|
|
|
on(event, handler) {
|
|
if (!this.#handlers.has(event)) this.#handlers.set(event, new Set());
|
|
this.#handlers.get(event).add(handler);
|
|
return () => this.#handlers.get(event).delete(handler);
|
|
}
|
|
|
|
#onMessage(raw) {
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(raw);
|
|
} catch {
|
|
return;
|
|
}
|
|
if (msg.id) {
|
|
const p = this.#pending.get(msg.id);
|
|
if (!p) return;
|
|
this.#pending.delete(msg.id);
|
|
if (msg.error) p.reject(new Error(`${msg.error.message} (${msg.error.code})`));
|
|
else p.resolve(msg.result);
|
|
return;
|
|
}
|
|
const set = this.#handlers.get(msg.method);
|
|
if (set) for (const fn of set) fn(msg.params);
|
|
}
|
|
|
|
close() {
|
|
try {
|
|
this.#ws.close();
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function attach(port) {
|
|
const target = await pageTarget(port);
|
|
if (!target) throw new Error('没有可用的页面标签');
|
|
const cdp = await CDP.connect(target.webSocketDebuggerUrl);
|
|
await cdp.send('Page.enable').catch(() => {});
|
|
await cdp.send('Runtime.enable').catch(() => {});
|
|
return { cdp, target };
|
|
}
|
|
|
|
/** 导航并等待主文档 load 事件(或超时)。 */
|
|
export async function navigate(cdp, url, { timeout = 45000 } = {}) {
|
|
const loaded = new Promise((resolve) => {
|
|
const off = cdp.on('Page.loadEventFired', () => {
|
|
off();
|
|
resolve(true);
|
|
});
|
|
setTimeout(() => {
|
|
off();
|
|
resolve(false);
|
|
}, timeout);
|
|
});
|
|
await cdp.send('Page.navigate', { url });
|
|
await loaded;
|
|
// 再等一拍,给 SPA 的水合和首屏请求一点时间
|
|
await sleep(1200);
|
|
}
|
|
|
|
/** 在页面上下文里执行 JS,返回可序列化的结果。 */
|
|
export async function evaluate(cdp, expression, { awaitPromise = false, timeout = 30000 } = {}) {
|
|
const r = await cdp.send('Runtime.evaluate', {
|
|
expression,
|
|
returnByValue: true,
|
|
awaitPromise,
|
|
timeout,
|
|
userGesture: true,
|
|
includeCommandLineAPI: false,
|
|
});
|
|
if (r.exceptionDetails) {
|
|
const d = r.exceptionDetails;
|
|
throw new Error(d.exception?.description || d.text || '页面内 JS 执行失败');
|
|
}
|
|
return r.result?.value;
|
|
}
|
|
|
|
export async function currentUrl(cdp) {
|
|
return evaluate(cdp, 'location.href').catch(() => '');
|
|
}
|
|
|
|
/**
|
|
* 网络嗅探:拦截页面自己发出的 /api/sns/web/** JSON 响应。
|
|
* 我们不解密、不签名,只是把浏览器已经拿到的数据存下来。
|
|
*/
|
|
export class NetSniffer {
|
|
constructor(cdp, { urlIncludes = '/api/sns/web/' } = {}) {
|
|
this.cdp = cdp;
|
|
this.urlIncludes = urlIncludes;
|
|
this.bodies = [];
|
|
this.urls = new Map();
|
|
this.inflight = new Set();
|
|
|
|
cdp.on('Network.responseReceived', (p) => {
|
|
if (p.type !== 'XHR' && p.type !== 'Fetch' && p.type !== 'Other') return;
|
|
const url = p.response?.url || '';
|
|
if (!url.includes(this.urlIncludes)) return;
|
|
if (!/json/i.test(p.response?.mimeType || '')) return;
|
|
this.inflight.add(p.requestId);
|
|
this.urls.set(p.requestId, url);
|
|
});
|
|
|
|
cdp.on('Network.loadingFinished', (p) => {
|
|
if (!this.inflight.has(p.requestId)) return;
|
|
this.inflight.delete(p.requestId);
|
|
const url = this.urls.get(p.requestId) || '';
|
|
this.cdp
|
|
.send('Network.getResponseBody', { requestId: p.requestId })
|
|
.then((b) => {
|
|
let text = b.body;
|
|
if (b.base64Encoded) text = Buffer.from(text, 'base64').toString('utf8');
|
|
if (!text || text[0] !== '{') return;
|
|
const json = JSON.parse(text);
|
|
this.bodies.push({ url, json, at: Date.now() });
|
|
})
|
|
.catch(() => {});
|
|
});
|
|
}
|
|
|
|
async enable() {
|
|
await this.cdp.send('Network.enable', {
|
|
maxTotalBufferSize: 200 * 1024 * 1024,
|
|
maxResourceBufferSize: 50 * 1024 * 1024,
|
|
});
|
|
}
|
|
|
|
reset() {
|
|
this.bodies.length = 0;
|
|
this.urls.clear();
|
|
}
|
|
|
|
dump(filterFn) {
|
|
return this.bodies.filter((b) => (filterFn ? filterFn(b) : true));
|
|
}
|
|
}
|
|
|
|
/** 深度遍历任意 JSON,对每个对象调用 visit。 */
|
|
export function walk(obj, visit, depth = 0) {
|
|
if (!obj || typeof obj !== 'object' || depth > 14) return;
|
|
if (Array.isArray(obj)) {
|
|
for (const v of obj) walk(v, visit, depth + 1);
|
|
return;
|
|
}
|
|
visit(obj);
|
|
for (const k of Object.keys(obj)) walk(obj[k], visit, depth + 1);
|
|
}
|