deepspider 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/.env.example +3 -0
  2. package/README.md +13 -13
  3. package/package.json +6 -6
  4. package/src/agent/core/PanelBridge.js +28 -76
  5. package/src/agent/core/StreamHandler.js +139 -14
  6. package/src/agent/index.js +51 -12
  7. package/src/agent/logger.js +183 -8
  8. package/src/agent/middleware/report.js +41 -15
  9. package/src/agent/middleware/subagent.js +233 -0
  10. package/src/agent/middleware/toolGuard.js +77 -0
  11. package/src/agent/middleware/validationWorkflow.js +171 -0
  12. package/src/agent/prompts/system.js +181 -59
  13. package/src/agent/run.js +41 -6
  14. package/src/agent/skills/crawler/SKILL.md +64 -3
  15. package/src/agent/skills/crawler/evolved.md +9 -1
  16. package/src/agent/skills/dynamic-analysis/SKILL.md +74 -7
  17. package/src/agent/skills/env/SKILL.md +75 -0
  18. package/src/agent/skills/sandbox/SKILL.md +35 -0
  19. package/src/agent/skills/static-analysis/SKILL.md +98 -2
  20. package/src/agent/subagents/anti-detect.js +10 -20
  21. package/src/agent/subagents/captcha.js +7 -19
  22. package/src/agent/subagents/crawler.js +25 -37
  23. package/src/agent/subagents/factory.js +109 -9
  24. package/src/agent/subagents/index.js +4 -13
  25. package/src/agent/subagents/js2python.js +7 -19
  26. package/src/agent/subagents/reverse.js +180 -0
  27. package/src/agent/tools/analysis.js +84 -1
  28. package/src/agent/tools/anti-detect.js +5 -2
  29. package/src/agent/tools/browser.js +160 -0
  30. package/src/agent/tools/capture.js +24 -3
  31. package/src/agent/tools/correlate.js +129 -15
  32. package/src/agent/tools/crawler.js +2 -1
  33. package/src/agent/tools/crawlerGenerator.js +90 -0
  34. package/src/agent/tools/debug.js +43 -6
  35. package/src/agent/tools/evolve.js +5 -2
  36. package/src/agent/tools/extractor.js +5 -1
  37. package/src/agent/tools/file.js +14 -5
  38. package/src/agent/tools/generateHook.js +66 -0
  39. package/src/agent/tools/hookManager.js +19 -9
  40. package/src/agent/tools/index.js +33 -20
  41. package/src/agent/tools/nodejs.js +41 -6
  42. package/src/agent/tools/sandbox.js +21 -1
  43. package/src/agent/tools/scratchpad.js +70 -0
  44. package/src/agent/tools/tracing.js +26 -0
  45. package/src/agent/tools/verifyAlgorithm.js +117 -0
  46. package/src/browser/EnvBridge.js +27 -13
  47. package/src/browser/client.js +124 -18
  48. package/src/browser/collector.js +101 -22
  49. package/src/browser/defaultHooks.js +3 -1
  50. package/src/browser/hooks/index.js +5 -0
  51. package/src/browser/interceptors/AntiDebugInterceptor.js +132 -0
  52. package/src/browser/interceptors/NetworkInterceptor.js +76 -12
  53. package/src/browser/interceptors/ScriptInterceptor.js +32 -7
  54. package/src/browser/interceptors/index.js +1 -0
  55. package/src/browser/ui/analysisPanel.js +469 -464
  56. package/src/cli/commands/config.js +11 -3
  57. package/src/config/paths.js +9 -1
  58. package/src/config/settings.js +7 -1
  59. package/src/core/PatchGenerator.js +24 -4
  60. package/src/core/Sandbox.js +140 -3
  61. package/src/env/EnvCodeGenerator.js +60 -88
  62. package/src/env/modules/bom/history.js +6 -0
  63. package/src/env/modules/bom/location.js +6 -0
  64. package/src/env/modules/bom/navigator.js +13 -0
  65. package/src/env/modules/bom/screen.js +6 -0
  66. package/src/env/modules/bom/storage.js +7 -0
  67. package/src/env/modules/dom/document.js +14 -0
  68. package/src/env/modules/dom/event.js +4 -0
  69. package/src/env/modules/index.js +27 -10
  70. package/src/env/modules/webapi/fetch.js +4 -0
  71. package/src/env/modules/webapi/url.js +4 -0
  72. package/src/env/modules/webapi/xhr.js +8 -0
  73. package/src/store/DataStore.js +125 -42
  74. package/src/store/Store.js +2 -1
  75. package/src/agent/subagents/dynamic.js +0 -64
  76. package/src/agent/subagents/env-agent.js +0 -82
  77. package/src/agent/subagents/sandbox.js +0 -55
  78. package/src/agent/subagents/static.js +0 -66
@@ -8,6 +8,7 @@ import { EventEmitter } from 'events';
8
8
  import { getDefaultHookScript } from './defaultHooks.js';
9
9
  import { NetworkInterceptor } from './interceptors/NetworkInterceptor.js';
10
10
  import { ScriptInterceptor } from './interceptors/ScriptInterceptor.js';
11
+ import { AntiDebugInterceptor } from './interceptors/AntiDebugInterceptor.js';
11
12
  import { getDataStore } from '../store/DataStore.js';
12
13
 
13
14
  export class BrowserClient extends EventEmitter {
@@ -20,9 +21,13 @@ export class BrowserClient extends EventEmitter {
20
21
  this.cdpSession = null;
21
22
  this.networkInterceptor = null;
22
23
  this.scriptInterceptor = null;
24
+ this.antiDebugInterceptor = null;
23
25
  this.hookScript = null;
24
26
  this.onMessage = null;
25
27
  this._isCleaningUp = false;
28
+ // CDP session 健康检查节流
29
+ this._cdpLastCheck = 0;
30
+ this._cdpCheckInterval = 5000; // 5秒内不重复检查
26
31
  }
27
32
 
28
33
  /**
@@ -37,6 +42,7 @@ export class BrowserClient extends EventEmitter {
37
42
  headless = false,
38
43
  executablePath = null,
39
44
  args = [],
45
+ userDataDir = null,
40
46
  } = options;
41
47
 
42
48
  const launchOptions = {
@@ -53,12 +59,22 @@ export class BrowserClient extends EventEmitter {
53
59
  launchOptions.executablePath = executablePath;
54
60
  }
55
61
 
56
- this.browser = await chromium.launch(launchOptions);
57
- this.emit('launched', { headless });
58
-
59
- this.context = await this.browser.newContext({
60
- ignoreHTTPSErrors: true,
61
- });
62
+ this._persistent = !!userDataDir;
63
+
64
+ if (userDataDir) {
65
+ // 持久化模式:launchPersistentContext 返回 BrowserContext
66
+ launchOptions.ignoreHTTPSErrors = true;
67
+ this.context = await chromium.launchPersistentContext(userDataDir, launchOptions);
68
+ this.browser = this.context.browser();
69
+ this.emit('launched', { headless, persistent: true });
70
+ } else {
71
+ // 临时模式(原有逻辑)
72
+ this.browser = await chromium.launch(launchOptions);
73
+ this.emit('launched', { headless });
74
+ this.context = await this.browser.newContext({
75
+ ignoreHTTPSErrors: true,
76
+ });
77
+ }
62
78
 
63
79
  // 保存 hook 脚本
64
80
  this.hookScript = getDefaultHookScript();
@@ -66,11 +82,22 @@ export class BrowserClient extends EventEmitter {
66
82
  // 使用 addInitScript 在 context 级别注入
67
83
  await this.context.addInitScript(this.hookScript);
68
84
 
69
- this.page = await this.context.newPage();
85
+ // 持久化上下文自带默认页面,临时模式需要新建
86
+ this.page = this._persistent
87
+ ? (this.context.pages()[0] || await this.context.newPage())
88
+ : await this.context.newPage();
70
89
 
71
90
  // 监听新页面创建(弹窗、新标签页)
72
91
  this.context.on('page', async (newPage) => {
73
92
  console.log('[BrowserClient] 检测到新页面');
93
+
94
+ // 清理旧页面的 CDP session(避免泄漏)
95
+ if (this.cdpSession && this._cdpSessionPage && this._cdpSessionPage !== newPage) {
96
+ await this.cdpSession.detach().catch(() => {});
97
+ this.cdpSession = null;
98
+ this._cdpSessionPage = null;
99
+ }
100
+
74
101
  this.pages.push(newPage);
75
102
  this.page = newPage; // 切换到新页面
76
103
  await this.setupPage(newPage);
@@ -96,6 +123,13 @@ export class BrowserClient extends EventEmitter {
96
123
  */
97
124
  async setupPage(page) {
98
125
  try {
126
+ // 如果这是当前页面的重新设置,先清理旧的 session
127
+ if (page === this.page && this.cdpSession && this._cdpSessionPage === page) {
128
+ await this.cdpSession.detach().catch(() => {});
129
+ this.cdpSession = null;
130
+ this._cdpSessionPage = null;
131
+ }
132
+
99
133
  const cdp = await page.context().newCDPSession(page);
100
134
 
101
135
  // 1. 启用 Runtime 域
@@ -125,11 +159,22 @@ export class BrowserClient extends EventEmitter {
125
159
  await networkInterceptor.start();
126
160
  await scriptInterceptor.start();
127
161
 
128
- // 保存引用
162
+ // 反无限 debugger:必须在 ScriptInterceptor 之后(Debugger 域已启用)
163
+ const antiDebugInterceptor = new AntiDebugInterceptor(cdp);
164
+ await antiDebugInterceptor.start();
165
+
166
+ // ScriptInterceptor 拉取源码后通知 AntiDebugInterceptor,避免重复 CDP 调用
167
+ scriptInterceptor.onSource = (scriptId, source) => {
168
+ antiDebugInterceptor.checkScript(scriptId, source);
169
+ };
170
+
171
+ // 保存引用(仅对当前活动页面)
129
172
  if (page === this.page) {
130
173
  this.cdpSession = cdp;
174
+ this._cdpSessionPage = page; // 关键:设置标记,让 getCDPSession 知道这是当前页面的 session
131
175
  this.networkInterceptor = networkInterceptor;
132
176
  this.scriptInterceptor = scriptInterceptor;
177
+ this.antiDebugInterceptor = antiDebugInterceptor;
133
178
  }
134
179
 
135
180
  // 监听页面导航
@@ -146,17 +191,52 @@ export class BrowserClient extends EventEmitter {
146
191
  }
147
192
 
148
193
  /**
149
- * 获取 CDP 会话(始终使用当前页面的 session
194
+ * 获取 CDP 会话(复用已有 session,仅在 page 变化时重建)
150
195
  */
151
196
  async getCDPSession() {
152
- // 每次都为当前页面创建新的 CDP session,确保上下文正确
153
- if (this.page) {
197
+ if (!this.page) return this.cdpSession;
198
+
199
+ // page 未变且 session 存在 → 复用
200
+ if (this.cdpSession && this._cdpSessionPage === this.page) {
201
+ // 节流:避免频繁健康检查
202
+ const now = Date.now();
203
+ if (now - this._cdpLastCheck < this._cdpCheckInterval) {
204
+ return this.cdpSession;
205
+ }
206
+
207
+ try {
208
+ // 通过简单的 Runtime.evaluate 验证 session 是否还活着
209
+ await this.cdpSession.send('Runtime.evaluate', { expression: '1' });
210
+ this._cdpLastCheck = now;
211
+ return this.cdpSession;
212
+ } catch {
213
+ // session 已失效,需要重新创建
214
+ console.log('[BrowserClient] CDP session 已失效,重新创建');
215
+ this.cdpSession = null;
216
+ this._cdpSessionPage = null;
217
+ }
218
+ }
219
+
220
+ // page 变了或 session 失效 → detach 旧 session,创建新的
221
+ if (this.cdpSession) {
154
222
  try {
155
- this.cdpSession = await this.page.context().newCDPSession(this.page);
156
- } catch (e) {
157
- console.error('[BrowserClient] 创建 CDP session 失败:', e.message);
158
- return null;
223
+ await this.cdpSession.detach();
224
+ } catch {
225
+ // 忽略 detach 错误(session 可能已断开)
159
226
  }
227
+ this.cdpSession = null;
228
+ }
229
+
230
+ try {
231
+ this.cdpSession = await this.page.context().newCDPSession(this.page);
232
+ this._cdpSessionPage = this.page;
233
+ this._cdpLastCheck = Date.now();
234
+ console.log('[BrowserClient] CDP session 已创建');
235
+ } catch (e) {
236
+ console.error('[BrowserClient] 创建 CDP session 失败:', e.message);
237
+ this.cdpSession = null;
238
+ this._cdpSessionPage = null;
239
+ return null;
160
240
  }
161
241
  return this.cdpSession;
162
242
  }
@@ -165,8 +245,19 @@ export class BrowserClient extends EventEmitter {
165
245
  * 导航到 URL
166
246
  */
167
247
  async navigate(url, options = {}) {
168
- const { waitUntil = 'domcontentloaded' } = options;
169
- await this.page.goto(url, { waitUntil });
248
+ const { waitUntil = 'domcontentloaded', timeout = 30000 } = options;
249
+ try {
250
+ await this.page.goto(url, { waitUntil, timeout });
251
+ } catch (e) {
252
+ // 超时不一定是错误,页面可能仍在加载,继续执行
253
+ if (e.message?.includes('timeout')) {
254
+ console.log('[BrowserClient] 导航超时,继续等待页面稳定...');
255
+ // 等待一小段时间让页面尽可能完成加载
256
+ await this.page.waitForTimeout(2000);
257
+ } else {
258
+ throw e;
259
+ }
260
+ }
170
261
  return this.page.url();
171
262
  }
172
263
 
@@ -208,6 +299,9 @@ export class BrowserClient extends EventEmitter {
208
299
  await this.scriptInterceptor.stop?.().catch(() => {});
209
300
  this.scriptInterceptor = null;
210
301
  }
302
+ if (this.antiDebugInterceptor) {
303
+ this.antiDebugInterceptor = null;
304
+ }
211
305
 
212
306
  // 分离 CDP session
213
307
  if (this.cdpSession) {
@@ -216,7 +310,16 @@ export class BrowserClient extends EventEmitter {
216
310
  }
217
311
 
218
312
  // 关闭浏览器
219
- if (this.browser) {
313
+ if (this._persistent) {
314
+ // 持久化模式:关闭 context 即保存数据并关闭浏览器
315
+ if (this.context) {
316
+ await this.context.close();
317
+ this.context = null;
318
+ this.browser = null;
319
+ this.page = null;
320
+ this.pages = [];
321
+ }
322
+ } else if (this.browser) {
220
323
  await this.browser.close();
221
324
  this.browser = null;
222
325
  this.context = null;
@@ -229,6 +332,9 @@ export class BrowserClient extends EventEmitter {
229
332
  this.emit('error', e);
230
333
  } finally {
231
334
  this._isCleaningUp = false;
335
+ // 重置 CDP 相关状态
336
+ this._cdpLastCheck = 0;
337
+ this._cdpSessionPage = null;
232
338
  }
233
339
  }
234
340
  }
@@ -15,13 +15,17 @@ export class EnvCollector {
15
15
  * @param {object} options - 采集选项
16
16
  */
17
17
  async collect(path, options = {}) {
18
- const { depth = 1, includeProto = false, useCache = true } = options;
18
+ const { depth = 1, includeProto = false, useCache = true, timeout = 5000 } = options;
19
19
 
20
20
  if (useCache && this.cache.has(path)) {
21
21
  return this.cache.get(path);
22
22
  }
23
23
 
24
- const result = await this.page.evaluate(({ path, depth, includeProto: _includeProto }) => {
24
+ // 使用 Promise.race 添加超时保护
25
+ const evaluatePromise = this.page.evaluate(({ path, depth, includeProto: _includeProto }) => {
26
+ // 用于检测循环引用的 WeakSet
27
+ const seen = new WeakSet();
28
+
25
29
  function getByPath(obj, path) {
26
30
  return path.split('.').reduce((o, k) => o && o[k], obj);
27
31
  }
@@ -40,29 +44,55 @@ export class EnvCollector {
40
44
  return { type, value: val };
41
45
  }
42
46
 
47
+ // 检测循环引用
48
+ if (seen.has(val)) {
49
+ return { type: 'object', value: '[Circular]', circular: true };
50
+ }
51
+
43
52
  if (currentDepth >= maxDepth) {
44
53
  return { type: 'object', value: '[Object]', truncated: true };
45
54
  }
46
55
 
56
+ seen.add(val);
57
+
47
58
  if (Array.isArray(val)) {
48
59
  return {
49
60
  type: 'array',
50
- value: val.map(v => serialize(v, currentDepth + 1, maxDepth))
61
+ length: val.length,
62
+ value: val.slice(0, 20).map(v => serialize(v, currentDepth + 1, maxDepth))
51
63
  };
52
64
  }
53
65
 
54
66
  const result = { type: 'object', properties: {} };
55
- const keys = Object.getOwnPropertyNames(val);
67
+ let keys;
68
+ try {
69
+ keys = Object.getOwnPropertyNames(val);
70
+ } catch (e) {
71
+ return { type: 'object', value: '[Error accessing keys]', error: e.message };
72
+ }
56
73
 
57
- for (const key of keys.slice(0, 50)) {
74
+ for (const key of keys.slice(0, 30)) {
58
75
  try {
59
76
  const desc = Object.getOwnPropertyDescriptor(val, key);
77
+ if (!desc) continue;
78
+
79
+ // 安全处理:避免触发有副作用的 getter
60
80
  if (desc.get) {
81
+ // 对于 getter,只记录描述符信息,不执行 getter
82
+ result.properties[key] = {
83
+ type: 'getter',
84
+ hasGetter: true,
85
+ enumerable: desc.enumerable,
86
+ configurable: desc.configurable
87
+ };
88
+ } else if (desc.set && desc.value === undefined) {
89
+ // 只有 setter 没有 getter
61
90
  result.properties[key] = {
62
- ...serialize(val[key], currentDepth + 1, maxDepth),
63
- hasGetter: true
91
+ type: 'setter',
92
+ hasSetter: true
64
93
  };
65
94
  } else {
95
+ // 普通值
66
96
  result.properties[key] = serialize(desc.value, currentDepth + 1, maxDepth);
67
97
  }
68
98
  } catch (e) {
@@ -89,15 +119,19 @@ export class EnvCollector {
89
119
 
90
120
  let descriptor = null;
91
121
  if (parent) {
92
- const desc = Object.getOwnPropertyDescriptor(parent, propName);
93
- if (desc) {
94
- descriptor = {
95
- configurable: desc.configurable,
96
- enumerable: desc.enumerable,
97
- writable: desc.writable,
98
- hasGetter: !!desc.get,
99
- hasSetter: !!desc.set
100
- };
122
+ try {
123
+ const desc = Object.getOwnPropertyDescriptor(parent, propName);
124
+ if (desc) {
125
+ descriptor = {
126
+ configurable: desc.configurable,
127
+ enumerable: desc.enumerable,
128
+ writable: desc.writable,
129
+ hasGetter: !!desc.get,
130
+ hasSetter: !!desc.set
131
+ };
132
+ }
133
+ } catch (e) {
134
+ // 忽略描述符读取错误
101
135
  }
102
136
  }
103
137
 
@@ -112,7 +146,19 @@ export class EnvCollector {
112
146
  }
113
147
  }, { path, depth, includeProto });
114
148
 
115
- if (result.success && useCache) {
149
+ // 添加超时
150
+ const timeoutPromise = new Promise((_, reject) =>
151
+ setTimeout(() => reject(new Error('采集超时')), timeout)
152
+ );
153
+
154
+ let result;
155
+ try {
156
+ result = await Promise.race([evaluatePromise, timeoutPromise]);
157
+ } catch (e) {
158
+ result = { success: false, error: e.message };
159
+ }
160
+
161
+ if (result?.success && useCache) {
116
162
  this.cache.set(path, result);
117
163
  }
118
164
 
@@ -154,9 +200,12 @@ export class EnvCollector {
154
200
  * 深度采集整个对象
155
201
  */
156
202
  async collectDeep(rootPath, options = {}) {
157
- const { maxDepth = 3, maxProps = 100 } = options;
203
+ const { maxDepth = 3, maxProps = 100, timeout = 5000 } = options;
204
+
205
+ const evaluatePromise = this.page.evaluate(({ rootPath, maxDepth, maxProps }) => {
206
+ // 用于检测循环引用的 WeakSet
207
+ const seen = new WeakSet();
158
208
 
159
- return await this.page.evaluate(({ rootPath, maxDepth, maxProps }) => {
160
209
  function getByPath(obj, path) {
161
210
  return path.split('.').reduce((o, k) => o && o[k], obj);
162
211
  }
@@ -165,19 +214,38 @@ export class EnvCollector {
165
214
  if (depth > maxDepth || collected.size > maxProps) return;
166
215
  if (!obj || typeof obj !== 'object') return;
167
216
 
217
+ // 检测循环引用
218
+ if (seen.has(obj)) return;
219
+ seen.add(obj);
220
+
168
221
  const keys = Object.getOwnPropertyNames(obj);
169
- for (const key of keys) {
222
+ for (const key of keys.slice(0, 30)) {
170
223
  if (collected.size > maxProps) break;
171
224
 
172
225
  const fullPath = path ? `${path}.${key}` : key;
173
226
  try {
174
- const val = obj[key];
175
- const type = typeof val;
227
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
228
+ if (!desc) continue;
229
+
230
+ // 安全处理:避免触发有副作用的 getter
231
+ let val;
232
+ let type;
233
+ if (desc.get) {
234
+ type = 'getter';
235
+ val = '[Getter]';
236
+ } else if (desc.set && desc.value === undefined) {
237
+ type = 'setter';
238
+ val = '[Setter]';
239
+ } else {
240
+ val = desc.value;
241
+ type = typeof val;
242
+ }
176
243
 
177
244
  collected.set(fullPath, {
178
245
  type,
179
246
  value: type === 'function' ? '[Function]' :
180
247
  type === 'object' ? '[Object]' :
248
+ type === 'getter' || type === 'setter' ? val :
181
249
  val
182
250
  });
183
251
 
@@ -204,6 +272,17 @@ export class EnvCollector {
204
272
  properties: Object.fromEntries(collected)
205
273
  };
206
274
  }, { rootPath, maxDepth, maxProps });
275
+
276
+ // 添加超时保护
277
+ const timeoutPromise = new Promise((_, reject) =>
278
+ setTimeout(() => reject(new Error('collectDeep timeout')), timeout)
279
+ );
280
+
281
+ try {
282
+ return await Promise.race([evaluatePromise, timeoutPromise]);
283
+ } catch (e) {
284
+ return { success: false, error: e.message };
285
+ }
207
286
  }
208
287
 
209
288
  // === 特殊环境采集 ===
@@ -160,7 +160,9 @@ function getCookieHook() {
160
160
  return value;
161
161
  },
162
162
  set: function(val) {
163
- deepspider.log('cookie', { action: 'write', value: val });
163
+ // 解析 cookie name(cookie 格式: "name=value; expires=...; path=...")
164
+ const cookieName = val?.split('=')[0]?.trim();
165
+ deepspider.log('cookie', { action: 'write', name: cookieName, value: val });
164
166
  return cookieDesc.set.call(document, val);
165
167
  },
166
168
  configurable: true
@@ -7,6 +7,7 @@
7
7
  export class HookManager {
8
8
  constructor() {
9
9
  this.logs = [];
10
+ this.maxLogs = 5000;
10
11
  this.onLog = null;
11
12
  this.injected = false;
12
13
  }
@@ -37,6 +38,10 @@ export class HookManager {
37
38
  text,
38
39
  timestamp: Date.now(),
39
40
  });
41
+ // 超过上限时丢弃最旧的 20%
42
+ if (this.logs.length > this.maxLogs) {
43
+ this.logs = this.logs.slice(Math.floor(this.maxLogs * 0.2));
44
+ }
40
45
  if (this.onLog) {
41
46
  this.onLog({ type: msg.type(), text });
42
47
  }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * DeepSpider - 反无限 debugger 拦截器
3
+ * 通过 CDP Debugger.setBlackboxedRanges 跳过包含 debugger 语句的脚本
4
+ * 零运行时开销,不修改源码,不触发完整性校验
5
+ *
6
+ * 已知限制:/\bdebugger\b/ 会匹配字符串/注释中的 debugger,
7
+ * 对反爬场景可接受(误 blackbox 的脚本仍正常执行,只是不可调试)
8
+ */
9
+
10
+ export class AntiDebugInterceptor {
11
+ constructor(cdpClient) {
12
+ this.client = cdpClient;
13
+ this.blackboxedScripts = new Set();
14
+ // 高频 debugger 检测
15
+ this.pausedCount = 0;
16
+ this.pausedWindowStart = 0;
17
+ this.PAUSED_WINDOW_MS = 1000; // 1秒窗口
18
+ this.PAUSED_THRESHOLD = 5; // 1秒内超过5次paused认为是debugger风暴
19
+ this.stormMode = false; // 风暴模式:跳过所有断点
20
+ this.stormTimer = null; // 风暴模式自动退出定时器
21
+ }
22
+
23
+ async start() {
24
+ // 兜底:对于 blackbox 来不及处理的同步 debugger(时序竞争),自动 resume
25
+ // reason 可能是 'other' 或 'debugCommand'(不同 Chrome 版本),
26
+ // 只要不是我们主动设的断点(hitBreakpoints 非空 / reason=breakpoint)就 resume
27
+ this.client.on('Debugger.paused', (params) => {
28
+ // 手动设置的断点(除非在风暴模式)
29
+ if (!this.stormMode && params.reason === 'breakpoint') return;
30
+ if (!this.stormMode && params.hitBreakpoints?.length > 0) return;
31
+
32
+ // 风暴模式下直接 resume,不参与计数
33
+ if (this.stormMode) {
34
+ this.client.send('Debugger.resume').catch(() => {});
35
+ return;
36
+ }
37
+
38
+ // 高频 debugger 检测
39
+ const now = Date.now();
40
+ if (now - this.pausedWindowStart > this.PAUSED_WINDOW_MS) {
41
+ // 新窗口
42
+ this.pausedWindowStart = now;
43
+ this.pausedCount = 1;
44
+ } else {
45
+ this.pausedCount++;
46
+ }
47
+
48
+ // 触发风暴模式
49
+ if (this.pausedCount > this.PAUSED_THRESHOLD) {
50
+ console.log('[AntiDebugInterceptor] 检测到 debugger 风暴,启用风暴模式');
51
+ this.stormMode = true;
52
+ // 清除之前的定时器
53
+ if (this.stormTimer) {
54
+ clearTimeout(this.stormTimer);
55
+ }
56
+ // 3秒后退出风暴模式
57
+ this.stormTimer = setTimeout(() => {
58
+ console.log('[AntiDebugInterceptor] 退出风暴模式');
59
+ this.stormMode = false;
60
+ this.pausedCount = 0;
61
+ this.stormTimer = null;
62
+ }, 3000);
63
+ }
64
+
65
+ // 自动 resume
66
+ this.client.send('Debugger.resume').catch(() => {});
67
+ });
68
+
69
+ console.log('[AntiDebugInterceptor] 已启动');
70
+ }
71
+
72
+ /**
73
+ * 检查脚本源码,包含 debugger 则 blackbox 整个脚本
74
+ * 由 ScriptInterceptor.onSource 回调驱动,避免重复拉取源码
75
+ */
76
+ checkScript(scriptId, scriptSource) {
77
+ if (/\bdebugger\b/.test(scriptSource)) {
78
+ this.client.send('Debugger.setBlackboxedRanges', {
79
+ scriptId,
80
+ positions: [{ lineNumber: 0, columnNumber: 0 }],
81
+ }).then(() => {
82
+ this.blackboxedScripts.add(scriptId);
83
+ }).catch(() => {});
84
+ }
85
+ }
86
+
87
+ /**
88
+ * 取消指定脚本的 blackbox(供断点工具调用)
89
+ */
90
+ async unblackbox(scriptId) {
91
+ if (this.blackboxedScripts.has(scriptId)) {
92
+ await this.client.send('Debugger.setBlackboxedRanges', {
93
+ scriptId,
94
+ positions: [],
95
+ });
96
+ this.blackboxedScripts.delete(scriptId);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * 手动启用/禁用风暴模式
102
+ * 用于绕过强反调试场景
103
+ */
104
+ setStormMode(enabled) {
105
+ // 清除之前的定时器
106
+ if (this.stormTimer) {
107
+ clearTimeout(this.stormTimer);
108
+ this.stormTimer = null;
109
+ }
110
+
111
+ this.stormMode = enabled;
112
+ if (enabled) {
113
+ console.log('[AntiDebugInterceptor] 手动启用风暴模式');
114
+ // 自动退出
115
+ this.stormTimer = setTimeout(() => {
116
+ this.stormMode = false;
117
+ this.stormTimer = null;
118
+ console.log('[AntiDebugInterceptor] 自动退出风暴模式');
119
+ }, 5000);
120
+ } else {
121
+ console.log('[AntiDebugInterceptor] 手动禁用风暴模式');
122
+ this.pausedCount = 0;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 检查当前是否在风暴模式
128
+ */
129
+ isStormMode() {
130
+ return this.stormMode;
131
+ }
132
+ }