dsh-fish-soul 0.18.0 → 0.18.1

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.18.0**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.18.1**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -559,7 +559,16 @@ export class Browser {
559
559
  })
560
560
  }
561
561
 
562
- /** 在页面里执行 JS,返回结果 */
562
+ /**
563
+ * 在页面里执行 JS,返回结果
564
+ *
565
+ * @param {string} expression
566
+ * @param {object} opts
567
+ * @param {boolean} opts.awaitPromise
568
+ * @param {number} opts.timeoutMs 这次 eval 的上限(默认 60 秒 = send 的默认值)。
569
+ * 页面 renderer 卡死但 CDP 连接还在时,Runtime.evaluate **永不回包** ——
570
+ * 不给短超时时一把浏览器锁能被拖住好几分钟。
571
+ */
563
572
  async eval(expression, opts = {}) {
564
573
  // 🔴 **绝不在这里启动浏览器**。
565
574
  // 以前是 `if (!this.ready) await this.launch()` —— 而后台累积器每 2 秒
@@ -567,12 +576,13 @@ export class Browser {
567
576
  // **窗口每隔 2 秒自己弹一次**。
568
577
  // 要不要开浏览器只有一个地方能决定:桥的 ensureBrowser()。
569
578
  if (!this.ready) throw new Error('浏览器没连上(连接已断),需要重新获取浏览器')
579
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : 60000
570
580
  const r = await this.send('Runtime.evaluate', {
571
581
  expression,
572
582
  returnByValue: true,
573
583
  awaitPromise: opts.awaitPromise !== false,
574
584
  userGesture: true,
575
- }, this.sessionId)
585
+ }, this.sessionId, timeoutMs)
576
586
  if (r.exceptionDetails) {
577
587
  throw new Error(`页面 JS 报错:${r.exceptionDetails.exception?.description || r.exceptionDetails.text}`)
578
588
  }
@@ -584,8 +594,13 @@ export class Browser {
584
594
  *
585
595
  * 🔴 Page.navigate 会**静默失败**(不报错,但页面停在 about:blank)。
586
596
  * ⇒ 必须验证 location.href,不对就重试。
597
+ *
598
+ * @param {object} opts
599
+ * @param {number} opts.timeoutMs **整个导航**的上限(毫秒);不给 = 不设限(老行为)。
600
+ * 页面卡死时验证用的 location.href 读不回(Runtime.evaluate 永不回包)。
601
+ * 这个上限**包住整段导航**:重试间隔、导航后等待、成功后的 settle 都算在里面。
587
602
  */
588
- async goto(url, { settleMs = 9000, retries = 2 } = {}) {
603
+ async goto(url, { settleMs = 9000, retries = 2, timeoutMs = 0 } = {}) {
589
604
  // 🔴 同 eval():不在这里启动浏览器(见上面的说明)
590
605
  if (!this.ready) throw new Error('浏览器没连上(连接已断),需要重新获取浏览器')
591
606
  this.events = []
@@ -593,23 +608,65 @@ export class Browser {
593
608
  this.seq = 0
594
609
  this.messageResponses.clear()
595
610
 
611
+ // 🔴 整个导航的上限(给了才生效)。页面 renderer 卡死但 CDP 连接还在时,
612
+ // 验证用的 location.href 读不回(Runtime.evaluate 永不回包),
613
+ // 没有上限就是 60 秒 × 重试次数。
614
+ const bounded = Number(timeoutMs) > 0
615
+ const end = bounded ? Date.now() + Number(timeoutMs) : 0
616
+ /** 这次还能花多少毫秒;不设限时返回 Infinity(各步都按老行为走) */
617
+ const left = () => (bounded ? end - Date.now() : Infinity)
618
+
619
+ /**
620
+ * 睡一段,但不许睡过预算:睡 min(原值, 剩余)。
621
+ *
622
+ * 🔴 以前这几处是**裸 sleep** —— 导航请求本身有上限,等待却不管:
623
+ * 导航请求超时后还要再睡 800ms × 重试次数,导航成功后还要再睡 settle
624
+ * (settleMs 7000 时是 4500ms)才返回。
625
+ * openWork 把这个上限当整操作 deadline 的一部分 ⇒ 整操作能超过 30 秒
626
+ * (2026-11-15 独立审查打回的阻断项)。
627
+ *
628
+ * 不设限时(left() = Infinity)时就是原来的 sleep(ms),老行为完全不变。
629
+ *
630
+ * 🔴 true = **醒来时**仍在预算内。只看入睡前的 remain 会漏判:
631
+ * 定时器可能迟到(事件循环被占 / 系统休眠 / 后台标签页被节流),
632
+ * 入睡时预算够 ≠ 醒来时预算还在 ⇒ 睡完必须重新核对 left()。
633
+ *
634
+ * @returns {boolean} true = 睡够了且醒来时仍在预算内;false = 没睡够 / 醒来时已超预算
635
+ */
636
+ const sleepWithin = async (ms) => {
637
+ const remain = left()
638
+ if (remain <= 0) return false
639
+ if (remain >= ms) {
640
+ await sleep(ms)
641
+ return left() > 0 // 睡醒后重新核对:定时器可能迟到
642
+ }
643
+ await sleep(remain)
644
+ return false
645
+ }
646
+
596
647
  let lastHref = ''
597
648
  for (let attempt = 0; attempt <= retries; attempt++) {
649
+ if (bounded && left() <= 0) throw new Error(`导航超时(${timeoutMs}ms):${url}`)
650
+ // 这次导航能花多少:整操作预算的剩余时间(没给预算时 = 15 秒,老行为不变)
651
+ const navTimeout = Math.min(15000, left())
598
652
  try {
599
653
  // 导航卡死时不能无限等:CDP 的 Page.navigate 要等对话框被处理才会回包,
600
654
  // 对话框一旦没人点,这里会挂满 send() 默认的 60 秒才报错,重试也跟着等。
601
655
  // 导航单独给 15 秒上限(超时由 send 自己清 pending 和计时器,不会空挂),
602
656
  // 超时当这次失败,走下面的重试 / 报错。
603
- await this.send('Page.navigate', { url }, this.sessionId, 15000)
657
+ await this.send('Page.navigate', { url }, this.sessionId, navTimeout)
604
658
  } catch (e) {
605
659
  const timedOut = /超时/.test(e.message)
606
- if (attempt >= retries) throw new Error(timedOut ? '导航请求超时(15 秒):页面可能被原生确认框挡住' : `导航请求失败:${e.message}`)
607
- await sleep(800)
660
+ if (attempt >= retries) throw new Error(timedOut ? `导航请求超时(${Math.round(navTimeout)}ms):页面可能被原生确认框挡住` : `导航请求失败:${e.message}`)
661
+ await sleepWithin(800)
608
662
  continue
609
663
  }
610
664
 
611
- await sleep(Math.min(2500, Math.max(800, settleMs / 3)))
612
- lastHref = await this.eval('location.href').catch(() => '')
665
+ // 🔴 导航后的首次等待也要看结果:睡醒时已过 deadline ⇒ 别再往下走
666
+ // (再 eval 只会白等,页面多半也是半成品)。
667
+ const waited = await sleepWithin(Math.min(2500, Math.max(800, settleMs / 3)))
668
+ if (bounded && !(waited && left() > 0)) throw new Error(`导航超时(${timeoutMs}ms):导航后等待超预算,${url}`)
669
+ lastHref = await this.eval('location.href', bounded ? { timeoutMs: Math.max(1, left()) } : {}).catch(() => '')
613
670
 
614
671
  const ok = lastHref
615
672
  && lastHref !== 'about:blank'
@@ -617,12 +674,15 @@ export class Browser {
617
674
  && lastHref !== 'chrome://newtab/'
618
675
 
619
676
  if (ok) {
620
- await sleep(Math.max(0, settleMs - 2500))
677
+ // 🔴 成功返回前查 deadline:settle 没睡完 / 睡醒时已过 deadline,
678
+ // 都不能当作成功(页面可能还没渲染完,调用方会拿着半成品继续)。
679
+ const settled = await sleepWithin(Math.max(0, settleMs - 2500))
680
+ if (bounded && !(settled && left() > 0)) throw new Error(`导航超时(${timeoutMs}ms):settle 没睡完,${url}`)
621
681
  return { url: lastHref, attempt }
622
682
  }
623
683
  if (attempt < retries) {
624
684
  this.log(`导航没生效(还在 ${lastHref || 'about:blank'}),重试…`)
625
- await sleep(1000)
685
+ await sleepWithin(1000)
626
686
  }
627
687
  }
628
688
 
@@ -27,7 +27,21 @@
27
27
  // `commentBridgeReady()` 比的是版本号,号没变就认为「已装好」,于是线上一直跑旧代码。
28
28
  // 2026-11-08 就踩过:改了 collect 的端点,验证时抓到的请求还是旧端点。
29
29
  // v2:收藏改走 aweme/collect(原来猜的 commit/collect 是 404 Janus)
30
- export const COMMENT_BRIDGE_VERSION = 3;
30
+ // v5:postComment 的本地校验(缺作品 id / 正文图片都空)改成 NOT_ATTEMPTED —— 请求根本没发出去
31
+ export const COMMENT_BRIDGE_VERSION = 5;
32
+
33
+ /**
34
+ * 写操作状态(页面桥和 Node 侧共用同一套值)。
35
+ *
36
+ * NOT_ATTEMPTED —— 写操作**根本没发出去**(桥没装上 / 图没传上去):
37
+ * 调用方可以退回 DOM 点击重来。
38
+ * ATTEMPTED_UNKNOWN —— 写操作**可能已经发出去了**(超时 / 断连 / 抖音没回评论 id):
39
+ * 调用方绝不能再发一次(再发就是重复评论)。
40
+ *
41
+ * ⚠️ 靠状态字段判断,不要拿错误文本匹配 —— 文本会变,状态不会。
42
+ */
43
+ export const WRITE_NOT_ATTEMPTED = 'NOT_ATTEMPTED';
44
+ export const WRITE_ATTEMPTED_UNKNOWN = 'ATTEMPTED_UNKNOWN';
31
45
 
32
46
  /**
33
47
  * 页面内脚本。挂在 `window.__fishComment` 上。
@@ -43,6 +57,9 @@ export const COMMENT_BRIDGE_SOURCE = String.raw`
43
57
 
44
58
  const ok = (o) => Object.assign({ ok: true }, o);
45
59
  const bad = (e, extra) => Object.assign({ ok: false, error: String((e && e.message) || e) }, extra || {});
60
+ // 写操作状态(和 Node 侧同名)
61
+ const WRITE_NOT_ATTEMPTED = '${WRITE_NOT_ATTEMPTED}';
62
+ const WRITE_ATTEMPTED_UNKNOWN = '${WRITE_ATTEMPTED_UNKNOWN}';
46
63
 
47
64
  /** 页面加载时刻 —— celltime 两个字段都从它算起(实测抖音自己也是这么算的)。 */
48
65
  const PAGE_LOAD_TIME = Date.now();
@@ -277,13 +294,17 @@ export const COMMENT_BRIDGE_SOURCE = String.raw`
277
294
  * @param {Array} [o.images] [{uri,width,height,format}]
278
295
  */
279
296
  async postComment(o) {
297
+ // ⚠️ 分两段:
298
+ // · 本地校验没过 → 请求**根本没发出去**(NOT_ATTEMPTED),调用方可以退回 DOM;
299
+ // · 请求已经发出去了 → 后面的一切(超时 / 断连 / 抖音没回评论 id)都算
300
+ // 「可能已经发出去了」(ATTEMPTED_UNKNOWN),调用方绝不能再发一次。
280
301
  try {
281
302
  const opt = o || {};
282
303
  const awemeId = String(opt.awemeId || '');
283
- if (!awemeId) return { ok: false, error: '没给作品 id' };
304
+ if (!awemeId) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: '没给作品 id' };
284
305
  const images = Array.isArray(opt.images) ? opt.images : [];
285
306
  const text = String(opt.text || '');
286
- if (!text && !images.length) return { ok: false, error: '正文和图片都是空的' };
307
+ if (!text && !images.length) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: '正文和图片都是空的' };
287
308
 
288
309
  const now = Date.now();
289
310
  const sendCelltime = String(Math.floor((now - PAGE_LOAD_TIME) / 1000) * 1000);
@@ -317,12 +338,13 @@ export const COMMENT_BRIDGE_SOURCE = String.raw`
317
338
  const uifid = cookie('UIFID') || cookie('UIFID_TEMP');
318
339
  if (uifid) extra.uifid = uifid;
319
340
  const r = await api('/aweme/v1/web/comment/publish/', extra, b.toString());
320
- if (!r.ok) return r;
341
+ // 请求已经发出去了(可能服务端已经落库),后面的结果一律「不明」
342
+ if (!r.ok) return Object.assign({ writeState: WRITE_ATTEMPTED_UNKNOWN }, r);
321
343
  const cid = r.data && r.data.comment && r.data.comment.cid;
322
- if (!cid) return { ok: false, error: '抖音没回评论 id', raw: r.data };
344
+ if (!cid) return { ok: false, writeState: WRITE_ATTEMPTED_UNKNOWN, error: '抖音没回评论 id', raw: r.data };
323
345
  // cid 是 19 位整数,JS Number 只能精确到 16 位 —— JSON 里若是数字必须 toFixed(0) 保精度
324
346
  return ok({ cid: typeof cid === 'number' ? cid.toFixed(0) : String(cid) });
325
- } catch (e) { return bad(e); }
347
+ } catch (e) { return { ok: false, writeState: WRITE_ATTEMPTED_UNKNOWN, error: String((e && e.message) || e) }; }
326
348
  },
327
349
 
328
350
  /**
@@ -420,30 +442,30 @@ export const COMMENT_BRIDGE_SOURCE = String.raw`
420
442
  * 在当前页面装上桥(不依赖 preload —— 当前页立刻能用)。
421
443
  * 返回 { ok, error? }。
422
444
  */
423
- export async function installCommentBridge(browser) {
445
+ export async function installCommentBridge(browser, { timeoutMs } = {}) {
424
446
  try {
425
447
  browser.addPreloadScript(COMMENT_BRIDGE_SOURCE);
426
448
  } catch { /* 老版本 Browser 没这方法 */ }
427
449
  try {
428
- await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: COMMENT_BRIDGE_SOURCE }, browser.sessionId);
450
+ await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: COMMENT_BRIDGE_SOURCE }, browser.sessionId, timeoutMs);
429
451
  } catch { /* 装了 preload 就够 */ }
430
452
  try {
431
- await browser.eval(COMMENT_BRIDGE_SOURCE);
453
+ await browser.eval(COMMENT_BRIDGE_SOURCE, { timeoutMs });
432
454
  } catch (error) {
433
455
  return { ok: false, error: String(error instanceof Error ? error.message : error) };
434
456
  }
435
457
  // ⚠️ eval 没抛异常 ≠ 桥真的装上了:页面如果不是真抖音(比如测试用的本地假站),
436
458
  // eval 会静静地什么都没做。所以装完回头验一次版本号。
437
- if (!(await commentBridgeReady(browser))) {
459
+ if (!(await commentBridgeReady(browser, { timeoutMs }))) {
438
460
  return { ok: false, error: '装完验不到桥(页面里没有 window.__fishComment)' };
439
461
  }
440
462
  return { ok: true };
441
463
  }
442
464
 
443
465
  /** 桥是否在位。 */
444
- export async function commentBridgeReady(browser) {
466
+ export async function commentBridgeReady(browser, { timeoutMs } = {}) {
445
467
  try {
446
- const v = await browser.eval('window.__fishComment ? window.__fishComment.version : 0');
468
+ const v = await browser.eval('window.__fishComment ? window.__fishComment.version : 0', { timeoutMs });
447
469
  return Number(v) === COMMENT_BRIDGE_VERSION;
448
470
  } catch {
449
471
  return false;
@@ -455,21 +477,36 @@ export async function commentBridgeReady(browser) {
455
477
  * @param {import('./browser.mjs').Browser} browser
456
478
  * @param {string} method 桥上的方法名
457
479
  * @param {object} args 参数
458
- * @returns {Promise<{ok: boolean, error?: string}>}
480
+ * @param {object} [opts]
481
+ * @param {boolean} [opts.write] 这是写操作吗?写操作的结果不明(超时 / 断连 / 页面没回结果)
482
+ * 一律标成 ATTEMPTED_UNKNOWN —— 调用方绝不能再发一次。
483
+ * @param {number} [opts.timeoutMs] 这次桥调用的上限(毫秒)。不给 = eval 的默认 60 秒。
484
+ * 页面卡死时 Runtime.evaluate 永不回包,不给上限就是 60 秒。
485
+ * @returns {Promise<{ok: boolean, error?: string, writeState?: string}>}
459
486
  */
460
- export async function callBridge(browser, method, args = {}) {
487
+ export async function callBridge(browser, method, args = {}, opts = {}) {
488
+ const write = opts.write === true;
461
489
  const expr = `window.__fishComment && window.__fishComment.${method}
462
490
  ? window.__fishComment.${method}(${JSON.stringify(args)})
463
- : Promise.resolve({ ok: false, error: '桥没装上(window.__fishComment 不存在)' })`;
491
+ : Promise.resolve({ ok: false, writeState: '${WRITE_NOT_ATTEMPTED}', error: '桥没装上(window.__fishComment 不存在)' })`;
464
492
  let r;
465
493
  try {
466
- r = await browser.eval(expr);
494
+ r = await browser.eval(expr, { timeoutMs: opts.timeoutMs });
467
495
  } catch (error) {
468
496
  // CDP 断了 / 页面崩了 —— 抛给调用方没意义,统一转成 ok:false
469
- return { ok: false, error: '桥调用失败:' + String(error instanceof Error ? error.message : error) };
497
+ const out = { ok: false, error: '桥调用失败:' + String(error instanceof Error ? error.message : error) };
498
+ // 写操作:CDP 断了不代表没发出去(请求可能已经发出去了,只是结果没回来)
499
+ if (write) out.writeState = WRITE_ATTEMPTED_UNKNOWN;
500
+ return out;
501
+ }
502
+ if (r && typeof r === 'object' && typeof r.ok === 'boolean') {
503
+ // 写操作:页面侧没给状态就按「可能已经发出去了」处理(宁可这次没回,也别重复发)
504
+ if (write && r.ok === false && !r.writeState) return Object.assign({}, r, { writeState: WRITE_ATTEMPTED_UNKNOWN });
505
+ return r;
470
506
  }
471
- if (r && typeof r === 'object' && typeof r.ok === 'boolean') return r;
472
- return { ok: false, error: '桥调用没返回结果:' + String(JSON.stringify(r) ?? r).slice(0, 200) };
507
+ const out = { ok: false, error: '桥调用没返回结果:' + String(JSON.stringify(r) ?? r).slice(0, 200) };
508
+ if (write) out.writeState = WRITE_ATTEMPTED_UNKNOWN;
509
+ return out;
473
510
  }
474
511
 
475
512
  /**
@@ -11,14 +11,15 @@ import { sleep } from './time-util.js';
11
11
  * 抖音常在发评论前要短信验证:碰到就停下、提醒主人去浏览器里验证一次,6 小时内不再试。
12
12
  * 评论区 / 输入框的结构参考了 pcmxiao/dsh-douyin-bridge 的 lib/comment.mjs(MIT),代码是这里自己写的。
13
13
  */
14
- import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
15
- import { callBridge, commentBridgeReady, installCommentBridge, uploadImage as uploadCommentImage } from './channels/vendor/douyin-bridge/douyin-comment.js';
16
- import { join } from 'node:path';
14
+ import { mkdirSync, writeFileSync, readFileSync, realpathSync, statSync, lstatSync } from 'node:fs';
15
+ import { callBridge, commentBridgeReady, installCommentBridge, uploadImage as uploadCommentImage, WRITE_NOT_ATTEMPTED, WRITE_ATTEMPTED_UNKNOWN } from './channels/vendor/douyin-bridge/douyin-comment.js';
16
+ import { extname, join, resolve } from 'node:path';
17
17
  import { createHash } from 'node:crypto';
18
18
  import { SocialBase, socialCfg, cleanSocialText } from './social.js';
19
19
  import { DouyinPostJobs } from './douyin-post-jobs.js';
20
20
  import { 抠正文图 } from './channels/vendor/qq-bridge.js';
21
21
  import { fishSoulDir, getKv, setKv } from './db.js';
22
+ import { isInside } from './gateway-util.js';
22
23
 
23
24
  const HOUR_MS = 3600_000;
24
25
  const VERIFY_BACKOFF_MS = 6 * HOUR_MS;
@@ -34,9 +35,97 @@ const SEL = {
34
35
  commentBtn: '[data-e2e="feed-comment-icon"]'
35
36
  };
36
37
 
38
+ /**
39
+ * 页面操作的时间上限。
40
+ *
41
+ * 🔴 页面 renderer 卡死但 CDP 连接还在时,Runtime.evaluate **永不回包**:
42
+ * send 默认 60 秒才超时,waitFor 再乘上轮数(配乐 6 轮 = 6 分钟),
43
+ * 浏览器锁一直被占,期间所有页面操作排队(2026-11-15 巡检 P2)。
44
+ * ⇒ 每个 eval 都给短超时,waitFor 再加一道总预算兜底。
45
+ *
46
+ * 🔴 多次 eval 的操作(openWork / reply)还要**整操作**的总预算:
47
+ * 光有单次 eval 的短超时不够 —— openWork 是两个 URL 各 12 轮,
48
+ * 24 × 12 秒 = 5 分钟,照样霸着锁(独占锁超时只报错给调用方,
49
+ * 不放锁:见 lib/channels/douyin.js 的 exclusive)。
50
+ */
51
+ const PAGE_TIMING = {
52
+ evalTimeoutMs: 12_000, // 单次 eval 的上限
53
+ waitBudgetMs: 60_000, // waitFor 的总预算
54
+ gotoTimeoutMs: 15_000, // 单次导航的上限
55
+ openWorkBudgetMs: 30_000, // openWork 整操作的总预算
56
+ replyBudgetMs: 30_000, // reply 整操作的总预算
57
+ };
58
+
59
+ /**
60
+ * 整操作的总预算(终点)。
61
+ *
62
+ * 终点同时管三件事:单次 eval 的超时、轮次之间的等待、还要不要发起下一次 eval。
63
+ * 只在轮次之间查时间是没用的 —— 页面卡死时 eval 自己就挂死(永不回包)。
64
+ *
65
+ * @param {number} totalMs 总预算(毫秒)
66
+ */
67
+ function deadline(totalMs) {
68
+ const end = Date.now() + totalMs;
69
+ const left = () => end - Date.now();
70
+ return {
71
+ left,
72
+ /** 到点了没 */
73
+ expired: () => left() <= 0,
74
+ /** 这次 eval 给多少超时:不超过上限,也不越过终点 */
75
+ timeoutFor: (cap) => Math.max(1, Math.min(cap, left())),
76
+ /** 这次该等多久:不超过原时长,也不越过终点 */
77
+ waitFor: (ms) => Math.max(0, Math.min(ms, left()))
78
+ };
79
+ }
80
+
37
81
  const oneLine = (s, n) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
38
82
  const errText = (e) => String(e instanceof Error ? e.message : e);
39
83
 
84
+ const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
85
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
86
+
87
+ /**
88
+ * 评论图片只能取工作区 `_stickers/` 里的图。
89
+ *
90
+ * 路径是模型写的 = 不可信:`..` 能拼出工作区外的文件,软链接 / junction 能把
91
+ * `_stickers/` 里的一项指到别处。所以边界收在**真实路径**上 ——
92
+ * 目录、软链接/junction 逃逸、非图片格式、超大图一律不发(关掉,不抛)。
93
+ *
94
+ * 信任根本身也要先验:`_stickers` 必须是普通目录 —— 它自己是 junction / 软链接的话,
95
+ * 真实路径整个落到工作区外,只拿 `realRoot` 去比是拦不住的。
96
+ *
97
+ * @param {string} rel `_stickers/xxx` 形状的相对路径
98
+ * @param {string} root 工作区里的 `_stickers` 目录
99
+ * @param {(level: string, msg: string) => void} log
100
+ * @returns {string|null} 校验过的真实路径;不合格返回 null
101
+ */
102
+ function safeStickerImagePath(rel, root, log) {
103
+ const deny = () => {
104
+ log('warn', `[fish-soul] 抖音评论图片越界,已忽略:${rel}`);
105
+ return null;
106
+ };
107
+ let rootStat;
108
+ try { rootStat = lstatSync(root); } catch { return null; } // 没有 _stickers 目录 = 没有可发的图
109
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
110
+ log('warn', `[fish-soul] 抖音评论图片根目录不可信(_stickers 不是普通目录),已拒绝:${rel}`);
111
+ return null;
112
+ }
113
+ const abs = resolve(root, rel.slice('_stickers/'.length));
114
+ if (!isInside(root, abs)) return deny();
115
+ if (!IMAGE_EXT.has(extname(abs).toLowerCase())) return null;
116
+ let realRoot, real;
117
+ try {
118
+ realRoot = realpathSync.native(root);
119
+ real = realpathSync.native(abs);
120
+ } catch { return null; }
121
+ if (!isInside(realRoot, real)) return deny();
122
+ try {
123
+ const st = statSync(real);
124
+ if (!st.isFile() || st.size > MAX_IMAGE_BYTES) return null;
125
+ } catch { return null; }
126
+ return real;
127
+ }
128
+
40
129
  /** 标题:正文第一句,最多 20 字(抖音图文标题上限 20)。 */
41
130
  export function noteTitle(text) {
42
131
  const first = String(text ?? '').split(/[。!?!?\n]/).map((s) => s.trim()).find(Boolean) ?? '';
@@ -74,13 +163,33 @@ export function commentKey(workId, author, content) {
74
163
  return `${workId}:${createHash('sha1').update(`${author}\n${content}`).digest('hex').slice(0, 16)}`;
75
164
  }
76
165
 
166
+ /**
167
+ * 评论去重 id:优先用评论自己的 cid(`作品:cid:xxx`),没有 cid 才落回文本哈希。
168
+ *
169
+ * 文本 key 的毛病:作者改了评论,正文变了 → key 变了 → 同一条评论被当成新的又回一遍
170
+ * (在真实账号上回两遍)。cid 是抖音给的评论 id,不随正文变。
171
+ *
172
+ * @param {string} workId 作品 id
173
+ * @param {string} cid 评论 id(没有就空串)
174
+ * @param {string} author 作者昵称
175
+ * @param {string} content 评论正文
176
+ * @returns {string} 去重 id
177
+ */
178
+ export function commentId(workId, cid, author, content) {
179
+ const c = String(cid ?? '').trim();
180
+ if (c !== '') return `${workId}:cid:${c}`;
181
+ return commentKey(workId, author, content);
182
+ }
183
+
77
184
  // ───────────── 页面脚本 ─────────────
78
185
 
79
- const VERIFY_JS = String.raw`(() => {
186
+ export const VERIFY_JS = String.raw`(() => {
80
187
  const t = document.body ? document.body.innerText : '';
81
188
  const sms = /接收短信验证码|获取验证码|请输入验证码/.test(t);
82
189
  const captcha = /滑块验证|安全验证|请完成验证|拖动滑块/.test(t);
83
- return sms || captcha ? (sms ? 'sms' : 'captcha') : '';
190
+ // 滑块常挂在独立 iframe(rc-verifycenter)里,body 文本一个字都不露(2026-11-15 真机踩过)
191
+ const frame = [...document.querySelectorAll('iframe')].some((f) => /rc-verifycenter|verifycenter|captcha/i.test(String(f.src || '')));
192
+ return sms || captcha || frame ? (sms ? 'sms' : 'captcha') : '';
84
193
  })()`;
85
194
 
86
195
  /** 文字卡片(1080×1440 PNG,base64)。 */
@@ -219,24 +328,72 @@ export const LIST_COMMENTS_JS = `(() => [...document.querySelectorAll('${SEL.ite
219
328
  return { i, author: author.slice(0, 40), content: content.slice(0, 300), isAuthor, canReply };
220
329
  }))()`;
221
330
 
222
- async function realClick(br, x, y) {
331
+ async function realClick(br, x, y, timeoutMs) {
223
332
  for (const type of ['mousePressed', 'mouseReleased']) {
224
- await br.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons: type === 'mousePressed' ? 1 : 0 }, br.sessionId);
333
+ await br.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons: type === 'mousePressed' ? 1 : 0 }, br.sessionId, timeoutMs);
225
334
  }
226
335
  }
227
336
 
228
- async function waitFor(fn, { tries = 10, gapMs = 1000 } = {}) {
337
+ /** 预算到期的哨兵:区分「没等到」和「等到的是假值」。 */
338
+ const BUDGET_OUT = Symbol('budget-out');
339
+
340
+ /**
341
+ * 等 fn 出结果,最长等 budgetMs。
342
+ *
343
+ * 🔴 预算必须**包住 fn 这一次调用** —— 页面 renderer 卡死时 fn 自己就挂死
344
+ * (Runtime.evaluate 永不回包),只在轮次之间查时间没用:
345
+ * 配乐 6 轮 × 60 秒 = 锁被占 6 分钟(2026-11-15 巡检 P2)。
346
+ *
347
+ * @param {Function} fn 每轮调用一次;返回假值 / 抛错 = 还没等到
348
+ * @param {object} opts
349
+ * @param {number} opts.tries 最多试几轮
350
+ * @param {number} opts.gapMs 两轮之间隔多久
351
+ * @param {number} opts.budgetMs 总预算(毫秒);到点直接返回 null(非正数 = 不等,直接返回 null)
352
+ * @returns {Promise<any>} 等到的值;没等到返回 null
353
+ */
354
+ async function waitFor(fn, { tries = 10, gapMs = 1000, budgetMs = PAGE_TIMING.waitBudgetMs } = {}) {
355
+ const end = Date.now() + budgetMs;
229
356
  for (let i = 0; i < tries; i++) {
230
- const v = await fn().catch(() => null);
357
+ const left = end - Date.now();
358
+ if (left <= 0) return null;
359
+ let timer;
360
+ const v = await Promise.race([
361
+ fn().catch(() => null),
362
+ new Promise((resolve) => { timer = setTimeout(() => resolve(BUDGET_OUT), left); timer.unref?.(); }),
363
+ ]).finally(() => clearTimeout(timer));
364
+ if (v === BUDGET_OUT) return null;
231
365
  if (v) return v;
232
- await sleep(gapMs);
366
+ const rest = end - Date.now();
367
+ if (rest <= 0) return null;
368
+ await sleep(Math.min(gapMs, rest));
233
369
  }
234
370
  return null;
235
371
  }
236
372
 
237
373
  /** 点编辑页上的「选择音乐」入口(真点,不是 JS click),返回点了没。 */
238
- async function clickMusicEntry(br) {
239
- const sel = await br.eval(MUSIC_ENTRY_JS).catch(() => null);
374
+ /** 页面活性检测(导出供测试)。renderer 卡死时 eval 会永远 pending,必须带超时竞速。
375
+ * 不通就 reload 一次再试;还不通返回 false,调用方别再往死页面上发操作。
376
+ * (2026-11-15 真机实录:创作者中心页挂着验证码 iframe 后整页 hung 死,
377
+ * Runtime.evaluate / Page.navigate 全部无响应,配乐两次报错的根因。) */
378
+ export async function ensurePageAlive(br, { timeoutMs = 3000, reload = true } = {}) {
379
+ const probe = () => Promise.race([
380
+ br.eval('1').then(() => true, () => false),
381
+ sleep(timeoutMs).then(() => false),
382
+ ]);
383
+ if (await probe()) return true;
384
+ if (!reload) return false;
385
+ // 死页面上 reload 命令本身也不回。send 的超时参数只对真 Browser 生效,
386
+ // 这里再套一层竞速,任何实现都不会卡死超过 5 秒。
387
+ await Promise.race([
388
+ br.send('Page.reload', {}, br.sessionId, 5000).catch(() => {}),
389
+ sleep(5000),
390
+ ]);
391
+ await sleep(3000);
392
+ return await probe();
393
+ }
394
+
395
+ async function clickMusicEntry(br, timing) {
396
+ const sel = await br.eval(MUSIC_ENTRY_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => null);
240
397
  if (!sel) return false;
241
398
  await realClick(br, sel.x, sel.y);
242
399
  await sleep(1200);
@@ -244,20 +401,23 @@ async function clickMusicEntry(br) {
244
401
  }
245
402
 
246
403
  /** 打开音乐面板,返回面板开了没。 */
247
- async function openMusicPanel(br) {
248
- if (!await clickMusicEntry(br)) return false;
249
- const opened = await waitFor(() => br.eval(MUSIC_OPEN_JS).catch(() => false), { tries: 6, gapMs: 800 });
404
+ async function openMusicPanel(br, timing) {
405
+ if (!await clickMusicEntry(br, timing)) return false;
406
+ const opened = await waitFor(() => br.eval(MUSIC_OPEN_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false), { tries: 6, gapMs: 800, budgetMs: timing.waitBudgetMs });
250
407
  return opened === true;
251
408
  }
252
409
 
253
410
  /** 打开推荐列表并保持抽屉打开,模型选完后直接点击同一张卡片。 */
254
- async function grabRecommendedMusic(br) {
255
- if (!await openMusicPanel(br)) return { ok: false, error: '没找到或打开音乐面板' };
256
- await br.eval(MUSIC_TAB_JS).catch(() => false);
411
+ async function grabRecommendedMusic(br, timing) {
412
+ // 页面卡死时 eval 永远 pending,waitFor 会空等十几秒再报「没找到面板」(2026-11-15 真机)。
413
+ // 先探活,死了就 reload 一次;还死就直接报原因,不在死页面上盲点。
414
+ if (!await ensurePageAlive(br)) return { ok: false, error: '页面没响应(已尝试刷新一次),没找到或打开音乐面板' };
415
+ if (!await openMusicPanel(br, timing)) return { ok: false, error: '没找到或打开音乐面板' };
416
+ await br.eval(MUSIC_TAB_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false);
257
417
  const songs = await waitFor(async () => {
258
- const list = await br.eval(MUSIC_ROWS_JS).catch(() => []);
418
+ const list = await br.eval(MUSIC_ROWS_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => []);
259
419
  return Array.isArray(list) && list.length ? list : null;
260
- }, { tries: 12, gapMs: 800 });
420
+ }, { tries: 12, gapMs: 800, budgetMs: timing.waitBudgetMs });
261
421
  if (!songs) return { ok: false, error: '音乐面板没有加载出推荐歌曲' };
262
422
  const counts = {};
263
423
  for (const name of songs) counts[name] = (counts[name] ?? 0) + 1;
@@ -265,8 +425,8 @@ async function grabRecommendedMusic(br) {
265
425
  }
266
426
 
267
427
  /** 关掉音乐面板,避免失败后影响下一次操作。 */
268
- async function shutMusicPanel(br) {
269
- if (!await br.eval(MUSIC_OPEN_JS).catch(() => false)) return;
428
+ async function shutMusicPanel(br, timing) {
429
+ if (!await br.eval(MUSIC_OPEN_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false)) return;
270
430
  for (const type of ['keyDown', 'keyUp']) {
271
431
  await br.send('Input.dispatchKeyEvent', { type, key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 }, br.sessionId).catch(() => {});
272
432
  }
@@ -277,12 +437,12 @@ async function shutMusicPanel(br) {
277
437
  const close = panel.closest('.semi-sidesheet')?.querySelector('.semi-sidesheet-close, [aria-label="close"]');
278
438
  if (close) close.click();
279
439
  return true;
280
- })()`).catch(() => false);
440
+ })()`, { timeoutMs: timing.evalTimeoutMs }).catch(() => false);
281
441
  }
282
442
 
283
443
  /** 仅点击匹配歌曲卡片内的「使用」,并在编辑区确认歌名后才允许发布。
284
444
  * allowDuplicate:推荐里同名卡不止一张时点第一张。编辑页仍要确认歌名,确认不了就不发布。 */
285
- async function pickNoteMusic(br, music, { allowDuplicate = false } = {}) {
445
+ async function pickNoteMusic(br, music, { allowDuplicate = false, timing = PAGE_TIMING } = {}) {
286
446
  if (!music) return { ok: false, error: '模型没有选出推荐歌曲' };
287
447
  try {
288
448
  const card = await br.eval(`(() => { ${MUSIC_DOM_JS}
@@ -293,7 +453,7 @@ async function pickNoteMusic(br, music, { allowDuplicate = false } = {}) {
293
453
  target.scrollIntoView({ block: 'center' });
294
454
  const r = target.getBoundingClientRect();
295
455
  return { count: matches.length, x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
296
- })()`);
456
+ })()`, { timeoutMs: timing.evalTimeoutMs });
297
457
  if (!card?.count) return { ok: false, error: '选中的歌曲已不在推荐列表' };
298
458
  // 同名(剪辑版 / 合集版)不整单作废。点第一张,后面仍要编辑页确认歌名。
299
459
  if (card.count !== 1 && !allowDuplicate) return { ok: false, error: '推荐列表里有同名歌曲,无法确定选哪首' };
@@ -305,7 +465,7 @@ async function pickNoteMusic(br, music, { allowDuplicate = false } = {}) {
305
465
  if (!b) return null;
306
466
  const r = b.getBoundingClientRect();
307
467
  return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
308
- })()`), { tries: 8, gapMs: 500 });
468
+ })()`, { timeoutMs: timing.evalTimeoutMs }), { tries: 8, gapMs: 500, budgetMs: timing.waitBudgetMs });
309
469
  if (!btn) return { ok: false, error: '歌曲卡片悬停后没有出现使用按钮' };
310
470
  await realClick(br, btn.x, btn.y);
311
471
  const verified = await waitFor(() => br.eval(`(() => {
@@ -322,49 +482,70 @@ async function pickNoteMusic(br, music, { allowDuplicate = false } = {}) {
322
482
  }
323
483
  }
324
484
  return false;
325
- })()`).catch(() => false), { tries: 10, gapMs: 500 });
485
+ })()`, { timeoutMs: timing.evalTimeoutMs }).catch(() => false), { tries: 10, gapMs: 500, budgetMs: timing.waitBudgetMs });
326
486
  return verified ? { ok: true } : { ok: false, error: '已点击使用,但编辑页未确认显示歌名' };
327
487
  } catch (error) {
328
488
  return { ok: false, error: `配乐操作出错:${String(error?.message ?? error).slice(0, 80)}` };
329
489
  }
330
490
  }
331
491
 
332
- /** 真正的页面驱动(测试里换成假的)。全部都得在 host.exclusive 里调。 */
333
- export function douyinSocialDriver(host) {
492
+ /** 真正的页面驱动(测试里换成假的)。全部都得在 host.exclusive 里调。
493
+ * timing:页面操作的时间上限(eval 单次超时 / waitFor 总预算),测试可以调小。 */
494
+ export function douyinSocialDriver(host, timing = {}) {
495
+ const tm = { ...PAGE_TIMING, ...timing };
334
496
  const b = () => {
335
497
  if (!host.running) throw new Error('抖音浏览器没在运行');
336
498
  return host.browser;
337
499
  };
338
- const verifyKind = async () => String(await b().eval(VERIFY_JS).catch(() => '') ?? '');
500
+ /**
501
+ * 读页面上的验证类型 —— **区分「没有验证码」和「没读到」**。
502
+ *
503
+ * ⚠️ eval 失败(超时 / CDP 断连 / 页面崩了)时读回来是空串,
504
+ * 和「没有验证码」分不开。分不开就等于把「不知道」当成「不用验证」。
505
+ *
506
+ * @param {number} timeoutMs 这次读的超时(reply 走整操作预算,别超预算)
507
+ * @returns {Promise<{kind: string, error: string}>} error 非空 = 没读到
508
+ */
509
+ const readVerifyKind = async (timeoutMs) => {
510
+ try {
511
+ return { kind: String(await b().eval(VERIFY_JS, { timeoutMs }) ?? ''), error: '' };
512
+ } catch (error) {
513
+ return { kind: '', error: errText(error) };
514
+ }
515
+ };
516
+ /** 发作品那条路用:读不到就当没有(它还有「发布成功」这个更硬的凭据兜底)。 */
517
+ const verifyKind = async () => (await readVerifyKind(tm.evalTimeoutMs)).kind;
339
518
 
340
519
  return {
341
520
  async renderCard(text, foot, theme = 0) {
342
- const out = await b().eval(cardJs(text, foot, theme));
521
+ const out = await b().eval(cardJs(text, foot, theme), { timeoutMs: tm.evalTimeoutMs });
343
522
  return typeof out === 'string' && out !== '' ? Buffer.from(out, 'base64') : null;
344
523
  },
345
524
 
346
525
  /** 创作者中心:传图 + 填标题描述,停在编辑页。返回 {ok, code?, error?}。 */
347
526
  async prepareNote({ title, text, file }) {
348
527
  const br = b();
528
+ // 进创作者中心前先探活:renderer 卡死时 goto 会白等 60 秒超时(2026-11-15 真机)。
529
+ if (!await ensurePageAlive(br)) return { ok: false, code: 'PAGE_DEAD', error: '抖音浏览器页面没响应(已尝试刷新一次),过会儿再试' };
349
530
  await br.goto(CREATOR_UPLOAD_URL, { settleMs: 8000 });
350
- const url = String(await br.eval('location.href').catch(() => '') ?? '');
531
+ const url = String(await br.eval('location.href', { timeoutMs: tm.evalTimeoutMs }).catch(() => '') ?? '');
351
532
  if (!/creator\.douyin\.com\/creator-micro/.test(url)) return { ok: false, code: 'NOT_LOGGED_IN', error: '创作者中心没登录:在抖音浏览器里打开 creator.douyin.com 登录一次' };
352
533
  // 切到「发布图文」页签(默认就是的话点了也没事)
353
534
  await br.eval(String.raw`(() => {
354
535
  const el = [...document.querySelectorAll('div, span, button')].find((x) => x.children.length === 0 && /^发布图文$/.test((x.innerText || '').trim()));
355
536
  if (el) el.click();
356
537
  return Boolean(el);
357
- })()`).catch(() => false);
538
+ })()`, { timeoutMs: tm.evalTimeoutMs }).catch(() => false);
358
539
  await sleep(1500);
359
- const r = await br.send('Runtime.evaluate', { expression: `document.querySelector('input[type="file"][accept*="image"]') || document.querySelector('input[type="file"]')` }, br.sessionId);
540
+ const r = await br.send('Runtime.evaluate', { expression: `document.querySelector('input[type="file"][accept*="image"]') || document.querySelector('input[type="file"]')` }, br.sessionId, tm.evalTimeoutMs);
360
541
  const objectId = r?.result?.objectId;
361
542
  if (!objectId) return { ok: false, code: 'NO_UPLOAD', error: '创作者中心页面上没找到上传图片的地方(可能改版了)' };
362
543
  await br.send('DOM.setFileInputFiles', { files: [file], objectId }, br.sessionId);
363
- const ready = await waitFor(() => br.eval(`(() => Boolean(document.querySelector('input[placeholder*="标题"]') || document.querySelector('[contenteditable="true"]')))()`), { tries: 40 });
544
+ const ready = await waitFor(() => br.eval(`(() => Boolean(document.querySelector('input[placeholder*="标题"]') || document.querySelector('[contenteditable="true"]')))()`, { timeoutMs: tm.evalTimeoutMs }), { tries: 40, budgetMs: tm.waitBudgetMs });
364
545
  if (!ready) return { ok: false, code: 'NO_EDITOR', error: '传完图片没进到编辑页' };
365
546
  await sleep(1500);
366
547
  if (title) {
367
- const has = await br.eval(`(() => { const el = document.querySelector('input[placeholder*="标题"]'); if (!el) return false; el.scrollIntoView({ block: 'center' }); el.focus(); el.select && el.select(); return true; })()`).catch(() => false);
548
+ const has = await br.eval(`(() => { const el = document.querySelector('input[placeholder*="标题"]'); if (!el) return false; el.scrollIntoView({ block: 'center' }); el.focus(); el.select && el.select(); return true; })()`, { timeoutMs: tm.evalTimeoutMs }).catch(() => false);
368
549
  if (has) { await br.send('Input.insertText', { text: title }, br.sessionId); await sleep(500); }
369
550
  }
370
551
  const pos = await br.eval(String.raw`(() => {
@@ -373,28 +554,28 @@ export function douyinSocialDriver(host) {
373
554
  el.scrollIntoView({ block: 'center' });
374
555
  const r = el.getBoundingClientRect();
375
556
  return r.width && r.height ? { x: Math.round(r.left + Math.min(40, r.width / 2)), y: Math.round(r.top + Math.min(20, r.height / 2)) } : null;
376
- })()`).catch(() => null);
557
+ })()`, { timeoutMs: tm.evalTimeoutMs }).catch(() => null);
377
558
  if (!pos) return { ok: false, code: 'NO_EDITOR', error: '编辑页上没找到写描述的地方' };
378
559
  await realClick(br, pos.x, pos.y);
379
560
  await sleep(500);
380
561
  await br.send('Input.insertText', { text }, br.sessionId);
381
562
  await sleep(1000);
382
563
  // 等图片传完("上传中"没了)
383
- await waitFor(async () => !/上传中|正在上传/.test(String(await br.eval('document.body.innerText').catch(() => '') ?? '')), { tries: 30 });
564
+ await waitFor(async () => !/上传中|正在上传/.test(String(await br.eval('document.body.innerText', { timeoutMs: tm.evalTimeoutMs }).catch(() => '') ?? '')), { tries: 30, budgetMs: tm.waitBudgetMs });
384
565
  return { ok: true };
385
566
  },
386
567
 
387
568
  /** 打开音乐面板,抓推荐歌并保持面板打开。 */
388
569
  async listRecommendedMusic() {
389
- return await grabRecommendedMusic(b());
570
+ return await grabRecommendedMusic(b(), tm);
390
571
  },
391
572
 
392
- async closeMusicPanel() { await shutMusicPanel(b()); },
573
+ async closeMusicPanel() { await shutMusicPanel(b(), tm); },
393
574
 
394
575
  /** 配乐确认成功后才能点发布。 */
395
576
  async publishNote({ music, beforeSubmit, allowDuplicate = false }) {
396
577
  const br = b();
397
- const picked = await pickNoteMusic(br, String(music ?? ''), { allowDuplicate });
578
+ const picked = await pickNoteMusic(br, String(music ?? ''), { allowDuplicate, timing: tm });
398
579
  if (!picked.ok) return { ok: false, code: 'MUSIC_FAILED', error: `配乐失败,未发布:${picked.error}` };
399
580
  if (beforeSubmit) await beforeSubmit(); // 在可能产生平台副作用之前持久化
400
581
  const clicked = await br.eval(String.raw`(() => {
@@ -404,14 +585,14 @@ export function douyinSocialDriver(host) {
404
585
  el.scrollIntoView({ block: 'center' });
405
586
  el.click();
406
587
  return true;
407
- })()`).catch(() => false);
588
+ })()`, { timeoutMs: tm.evalTimeoutMs }).catch(() => false);
408
589
  if (!clicked) return { ok: false, code: 'NO_PUBLISH', error: '编辑页上没找到「发布」按钮' };
409
590
  const done = await waitFor(async () => {
410
591
  const v = await verifyKind();
411
592
  if (v) return { verify: v };
412
- const st = await br.eval(`(() => ({ url: location.href, text: (document.body.innerText || '').slice(0, 3000) }))()`);
593
+ const st = await br.eval(`(() => ({ url: location.href, text: (document.body.innerText || '').slice(0, 3000) }))()`, { timeoutMs: tm.evalTimeoutMs });
413
594
  return /content\/manage/.test(st?.url ?? '') || /发布成功/.test(st?.text ?? '') ? { ok: true } : null;
414
- }, { tries: 25 });
595
+ }, { tries: 25, budgetMs: tm.waitBudgetMs });
415
596
  if (done?.verify) return { ok: false, code: 'NEEDS_VERIFY', error: '抖音要验证(短信 / 滑块)才能发' };
416
597
  if (!done?.ok) return { ok: false, code: 'NOT_CONFIRMED', error: '点了发布,但没等到「发布成功」(可能在审核,或者页面改版了)' };
417
598
  return { ok: true, musicPicked: true };
@@ -420,28 +601,34 @@ export function douyinSocialDriver(host) {
420
601
  /** 「我的」作品(最多 limit 个,新的在前)。 */
421
602
  async listWorks(limit = 3) {
422
603
  const br = b();
423
- await br.goto(SELF_URL, { settleMs: 7000 });
424
- const list = await waitFor(async () => { const l = await br.eval(WORKS_JS); return Array.isArray(l) && l.length > 0 ? l : null; }, { tries: 6 });
604
+ await br.goto(SELF_URL, { settleMs: 7000, timeoutMs: tm.gotoTimeoutMs });
605
+ const list = await waitFor(async () => { const l = await br.eval(WORKS_JS, { timeoutMs: tm.evalTimeoutMs }); return Array.isArray(l) && l.length > 0 ? l : null; }, { tries: 6, budgetMs: tm.waitBudgetMs });
425
606
  return (list ?? []).slice(0, limit);
426
607
  },
427
608
 
428
609
  /** 打开作品并展开评论区。评论区默认折叠时要点图标展开,且可能一次点不开(面板动画 / 被别的东西盖住),
429
- * 所以每 3 轮重试一次、最多点 4 次;全程以「输入框可见」为准,不靠「元素存在」误判。 */
610
+ * 所以每 3 轮重试一次、最多点 4 次;全程以「输入框可见」为准,不靠「元素存在」误判。
611
+ *
612
+ * 🔴 整操作有总预算(deadline):两个 URL 各 12 轮,每轮至少一次 eval,
613
+ * 页面卡死时一轮就 60 秒 ⇒ 光靠单次 eval 的短超时也要 5 分钟,照样霸着锁。 */
430
614
  async openWork(w) {
431
615
  const br = b();
616
+ const dl = deadline(tm.openWorkBudgetMs);
432
617
  let last = null;
433
618
  for (const url of [`https://www.douyin.com/?modal_id=${w.id}`, `https://www.douyin.com/${w.kind === 'note' ? 'note' : 'video'}/${w.id}`]) {
434
- try { await br.goto(url, { settleMs: 7000 }); } catch { continue; }
619
+ if (dl.expired()) break;
620
+ try { await br.goto(url, { settleMs: 7000, timeoutMs: dl.timeoutFor(tm.gotoTimeoutMs) }); } catch { continue; }
435
621
  let clicks = 0;
436
622
  for (let i = 0; i < 12; i++) {
437
- const st = await br.eval(COMMENT_STATE_JS).catch(() => null);
623
+ if (dl.expired()) break;
624
+ const st = await br.eval(COMMENT_STATE_JS, { timeoutMs: dl.timeoutFor(tm.evalTimeoutMs) }).catch(() => null);
438
625
  last = st ?? last;
439
626
  if (st?.box) return { ok: true };
440
627
  if (st?.btn && clicks < 4 && i % 3 === 0) {
441
- const p = await br.eval(`(() => { const el = document.querySelector('${SEL.commentBtn}'); if (!el) return null; const r = el.getBoundingClientRect(); return r.width && r.top >= 0 && r.bottom <= innerHeight ? { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) } : null; })()`).catch(() => null);
442
- if (p) { await realClick(br, p.x, p.y); clicks++; }
628
+ const p = await br.eval(`(() => { const el = document.querySelector('${SEL.commentBtn}'); if (!el) return null; const r = el.getBoundingClientRect(); return r.width && r.top >= 0 && r.bottom <= innerHeight ? { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) } : null; })()`, { timeoutMs: dl.timeoutFor(tm.evalTimeoutMs) }).catch(() => null);
629
+ if (p) { await realClick(br, p.x, p.y, dl.timeoutFor(tm.evalTimeoutMs)); clicks++; }
443
630
  }
444
- await sleep(1000);
631
+ await sleep(dl.waitFor(1000));
445
632
  }
446
633
  }
447
634
  const why = last === null ? '读不到页面状态' : `输入框${last.inDom ? '在 DOM 里但不可见' : '不存在'}、评论图标${last.btn ? '在' : '不在'}、已读到 ${last.items} 条评论`;
@@ -449,7 +636,7 @@ export function douyinSocialDriver(host) {
449
636
  },
450
637
 
451
638
  async listComments() {
452
- const l = await b().eval(LIST_COMMENTS_JS).catch(() => []);
639
+ const l = await b().eval(LIST_COMMENTS_JS, { timeoutMs: tm.evalTimeoutMs }).catch(() => []);
453
640
  return Array.isArray(l) ? l : [];
454
641
  },
455
642
 
@@ -494,15 +681,15 @@ export function douyinSocialDriver(host) {
494
681
  const onWork = await br.eval(`(() => {
495
682
  const id = ${JSON.stringify(String(awemeId || ''))};
496
683
  return location.pathname.indexOf('/note/' + id) >= 0 || location.pathname.indexOf('/video/' + id) >= 0;
497
- })()`).catch(() => false);
684
+ })()`, { timeoutMs: tm.evalTimeoutMs }).catch(() => false);
498
685
  if (!onWork) {
499
- await br.goto(`https://www.douyin.com/note/${awemeId}`, { settleMs: 8000 }).catch(() => {});
686
+ await br.goto(`https://www.douyin.com/note/${awemeId}`, { settleMs: 8000, timeoutMs: tm.gotoTimeoutMs }).catch(() => {});
500
687
  }
501
- if (!(await commentBridgeReady(br))) {
502
- const ins = await installCommentBridge(br);
688
+ if (!(await commentBridgeReady(br, { timeoutMs: tm.evalTimeoutMs }))) {
689
+ const ins = await installCommentBridge(br, { timeoutMs: tm.evalTimeoutMs });
503
690
  if (!ins.ok) return [];
504
691
  }
505
- const r = await callBridge(br, 'commentList', { awemeId, count });
692
+ const r = await callBridge(br, 'commentList', { awemeId, count }, { timeoutMs: tm.evalTimeoutMs });
506
693
  if (!r.ok) return [];
507
694
  return (r.list || []).map((c) => ({
508
695
  author: c.author || '', content: c.text || '', cid: c.cid || '',
@@ -514,35 +701,66 @@ export function douyinSocialDriver(host) {
514
701
  * 接口版回评论(带 reply_id)。text 可为空(只发图)。
515
702
  *
516
703
  * ⚠️ 这是写操作,**不做自动重试** —— 重试就是重复发评论。
704
+ * ⚠️ 失败分两种(writeState 是结构化字段,别拿错误文本猜):
705
+ * · NOT_ATTEMPTED —— 根本没发出去(桥没装上 / 本地校验没过 / 图没传上去),
706
+ * 调用方可以退回 DOM 点击;
707
+ * · ATTEMPTED_UNKNOWN —— 可能已经发出去了(超时 / 断连 / 抖音没回评论 id),
708
+ * 调用方**绝不能再发一次**。
709
+ *
710
+ * @param {object} opts
711
+ * @param {() => void} [opts.onBeforeWrite] 真正把评论发出去**之前**叫一次(同步)。
712
+ * 只有这一刻才算「可能已经发出去了」—— 本地校验 / 前置阶段没过时**不许**叫:
713
+ * 叫了,调用方就会把「压根没发出去」当成「可能发出去了」,这条评论再也回不了。
517
714
  */
518
715
  async replyApi({ awemeId, cid, text, images }, opts = {}) {
716
+ // ⚠️ 本地校验在 Node 侧先判一遍:请求根本没发出去 → NOT_ATTEMPTED。
717
+ // 页面桥里也有一份(防别的调用方绕过),但这里必须先判 ——
718
+ // 否则 onBeforeWrite 会被叫到,白白把「没发出去」记成「可能发出去了」。
719
+ if (!awemeId) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: '没给作品 id' };
519
720
  const br = b();
520
721
  if (!(await commentBridgeReady(br))) {
521
722
  const ins = await installCommentBridge(br);
522
- if (!ins.ok) return { ok: false, error: '评论桥没装上' };
723
+ if (!ins.ok) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: '评论桥没装上' };
523
724
  }
524
725
  const posted = [];
525
- for (const img of images || []) {
526
- const bytes = img.bytes;
527
- if (!bytes) continue;
528
- const auth = await callBridge(br, 'uploadAuth', {});
529
- if (!auth.ok) return { ok: false, error: `取图片上传授权失败:${auth.error ?? ''}`.slice(0, 120) };
530
- const up = await uploadCommentImage({ auth, bytes, format: img.format });
531
- if (!up.ok) return { ok: false, error: `图片上传失败:${up.error ?? ''}`.slice(0, 120) };
532
- posted.push({ uri: up.uri, width: up.width, height: up.height, format: up.format });
726
+ // ⚠️ 只把**前置阶段**(取授权 + 传图)包起来,不包 postComment:
727
+ // 前置阶段抛了 = 图还没传上去,评论**根本没发出去** → NOT_ATTEMPTED,
728
+ // 调用方还能退回 DOM 点击。postComment 抛了性质完全不同(可能已经发出去了)。
729
+ try {
730
+ for (const img of images || []) {
731
+ const bytes = img.bytes;
732
+ if (!bytes) continue;
733
+ const auth = await callBridge(br, 'uploadAuth', {});
734
+ if (!auth.ok) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: `取图片上传授权失败:${auth.error ?? ''}`.slice(0, 120) };
735
+ const up = await uploadCommentImage({ auth, bytes, format: img.format });
736
+ if (!up.ok) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: `图片上传失败:${up.error ?? ''}`.slice(0, 120) };
737
+ posted.push({ uri: up.uri, width: up.width, height: up.height, format: up.format });
738
+ }
739
+ } catch (error) {
740
+ // 前置阶段的网络异常(授权 / 上传):评论没发出去 → NOT_ATTEMPTED,保留 DOM 回退
741
+ return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: `图片前置失败:${errText(error)}`.slice(0, 120) };
533
742
  }
743
+ // 正文和图片都空 = 请求根本没发出去(同页面桥那份;这里先判:onBeforeWrite 不能叫)
744
+ if (!text && !posted.length) return { ok: false, writeState: WRITE_NOT_ATTEMPTED, error: '正文和图片都是空的' };
745
+ // ⚠️ 真正要发出去了 —— 只有这一刻才算「可能已经发出去了」
746
+ opts.onBeforeWrite?.();
534
747
  const r = await callBridge(br, 'postComment', {
535
748
  awemeId, text: text || '', replyId: cid || '', images: posted,
536
- });
537
- if (!r.ok) return { ok: false, error: r.error ?? '没发出去' };
749
+ }, { write: true });
750
+ if (!r.ok) return { ok: false, writeState: r.writeState ?? WRITE_ATTEMPTED_UNKNOWN, error: r.error ?? '没发出去' };
538
751
  return { ok: true, cid: r.cid };
539
752
  },
540
753
 
541
754
  /** 回复某条评论(按作者 + 内容找,不靠序号)。内容是「...」这类截断残渣时只按作者找
542
- * (2026-11-06:按「...」includes 永远匹配不到,5 条想回的评论全 NOT_FOUND)。返回 {ok, code?, error?}。 */
755
+ * (2026-11-06:按「...」includes 永远匹配不到,5 条想回的评论全 NOT_FOUND)。返回 {ok, code?, error?}。
756
+ *
757
+ * 🔴 整操作有总预算(deadline):这里 6 次 eval + 4 段固定等待,
758
+ * 页面卡死时不设预算就是 6 × 60 秒 = 6 分钟,照样霸着浏览器锁。 */
543
759
  async reply({ author, content }, text) {
544
760
  const br = b();
545
- const before = await br.eval(`document.querySelectorAll('${SEL.input}').length`).catch(() => 0);
761
+ const dl = deadline(tm.replyBudgetMs);
762
+ const to = () => dl.timeoutFor(tm.evalTimeoutMs);
763
+ const before = await br.eval(`document.querySelectorAll('${SEL.input}').length`, { timeoutMs: to() }).catch(() => 0);
546
764
  const usable = String(content ?? '').trim();
547
765
  const contentKey = usable === '' || usable === '...' || usable === '···' || usable === '…' ? null : usable.slice(0, 40);
548
766
  const clicked = await br.eval(`(() => {
@@ -556,9 +774,9 @@ export function douyinSocialDriver(host) {
556
774
  el.setAttribute('data-fish-reply', '1');
557
775
  leaf.click();
558
776
  return true;
559
- })()`).catch(() => false);
777
+ })()`, { timeoutMs: to() }).catch(() => false);
560
778
  if (!clicked) return { ok: false, code: 'NOT_FOUND', error: '评论区里没找到这条评论' };
561
- await sleep(1200);
779
+ await sleep(dl.waitFor(1200));
562
780
  // 回复框:这条评论里面的输入框,没有就用新冒出来的那个
563
781
  const pos = await br.eval(`(() => {
564
782
  const item = document.querySelector('[data-fish-reply="1"]');
@@ -569,15 +787,15 @@ export function douyinSocialDriver(host) {
569
787
  box.scrollIntoView({ block: 'center' });
570
788
  const r = box.getBoundingClientRect();
571
789
  return r.width && r.height ? { x: Math.round(r.left + Math.min(30, r.width / 2)), y: Math.round(r.top + r.height / 2) } : null;
572
- })()`).catch(() => null);
573
- const cleanup = () => br.eval(`(() => { for (const el of document.querySelectorAll('[data-fish-reply],[data-fish-box]')) { el.removeAttribute('data-fish-reply'); el.removeAttribute('data-fish-box'); } return true; })()`).catch(() => {});
790
+ })()`, { timeoutMs: to() }).catch(() => null);
791
+ const cleanup = () => br.eval(`(() => { for (const el of document.querySelectorAll('[data-fish-reply],[data-fish-box]')) { el.removeAttribute('data-fish-reply'); el.removeAttribute('data-fish-box'); } return true; })()`, { timeoutMs: to() }).catch(() => {});
574
792
  try {
575
793
  if (!pos) return { ok: false, code: 'NO_BOX', error: '点了「回复」没出来输入框' };
576
- await realClick(br, pos.x, pos.y);
577
- const focused = await waitFor(() => br.eval(`(() => { const box = document.querySelector('[data-fish-box="1"]'); const ed = box && box.querySelector('${SEL.editor}'); if (!ed) return false; const a = document.activeElement; if (!(a && (a === ed || ed.contains(a)))) ed.focus(); return true; })()`), { tries: 12, gapMs: 300 });
794
+ await realClick(br, pos.x, pos.y, to());
795
+ const focused = await waitFor(() => br.eval(`(() => { const box = document.querySelector('[data-fish-box="1"]'); const ed = box && box.querySelector('${SEL.editor}'); if (!ed) return false; const a = document.activeElement; if (!(a && (a === ed || ed.contains(a)))) ed.focus(); return true; })()`, { timeoutMs: to() }), { tries: 12, gapMs: 300, budgetMs: Math.min(tm.waitBudgetMs, dl.left()) });
578
796
  if (!focused) return { ok: false, code: 'NO_EDITOR', error: '回复框没聚焦上' };
579
- await br.send('Input.insertText', { text }, br.sessionId);
580
- await sleep(800);
797
+ await br.send('Input.insertText', { text }, br.sessionId, to());
798
+ await sleep(dl.waitFor(800));
581
799
  const sent = await br.eval(`(() => {
582
800
  const box = document.querySelector('[data-fish-box="1"]');
583
801
  const scope = (box && (box.parentElement?.querySelector('${SEL.right}') || box.parentElement)) || null;
@@ -588,12 +806,24 @@ export function douyinSocialDriver(host) {
588
806
  if (!el) return false;
589
807
  el.click();
590
808
  return true;
591
- })()`).catch(() => false);
809
+ })()`, { timeoutMs: to() }).catch(() => false);
592
810
  if (!sent) return { ok: false, code: 'NO_SEND', error: '回复框旁边没找到发送按钮' };
593
- await sleep(2000);
594
- const v = await verifyKind();
595
- if (v) return { ok: false, code: 'NEEDS_VERIFY', error: '抖音要验证(短信 / 滑块)才能发评论' };
596
- const left = await br.eval(`(() => { const ed = document.querySelector('[data-fish-box="1"] ${SEL.editor}'); return ed ? (ed.innerText || '').trim() : ''; })()`).catch(() => '');
811
+ await sleep(dl.waitFor(2000));
812
+ // ⚠️ 「读不回来」和「读到空」必须分开(2026-11-16 巡检 P2):
813
+ // eval 超时 / CDP 断连 / 页面崩了,读回来的都是空串 —— 和
814
+ // 「没有验证码」「框里真没字」分不开。分不开就一路落到 ok: true,
815
+ // 主人被告知「回了 X 的评论」,其实压根没发出去(状态虚报)。
816
+ // 读失败只能说「不知道」:宁可报失败(下一轮按 failed 记、不重发),
817
+ // 也不能把「不知道」报成「发出去了」。
818
+ const verified = await readVerifyKind(to());
819
+ if (verified.error) return { ok: false, code: 'VERIFY_UNKNOWN', error: `读不到抖音的验证状态:${verified.error}` };
820
+ if (verified.kind) return { ok: false, code: 'NEEDS_VERIFY', error: '抖音要验证(短信 / 滑块)才能发评论' };
821
+ let left;
822
+ try {
823
+ left = String(await br.eval(`(() => { const ed = document.querySelector('[data-fish-box="1"] ${SEL.editor}'); return ed ? (ed.innerText || '').trim() : ''; })()`, { timeoutMs: to() }) ?? '');
824
+ } catch (error) {
825
+ return { ok: false, code: 'SEND_UNKNOWN', error: `点了发送,但读不回回复框:${errText(error)}` };
826
+ }
597
827
  if (left) return { ok: false, code: 'NOT_SENT', error: '点了发送,但字还在框里(可能没发出去)' };
598
828
  return { ok: true };
599
829
  } finally {
@@ -804,8 +1034,13 @@ export class DouyinSocial extends SocialBase {
804
1034
  }, { maxMs: 90_000 });
805
1035
  for (const cm of comments) {
806
1036
  if (!cm.author || !cm.content) continue;
807
- const it = { id: commentKey(w.id, cm.author, cm.content), mid: '', name: cm.author, title: w.title, content: cm.content, where: w.kind === 'note' ? '图文' : '视频', author: cm.author };
808
- if (this.handled(it.id)) continue;
1037
+ const cid = String(cm.cid ?? '').trim();
1038
+ const it = { id: commentId(w.id, cid, cm.author, cm.content), mid: '', name: cm.author, title: w.title, content: cm.content, where: w.kind === 'note' ? '图文' : '视频', author: cm.author };
1039
+ // ⚠️ 兼容旧记录:库里存的都是文本 key(作品+作者+原文的哈希)。
1040
+ // 只查新 key 会把**已经回过**的评论当成新评论再回一遍 —— 双查,
1041
+ // 新 key 或旧文本 key 命中任一个都算已处理(record 只写新 id)。
1042
+ const legacyId = cid !== '' ? commentKey(w.id, cm.author, cm.content) : '';
1043
+ if (this.handled(it.id) || (legacyId !== '' && this.handled(legacyId))) continue;
809
1044
  if (!seeded) { this.record(it, 'backlog'); continue; } // 第一次:只记下来,不回旧的
810
1045
  if (cm.isAuthor) { this.record(it, 'skipped'); continue; }
811
1046
  if (!cm.canReply) continue;
@@ -824,18 +1059,55 @@ export class DouyinSocial extends SocialBase {
824
1059
  }
825
1060
  const wait = this.replyGapMs - (Date.now() - this.lastReplyRealMs);
826
1061
  if (wait > 0) await sleep(wait);
827
- const r = await this.host.exclusive('回抖音评论', async () => {
828
- // 有 cid 就走接口(稳、不依赖页面结构);没有(DOM 版列表)才走点击
829
- if (cm.cid) {
830
- const x = await this.driver.replyApi({ awemeId: w.id, cid: cm.cid, text, images: withImg.images });
831
- if (x?.ok) return x;
832
- // 接口失败退回点击(老路),但**不重试接口** —— 重试就是重复发
833
- this.log('warn', `[fish-soul] 抖音评论接口失败,退回点击:${x?.error ?? ''}`);
834
- }
835
- let x = await this.driver.reply(cm, text);
836
- if (x?.code === 'NOT_FOUND' && (await this.driver.openWork(w)).ok) x = await this.driver.reply(cm, text); // 页面被别的事换掉了:重开一次
837
- return x;
838
- }, { maxMs: 90_000 });
1062
+ // ⚠️ mayHaveSent:写操作**可能已经发出去了**(或者正在发出去的半路上)。
1063
+ // exclusive 超时(请求挂住 / CDP 卡住)时,异常从回调里冒出来,
1064
+ // 这时我们不知道评论到底发出去了没有 —— 发出去的就记 failed(下一轮不再发),
1065
+ // **压根没发出去的一条都不记**(还能回,别把这条评论白白丢掉)。
1066
+ // 两条写路径的标记时机不一样:
1067
+ // · 接口路径:真正 callBridge(postComment) 之前才标记 ——
1068
+ // 本地校验 / 前置阶段没过 = 压根没发出去(还能退回 DOM),不能标;
1069
+ // · DOM 路径:**进写路径就标记** —— 点回复 / 找输入框 / 插字这些步骤卡住时,
1070
+ // exclusive 超时只把错误交给调用方,回调还在锁里接着跑,
1071
+ // 它可能随后自己点下「发送」把评论发出去。
1072
+ // 这时候不提前标记,下一轮就会再发一遍 = 重复公开评论。
1073
+ let mayHaveSent = false;
1074
+ // ⚠️ writeAbandoned:外层**已经放弃**了(exclusive 超时 → 错误抛给调用方,
1075
+ // 回调还在锁里接着跑)。放弃之后回调再走到「真要写出去」那一刻,
1076
+ // 外层已经没人接结果了 —— 那一刻就地补记 failed,
1077
+ // 否则数据库里一条记录都没有,下一轮会把同一条评论再发一遍(重复公开评论)。
1078
+ let writeAbandoned = false;
1079
+ const markSent = () => {
1080
+ mayHaveSent = true;
1081
+ if (writeAbandoned) this.record(it, 'failed', text);
1082
+ };
1083
+ let r;
1084
+ try {
1085
+ r = await this.host.exclusive('回抖音评论', async () => {
1086
+ // 有 cid 就走接口(稳、不依赖页面结构);没有(DOM 版列表)才走点击
1087
+ if (cm.cid) {
1088
+ const x = await this.driver.replyApi({ awemeId: w.id, cid: cm.cid, text, images: withImg.images }, { onBeforeWrite: markSent });
1089
+ if (x?.ok) return x;
1090
+ // ⚠️ 结果不明 = 可能已经发出去了 —— 再退回 DOM 点一次就是重复评论,比不回严重得多
1091
+ if (x?.writeState === WRITE_ATTEMPTED_UNKNOWN) {
1092
+ this.log('warn', `[fish-soul] 抖音评论接口结果不明,不再重复发:${x?.error ?? ''}`);
1093
+ return { ok: false, code: 'WRITE_UNKNOWN', error: `接口结果不明,可能已经发出去了:${x?.error ?? ''}`.slice(0, 120) };
1094
+ }
1095
+ // 接口失败退回点击(老路),但**不重试接口** —— 重试就是重复发
1096
+ this.log('warn', `[fish-soul] 抖音评论接口失败,退回点击:${x?.error ?? ''}`);
1097
+ }
1098
+ // ⚠️ DOM 路径保守标记:进写路径就算「可能已经发出去了」(见上)
1099
+ markSent();
1100
+ let x = await this.driver.reply(cm, text);
1101
+ if (x?.code === 'NOT_FOUND' && (await this.driver.openWork(w)).ok) x = await this.driver.reply(cm, text); // 页面被别的事换掉了:重开一次
1102
+ return x;
1103
+ }, { maxMs: 90_000 });
1104
+ } catch (error) {
1105
+ // 外层放弃:回调后面再走到写出去那一刻,就地补记 failed(见 writeAbandoned)
1106
+ writeAbandoned = true;
1107
+ // 写操作可能已经发出去了(超时 / 断连)→ 记成 failed,下一轮不再发这条
1108
+ if (mayHaveSent) this.record(it, 'failed', text);
1109
+ throw error;
1110
+ }
839
1111
  this.lastReplyRealMs = Date.now();
840
1112
  if (r?.ok) {
841
1113
  this.verifyCleared(); // 这次没被拦:验证计数清零
@@ -863,12 +1135,14 @@ export class DouyinSocial extends SocialBase {
863
1135
  }
864
1136
 
865
1137
  /**
866
- * 图片评论:从回复文本里解析 `![说明](_stickers/文件)`,读文件 → 转 png → 带图发。
1138
+ * 图片评论:从回复文本里解析 `![说明](_stickers/文件)`,读文件 → 带图发。
867
1139
  *
868
1140
  * 模型挑图的语法和 QQ / B站 私信一致(`![得意](_stickers/得意猫.png)`),
869
1141
  * 也支持按感觉挑(`![得意](_stickers/@得意)`,先换成库里最像的那张)。
870
1142
  * 一次最多 1 张(抖音图片评论一条一张)。
871
1143
  *
1144
+ * 路径不可信:只收工作区 `_stickers/` 里的真图(越界 / 目录 / 非图片 / 超 10MB 一律不发)。
1145
+ *
872
1146
  * @returns {Promise<{text: string, images: Array<{bytes: Buffer, format: string}>}>}
873
1147
  */
874
1148
  async replyImages(raw) {
@@ -883,14 +1157,18 @@ export class DouyinSocial extends SocialBase {
883
1157
  }
884
1158
  const picked = 抠正文图(out.text);
885
1159
  out.text = picked.净文字;
1160
+ const ws = String(this.workspacePath() ?? '').trim();
1161
+ if (ws === '') return out; // 没有工作区 = 没有可发的图(别拿进程当前目录顶)
1162
+ const root = join(ws, '_stickers');
886
1163
  for (const img of picked.图.slice(0, 1)) {
887
1164
  if (img.kind !== 'path') continue;
888
1165
  const rel = String(img.value).replace(/^\.\//, '');
889
1166
  if (!rel.startsWith('_stickers/')) continue;
890
- const file = join(this.workspacePath(), rel);
1167
+ const file = safeStickerImagePath(rel, root, (...args) => this.log(...args));
1168
+ if (!file) continue;
891
1169
  let bytes = null;
892
1170
  try { bytes = readFileSync(file); } catch { continue; }
893
- // ⚠️ 不转格式、不挑扩展名 —— 实测(2026-11-08)png / jpg / gif / webp 都能直接发:
1171
+ // ⚠️ 不转格式 —— 实测(2026-11-08)png / jpg / gif / webp 都能直接发:
894
1172
  // ImageX 照收,返回的 format 就是它认的格式,抖音服务端也照渲染。
895
1173
  // 以前那版把 webp 转 png、还跳过 gif —— 两个都是错判:
896
1174
  // · 「抖音不收 gif」是看评论框 accept 属性猜的,那是**文件选择器的 UI 过滤**,
@@ -2,7 +2,7 @@
2
2
  * gateway-media.js —— 网关的图片 / 私信(B站、抖音)/ 视频介绍部分(从 gateway.js 拆出来,混入 ChatGateway.prototype)。
3
3
  */
4
4
  import { createHash } from 'node:crypto';
5
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { extname, isAbsolute, join, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { fishSoulDir, resolveOrCreatePlatformPerson, cleanupMergedDouyinNames, getKv } from './db.js';
@@ -23,7 +23,12 @@ const DOUYIN_EMOJI_RE = /^\[([\u4e00-\u9fa5A-Za-z0-9]{1,8})\]$/;
23
23
  const VOICE_TAG_RE = /^\s*\[语音\]\s*/;
24
24
  const platformName = (channelId) => (String(channelId).startsWith('bili:') ? 'B站' : '抖音');
25
25
 
26
- /** 共同校验 QQ 和私信出站图片;返回实际文件路径,失败关闭。 */
26
+ /**
27
+ * 共同校验 QQ 和私信出站图片;返回实际文件路径,失败关闭。
28
+ *
29
+ * 信任根(工作区 / 插件数据目录)自己得是普通目录:它要是 junction / 软链接,
30
+ * 真实路径整个落到工作区外,只拿 realRoot 去比是拦不住的 —— 工作区外的图照样发得出去。
31
+ */
27
32
  function safeLocalImagePath(p, workspacePath, log) {
28
33
  let raw = String(p ?? '').trim();
29
34
  if (raw === '' || /^https?:\/\//i.test(raw)) return null;
@@ -38,6 +43,12 @@ function safeLocalImagePath(p, workspacePath, log) {
38
43
  try {
39
44
  const realRoots = roots.flatMap((root) => {
40
45
  try {
46
+ // 先验根:lstat 不跟随,根自己是不是链接这里就露馅(Windows 上 junction 的 lstat 就是符号链接)。
47
+ const st = lstatSync(root);
48
+ if (!st.isDirectory() || st.isSymbolicLink()) {
49
+ log('warn', `[fish-soul] 图片允许目录不可信(不是普通目录),已拒绝:${root}`);
50
+ return [];
51
+ }
41
52
  const path = realpathSync.native(root);
42
53
  return statSync(path).isDirectory() ? [path] : [];
43
54
  } catch { return []; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-soul",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.15.37)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "scripts": {
67
- "test": "node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs",
67
+ "test": "node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs",
68
68
  "eval": "node test/eval/persona-eval.mjs"
69
69
  }
70
70
  }