From 27dc571531afde2891c9f0e8a440ca1387a4eccb Mon Sep 17 00:00:00 2001 From: qinqiu <2186498057@qq.com> Date: Tue, 17 Nov 2026 19:21:19 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(relay):=20=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?=E7=86=9F=E4=BA=BA=E5=8F=AF=E4=BB=A5=E6=89=98=E5=A5=B9=E7=BB=99?= =?UTF-8?q?=E5=8F=A6=E4=B8=80=E4=B8=AA=E7=86=9F=E4=BA=BA=E5=B8=A6=E5=8F=A5?= =?UTF-8?q?=E8=AF=9D=EF=BC=88=E9=BB=98=E8=AE=A4=E5=85=B3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why 反馈希望「白名单里的 A 能让 AI 给 B 发一条消息」。 只放行发起人挡不住三件事:B 没同意收(骚扰话术照样出去,封的是 bot 号)、 按昵称解析「B 是谁」会被冒充、出事查不到是谁让发的。 所以做的是「熟人留言板」,不是「任意转发器」。 ## 四道闸 1. `relay.enabled` 默认关 2. 发起人在白名单 3. 收件人在白名单(退化成熟人之间传话) 4. 按发起人每天限条(kv `relay.count.<日期>.`) 发出的消息强制带「【xx托我带句话】」前缀 —— 收件人知道是谁托的,她不能匿名传话。 白名单只认平台 uid(`qq:`/`bili:`/`douyin:` + 数字),昵称不参与授权: 同名可冒充、改名又对不上。路由校验格式,填错当场报错而不是静默失效。 抖音必须有确认过的会话 ID 才发(昵称只能找会话,证明不了对面是谁)—— 和主动私信同一条规矩。 ## 改动 - `lib/gateway-media.js`:`relayToFriend` + `normalizeRelayId`/`setKvRelay`/`relayPersonName`/`relayChannelOf` - `lib/gateway.js`:`RELAY_FRIEND_TOOL` + `relayConfig()` + 进 `CHAT_TOOLS` - `lib/index.js`:注册 `relay_to_friend` 工具 + `relaySenderId`(从会话反查发起人 uid) - `lib/routes.js`:`POST /relay/config` - `lib/client.js`:`RelayPane`(日常 → 熟人传话) - `lib/life.js`:`stateSnapshot` 带 `relayConfig` 供面板回显 ## 验证 `npm test` EXIT=0,501 项断言全绿。 新增 `test/relay-to-friend.mjs` 12 条断言,并对 7 道闸逐条做了撤掉验证 (撤掉 → 真红 → 恢复 → 绿)。撤抖音外层闸时第一次没红 —— `sendDouyin` 里还有第二道同类闸,断言改成打外层专属文案才验得出来。 ## 未验证 真机上由真人触发一次完整传话(要真发消息给第三方,没做)。 --- CHANGELOG.md | 6 ++ lib/client.js | 37 ++++++++- lib/config-schema.js | 8 ++ lib/gateway-media.js | 114 +++++++++++++++++++++++++++ lib/gateway.js | 14 +++- lib/index.js | 81 ++++++++++++++++++- lib/life.js | 4 +- lib/routes.js | 22 ++++++ package.json | 2 +- test/client-lint.mjs | 2 +- test/relay-to-friend.mjs | 165 +++++++++++++++++++++++++++++++++++++++ test/smoke.mjs | 2 +- 12 files changed, 448 insertions(+), 9 deletions(-) create mode 100644 test/relay-to-friend.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d42eda..a389713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # dsh-fish-soul 变更记录 +- 未发布:白名单里的熟人可以托她给另一个熟人带一句话了(默认关)。 + - **能做什么**:设置页「日常 → 熟人传话」里配一份白名单(平台 uid,一行一个),打开开关后,白名单里的人可以说「帮我跟 xx 说一声……」,她就替这人给对方带一句。适合「手机没电帮传个话」「不在电脑前让朋友转达」这类场景。 + - **为什么不是「白名单里的人随便指定谁都行」**:只判发起人挡不住三件事。一来对方没同意收,骚扰话术照样能出去,最后被封的是你这个 bot 号;二来「xx 是谁」如果按昵称解析,改个名就能冒充(这个仓库被昵称冒充坑过好几次);三来出了事查不到是谁让发的。所以这里设了四道闸:开关默认关、发起人和收件人都得在白名单里、按发起人每天限条数、发出的消息强制带「【xx托我带句话】」前缀 —— 收件人看得见是谁托的,她没法匿名传话。 + - **白名单只认平台 uid**(`qq:` / `bili:` / `douyin:` + 数字),昵称不参与授权:同名可以冒充,改名又会对不上。填错了保存时当场报错,不会静默失效。 + - **抖音要求会话确认过**:要发给某个抖音号,得先跟她确认过那个会话(对方发过消息),否则不知道对面是谁就不发 —— 和主动私信同一条规矩。 + - **验证范围**:新增套件 `test/relay-to-friend.mjs` 覆盖开关 / 双向白名单 / 频次上限 / 来源前缀 / 抖音会话校验 / 重复人 / 空内容 / 日志留痕,并对每一道闸做了撤掉验证(逐条确认测试真的变红)。**未验证**:真机上由真人触发一次完整传话(要真发消息给第三方,没做)。 - v0.18.6:设置页能翻到更早的记录了,Agent 常见的几类失误改成了机器自动拦截,仓库里残留的真实身份信息清干净了(#132、#135、#136、#137、#138)。 - **B站设置页能翻页了**(#132):「最近看过」和「动态和评论」以前只显示最近几条,更早的记录明明存着却看不到。现在两个列表各有一个「加载更多」,能一直翻到最早。顺带说明一下位置:评论和动态本来就在「动态和评论」那一组的底部(只是没写标题,容易被忽略);B站私信内容在「记忆 → 记忆存档 → 聊天文本存档」里按会话分页查看(要先开启聊天存档,默认关闭,且不补录开启前的历史)。 - **新增三个自动检查**(#135):新增测试忘了加进测试清单(CI 根本不跑)、写操作的路由漏了来源校验(任何网页都能改你的设置)、面板代码误引用宿主侧模块(面板直接空白)—— 这三类以前全靠「记得做」,现在改成了机器拦。 diff --git a/lib/client.js b/lib/client.js index 975089e..fcfdee6 100644 --- a/lib/client.js +++ b/lib/client.js @@ -497,6 +497,40 @@ window.__ModuleLoader__.load({ Button({ variant: "ghost", disabled: newGroup.trim() === "", onClick: addGroup }, "添加")) : null)); } + // ── 熟人传话:白名单里的人可以托她给白名单里的另一个人带句话(默认关)── + function RelayPane({ data, refresh, notify }) { + const rc = data?.relayConfig ?? {}; + const [form, setForm, patch] = useForm(data, () => ({ + enabled: rc.enabled === true, + allowList: (rc.allowList ?? []).join(", "), + perDay: rc.perDay ?? 5 + })); + if (!data || !form) return null; + + async function save(p = {}) { + const next = { ...form, ...p }; + setForm(next); + const res = await api("POST", "/relay/config", { + enabled: next.enabled === true, + allowList: split(next.allowList), + perDay: Number(next.perDay) + }); + if (res?.ok) refresh(); else notify(res?.error ?? "保存失败"); + } + + return h(react.Fragment, null, + Group({ className: "fs-life-settings" }, + Row({ title: "熟人传话", stack: true }, + h(Switch, { label: "熟人传话", checked: form.enabled, onChange: (v) => save({ enabled: v }) }), + Muted("打开后,白名单里的人可以让她给对方带一句话。发出的消息会自动带「xx托我带句话」前缀 —— 收件人知道是谁说的,她不能匿名传话。")), + form.enabled ? Row({ title: "白名单", stack: true }, + Area({ value: form.allowList, placeholder: "平台 uid,逗号或换行分隔:\nqq:12345678\nbili:1234567890\ndouyin:1234567890123456789", onChange: (e) => patch({ allowList: e.target.value }), onBlur: () => save() }), + Muted("填平台 uid,不是昵称 —— 昵称可以改、可以撞名。发起人和收件人都要在这里面。")) : null, + form.enabled ? Row({ title: "每人每天最多", stack: true }, + Num({ min: 1, max: 50, value: form.perDay, "aria-label": "每人每天最多", onChange: (e) => patch({ perDay: e.target.value === "" ? "" : Number(e.target.value) }), onBlur: () => save({ perDay: form.perDay === "" ? 5 : form.perDay }) }), + Muted("条。到上限就拒,防止拿她当群发工具。")) : null)); + } + // ── QQ 接入(SnowLuma 直连)与会话工作区 ── function ChannelPane({ data, refresh, notify }) { const qq = data?.qq ?? {}; @@ -855,7 +889,7 @@ window.__ModuleLoader__.load({ const TABS = [ ["memory", "记忆", [["retrieval", "检索设置"], ["people", "人物与关系"], ["memories", "记忆内容"], ["recall-test", "检索测试"], ["weekly", "周记"], ["archives", "记忆存档"], ["backups", "导入与备份"]]], ["character", "角色", [["persona", "人格卡"], ["templates", "人格模板"], ["growth", "成长"], ["worldinfo", "世界书"], ["habits", "说话习惯"], ["groups", "群设定"], ["chat-models", "聊天模型"]]], - ["daily", "日常", [["life", "主动开口"], ["activity", "最近动态"], ["diary", "日记"], ["stickers", "表情包"], ["slang", "学到的说法"]]], + ["daily", "日常", [["life", "主动开口"], ["relay", "熟人传话"], ["activity", "最近动态"], ["diary", "日记"], ["stickers", "表情包"], ["slang", "学到的说法"]]], ["channels", "平台", [["qq", "QQ"], ["bili", "B站"], ["douyin", "抖音"]]], ["models", "模型", [["models", "功能模型"], ["usage", "用量与价格"], ["web", "联网搜索"], ["voice", "语音"]]], ["system", "系统", [["interface", "界面"], ["version", "版本更新"], ["diag", "运行日志"]]] @@ -1050,6 +1084,7 @@ window.__ModuleLoader__.load({ : subtab === "version" ? h(Boundary, { name: "版本" }, h(UpdateBar, { notify, onUpdateState: setUpdateAvailable })) : subtab === "retrieval" ? h(RetrievalPane, { data: retrieval, refresh: loadRetrieval, notify }) : subtab === "life" ? h(LifePane, { data: life, refresh: loadLife, notify }) + : subtab === "relay" ? h(RelayPane, { data: life, refresh: loadLife, notify }) : ["people", "memories", "recall-test", "weekly", "archives", "backups"].includes(subtab) ? h(ChunkTab, { file: "client.soul.js", pick: (m) => m.InspectorPane, failText: "记忆管理加载失败", section: subtab, notify }) : ["activity", "stickers", "slang"].includes(subtab) ? h(ChunkTab, { file: "client.soul.js", pick: (m) => m.ActivityPane, failText: "动态加载失败", section: subtab, notify }) : ["habits", "groups", "chat-models", "diary"].includes(subtab) ? h(ChunkTab, { file: "client.behavior.js", pick: (m) => m.BehaviorPane, failText: "习惯页加载失败", section: subtab === "chat-models" ? "models" : subtab, notify }) diff --git a/lib/config-schema.js b/lib/config-schema.js index 904b2df..7a33be5 100644 --- a/lib/config-schema.js +++ b/lib/config-schema.js @@ -101,6 +101,14 @@ export function fishSoulConfigSchema(z) { expressions: z.boolean().default(true), // 学「什么场合怎么说」(只学别人的话、不带人名) privateChats: z.boolean().default(true) // 好友私聊也学(只在那个私聊里用) }).default({}), + // 熟人传话:白名单里的人 A 托她给白名单里的 B 带一句话(默认关)。 + // 白名单按平台身份(QQ 号 / B站 UID / 抖音 uid)精确匹配,昵称不参与 —— 同名可冒充。 + // 发出的消息自动带来源前缀,B 知道是谁托带的,她不能匿名传话。 + relay: z.object({ + enabled: z.boolean().default(false), + allowList: z.array(z.string()).default([]), // 白名单(平台 uid,一行一个);空 = 谁都不能用 + perDay: z.number().default(5) // 每个发起人每天最多带几条 + }).default({}), tools: z.object({ web: z.object({ // 让她能上网查东西(默认关):DSH 自带的 web_search,或自己填的搜索 API key enabled: z.boolean().default(false), diff --git a/lib/gateway-media.js b/lib/gateway-media.js index c04b804..a6baf51 100644 --- a/lib/gateway-media.js +++ b/lib/gateway-media.js @@ -23,6 +23,44 @@ const DOUYIN_EMOJI_RE = /^\[([\u4e00-\u9fa5A-Za-z0-9]{1,8})\]$/; const VOICE_TAG_RE = /^\s*\[语音\]\s*/; const platformName = (channelId) => (String(channelId).startsWith('bili:') ? 'B站' : '抖音'); +/** 传话:把 "qq:123" / "bili:456" / "douyin:789" 规整成统一形态;认不出返回 null。 */ +function normalizeRelayId(raw) { + const s = String(raw ?? '').trim(); + if (!s) return null; + // 纯数字默认当 QQ 号(群里最常这么写) + if (/^\d+$/.test(s)) return `qq:${s}`; + const m = /^(qq|bili|douyin):(\d+)$/.exec(s); + return m === null ? null : `${m[1]}:${m[2]}`; +} + +/** 传话计数写回:失败不影响已经发出去的消息。 */ +function setKvRelay(db, key, n) { + try { + db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, JSON.stringify(n)); + } catch { /* 记不下来不影响已经发出去的消息 */ } +} + +/** 按平台 uid 查显示名;查不到返回 null(只用于来源前缀,不参与授权)。 */ +function relayPersonName(db, relayId) { + const [plat, id] = relayId.split(':'); + let row = null; + try { + if (plat === 'qq') row = db.prepare('SELECT display_name FROM person WHERE qq_uin = ?').get(id); + else if (plat === 'bili') row = db.prepare('SELECT display_name FROM person WHERE bili_uid = ?').get(id); + else if (plat === 'douyin') row = db.prepare('SELECT display_name FROM person WHERE douyin_uid = ?').get(`douyin:${id}`); + } catch { /* 读不到就当没名字 */ } + const name = String(row?.display_name ?? '').trim(); + return name === '' ? null : name; +} + +/** relayId → 给别人看的 channelId(journalOut / note 用)。 */ +function relayChannelOf(relayId) { + const [plat, id] = relayId.split(':'); + if (plat === 'qq') return `private:${id}`; + if (plat === 'bili') return `bili:${id}`; + return `douyin:${id}`; +} + /** * 共同校验 QQ 和私信出站图片;返回实际文件路径,失败关闭。 * @@ -685,5 +723,81 @@ export const mediaMethods = { afterRelay(channelId, text, platform) { try { this.soul.journalOut?.(channelId, text); } catch { /* 记日志失败不影响已经发出去的消息 */ } this.note('relay', { channelId, text, reason: `主人让去${platform === 'bili' ? 'B站' : '抖音'}发的` }); + }, + + /** + * 熟人传话:白名单里的人托她给白名单里的另一个人带一句话。默认关(`relay.enabled`)。 + * + * 四道闸:① 开关 ② 发起人在白名单 ③ 收件人在白名单 ④ 发起人当天没超 `relay.perDay` 条。 + * + * 白名单按平台 uid 精确匹配(`qq:` / `bili:` / `douyin:` + 数字),昵称不参与 —— + * 同名可以冒充,改名又会对不上。 + * + * 发出的消息自动带「【xx托我带句话】」前缀:收件人知道这不是她自己的话、也知道是谁托的, + * 她没法匿名传话。 + * + * @returns {Promise<{ok: boolean, delivered: boolean, reason: string}>} + */ + async relayToFriend(fromId, toId, text) { + const said = String(text ?? '').trim(); + if (said === '') return { ok: false, delivered: false, reason: '内容是空的,没带' }; + const rcfg = this.relayConfig(); + if (rcfg.enabled !== true) return { ok: false, delivered: false, reason: '传话功能没开(设置页「日常」→ 传话)' }; + const from = normalizeRelayId(fromId); + const to = normalizeRelayId(toId); + if (from === null) return { ok: false, delivered: false, reason: '认不出是谁要传话(要 QQ 号 / B站 / 抖音的数字 uid)' }; + if (to === null) return { ok: false, delivered: false, reason: '认不出要带给谁(要 QQ 号 / B站 / 抖音的数字 uid)' }; + if (!rcfg.allowList.includes(from)) return { ok: false, delivered: false, reason: '发起的人不在传话白名单里' }; + if (!rcfg.allowList.includes(to)) return { ok: false, delivered: false, reason: '要带给的人不在传话白名单里' }; + if (from === to) return { ok: false, delivered: false, reason: '不用传话,要带话给他自己的那个人就是他本人' }; + const today = new Date().toISOString().slice(0, 10); + const key = `relay.count.${today}.${from}`; + const used = Number(getKv(this.db, key, 0) ?? 0); + if (used >= rcfg.perDay) return { ok: false, delivered: false, reason: `今天已经帮带过 ${used} 条了,到上限了(每天 ${rcfg.perDay} 条)` }; + // 人名只用来做「来源前缀」的显示,查不到就用 uid —— 白名单才是授权依据。 + const fromP = relayPersonName(this.db, from); + const [plat] = from.split(':'); + const [tplat, tid] = to.split(':'); + const fwd = `【${fromP ?? from}托我带句话】${said}`; + try { + let r; + if (tplat === 'qq') { + if (!this.qqConfig().enabled) return { ok: false, delivered: false, reason: 'QQ 那边没开' }; + if (this.channel === null || this.channel.connected !== true) return { ok: false, delivered: false, reason: 'QQ 没连上' }; + await this.channel.send(`private:${tid}`, [{ type: 'text', data: { text: fwd } }]); + r = { ok: true, delivered: true }; + } else if (tplat === 'bili') { + const bcfg = this.biliConfig(); + if (!bcfg.enabled) return { ok: false, delivered: false, reason: 'B站那边没开' }; + if (this.bili === null || !this.bili.connected) return { ok: false, delivered: false, reason: 'B站没连上' }; + const toP = relayPersonName(this.db, to); + const okSend = await this.sendBili({ channel_id: `bili:${tid}`, title: 'B站·' + (toP ?? tid) }, fwd, []); + r = { ok: okSend, delivered: okSend }; + } else if (tplat === 'douyin') { + const dcfg = this.douyinConfig(); + if (!dcfg.enabled) return { ok: false, delivered: false, reason: '抖音那边没开' }; + if (this.douyin === null || !this.douyin.connected) return { ok: false, delivered: false, reason: '抖音没连上' }; + // 抖音必须有确认过的会话 ID 才发:昵称只能用来找会话,证明不了对面是谁。 + const convId = String(getKv(this.db, `douyin.convId.${to}`, '') ?? '').trim(); + if (!/^0:1:\d+:\d+$/.test(convId)) return { ok: false, delivered: false, reason: '要带给的人还没跟她确认过抖音会话,没法发' }; + const toP = relayPersonName(this.db, to); + const row = { channel_id: `douyin:${toP ?? tid}`, title: '抖音·' + (toP ?? tid) }; + const dr = await this.sendDouyin(row, fwd, [], convId); + r = { ok: dr.ok === true, delivered: dr.delivered === true, reason: dr.error ?? '' }; + } else { + return { ok: false, delivered: false, reason: '只认 qq / bili / douyin 的 uid' }; + } + if (r.ok === true) { + setKvRelay(this.db, key, used + 1); + try { this.soul.journalOut?.(relayChannelOf(to), fwd); } catch { /* 日志失败不影响 */ } + const toP = relayPersonName(this.db, to); + this.note('relay', { channelId: relayChannelOf(to), text: fwd, reason: `${fromP ?? from} 让带给 ${toP ?? to} 的(${plat})` }); + } + return { ok: r.ok === true, delivered: r.delivered === true, reason: r.ok === true ? '' : (r.reason || '发送时报错了,看日志') }; + } catch (error) { + const msg = String(error instanceof Error ? error.message : error); + this.log('error', `[fish-soul] 传话失败:${msg}`); + return { ok: false, delivered: false, reason: msg.slice(0, 120) }; + } } }; diff --git a/lib/gateway.js b/lib/gateway.js index 6d3900f..6614d88 100644 --- a/lib/gateway.js +++ b/lib/gateway.js @@ -56,8 +56,10 @@ const OUR_SOURCES = new Set([SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DO export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget']; /** 跨平台转达:主人在 QQ 私聊里让她去抖音 / B站 私信自己一条。 */ export const RELAY_TOOL = 'send_elsewhere'; +/** 熟人传话:白名单里的人托她给白名单里的另一个人带句话(默认关)。 */ +export const RELAY_FRIEND_TOOL = 'relay_to_friend'; /** 聊天会话里放行的插件工具(记忆 + 跨平台转达)。 */ -export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL]; +export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL]; /** 宿主的联网工具:设置里打开「让她能上网查」才放行(护栏按天限次数)。 */ export const WEB_TOOLS = ['web_search', 'web_fetch']; /** 自己填 key 的搜索服务(插件注册的工具) */ @@ -785,6 +787,16 @@ export class ChatGateway { } /** #37 聊天会话的工具放行档位:memory(默认,只放记忆 + 联网)| master(主人私聊全放开)| all(所有会话全放开)。 */ + + /** 传话配置:熟人托她给另一个人带句话(默认关,白名单按平台 uid 精确匹配)。 */ + relayConfig() { + const r = this.getConfig().relay ?? {}; + return { + enabled: r.enabled === true, + allowList: Array.isArray(r.allowList) ? r.allowList.map((x) => String(x).trim()).filter(Boolean) : [], + perDay: Number.isFinite(Number(r.perDay)) ? Math.max(1, Math.min(50, Math.floor(Number(r.perDay)))) : 5 + }; + } sessionAllowMode() { const v = String(this.getConfig().tools?.sessionAllow ?? 'memory').trim().toLowerCase(); return v === 'master' || v === 'all' ? v : 'memory'; diff --git a/lib/index.js b/lib/index.js index cb0ff60..17c01fa 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,7 +15,7 @@ import { readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs'; import { loadHostDeps } from './hostdeps.mjs'; import { openDatabase, configPath, fishSoulDir, resolveOrCreatePerson, resolveOrCreateBiliPerson, - findPersonByQq, findPersonByBili, readVecMeta, getKv, setKv, getProfile, ensureMasterPerson + findPersonByQq, findPersonByBili, findPersonByDouyin, readVecMeta, getKv, setKv, getProfile, ensureMasterPerson } from './db.js'; import { WeeklyCompressor } from './weekly.js'; import { MemoryArchive } from './storage.js'; @@ -47,7 +47,7 @@ import { DouyinHttp } from './douyin-http.js'; import { fishSoulConfigSchema } from './config-schema.js'; import { loadSharp, sharpReady } from './imageconv.js'; import { - ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf + ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf } from './gateway.js'; import { platformLabelOf, platformOf } from './gateway-util.js'; import { VirtualClock } from './clock.js'; @@ -582,7 +582,44 @@ async function startup(ctx, config, { log, gate }) { }; } - /** 工具调用:按调用所在会话(toolCtx.agent.id)认人;认不出就是 unknown(不读写任何人的记忆)。 */ + /** + * 传话工具:从会话反查发起人的平台 uid(qq:123 / bili:456 / douyin:789);认不出返回空串。 + * + * 抖音这一支:会话里消息的 senderId 不是当前说话人就是机器人自己。 + * 用 conversationIdentity 把「我方 uid / 对方 uid」从 convId 里分出来, + * 对方 uid = 当前在跟她说话的那个人。 + */ + function relaySenderId(session) { + const channelId = String(session?.channelId ?? ''); + if (channelId === '') return ''; + const [kind, id] = splitChannelId(channelId); + if (kind === 'private') { + const person = findPersonByQq(db, id); + return person?.qq_uin ? `qq:${person.qq_uin}` : ''; + } + if (kind === 'bili') { + const person = findPersonByBili(db, id); + return person?.bili_uid ? `bili:${person.bili_uid}` : ''; + } + if (kind === 'douyin') { + const convId = String(getKv(db, `douyin.convId.douyin:${id}`, '') ?? '').trim(); + if (!/^0:1:\d+:\d+$/.test(convId)) return ''; + const selfUids = Array.isArray(getKv(db, 'douyin.selfUidList', null)) ? getKv(db, 'douyin.selfUidList', null) : []; + // selfUidList 是老路径:主路径是 conversationIdentity(从 convId 反推我方) + const parts = convId.split(':'); + const selfUids2 = selfUids.length > 0 ? selfUids : [String(getKv(db, 'douyin.selfUid', '') ?? '').trim()].filter(Boolean); + if (selfUids2.length === 0) return ''; + const other = parts.find((p) => /^\d+$/.test(p) && !selfUids2.includes(p)); + return otherUidOk(other) ? `douyin:${other}` : ''; + } + return ''; + } + + /** 从 convId 里挑出来的对方 uid:两段都合法才认(防 convId 脏数据)。 */ + function otherUidOk(uid) { + return typeof uid === 'string' && /^\d+$/.test(uid); + } + function sessionForTool(toolCtx, speakerName) { const id = toolCtx?.agent?.id ?? toolCtx?.sessionId; const activeChannel = gateway?.turns?.get(String(id))?.channelId; @@ -1460,6 +1497,44 @@ async function startup(ctx, config, { log, gate }) { } })), 'dsh-fish-soul: send_elsewhere'); + // ── 工具:relay_to_friend(白名单里的人 A 托她给白名单里的 B 带句话;默认关)── + ctx.effect(() => ctx.tools.register(defineTool({ + name: RELAY_FRIEND_TOOL, + description: '帮当前说话的人给另一个熟人带一句话(对方会收到「xx 托我带句话:…」)。' + + '只有对方明确要求(「帮我跟 xx 说一声」「带句话给 xx」这类)时才用,别自己找机会用。' + + '收件人必须给平台 uid(QQ 号 / B站 UID / 抖音 uid),昵称会发错人所以不认。' + + '两边都得在主人配的传话白名单里才能用,发不出去会告诉你原因,照实跟对方说,别编。', + parameters: objectSchema({ + to: { type: 'string', required: true, description: '收件人的平台 uid:QQ 号 / B站 UID / 抖音 uid(纯数字)' }, + platform: { type: 'string', description: "收件人在哪个平台:'qq' | 'bili' | 'douyin'(跟 to 一起用;不填默认 qq)" }, + text: { type: 'string', required: true, description: '要带的那句话(一段,照对方的意思写,别加引号)' } + }), + output: textOutput, + async execute(args, toolCtx) { + if (gateway === null) return '网关没起来,带不了话。'; + const session = sessionForTool(toolCtx); + // 发起人:从会话绑定身份反查平台 uid。认不出是谁就不发 —— 白名单比的是 uid, + // 认不出 = 给不了 uid,宁可拒了也不能按昵称猜(昵称可以随便改)。 + const fromId = relaySenderId(db, session); + if (fromId === '') return '认不出你是谁(这个会话没绑到认识的人),带不了话。'; + const toUid = String(args.to ?? '').trim(); + const toPlatform = String(args.platform ?? 'qq').trim().toLowerCase(); + const toId = toUid === '' ? '' : `${['bili', 'douyin'].includes(toPlatform) ? toPlatform : 'qq'}:${toUid}`; + if (toId === '') return '没带收件人,话说不了。'; + const text = String(args.text ?? '').trim(); + if (text === '') return '要带的话是空的,没发。'; + try { + const r = await gateway.relayToFriend(fromId, toId, text); + if (!r.ok) return `没带到:${r.reason}。`; + return r.delivered ? '带到了。' : '发出去了,但回读没看到,可能没真到。'; + } catch (error) { + const msg = String(error instanceof Error ? error.message : error); + log('warn', `[fish-soul] 传话失败:${msg}`); + return `没带成:${msg.slice(0, 120)}。`; + } + } + })), 'dsh-fish-soul: relay_to_friend'); + // ── 工具:fish_search(自己填 key 的搜索服务;只在鱼的聊天会话里能用,开关 / 次数由上面的护栏管)── ctx.effect(() => ctx.tools.register(defineTool({ name: OWN_WEB_TOOL, diff --git a/lib/life.js b/lib/life.js index 1c9613b..16f66f8 100644 --- a/lib/life.js +++ b/lib/life.js @@ -930,7 +930,9 @@ export class LifeEngine { lastProactiveAt: day?.last_proactive_at ?? null, locks: { isTickRunning: this.isTickRunning, isDreamRunning: this.isDreamRunning } }, - proactiveConfig: this.getConfig().proactive ?? {} + proactiveConfig: this.getConfig().proactive ?? {}, + // 熟人传话(默认关;面板在「日常」页配白名单) + relayConfig: this.getConfig().relay ?? {} }; } } diff --git a/lib/routes.js b/lib/routes.js index db34a18..98bd4ce 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -384,6 +384,28 @@ export function registerRoutes(ctx, deps) { return send(200, { ok: true, savedAt: clock.now() }); } + // 熟人传话:白名单 + 每天上限(默认关) + if (method === 'POST' && path === '/relay/config') { + if (!sameOrigin(req)) return send(403, { ok: false, error: 'forbidden' }); + const body = JSON.parse(await readBody(req, logger) || '{}'); + const list = Array.isArray(body.allowList) ? body.allowList : []; + // 只收 qq:/bili:/douyin: + 数字:昵称不参与授权(同名可冒充),写错了当场报错而不是静默失效 + const bad = list.filter((x) => typeof x !== 'string' || !/^(qq|bili|douyin):\d+$/.test(x.trim())); + if (bad.length > 0) { + return send(200, { ok: false, error: `白名单里这些不是平台 uid(要 qq:数字 / bili:数字 / douyin:数字):${bad.slice(0, 3).join('、')}` }); + } + const rawPerDay = Number(body.perDay ?? 5); + const perDay = Number.isFinite(rawPerDay) ? Math.min(50, Math.max(1, Math.floor(rawPerDay))) : 5; + saveConfig({ + relay: { + enabled: body.enabled === true, + allowList: [...new Set(list.map((x) => x.trim()))], + perDay + } + }); + return send(200, { ok: true, savedAt: clock.now() }); + } + // ── 契约 7:记忆与人物检视 ── if (method === 'GET' && path === '/inspector/overview') { const ownerFilter = url.searchParams.get('ownerId'); diff --git a/package.json b/package.json index e175b72..577f21a 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,6 @@ } }, "scripts": { - "test": "node test/memory-bulk-move.mjs && 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-bridge-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-125-memory-filter.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/memory-recall-recent-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 && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" + "test": "node test/memory-bulk-move.mjs && 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-bridge-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-125-memory-filter.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/relay-to-friend.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/memory-recall-recent-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 && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" } } diff --git a/test/client-lint.mjs b/test/client-lint.mjs index 4153e2d..64dcbd3 100644 --- a/test/client-lint.mjs +++ b/test/client-lint.mjs @@ -84,7 +84,7 @@ assert.match(main, /hasUpdate: updateAvailable/); assert.match(main, /onUpdateState: setUpdateAvailable/); assert.match(css, /\.fs\.fs-standalone \.fs-side,\.fs\.fs-settings \.fs-side\{[^}]*position:sticky;top:0/); assert.match(main, /\["memory", "记忆", \[\["retrieval", "检索设置"\], \["people", "人物与关系"\], \["memories", "记忆内容"\], \["recall-test", "检索测试"\], \["weekly", "周记"\], \["archives", "记忆存档"\], \["backups", "导入与备份"\]\]\]/); -assert.match(main, /\["daily", "日常", \[\["life", "主动开口"\], \["activity", "最近动态"\], \["diary", "日记"\], \["stickers", "表情包"\], \["slang", "学到的说法"\]\]\]/); +assert.match(main, /\["daily", "日常", \[\["life", "主动开口"\], \["relay", "熟人传话"\], \["activity", "最近动态"\], \["diary", "日记"\], \["stickers", "表情包"\], \["slang", "学到的说法"\]\]\]/); assert.match(main, /\["channels", "平台", \[\["qq", "QQ"\], \["bili", "B站"\], \["douyin", "抖音"\]\]\]/); assert.match(main, /remembered\.current/); console.log(' ✓ 两级导航:完整分类、吸顶、状态记忆和更新提示'); diff --git a/test/relay-to-friend.mjs b/test/relay-to-friend.mjs new file mode 100644 index 0000000..27d74bd --- /dev/null +++ b/test/relay-to-friend.mjs @@ -0,0 +1,165 @@ +// 熟人传话:relayToFriend 的三道闸(开关 / 白名单 / 频次上限)+ 消息来源前缀。 +import assert from 'node:assert/strict'; +import { tmpHome } from './_tmp.mjs'; + +const home = tmpHome('dsh-relay-friend-'); +process.env.DSH_HOME = home; +const { openDatabase } = await import('../lib/db.js'); +const { ChatGateway } = await import('../lib/gateway.js'); + +const db = openDatabase(); + +const calls = []; +const notes = []; + +const cfg = { + qq: { enabled: true }, masterQqUin: '10001', + bili: { enabled: true, masterUid: '555', autoReply: true }, + douyin: { enabled: true, masterName: '未云', autoReply: true }, + relay: { enabled: true, allowList: ['qq:10001', 'qq:10002', 'bili:555', 'douyin:770'], perDay: 10 } +}; + +const bili = { connected: true, send: async (mid, text) => { calls.push(['bili', mid, text]); } }; +const douyin = { + connected: true, + send: async (name, parts, convId) => { + calls.push(['douyin', name, parts, convId]); + return { ok: true, delivered: true, parts: [] }; + } +}; + +const gw = new ChatGateway({ + ctx: { get: () => undefined }, db, clock: { now: () => Date.now() }, + getConfig: () => cfg, log: () => {}, + channel: { connected: true, selfId: '1000', send: async (cid, segs) => { calls.push(['qq', cid, segs]); return '1'; }, isFriend: () => true }, + bili, douyin, + soul: { + beginTurn: () => {}, nowLabel: () => '现在', resolvePerson: () => null, memorizeUnanswered: () => {}, + availability: () => 'idle', personaName: () => '小鱼', recallInfo: () => [], + journalOut: () => {} + }, + note: (kind, info) => { notes.push([kind, info]); } +}); + +const ok = (msg) => { console.log(' ✓ ' + msg); }; + +// 1. 功能没开时拒绝 +{ + cfg.relay.enabled = false; + const r = await gw.relayToFriend('qq:10001', 'bili:555', '在吗'); + assert.equal(r.ok, false); + assert.match(r.reason, /没开/); + ok('功能没开时拒绝'); +} + +// 2. 发起人不在白名单 +{ + cfg.relay.enabled = true; + const r = await gw.relayToFriend('qq:99999', 'bili:555', '在吗'); + assert.equal(r.ok, false); + assert.match(r.reason, /白名单/); + ok('发起人不在白名单时拒绝'); +} + +// 3. 收件人不在白名单 +{ + const r = await gw.relayToFriend('qq:10001', 'bili:99999', '在吗'); + assert.equal(r.ok, false); + assert.match(r.reason, /白名单/); + ok('收件人不在白名单时拒绝'); +} + +// 4. 两边都在白名单:B站 能发出去,且带来源前缀 +{ + const r = await gw.relayToFriend('qq:10001', 'bili:555', '晚上一起吃饭'); + assert.equal(r.ok, true); + assert.equal(r.delivered, true); + assert.equal(calls.at(-1)[0], 'bili'); + assert.equal(calls.at(-1)[1], '555'); + assert.ok(calls.at(-1)[2].includes('托我带句话'), '发出的消息要带来源前缀'); + assert.ok(calls.at(-1)[2].includes('晚上一起吃饭'), '内容要带原话'); + ok('B站 传话成功且带来源前缀'); +} + +// 5. QQ 收件人也能发 +{ + const r = await gw.relayToFriend('qq:10001', 'qq:10002', '帮忙带个快递'); + assert.equal(r.ok, true); + assert.equal(r.delivered, true); + assert.equal(calls.at(-1)[0], 'qq'); + assert.equal(calls.at(-1)[1], 'private:10002'); + assert.ok(calls.at(-1)[2][0].data.text.includes('托我带句话'), 'QQ 那条也要带来源前缀'); + ok('QQ 传话成功且带来源前缀'); +} + +// 6. 抖音没确认过会话 ID 时拒绝(不按昵称猜) +// 判据打「外层那道闸」专属的文案 —— 里面 sendDouyin 还有第二道同类闸, +// 两道 reason 都含「确认过」,只匹配 /确认过/ 的话撤掉外层这测试仍然绿(验不出来)。 +{ + const before = calls.length; + const r = await gw.relayToFriend('qq:10001', 'douyin:770', '在吗'); + assert.equal(r.ok, false); + assert.match(r.reason, /还没跟她确认过抖音会话/, '要挡在外层(没进到发送逻辑)'); + assert.equal(calls.length, before, '不该真的发出去'); + ok('抖音会话没确认时拒绝'); +} + +// 7. 抖音确认过会话 ID 后能发 +{ + const { setKv } = await import('../lib/db.js'); + setKv(db, 'douyin.convId.douyin:770', '0:1:111:770'); + const r = await gw.relayToFriend('qq:10001', 'douyin:770', '在吗'); + assert.equal(r.ok, true); + assert.equal(calls.at(-1)[0], 'douyin'); + assert.equal(calls.at(-1)[3], '0:1:111:770', '要带确认过的会话 ID'); + ok('抖音确认过会话后能发'); +} + +// 8. 自己带给自己(from == to) +{ + const r = await gw.relayToFriend('qq:10001', 'qq:10001', '测试'); + assert.equal(r.ok, false); + assert.match(r.reason, /不用传话/); + ok('自己带给自己拒绝'); +} + +// 9. 内容是空的 +{ + const r = await gw.relayToFriend('qq:10001', 'bili:555', ''); + assert.equal(r.ok, false); + assert.match(r.reason, /空的/); + ok('空内容拒绝'); +} + +// 10. 频次上限:perDay 改成 1,发 1 条后第 2 条拒 +{ + cfg.relay.perDay = 1; + const before = calls.length; + const r1 = await gw.relayToFriend('qq:10002', 'bili:555', '第一条'); + assert.equal(r1.ok, true, '额度内应该发出去'); + const r2 = await gw.relayToFriend('qq:10002', 'bili:555', '第二条'); + assert.equal(r2.ok, false, '超额度要拒'); + assert.match(r2.reason, /上限/); + assert.equal(calls.length, before + 1, '超额度的那条不能真发出去'); + ok('频次上限到了拒绝且没真的发出去'); +} + +// 11. 频次按人算:另一个人还有自己的额度(qq:10003 前面没用过) +{ + cfg.relay.perDay = 1; + cfg.relay.allowList = ['qq:10001', 'qq:10002', 'qq:10003', 'bili:555', 'douyin:770']; + const r = await gw.relayToFriend('qq:10003', 'bili:555', '别人第一条'); + assert.equal(r.ok, true, '额度是按人算的,别人的额度不该被这条吃掉'); + ok('频次按发起人分别计'); +} + +// 12. 传话进了动态日志 +{ + const relayNotes = gw.decisions.filter((d) => d.kind === 'relay'); + assert.ok(relayNotes.length >= 5, `应该至少有 5 条 relay 动态,实际 ${relayNotes.length}`); + const one = relayNotes.at(-1); + assert.ok(one.reason.includes('让带给'), '动态里要写清谁让带给谁'); + ok('传话进了动态日志'); +} + +console.log('relay-to-friend: all assertions passed'); diff --git a/test/smoke.mjs b/test/smoke.mjs index 904e4e2..bd53abb 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -592,7 +592,7 @@ assert.equal(host.created[0].meta.cwd, wsDir); assert.equal(section.text(at('main-session')), '', '同一个世界里的宿主会话仍然拿不到'); ok('#41 人格卡 / 瞬态块 per-agent 挂在自家会话上,宿主会话照旧干净'); } -assert.deepEqual(host.restricts[0][1], { allow: ['remember', 'recall', 'forget', 'send_elsewhere', 'web_search', 'web_fetch', 'fish_search'] }); // #26 联网工具不筛 +assert.deepEqual(host.restricts[0][1], { allow: ['remember', 'recall', 'forget', 'send_elsewhere', 'relay_to_friend', 'web_search', 'web_fetch', 'fish_search'] }); // #26 联网工具不筛;relay_to_friend = 熟人传话(默认关) assert.equal(f1.msg.source.kind, 'fish-soul/qq'); assert.match(f1.msg.content[0].text, /我想喝冰美式/); assert.match(host.titles[0][1], /QQ·主人(主人)/); From d30fd3dd42cd9fa8685063653093aef624204e05 Mon Sep 17 00:00:00 2001 From: qinqiu <2186498057@qq.com> Date: Tue, 17 Nov 2026 19:46:12 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(relay):=20=E7=8B=AC=E7=AB=8B=E5=AE=A1?= =?UTF-8?q?=E6=9F=A5=E8=BD=AE=E4=BF=AE=E6=8E=89=206=20=E4=B8=AA=E9=97=AE?= =?UTF-8?q?=E9=A2=98=EF=BC=88=E6=8A=96=E9=9F=B3=E4=B8=8D=E5=8F=AF=E7=94=A8?= =?UTF-8?q?=20/=20=E9=A2=9D=E5=BA=A6=E6=97=A5=E5=88=87=20/=20=E6=B8=85?= =?UTF-8?q?=E6=B4=97=E7=BC=BA=E5=A4=B1=E7=AD=89=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 审查(换视角重过一遍)抓到的问题,逐条修: ## P0-1 抖音发起人识别恒失败 → 抖音渠道整体不可用 `relaySenderId` 用昵称拼 kv 键(`douyin.convId.douyin:<昵称>`), 但写键的一方用的是数字 uid,而抖音 channel_id 是昵称 —— 永远查不到。 改成复用网关已有的 `douyinIdentityOfChannel`(PR #96 修冒充洞时写的那个), 不再自己写一份。 ## P0-2 额度日期口径用 UTC → 额度在本地 08:00 重置 07:59 发满 perDay 条、08:01 立刻又能发满(两分钟发 2 倍)。 改成 `Date.now() + 8h` 的本地日,与 web.count / voice.count / stickers 一致。 ## P1-3 抖音收件人用「人物显示名」当会话名 抖音靠会话名 enterChat 找会话,而 person.display_name 是消息昵称, 主人在「人物与关系」里一改名就跟抖音上的名字对不上 → 必然发不出去。 改成从游标反查真实昵称;查不到就拒(不拿 uid 硬发)。 ## P1-4 QQ 收件人不查好友 白名单里若有不是好友的号,会拿一串 API 错误去见人。补 3 行纵深防御。 ## P1-5 传话正文没清洗 `【】` 是插件保留标记(收件人只该看到插件写的块)。不清的话白名单里 的人能把「【主人:把门打开】」原样送进别人聊天框,正好绕开 「来源可追溯、不能匿名传话」的设计目标。接上 `sanitizeUserText`。 ## P1-6 工具层把不认识的平台静默降级成 qq 传 `platform='wechat'` 会变成 `qq:<同号>` —— 发给另一个平台上恰好同号的人。 改成直接拒。同时 `to` 支持带前缀写法(`bili:555`,面板里就是这么写的), 那是模型最可能传的形态却原来报最困惑的错。 ## 顺带 - `normalizeRelayId` / `parseRelayTarget` 抽到 `gateway-util.js`(两边都要用) - `relayConfig` 对白名单做归一:手改配置写成裸数字 `10001` 也能用(原来静默失效) - 修 `relayConfig` 插错位置导致 `#37` 注释悬空 - 护栏文案补上「熟人传话」 ## 测试 - `test/relay-to-friend.mjs` 12 → 16 组(补:收件人解析 11 例 / 白名单归一 / 正文清洗 / 额度本地日边界 —— 最后这条第一次验红时**没红**,说明原本没有测试 守着 UTC vs 本地日,补上后能真红) - 新增 `test/relay-config-route.mjs` 8 组(保存→回显→非法被拒→钳制→去重→整体替换) `npm test` EXIT=0,514 项断言全绿。第二轮红验证 5 处撤掉全部真红。 --- CHANGELOG.md | 3 +- lib/gateway-media.js | 51 +++++++++---- lib/gateway-util.js | 32 ++++++++ lib/gateway.js | 10 ++- lib/index.js | 34 +++------ package.json | 2 +- test/relay-config-route.mjs | 144 ++++++++++++++++++++++++++++++++++++ test/relay-to-friend.mjs | 109 +++++++++++++++++++++++++-- 8 files changed, 336 insertions(+), 49 deletions(-) create mode 100644 test/relay-config-route.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index a389713..ac6c6a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,8 @@ - **为什么不是「白名单里的人随便指定谁都行」**:只判发起人挡不住三件事。一来对方没同意收,骚扰话术照样能出去,最后被封的是你这个 bot 号;二来「xx 是谁」如果按昵称解析,改个名就能冒充(这个仓库被昵称冒充坑过好几次);三来出了事查不到是谁让发的。所以这里设了四道闸:开关默认关、发起人和收件人都得在白名单里、按发起人每天限条数、发出的消息强制带「【xx托我带句话】」前缀 —— 收件人看得见是谁托的,她没法匿名传话。 - **白名单只认平台 uid**(`qq:` / `bili:` / `douyin:` + 数字),昵称不参与授权:同名可以冒充,改名又会对不上。填错了保存时当场报错,不会静默失效。 - **抖音要求会话确认过**:要发给某个抖音号,得先跟她确认过那个会话(对方发过消息),否则不知道对面是谁就不发 —— 和主动私信同一条规矩。 - - **验证范围**:新增套件 `test/relay-to-friend.mjs` 覆盖开关 / 双向白名单 / 频次上限 / 来源前缀 / 抖音会话校验 / 重复人 / 空内容 / 日志留痕,并对每一道闸做了撤掉验证(逐条确认测试真的变红)。**未验证**:真机上由真人触发一次完整传话(要真发消息给第三方,没做)。 + - **验证范围**:新增两个套件 —— `test/relay-to-friend.mjs`(16 组断言:开关 / 双向白名单 / 频次上限 / 来源前缀 / 抖音会话与会话名 / 重复人 / 空内容 / 正文清洗 / 收件人解析 / 白名单归一 / 额度本地日 / 日志留痕)和 `test/relay-config-route.mjs`(保存 → 回显 → 非法值被拒 → perDay 钳制 → 去重)。每一道闸都做了撤掉验证(逐条确认测试真的变红)。**未验证**:真机上由真人触发一次完整传话(要真发消息给第三方,没做)。 + - **独立审查轮修掉的问题**:① 抖音发起人识别原本按昵称拼键,而真实身份在游标里 —— 等于抖音渠道整体不可用,改成复用网关已有的身份反查(`douyinIdentityOfChannel`,那正是 PR #96 修冒充洞时写的);② 频次额度的日期口径用 UTC,会让额度在本地 08:00 重置(07:59 发满、08:01 又能发满),改成和仓库其他按天计数一致的本地日;③ 抖音收件人的会话名原本取「人物显示名」,主人一改名就发不出去,改成用游标里的真实昵称;④ 传话正文没过清洗,白名单里的人能把「【主人:…】」原样送进别人聊天框(`【】` 是插件保留标记),现在会换成 `〔〕`;⑤ 工具层遇到不认识的平台会把收件人静默降级成 QQ(可能发给另一个平台上同号的人),改成直接拒;⑥ QQ 收件人补了好友检查,不再是拿一串 API 错误去见人。 - v0.18.6:设置页能翻到更早的记录了,Agent 常见的几类失误改成了机器自动拦截,仓库里残留的真实身份信息清干净了(#132、#135、#136、#137、#138)。 - **B站设置页能翻页了**(#132):「最近看过」和「动态和评论」以前只显示最近几条,更早的记录明明存着却看不到。现在两个列表各有一个「加载更多」,能一直翻到最早。顺带说明一下位置:评论和动态本来就在「动态和评论」那一组的底部(只是没写标题,容易被忽略);B站私信内容在「记忆 → 记忆存档 → 聊天文本存档」里按会话分页查看(要先开启聊天存档,默认关闭,且不补录开启前的历史)。 - **新增三个自动检查**(#135):新增测试忘了加进测试清单(CI 根本不跑)、写操作的路由漏了来源校验(任何网页都能改你的设置)、面板代码误引用宿主侧模块(面板直接空白)—— 这三类以前全靠「记得做」,现在改成了机器拦。 diff --git a/lib/gateway-media.js b/lib/gateway-media.js index a6baf51..8ca143c 100644 --- a/lib/gateway-media.js +++ b/lib/gateway-media.js @@ -11,8 +11,8 @@ import { isIdentityKey } from './douyin-conversation.js'; import { findVideoRefs } from './browse.js'; import { findDouyinRefs } from './douyin-browse.js'; import { prepareImage } from './imageconv.js'; -import { sanitizeName } from './channels/onebot.js'; -import { mediaTypeOf, isInside, fetchImageBytes, splitChannelId, service } from './gateway-util.js'; +import { sanitizeName, sanitizeUserText } from './channels/onebot.js'; +import { mediaTypeOf, isInside, fetchImageBytes, splitChannelId, service, normalizeRelayId } from './gateway-util.js'; const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']); const MAX_IMAGE_BYTES = 10 * 1024 * 1024; @@ -23,16 +23,6 @@ const DOUYIN_EMOJI_RE = /^\[([\u4e00-\u9fa5A-Za-z0-9]{1,8})\]$/; const VOICE_TAG_RE = /^\s*\[语音\]\s*/; const platformName = (channelId) => (String(channelId).startsWith('bili:') ? 'B站' : '抖音'); -/** 传话:把 "qq:123" / "bili:456" / "douyin:789" 规整成统一形态;认不出返回 null。 */ -function normalizeRelayId(raw) { - const s = String(raw ?? '').trim(); - if (!s) return null; - // 纯数字默认当 QQ 号(群里最常这么写) - if (/^\d+$/.test(s)) return `qq:${s}`; - const m = /^(qq|bili|douyin):(\d+)$/.exec(s); - return m === null ? null : `${m[1]}:${m[2]}`; -} - /** 传话计数写回:失败不影响已经发出去的消息。 */ function setKvRelay(db, key, n) { try { @@ -53,6 +43,22 @@ function relayPersonName(db, relayId) { return name === '' ? null : name; } +/** 抖音会话名(`douyin:` → 游标里记的真实昵称);查不到返回 null(不猜)。 */ +function relayDouyinName(db, relayId) { + try { + const identity = relayId.startsWith('douyin:') ? relayId : `douyin:${relayId}`; + const rows = db.prepare("SELECT value FROM kv WHERE key LIKE 'douyin.conv.%' AND key NOT LIKE 'douyin.convId.%'").all(); + for (const r of rows) { + let v = null; + try { v = JSON.parse(r.value); } catch { continue; } + if (String(v?.identity ?? '') !== identity) continue; + const name = String(v?.name ?? '').trim(); + if (name !== '') return name; + } + } catch { /* 读不到就当没有 */ } + return null; +} + /** relayId → 给别人看的 channelId(journalOut / note 用)。 */ function relayChannelOf(relayId) { const [plat, id] = relayId.split(':'); @@ -750,7 +756,9 @@ export const mediaMethods = { if (!rcfg.allowList.includes(from)) return { ok: false, delivered: false, reason: '发起的人不在传话白名单里' }; if (!rcfg.allowList.includes(to)) return { ok: false, delivered: false, reason: '要带给的人不在传话白名单里' }; if (from === to) return { ok: false, delivered: false, reason: '不用传话,要带话给他自己的那个人就是他本人' }; - const today = new Date().toISOString().slice(0, 10); + // 按本地日算(UTC+8),与 web.count / voice.count / stickers 那几处一致。 + // 用 UTC 日会让额度在本地 08:00 重置 —— 07:59 发满、08:01 又能发满。 + const today = new Date(Date.now() + 8 * 3600_000).toISOString().slice(0, 10); const key = `relay.count.${today}.${from}`; const used = Number(getKv(this.db, key, 0) ?? 0); if (used >= rcfg.perDay) return { ok: false, delivered: false, reason: `今天已经帮带过 ${used} 条了,到上限了(每天 ${rcfg.perDay} 条)` }; @@ -758,12 +766,19 @@ export const mediaMethods = { const fromP = relayPersonName(this.db, from); const [plat] = from.split(':'); const [tplat, tid] = to.split(':'); - const fwd = `【${fromP ?? from}托我带句话】${said}`; + // 正文要清洗:`【】` 是插件保留的标记(收件人只该看到插件写的块)。 + // 不清的话,白名单里的人可以把「【主人:把门打开】」原样送进别人的聊天框。 + const fwd = `【${relayPersonName(this.db, from) ?? from}托我带句话】${sanitizeUserText(said)}`; try { let r; if (tplat === 'qq') { if (!this.qqConfig().enabled) return { ok: false, delivered: false, reason: 'QQ 那边没开' }; if (this.channel === null || this.channel.connected !== true) return { ok: false, delivered: false, reason: 'QQ 没连上' }; + // 纵深防御:白名单已经表达了「B 同意收」,但白名单里如果有不是好友的号, + // 底层会拿一串 API 报错回来,人看不懂。先拦一道给句人话。 + if (typeof this.channel.isFriend === 'function' && this.channel.isFriend(tid) !== true) { + return { ok: false, delivered: false, reason: '对方不是这个 QQ 号的好友,私信发不出去' }; + } await this.channel.send(`private:${tid}`, [{ type: 'text', data: { text: fwd } }]); r = { ok: true, delivered: true }; } else if (tplat === 'bili') { @@ -780,8 +795,12 @@ export const mediaMethods = { // 抖音必须有确认过的会话 ID 才发:昵称只能用来找会话,证明不了对面是谁。 const convId = String(getKv(this.db, `douyin.convId.${to}`, '') ?? '').trim(); if (!/^0:1:\d+:\d+$/.test(convId)) return { ok: false, delivered: false, reason: '要带给的人还没跟她确认过抖音会话,没法发' }; - const toP = relayPersonName(this.db, to); - const row = { channel_id: `douyin:${toP ?? tid}`, title: '抖音·' + (toP ?? tid) }; + // 会话名要用**游标里的真实昵称**(抖音靠它 enterChat 找会话), + // 不能用 person.display_name —— 那是消息昵称,主人还能在「人物与关系」里改, + // 改了就跟抖音上的名字对不上,发不出去。 + const toName = relayDouyinName(this.db, to); + if (toName === null) return { ok: false, delivered: false, reason: '认不出这个抖音会话叫什么名字(还没读到过它的会话列表),暂时发不了' }; + const row = { channel_id: `douyin:${toName}`, title: '抖音·' + toName }; const dr = await this.sendDouyin(row, fwd, [], convId); r = { ok: dr.ok === true, delivered: dr.delivered === true, reason: dr.error ?? '' }; } else { diff --git a/lib/gateway-util.js b/lib/gateway-util.js index f69b937..a5db9ab 100644 --- a/lib/gateway-util.js +++ b/lib/gateway-util.js @@ -112,6 +112,38 @@ export function interjectConfig(raw) { }; } +/** 传话用的平台身份:把 "qq:123" / "bili:456" / "douyin:789" 规整成统一形态;认不出返回 null。 + * 纯数字默认当 QQ 号(群里最常这么写)。 */ +export function normalizeRelayId(raw) { + const s = String(raw ?? '').trim(); + if (!s) return null; + if (/^\d+$/.test(s)) return `qq:${s}`; + const m = /^(qq|bili|douyin):(\d+)$/.exec(s); + return m === null ? null : `${m[1]}:${m[2]}`; +} + +/** 传话工具的收件人解析:`to` + `platform` → `qq:123` / `bili:123` / `douyin:123`。 + * + * 两种写法都收:「带前缀」(`bili:12345`,面板里就是这么写的)和「纯数字 + platform」。 + * @returns {{ok: true, id: string} | {ok: false, error: string}} + * 🔴 不认识的 platform **必须拒**,不能静默降级成 qq —— 那会把话发给 + * 「另一个平台上恰好同号的人」。 + */ +export function parseRelayTarget(toRaw, platformRaw) { + const raw = String(toRaw ?? '').trim(); + if (raw === '') return { ok: false, error: '没带收件人(要给对方的平台 uid),话说不了。' }; + if (/^(qq|bili|douyin):\d+$/.test(raw)) return { ok: true, id: raw }; + if (/^\d+$/.test(raw)) { + const p = platformRaw === undefined || platformRaw === null || String(platformRaw).trim() === '' + ? 'qq' : String(platformRaw).trim().toLowerCase(); + if (!['qq', 'bili', 'douyin'].includes(p)) { + return { ok: false, error: `不认识的平台「${String(platformRaw).trim()}」,只认 qq / bili / douyin,这次没带。` }; + } + return { ok: true, id: `${p}:${raw}` }; + } + return { ok: false, error: `收件人「${raw}」看不出是哪个平台的号。要么给纯数字 + platform,要么写成 qq:123 / bili:123 / douyin:123。` }; +} + /** channel_id → 平台:bili: 是 B站私信,douyin:<名字> / douyin-group:<群名> 是抖音私信 / 群聊,其余(private:/group:)是 QQ。 */ export function platformOf(channelId) { const s = String(channelId ?? ''); diff --git a/lib/gateway.js b/lib/gateway.js index 6614d88..0fb9779 100644 --- a/lib/gateway.js +++ b/lib/gateway.js @@ -37,7 +37,7 @@ import { applyAttachments, attachmentConfig } from './attachments.js'; import { parseCollect } from './stickers.js'; import { UNHEARD } from './voice.js'; import { saveVoiceFile, voiceIncomingEpoch, audioExt } from './voice-files.js'; -import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow } from './gateway-util.js'; +import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow, normalizeRelayId } from './gateway-util.js'; import { mediaMethods } from './gateway-media.js'; import { Outbox, classifySendError } from './outbox.js'; import { safeDownload } from './safe-download.js'; @@ -786,17 +786,19 @@ export class ChatGateway { WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n)); } - /** #37 聊天会话的工具放行档位:memory(默认,只放记忆 + 联网)| master(主人私聊全放开)| all(所有会话全放开)。 */ - /** 传话配置:熟人托她给另一个人带句话(默认关,白名单按平台 uid 精确匹配)。 */ relayConfig() { const r = this.getConfig().relay ?? {}; return { enabled: r.enabled === true, - allowList: Array.isArray(r.allowList) ? r.allowList.map((x) => String(x).trim()).filter(Boolean) : [], + // 手改配置文件可能写成裸数字(`10001`)—— 归一成 `qq:10001` 再比, + // 不然形式对不上就静默失效(主人以为配了,实际一条也发不出去)。 + allowList: Array.isArray(r.allowList) ? r.allowList.map((x) => normalizeRelayId(x)).filter((x) => x !== null) : [], perDay: Number.isFinite(Number(r.perDay)) ? Math.max(1, Math.min(50, Math.floor(Number(r.perDay)))) : 5 }; } + + /** #37 聊天会话的工具放行档位:memory(默认,只放记忆 + 联网)| master(主人私聊全放开)| all(所有会话全放开)。 */ sessionAllowMode() { const v = String(this.getConfig().tools?.sessionAllow ?? 'memory').trim().toLowerCase(); return v === 'master' || v === 'all' ? v : 'memory'; diff --git a/lib/index.js b/lib/index.js index 17c01fa..a3e7085 100644 --- a/lib/index.js +++ b/lib/index.js @@ -49,7 +49,7 @@ import { loadSharp, sharpReady } from './imageconv.js'; import { ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf } from './gateway.js'; -import { platformLabelOf, platformOf } from './gateway-util.js'; +import { platformLabelOf, platformOf, parseRelayTarget } from './gateway-util.js'; import { VirtualClock } from './clock.js'; import { EmbeddingClient, VectorWorker, recall, recallSync, vectorRanks } from './retrieval.js'; import { LifeEngine } from './life.js'; @@ -602,24 +602,15 @@ async function startup(ctx, config, { log, gate }) { return person?.bili_uid ? `bili:${person.bili_uid}` : ''; } if (kind === 'douyin') { - const convId = String(getKv(db, `douyin.convId.douyin:${id}`, '') ?? '').trim(); - if (!/^0:1:\d+:\d+$/.test(convId)) return ''; - const selfUids = Array.isArray(getKv(db, 'douyin.selfUidList', null)) ? getKv(db, 'douyin.selfUidList', null) : []; - // selfUidList 是老路径:主路径是 conversationIdentity(从 convId 反推我方) - const parts = convId.split(':'); - const selfUids2 = selfUids.length > 0 ? selfUids : [String(getKv(db, 'douyin.selfUid', '') ?? '').trim()].filter(Boolean); - if (selfUids2.length === 0) return ''; - const other = parts.find((p) => /^\d+$/.test(p) && !selfUids2.includes(p)); - return otherUidOk(other) ? `douyin:${other}` : ''; + // 抖音的 channel_id 是昵称(`douyin:<昵称>`),**不是身份** —— 昵称能改、能撞名。 + // 真实身份要从游标反查(`douyin.conv.` 里的 identity,那是用会话 ID 推出来的)。 + // 复用网关已有的实现,别在这里再写一份(PR #96 的冒充洞就是按昵称认人)。 + const identity = String(gateway?.douyinIdentityOfChannel?.(channelId) ?? '').trim(); + return /^douyin:\d+$/.test(identity) ? identity : ''; } return ''; } - /** 从 convId 里挑出来的对方 uid:两段都合法才认(防 convId 脏数据)。 */ - function otherUidOk(uid) { - return typeof uid === 'string' && /^\d+$/.test(uid); - } - function sessionForTool(toolCtx, speakerName) { const id = toolCtx?.agent?.id ?? toolCtx?.sessionId; const activeChannel = gateway?.turns?.get(String(id))?.channelId; @@ -1291,7 +1282,7 @@ async function startup(ctx, config, { log, gate }) { } if (exec.name === 'run_code') return `聊天会话里不能运行代码(放开工具也不放 run_code:它能跑任意程序)`; if (sessionOpen(id)) return undefined; // #37 主人/全部放开:宿主工具都放 - return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达和上网查;设置页「模型」里可以放开)`; + return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达、熟人传话和上网查;设置页「模型」里可以放开)`; }); gateway.voiceGuardReady = true; return () => { gateway.voiceGuardReady = false; off?.(); }; @@ -1505,8 +1496,8 @@ async function startup(ctx, config, { log, gate }) { '收件人必须给平台 uid(QQ 号 / B站 UID / 抖音 uid),昵称会发错人所以不认。' + '两边都得在主人配的传话白名单里才能用,发不出去会告诉你原因,照实跟对方说,别编。', parameters: objectSchema({ - to: { type: 'string', required: true, description: '收件人的平台 uid:QQ 号 / B站 UID / 抖音 uid(纯数字)' }, - platform: { type: 'string', description: "收件人在哪个平台:'qq' | 'bili' | 'douyin'(跟 to 一起用;不填默认 qq)" }, + to: { type: 'string', required: true, description: "收件人的平台 uid。两种写法都收:纯数字 + platform(如 to='12345', platform='qq'),或直接带前缀(如 to='bili:12345')。白名单里怎么写的就照抄" }, + platform: { type: 'string', description: "收件人在哪个平台:'qq' | 'bili' | 'douyin'。to 已经带前缀时可以不给;两个都给就以前缀为准。**不认识的平台值会被拒**(不会默认成 QQ,那样可能把话发给另一个人)" }, text: { type: 'string', required: true, description: '要带的那句话(一段,照对方的意思写,别加引号)' } }), output: textOutput, @@ -1517,10 +1508,9 @@ async function startup(ctx, config, { log, gate }) { // 认不出 = 给不了 uid,宁可拒了也不能按昵称猜(昵称可以随便改)。 const fromId = relaySenderId(db, session); if (fromId === '') return '认不出你是谁(这个会话没绑到认识的人),带不了话。'; - const toUid = String(args.to ?? '').trim(); - const toPlatform = String(args.platform ?? 'qq').trim().toLowerCase(); - const toId = toUid === '' ? '' : `${['bili', 'douyin'].includes(toPlatform) ? toPlatform : 'qq'}:${toUid}`; - if (toId === '') return '没带收件人,话说不了。'; + const target = parseRelayTarget(args.to, args.platform); + if (target.ok !== true) return target.error; + const toId = target.id; const text = String(args.text ?? '').trim(); if (text === '') return '要带的话是空的,没发。'; try { diff --git a/package.json b/package.json index 577f21a..e95a91d 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,6 @@ } }, "scripts": { - "test": "node test/memory-bulk-move.mjs && 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-bridge-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-125-memory-filter.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/relay-to-friend.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/memory-recall-recent-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 && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" + "test": "node test/memory-bulk-move.mjs && 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-bridge-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-125-memory-filter.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/relay-to-friend.mjs && node test/relay-config-route.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/memory-recall-recent-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 && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" } } diff --git a/test/relay-config-route.mjs b/test/relay-config-route.mjs new file mode 100644 index 0000000..d819d87 --- /dev/null +++ b/test/relay-config-route.mjs @@ -0,0 +1,144 @@ +/** + * 熟人传话的配置路由:保存 → 回显 → 非法值被拒。 + * + * 为什么要有这个测试(和 qq-mention-only-echo / reply-window 同一族): + * 设置页保存成功但后端漏透传字段时,面板 refresh 后读不到 → UI 显示「关」 + * 而功能其实开着,或者反过来。凡是「写进去读不回来」的都要靠回显断言守着。 + * + * 另外白名单的格式校验必须在保存时就把关:填错了静默失效, + * 主人会以为配好了,直到某天想用才发现一条都发不出去。 + */ +import assert from 'node:assert/strict'; +import { tmpHome } from './_tmp.mjs'; + +const ok = (msg) => console.log('✓', msg); +process.env.DSH_HOME = tmpHome('dsh-relay-config-'); + +const { openDatabase } = await import('../lib/db.js'); +const { registerRoutes } = await import('../lib/routes.js'); + +const db = openDatabase(); + +let cfg = { qq: { enabled: true }, bili: {}, douyin: {}, masterQqUin: '10001' }; + +const deps = { + db, + clock: { getRoleDateParts: () => ({ dateStr: '2030-01-01' }), now: () => 1000 }, + embedder: {}, + worker: {}, + life: { browseState: () => ({ count: 0 }), stateSnapshot: () => ({ today: {}, relayConfig: cfg.relay ?? {} }) }, + getConfig: () => cfg, + saveConfig: (patch) => { cfg = { ...cfg, ...patch }; }, + log: () => {}, + gateway: { workspacePath: () => '/ws', listWorkspaces: () => [], isPaused: () => false }, + channel: { status: () => ({ connected: true }), restart() {} }, + bili: { status: () => ({ loggedIn: false }), restart() {} }, + biliClient: null, + browser: null, + biliSocial: null, + douyin: { status: () => ({ running: false }) }, + douyinHost: { browsers: [], status: () => ({ state: 'stopped' }) }, + douyinBrowser: null, + douyinSocial: null +}; + +function mount() { + let handler = null; + registerRoutes({ + effect: (fn) => { fn(); }, + webServer: { register: (o) => { handler = o.handler; } } + }, deps); + return handler; +} + +async function call(path, method = 'GET', body = null, headers = {}) { + const handler = mount(); + let out = ''; + const req = new (await import('node:stream')).Readable({ + read() { this.push(body === null ? null : JSON.stringify(body)); if (body !== null) this.push(null); } + }); + req.url = `/api/plugins/fish-soul${path}`; + req.method = method; + req.headers = headers; + const res = { writeHead: () => {}, end: (text) => { out = text; } }; + await handler(req, res); + return JSON.parse(out); +} + +// 1. 默认关:没配过就不能用 +{ + cfg = { qq: { enabled: true }, bili: {}, douyin: {}, masterQqUin: '10001' }; + const state = await call('/life/state'); + assert.equal(state.relayConfig?.enabled === true, false, '默认必须是关(功能默认关是红线)'); + assert.deepEqual(state.relayConfig?.allowList ?? [], [], '默认白名单是空的 = 谁都不能用'); + ok('默认关、白名单为空'); +} + +// 2. 打开 + 配白名单 → 保存成功 → 读得回来 +{ + const res = await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001', 'bili:555', 'douyin:770'], perDay: 3 }); + assert.equal(res.ok, true, `保存要成功,实际:${res.error}`); + assert.equal(cfg.relay.enabled, true, '开关要真的落进配置'); + assert.equal(cfg.relay.perDay, 3, '上限要真的落进配置'); + assert.deepEqual(cfg.relay.allowList, ['qq:10001', 'bili:555', 'douyin:770'], '白名单要真的落进配置'); + const state = await call('/life/state'); + assert.equal(state.relayConfig.enabled, true, '打开后要读回来 true(读不回来 = 开关自己弹回去)'); + assert.deepEqual(state.relayConfig.allowList, ['qq:10001', 'bili:555', 'douyin:770'], '白名单要读得回来'); + ok('保存 → 回显一致'); +} + +// 3. 关掉 → 读回来 false +{ + const res = await call('/relay/config', 'POST', { enabled: false, allowList: ['qq:10001'], perDay: 5 }); + assert.equal(res.ok, true); + assert.equal((await call('/life/state')).relayConfig.enabled, false, '关掉后要读回来 false'); + ok('关掉能读回来'); +} + +// 4. 白名单格式非法 → 拒绝保存(不能静默失效) +{ + const before = JSON.stringify(cfg.relay); + const res = await call('/relay/config', 'POST', { enabled: true, allowList: ['未云', 'qq:abc', 'bili:'], perDay: 5 }); + assert.equal(res.ok, false, '昵称 / 非数字 uid 必须被拒'); + assert.match(res.error, /不是平台 uid/, '要说清哪里不对'); + assert.equal(JSON.stringify(cfg.relay), before, '被拒时不能改动已存的配置'); + ok('非法白名单被拒且不改配置'); +} + +// 5. 白名单里有一条非法 → 整批拒(不做「能用的留下」的静默部分成功) +{ + const before = JSON.stringify(cfg.relay); + const res = await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001', '乱写'], perDay: 5 }); + assert.equal(res.ok, false, '混了非法项要整批拒'); + assert.equal(JSON.stringify(cfg.relay), before, '整批拒时不能改动配置'); + ok('混了非法项整批拒'); +} + +// 6. perDay 钳制到 1..50 +{ + await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001'], perDay: 999 }); + assert.equal(cfg.relay.perDay, 50, '上限过大的要钳到 50'); + await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001'], perDay: -3 }); + assert.equal(cfg.relay.perDay, 1, '下限要钳到 1'); + await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001'], perDay: 7.9 }); + assert.equal(cfg.relay.perDay, 7, '小数要取整'); + ok('perDay 钳制 1..50'); +} + +// 7. 白名单去重(同一人写两遍不该占两个位置) +{ + const res = await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001', 'qq:10001', 'bili:555'], perDay: 5 }); + assert.equal(res.ok, true); + assert.deepEqual(cfg.relay.allowList, ['qq:10001', 'bili:555'], '重复的要合并'); + ok('白名单去重'); +} + +// 8. 不幂等:每次保存都整体替换(不是追加) +{ + await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001', 'bili:555'], perDay: 5 }); + await call('/relay/config', 'POST', { enabled: true, allowList: ['qq:10001'], perDay: 5 }); + assert.deepEqual(cfg.relay.allowList, ['qq:10001'], '第二次保存要把 bili:555 移除(整体替换语义)'); + ok('每次保存整体替换'); +} + +console.log('relay-config-route: all assertions passed'); diff --git a/test/relay-to-friend.mjs b/test/relay-to-friend.mjs index 27d74bd..60907ac 100644 --- a/test/relay-to-friend.mjs +++ b/test/relay-to-friend.mjs @@ -105,14 +105,31 @@ const ok = (msg) => { console.log(' ✓ ' + msg); }; } // 7. 抖音确认过会话 ID 后能发 +// 会话名要从游标里反查(抖音靠它在 enterChat 里找会话),不能用 person.display_name —— +// 那是消息昵称,主人还能在「人物与关系」里改,改了就跟抖音上的名字对不上。 { const { setKv } = await import('../lib/db.js'); setKv(db, 'douyin.convId.douyin:770', '0:1:111:770'); - const r = await gw.relayToFriend('qq:10001', 'douyin:770', '在吗'); - assert.equal(r.ok, true); - assert.equal(calls.at(-1)[0], 'douyin'); - assert.equal(calls.at(-1)[3], '0:1:111:770', '要带确认过的会话 ID'); - ok('抖音确认过会话后能发'); + // 还没有游标:认不出会话名,必须拒(不能拿 uid 当会话名硬发) + { + const before = calls.length; + const r = await gw.relayToFriend('qq:10001', 'douyin:770', '在吗'); + assert.equal(r.ok, false, '没有游标时不该发'); + assert.match(r.reason, /叫什么名字/, '要说清是认不出会话名'); + assert.equal(calls.length, before, '不该真的发出去'); + ok('抖音没有游标(认不出会话名)时拒绝'); + } + // 有了游标:能发,且会话名用游标里的 name(setKv 自己会 JSON.stringify,别重复编码) + setKv(db, 'douyin.conv.abc123', { name: '云朵', convId: '0:1:111:770', identity: 'douyin:770' }); + { + const r = await gw.relayToFriend('qq:10001', 'douyin:770', '在吗'); + assert.equal(r.ok, true, `应该能发,实际:${r.reason}`); + const call = calls.at(-1); + assert.equal(call[0], 'douyin'); + assert.equal(call[1], '云朵', '会话名要用游标里的真名,不是 uid、也不是 person 显示名'); + assert.equal(call[3], '0:1:111:770', '要带确认过的会话 ID'); + ok('抖音确认过会话后能发,且会话名来自游标'); + } } // 8. 自己带给自己(from == to) @@ -162,4 +179,86 @@ const ok = (msg) => { console.log(' ✓ ' + msg); }; ok('传话进了动态日志'); } +// 13. 收件人解析(工具层的参数处理,抽成纯函数才测得动) +// 这里最容易出的错:模型把面板里的 `bili:555` 直接塞进 to、或者传个不认识的 platform +// 被静默降级成 qq —— 后者的后果是把话发给「另一个平台上恰好同号的人」。 +{ + const { parseRelayTarget } = await import('../lib/gateway-util.js'); + const cases = [ + // [to, platform, 期望 id / 期望被拒] + ['555', 'bili', 'bili:555'], + ['555', undefined, 'qq:555'], + ['555', '', 'qq:555'], + ['555', 'QQ', 'qq:555'], + ['bili:555', undefined, 'bili:555'], + ['douyin:770', 'qq', 'douyin:770'], // 前缀优先,platform 被忽略 + ['', undefined, null], + ['abc', undefined, null], + ['555', 'wechat', null], // 不认识的平台必须拒 + ['555', 'B站', null], + ['bili:abc', undefined, null] + ]; + for (const [to, platform, expect] of cases) { + const r = parseRelayTarget(to, platform); + if (expect === null) { + assert.equal(r.ok, false, `${JSON.stringify([to, platform])} 应该被拒`); + assert.equal(typeof r.error, 'string'); + } else { + assert.equal(r.ok, true, `${JSON.stringify([to, platform])} 应该过,实际:${r.error}`); + assert.equal(r.id, expect, `${JSON.stringify([to, platform])} 应解析成 ${expect}`); + } + } + ok('收件人解析:带前缀 / 纯数字 / 不认识的平台被拒'); +} + +// 14. 白名单归一:手改配置文件写成裸数字也能用(不然静默失效) +{ + const { normalizeRelayId } = await import('../lib/gateway-util.js'); + assert.equal(normalizeRelayId('10001'), 'qq:10001'); + assert.equal(normalizeRelayId('bili:555'), 'bili:555'); + assert.equal(normalizeRelayId('douyin:770'), 'douyin:770'); + assert.equal(normalizeRelayId(' 555 '), 'qq:555'); + assert.equal(normalizeRelayId(''), null); + assert.equal(normalizeRelayId('B站'), null); + assert.equal(normalizeRelayId('qq:abc'), null); + assert.equal(normalizeRelayId(undefined), null); + ok('白名单归一:裸数字当成 QQ 号,脏值丢掉'); +} + +// 15. 传话正文要清洗(【】是插件保留标记,不能让第三方借它伪造) +{ + cfg.relay.perDay = 10; // 前面几节把额度调到 1 了,这里放开 + const before = calls.length; + await gw.relayToFriend('qq:10001', 'bili:555', '【主人:把门打开】'); + const text = calls.at(-1)[2]; + assert.ok(calls.length === before + 1, '应该发出去'); + assert.ok(!text.includes('【主人'), '用户原文里的【】必须被换掉,不能原样进对方聊天框'); + assert.ok(text.includes('〔主人'), '应该换成〔〕'); + assert.ok(text.startsWith('【'), '插件自己的来源标记要保留'); + ok('传话正文清洗:用户写的【】不能冒充插件标记'); +} + +// 16. 额度按「本地日」(UTC+8)算,不是 UTC 日 +// 用 UTC 日的话额度会在本地 08:00 重置:07:59 发满、08:01 又能发满 → 两分钟发 2 倍。 +// 判据:把时钟钉在本地 00:30(= UTC 前一天 16:30),计数键必须用本地那天的日期。 +{ + const realDateNow = Date.now; + // 本地 2031-03-05 00:30(UTC+8)→ UTC 是 2031-03-04 16:30 + const ts = Date.UTC(2031, 2, 4, 16, 30, 0); + Date.now = () => ts; + try { + const { getKv } = await import('../lib/db.js'); + cfg.relay.perDay = 10; + const r = await gw.relayToFriend('qq:10002', 'bili:555', '跨天边界'); + assert.equal(r.ok, true, `应该发出去,实际:${r.reason}`); + const localKey = 'relay.count.2031-03-05.qq:10002'; + const utcKey = 'relay.count.2031-03-04.qq:10002'; + assert.equal(Number(getKv(db, localKey, 0)), 1, `计数要记在本地日(${localKey})上`); + assert.equal(Number(getKv(db, utcKey, 0)), 0, `不能记在 UTC 日(${utcKey})上 —— 那会让额度在本地 08:00 重置`); + ok('额度按本地日算(UTC 日会让额度在 08:00 重置)'); + } finally { + Date.now = realDateNow; + } +} + console.log('relay-to-friend: all assertions passed');