Commit Graph
361 Commits
Author SHA1 Message Date
DrSmoothl 1914807770 fix(onebot): apply the transport heartbeat to the reverse-WS server too
Symmetric with the ws-client fix (#208): the reverse-WS server now pings each
attached client and terminates one that goes fully silent for ~90s (2 unanswered
pings), reaping a half-open client that would otherwise linger in the connection
set. Reuses startHeartbeat with the same conservative, activity-reset tolerance,
so a client with live traffic is never dropped. The per-connection stop is kept
on the ForwardConn entry and cleared in both close() and the socket 'close'
handler; no shared instance state, so the #97 overlap does not apply here.
2026-07-07 21:20:19 +08:00
DrSmoothl c09c6e0883 fix(onebot): heal half-open reverse-WS client with a transport heartbeat
A reverse-WS client could end up half-open after the peer restarted: still
writable (events kept flowing out) but no longer readable, so inbound action
frames silently never arrived and only a full restart recovered it (#208). The
OneBot app-level meta heartbeat is a one-way push and cannot detect this.

Add an RFC6455 ping/pong keepalive (startHeartbeat) wired into the ws-client
adapter. It pings every 30s and declares the link dead only after 2 unanswered
pings (~90s of total silence), then terminates the socket so the existing
reconnect path runs. Any inbound activity — a pong OR a message — resets the
counter, so a connection carrying real traffic is never reaped; the conservative
tolerance keeps the false-positive rate near zero (a GC pause or latency spike is
absorbed). The stop is per-socket and also held on the instance so close()/reload
halt it immediately rather than waiting for the deferred 'close'; a symmetric
identity guard on 'open' mirrors the #97 stale-socket guard on 'close'.
2026-07-07 21:20:07 +08:00
DrSmoothl d9dfe513ee feat(onebot): report forced offline as notice/bot_offline
Register a handler for the StatusService.KickNT push (QQ NT's unified
forced-offline notification — kick / login-elsewhere / risk-control),
decode KickNTResponse and emit bot_offline {user_id, tag, message},
matching NapCat. Command + field layout (f4=tips_title, f3=tips_content)
RE-confirmed against wrapper.linux.node + Lagrange; not yet live-captured.
2026-07-07 15:25:35 +08:00
DrSmoothl 447b40a259 feat(onebot): report profile like as notify/profile_like
Decode the multiplexed 0x210 subType-39 push: when body.msgContent is a
ProfileLikeTip with inner msgType==0/subType==203, emit notify/profile_like
{operator_id, operator_nick, times}. times is parsed from detail.txt.
Proto shape from NapCat's raw decoder; wiring + decode verified, but the
byte-exact wire is pending a real like capture to confirm.
2026-07-07 03:05:14 +08:00
DrSmoothl 0d4d58605f feat(onebot): report group special title grant as notify/title
Decode the 0x2DC subType-16 field13==6 push: eventParam carries the member
uin (f5) and a gray-tip template (f2) whose last rich token holds the title
text. Emit notify/title {group_id, user_id, title}, matching NapCat. Field
layout taken from a real on-wire sample, not ported blindly.
2026-07-07 02:53:38 +08:00
DrSmoothl d3d1d2512e feat(onebot): report group member card change as notice/group_card
Detect a group member's card change from message traffic (sender card vs
cached roster card) and emit group_card {group_id, user_id, card_new,
card_old}, matching NapCat's parseCardChangedEvent. Fires only on a real
change of a known member; first-contact and unchanged cards are suppressed.
2026-07-07 02:23:17 +08:00
DrSmoothl bfde0daab4 feat(onebot): report group name change as notify/group_name
Dispatch the 0x2DC subType-16 push by NotifyMessageBody.field13 (was
emoji-react only); field13==12 decodes eventParam as GroupNameChange and
emits notify/group_name {group_id, user_id=operator, name_new}, matching
NapCat. Emoji-react (field13==35) path unchanged.
2026-07-07 02:05:52 +08:00
DrSmoothl 852870db59 feat(onebot): report C2C input status as notify/input_status
Decode the 0x210/0x115 input-state sys_msg (RE'd from wrapper.linux.node
aio_input_state_worker) into a friend_input_status event and map it to a
notify/input_status notice, matching NapCat's onInputStatusPush.
event_type 1 = typing, 3 = recording voice; status_text synthesised to
match the client's own strings.
2026-07-07 01:26:31 +08:00
DrSmoothl d35e276730 chore(release): v1.11.4 2026-07-06 15:04:55 +08:00
DrSmoothl b6107e38d8 fix(onebot): default forward node sender to self when user_id is 0/absent
A fake forward node (send_group_forward_msg / send_private_forward_msg) whose
data.user_id was "0" or omitted got rejected with "forward node user_id/uin is
required", even though the protocol端 is logged in and the core forward builder
(bridge/apis/forward.ts) already defaults a zero sender to the bot's own uin.
Upstream frameworks (AstrBot, etc.) don't manage QQ uins and legitimately send
user_id "0"; NapCat and LLBot accept it. parseForwardNodes now falls back to
ref.selfId, keeping the throw only for the not-logged-in case (selfId 0).
Verified on-target (#203).
2026-07-05 23:00:13 +08:00
DrSmoothl 0e6e2ec51d chore(release): v1.11.3 2026-07-05 14:26:10 +08:00
DrSmoothl 8dde7ef8e2 fix(onebot): seed self nickname on synthetic self-sent events
get_msg / get_group_msg_history returned an empty sender.nickname for the bot's
own group file / video sends. Those publish via OIDB (0x6d9_4 / c2c finalize)
rather than PbSendMsg, so the QQ server never echoes them back — and the echo is
what normally overwrites the synthetic self-sent store's placeholder nickname.
For a plain text send the echo arrives and fills it, which is why only file/video
surfaced empty.

Seed the synthetic event's sender.nickname from the bot's own
identity.nickname (we are the sender, so we know it). A normal text send's echo
still overwrites it with the same value. Verified on-target: a self-sent group
video now shows the bot nickname in history.
2026-07-05 14:20:36 +08:00
DrSmoothl c236bc86ee feat(video): raise video-path size limit to 1.5 GiB (#145)
The 100 MB cap that re-routed larger videos to the file-upload pipeline
was a workaround for the width/height=0 → 已过期 bug (fixed in the prior
commit), not a real QQ size limit. Real-machine verified on tempserver:
88 MB / 149 MB / 299 MB / 497 MB videos all upload, render and play as
normal videos in a group. Raise MAX_VIDEO_SIZE to 1.5 GiB (matching the
file-upload ceiling); only videos above that still fall back to the file
path. Collapse the redundant MAX_VIDEO_SIZE_HARD (was also 1.5 GiB) into
the single constant and drop the now-dead 100 MB warn branches.

Note: the whole video is buffered in RAM for the Highway upload, so a
1.5 GiB send costs ~1.5 GiB+ of process memory — that, not a QQ limit,
is what bounds the ceiling.
2026-07-04 23:45:36 +08:00
DrSmoothl 770b224d58 feat(onebot): decode incoming 闪传 flash-file messages (#199/#200)
Older QQ clients (≤9.9.30) deliver a 闪传 (flash transfer) file as a richui
markdown commonElem (svc=45, busId=FlashTransfer); SnowLuma had no decoder for
it, so the message decoded to 0 elements and was reported empty. (Newer
clients ≥9.9.31 send a plain text+link message that already decodes fine.)

Decode svc=45 markdown → parse the FlashTransfer card JSON → emit a flash_file
element, surfaced as the segment the issue asked for:
  { type: "flash_file", data: { title, file_set_id, scene_type } }

- Field names (fileSetId / sceneType / title) confirmed against QQ NT's
  flash-transfer manager in wrapper.node.i64. The card is built by the
  sender's client so the exact JSON nesting is unknown — values are pulled by
  a bounded recursive search rather than a pinned path (handles either shape).
- Non-FlashTransfer markdown is ignored; missing fields default (never empty).
- Manifest: D/S = yes, P/W = by-design-no (receive-only; sending is the
  existing send_flash_msg action). Log preview shows [闪传文件:title].
- Tests: card decode (nested + alias + defaults + non-flash) and the
  element→segment mapping.

Note: not end-to-end verified on a live message — the svc=45 format only comes
from ≤9.9.30 senders and no such client was available (every test sender here
is ≥9.9.31 → text format). Logic + field names are unit-tested / IDA-confirmed.

typecheck 12 包; protocol 596 / onebot 529 green.
2026-07-04 19:02:47 +08:00
Airline233andCopilot Autofix powered by AI d3eb3bae14 feat(qzone,onebot): add set_qzone_ban action for qzone blacklist management (#193)
* feat(onebot,qzone): add set_qzone_ban action for qzone blacklist management

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-04 14:32:40 +08:00
DrSmoothl 6cb7f2c6d0 chore(release): v1.11.2 2026-07-04 13:39:00 +08:00
DrSmoothl 07c08ed74d feat(onebot): enrich group/member info fields (#197)
Round out the OneBot v11 group-profile fields the issue asked for.

Group (get_group_info / get_group_list, inherited by get_group_info_ex /
get_group_detail_info):
- group_create_time + group_memo come free from the 0xFE5_2 list
  (createdTime / announcement), verified live (createdTime=1729505343,
  announcement populated).
- group_level lives only in the 0x88D_0 detail; get_group_info fetches it
  (memoized 5min) so a joined group doesn't hit the detail every call.
  get_group_list leaves it 0 — a per-group detail fetch across the whole
  list would be far too costly.

Member (get_group_member_info / get_group_member_list):
- Add area / unfriendly / title_expire_time / card_changeable. QQ NT does
  not expose these, so they're fixed placeholders ('' / false / 0 / true),
  matching go-cqhttp / NapCat. sex/age stay unknown/0 (real values need a
  per-member profile fetch — out of scope here).

typecheck 12 packages; onebot 523 / core 472 green.
2026-07-04 13:04:32 +08:00
DrSmoothl b20ed12761 fix(onebot): approve group requests from the filtered inbox too (#197)
set_group_add_request could fail with "matching group request not found"
for a request SnowLuma had itself just reported. handleGroupAddRequest only
fetched the main inbox (0x10C8 subCommand 1); a spam-filtered join/invite
lives in the filtered inbox (subCommand 2) and was never searched, so its
flag couldn't be resolved to a sequence.

Fetch both inboxes and search the union. Each request keeps the `filtered`
flag its approval subCommand needs, so a filtered request is approved
through subCommand 2. A failing inbox fetch degrades to the other instead
of aborting. Regular MSF invite pushes don't carry the approval msgseq
(only the private-card path does, #125), so the fetch is the only source.

Regression tests: filtered-only request is found + approved via subCommand
2; "not found" only when neither inbox has it.
2026-07-04 12:48:06 +08:00
DrSmoothl c027161a64 fix(protocol): get_group_file_system_info returns real counts + space (#196)
file_count 恒为 0(且 used_space/limit_count/total_space 是占位/写死值)。根因:
0x6D8 view 命令分三个 subcommand(1=List, 2=Count, 3=Space),但 getCount 错发到
**subCommand 3(Space)** 且 busId=0,并从 pb<1>/pb<2> 读计数——服务端根本没返回
Count 块,于是恒 0。

真机 RE(bot 在测试群传/删文件核对):
- Count 走 **0x6D8_2 + busId=6**,响应 Count 块里 fileCount=**field 4**、maxCount(文件
  数上限,如 1500)=**field 6**(旧 pb<1>/pb<2> 全落空)。
- Space 走 **0x6D8_3**,响应 Space 块 totalSpace=**field 4**、usedSpace=**field 5**(64 位)。
- 实测:fileCount=4、limitCount=1500、usedSpace=20103729、totalSpace=10737418240。

修复:改 GetGroupFileCount 到 subCommand 2 + busId 6 + 正确 tag;新增 GetGroupFileSpace
(0x6D8_3);action 并发查两者,四个字段全返回**服务端实际值**(优于 NapCat 的写死占位)。
含 count/space 编解码回归测试。catalog regen。

typecheck 12 包;protocol 591 / onebot 521 / core 472 全绿。
2026-07-04 01:59:52 +08:00
DrSmoothl 95b5878456 feat(onebot): return new folder info from create_group_file_folder (#195)
create_group_file_folder 之前只回 data:null,拿不到新建文件夹的 folderId。现对齐
NapCat 返回结构,data 带回文件夹信息:
  { result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName,
    folderPath, createTime, modifyTime, createUin, modifyUin } } }

- 0x6D7_0 创建响应本就在 field 4 携带 folderInfo,SnowLuma 旧 proto 没解(只读
  retcode/retMsg/clientWording)。补上 OidbGroupFileFolderInfoResp 并让 create 的
  deserialize / bridge / action 一路把它带出来。
- 真机验证(bot 在测试群建夹→读回 folderId→删除清理):确认 folderInfo 存在,且
  **modifyUin 在 field 9 而非 Lagrange proto 标注的 field 7**——按真机 wire 修正。
- 新增两个解码回归测试(带 folderInfo / 缺 folderInfo 兜底)。catalog regen。

typecheck 12 包;protocol 587 / onebot 521 / core 472 全绿。
2026-07-04 01:25:14 +08:00
DrSmoothl 7744e24af2 fix(protocol): make set_group_search actually apply search flags (#191)
旧实现走 OIDB 0x89a_0 但 settings 发空字节 → 服务端返 ok 却 no-op;action 也只收
group_id,没有设置搜索方式的参数(报告属实)。

真机 RE 定稿(tempserver,bot 为管理员的实群逐字段扫描 + GET 读回):
- 修改命令 = 0x89a_0(全量抓包确认,与 MuteAll 同命令,靠 body 形状区分)。结构
  = {1:groupUin, 2: 只含被改字段的 GroupDetailInfo modify 子消息}。这是与 0x88D_0
  群详情 GET **不同的消息域**(mute/shutUpTime 在此=tag17,在 GET 里却是字符串),
  所以标签不能照搬 GET。
- 在 modify 子消息里逐 tag 试写、经 0x88D_0 GET 读回效果,定位:
  noFingerOpen(关键词/群指纹搜索)=tag 35,noCodeFingerOpen(群号搜索/总开关)=tag 36;
  再对照客户端「被搜索方式」三选下拉(私密/群号/群号+关键词)核实语义与 0/1 取值。
- proto-defs:settings 改为 Oidb0x89a_0SearchSettings 子消息,两 flag 用 pb_optional
  (显式存在)——否则 proto3 丢 0 值,导致关闭(=0)被静默忽略。undefined 仍省略。
- set-search/bridge/action:透传 no_finger_open / no_code_finger_open;只下发提供的
  字段(同 NapCat filter 机制、与 modify-group-ext-info 一致)。catalog regen。
- 编码测试锁定:0 值必发 tag 35/36、未提供则省略、命令为 0x89a_0。

typecheck 12 包干净;protocol 585 / onebot 521 / core 472 全绿。
2026-07-03 17:37:55 +08:00
Airline233 884db940df feat(qzone): add set_qzone_msg_right to change a feed's visibility (#186)
* feat(qzone): add set_qzone_msg_right to change a feed's visibility

Add updateQzoneMsgRight in the protocol layer, porting php-qzone's
updateRight: fetch the feed via emotion_cgi_msgdetail_v6, rebuild the
full publish-shaped payload (richval/pic_bo/con), then override
ugc_right/allow_uins and POST to emotion_cgi_update. Expose it through
QzoneApi.updateRight and the OneBot set_qzone_msg_right action, with the
same ugc_right/target_uins validation as send_qzone_msg. Covered by
protocol, core and onebot tests.

* fix(qzone): make qzoneParse more stable and fixed a test example
2026-07-02 22:38:05 +08:00
DrSmoothl 72aedbc612 chore(release): v1.11.1 2026-07-01 22:15:01 +08:00
DrSmoothl 3932958c39 fix(bridge,common,onebot): reject phantom hook UINs + never crash logging (#162)
注入的竞态窗口里,native hook 偶发上报 13 位垃圾 UIN(时间戳型,读到 QQ 尚未落定
的内存)。TS 层防御缺失,导致两个连锁问题:

1) 幽灵账号:isRealUin 只查「纯数字且 ≥5 位」、无上限,垃圾值通过后建会话并把
   config/onebot_<垃圾>.json 落盘 → OneBot 节点配置里出现随机幽灵账号(跨重启残留)。
2) 进程崩溃:logger 彩色路径 ' '.repeat(SLOT - tagLen),UIN tag(含方括号)超宽 →
   负数 → RangeError: Invalid count value → uncaughtException。

跨平台(Win DLL / Linux .so 同逻辑)+「更新 QQ 后消失」都印证是 native 读到那块内存
的偶发垃圾;根修在 SnowLumaNative,此处补齐 TS 防御:

- 抽出唯一的 @snowluma/common/uin::isRealUin = /^\d{5,10}$/(真实 QQ ≤ uint32 →
  10 位)。删除 bridge/core 两处重复副本(重复正是这次漏加上限的温床)。等价旧逻辑,
  仅新增拒 11+ 位。
- logger.ts 加 Math.max(0, …),日志永不崩进程(独立健壮化)。
- 收紧 WebUI UIN_REGEX /^\d{5,12}$/ → /^\d{5,10}$/ 保持一致。
- 启动时 cleanupInvalidPerUinConfigs() 清掉已落盘的幽灵 onebot_<uin>.json(只删
  UIN 不合法的,绝不碰合法账号/全局配置)。

测试:common +8(uin 6 / logger 2)、onebot +3(cleanup)。typecheck 12 包干净;
common 58 / onebot 519 / core 471 / bridge 73 全绿。对抗性 Agent 逐输入核验等价性、
三层 gate 堵死幽灵入口、cleanup 安全时序,无回归。
2026-07-01 20:37:02 +08:00
DrSmoothl a8f24b8f13 refactor(onebot): converge self-sent message tail into finalizeSend
send/forward 路径里「记录自发消息」的尾巴(hashMessageIdInt32 + cacheMessageMeta +
cacheSelfSentMessage)逐字复制 6 份(sendPrivate/sendGroup/两个 forward/forwardSingle
的 group+private 分支),每处独立手工配对 isGroup ↔ eventName ↔ hash 事件常量——
漏改一处会静默产生错 message_id / 错 event 归属。抽 finalizeSend(ref, isGroup,
targetId, receipt, elements),由 isGroup 单点派生 eventName + 常量。

6 处塌成 6 行调用;forwardSingle 的 group/private if/else 只剩 send API 本身不同。
receipt 用结构类型覆盖所有调用点(含 line 630 合成的 fallback)。

行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
6 处等价、参数/返回正确。
2026-07-01 19:55:21 +08:00
DrSmoothl 85ca207279 refactor(onebot): extract openSqliteDb helper for the three stores
message/media/reaction store 构造器各自逐字复制同一段引导(mkdir 父目录 + 打开
DatabaseSync + PRAGMA journal_mode=WAL + PRAGMA synchronous=NORMAL),改一处 PRAGMA
要改三处。抽 openSqliteDb(dbPath) 收敛,schema init 与路径改写留在各调用方。

- message-store 的 .json→.db 改写保留(改写后同目录,mkdir 目标不变,等价)。
- 三文件删掉不再使用的 fs/path import。

行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
三处引导等价、路径细节无边角、无回归。
2026-07-01 18:37:42 +08:00
DrSmoothl 15a6fe3785 refactor(onebot): make event converter dispatch an exhaustive registry
阶段 2(零行为改动):把 convertEvent 的 17-arm switch 换成
CONVERTERS: { [K in QQEventVariant['kind']]: ConverterFor<K> | null } 表。mapped
type 对事件类型联合 total——新增一个 kind 却漏写 converter 会**编译报错**,而非
像原 switch 那样静默走 default: return null。

- ptt_trans_result(内部语音转文字事件,不对外)在表里显式标 null,与原 default
  行为等价。
- 派发一次 localized cast 解 correlated-union,纯类型层、运行时等价。
- 护栏实测有效:删任一 kind 条目即 TS2741 编译失败。

onebot 516 全绿、typecheck 干净;对抗性 Agent 逐一核对 17 映射、独立复现护栏报错。
2026-07-01 18:03:02 +08:00
DrSmoothl ae17bc0cf5 refactor(onebot): extract event envelope builders; collapse message triplets
阶段 1(零行为改动):消掉 17 个 converter 各手搓的 time/self_id/post_type 信封,
合并 message 三胞胎。

- 新增 event-converter/envelope.ts:notice/request/message 三个信封 builder,
  converter 只供应各自 post_type 的字段。
- to-notice(12)/to-request(2) 改用 notice()/request()。
- to-message:friend+temp 合成 convertPrivateMessage(subType)(仅 sub_type 差),
  group 独立;新增 toSegments 收敛 7 参 elementsToJson splat。导出名不变。

行为 byte 级不变(测试 toEqual 顺序无关,key 集合与值逐一保持):event-converter
48 + onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐 converter 对比 HEAD 确认
16 个输出等价、无字段增减/值变、无运行时循环。
2026-07-01 17:58:49 +08:00
DrSmoothl 891a197335 refactor(onebot): collapse action registration into a single barrel
加一个 action 文件原本要同步改三处手写清单:ApiHandler 的 12 个 register import +
12 行构造调用、各文件的 register footer、action-docs 的 13 import + GROUPS。现收敛
成一个 actions/index.ts barrel 作为「文件→动作 + 分类」的单一真相。

- action-kit:抽 RegisteredActionSpec(describe+register),ActionSpec/
  StreamActionSpec extends 它,registerActions 参数放宽到 RegisteredActionSpec[]
  (它只调 .register),于是 stream 动作也能并入统一注册。
- 新增 actions/index.ts:ACTION_GROUPS(11 组含分类,stream 合并)+ ALL_ACTIONS。
- api-handler:12 import+12 调用 → registerActions(this, context, ALL_ACTIONS);
  .handle_quick_operation(唯一非 ActionSpec 的裸 handler,需要 h 本身)从
  extended 搬进构造器一处显式注册。
- action-docs:改用 barrel 的 ACTION_GROUPS,删本地 GROUPS + 13 import。
- 删 12 个 register footer + 清理因此变 unused 的 ApiHandler/ApiActionContext import。

行为严格不变:注册的动作集合、.handle_quick_operation、文档分类/计数均一致。
onebot 516 全绿、全仓 12 包 typecheck Done;对抗性 Agent 逐条对比 HEAD 确认等价。
2026-07-01 17:49:07 +08:00
DrSmoothl 6f6f372337 refactor(onebot): drop 55 redundant ACTION_FAILED try/catch in extended actions
阶段 2b:从 extended.ts 删除 55 个「纯兜底」try/catch(catch 体恰为单条
return failedResponse(ACTION_FAILED, String(e)/e.message)),让抛错落到唯一 seam
runAction(已统一 100 + error.message)。retcode 不变(这些本就是 100),去的是
冗余包装。

- 保留:try/finally、带前缀的 catch(获取精华消息失败 / 语音转码失败)、
  download_file 保存失败的 BAD_REQUEST catch、fetchFilteredGroupRequests 的
  catch{return []} 吞值——均原样未动。
- 唯一文案变化:约 30 个原用 String(e) 的 catch,其 wording 由 "Error: X" 变为
  seam 的裸 "X"(丢类名前缀,retcode 不变;OidbError 的服务器码仍在 message 内)
  ——一致化改善,无测试/契约依赖该前缀。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐块比对 HEAD 确认等价、
  结构正确、无误删漏改。
2026-07-01 16:30:00 +08:00
DrSmoothl 5be852f394 refactor(onebot): drop redundant per-action try/catch in qzone/album/admin
阶段 2a:删除 qzone(7)、group-album(8)、group-admin(1) 共 16 个「纯兜底再包一层」
的 try/catch,让抛错自然落到唯一 seam runAction(阶段 1 已统一为 ACTION_FAILED 100
+ error.message)。qzone/album 原返回 1200 → 归一 100(本任务有意);group-admin
原本就是 100,仅去冗余包装。

- 保留:qzone helper uploadQzoneImages 的带前缀 re-throw catch、group-info 的
  honor-info 前缀 catch、message 的吞值 catch(best-effort 保留旧 URL)——均未动。
- 清理三文件不再使用的 RETCODE/failedResponse import。
- qzone-actions 测试断言 1200 → 100(wording 前缀经 seam 仍保留)。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐个对比 HEAD 确认纯兜底、
  无其它漂移、无误删漏改。
2026-07-01 16:20:26 +08:00
DrSmoothl ab45667fdf refactor(onebot): unify action-error retcode at the runAction seam
将「动作抛错返回什么错误码」从各处不一致(100 / 1200 / 漏包→1200)收敛到唯一
兜底处 ApiHandler.runAction,统一为 ACTION_FAILED(100) + error.message。

阶段 1(改 seam 本身):
- runAction catch:默认码 1200 → 100;文案 'internal error' 兜底改为 String(error)。
  OidbError.message 本就含 QQ 服务端 code,无需特判。
- 新增 3 个测试锁定策略:抛 Error→100+message;抛 OidbError→100 且 wording 含
  code+server msg;抛非 Error→100+String()。
- rename_group_file 那个原断言 1200 的测试(未包裹动作、落 runAction)改为 100。

各 action 里多余的 try/catch(qzone/group-album 等仍返回 1200)留待后续阶段删除,
在此之前其失败不经此 seam。onebot 全量 516 全绿、typecheck 干净。
2026-07-01 16:11:49 +08:00
DrSmoothl 8e173cf7d7 refactor(onebot): merge element toSegment/fromSegment into one codec table
阶段 2(零行为改动):把「同一种消息元素」的两个 onebot 方向——收·转
(to-segment) 与 发·解(message-parser)——从两个文件各写各的分支,合并到一张
按元素类型索引的 ELEMENT_CODECS 表,每种类型一条 { toSegment?, fromSegment? }。

- 新增 event-converter/element-codecs.ts:13 类 toSegment + 14 类 fromSegment
  逐字平移自原实现;私有 helper intOr/marketFaceElement/pickMediaSource 移来并导出。
- to-segment.ts:elementToSegment 改查表 + 保留原 default 透传兜底。
- message-parser.ts:segmentToElement 保留 9 个纯输入糖 case 作前置 normalize,
  真实类型改查表,末尾保留原 unsupported warn。
- onebot 对账测试升级为按表键核对 S/P(比正则更硬),并断言真实类型 case 不再
  残留于 parser、输入糖仍在。

行为 byte 级不变:onebot 全量 513 全绿、typecheck 干净;对抗性 Agent 逐字比对
确认无漂移、无运行时循环依赖。
2026-07-01 15:48:04 +08:00
DrSmoothl f4170b014a refactor(protocol,onebot): add message-element four-direction reconciliation manifest
消息元素散在 4 处派发(收·解 / 收·转 / 发·解 / 发·打包),历史上各写各的、
无对账,导致字段名对不上、漏写方向走 default 静默失败。

阶段 1(零行为改动):立一份权威清单 element-manifest + 两道架构护栏测试。
- element-manifest.ts:每种元素类型 × 四向支持('yes'/'no'/'by-design-no')
  + 字段契约 + typesForDirection() + 输入糖白名单。清单逐字反映当前行为。
- 两道对账测试(因包边界拆两处、共用清单):正则扫 4 处派发代码,比对清单。
  谁增删一个方向却不同步清单,测试当场报红,不再运行时静默。
- 取值域用 [A-Za-z0-9_]+,避免未来驼峰/下划线类型名被静默漏抓致护栏失效。
- poke 的 W=by-design-no:QQ 不允许戳一戳当消息段发送,缺席正确。

对抗性 Agent 两轮复审通过。
2026-07-01 15:48:04 +08:00
DrSmoothl 5d6ce86b66 refactor(onebot): give trans_group_file semantic param roles
Follow-up to #161: trans_group_file's group_id/file_id used plain
f.uint()/f.string(); switch them to f.groupId()/f.fileId() (identical
coercion) so the WebUI debug console renders a group picker + file-id
control for the new action and the catalog carries the roles. Catalog
regenerated.
2026-07-01 02:27:35 +08:00
Airline233 9ca64bed10 feat(core,onebot): implement trans_group_file action (#161) 2026-07-01 02:13:35 +08:00
Airline233 2f374ea8c9 feat(qzone): support post visibility rights when publishing qzone posts (#178)
Add ugc_right and target_uins to the qzone publish path across protocol,
bridge, and the send_qzone_msg OneBot action, regenerate the MCP catalog,
and cover restricted visibility (16/128) with validation tests.
2026-06-30 23:57:39 +08:00
DrSmoothl 48e2777bc3 chore(release): v1.11.0 2026-06-30 20:38:37 +08:00
DrSmoothl 90456def2e feat(onebot): get_record out_format — server-side voice transcode (#165)
#165: get_record gains an optional `out_format` (mp3/amr/wma/m4a/spx/ogg/
wav/flac, mirroring NapCat). When set, the QQ voice (SILK/AMR) is
transcoded server-side and the result is attached as `data.base64`; the
original info (file/url/file_size) is preserved. Absent ⇒ behaviour
unchanged. This spares ASR consumers from shipping a SILK decoder.

- protocol: convertAudioBytes(bytes, format, deps?) drives the bundled
  SILK-capable ffmpeg addon's convertFile through temp files (always
  cleaned up), with a format allowlist and an output-size cap. Pure/
  injectable, unit-tested with a fake addon (6 cases).
- core: ExtrasApi.convertRecord(source, format) = loadBinarySource (64 MiB
  cap) → convertAudioBytes.
- onebot: get_record wires out_format; transcode failure (incl. an addon
  lacking SILK decode) degrades to ACTION_FAILED, never crashes.

Adversarially reviewed: no path traversal (format allowlisted), no SSRF
(source is the cached CDN url, not user input), cleanup covers every path,
graceful degradation confirmed. Catalog regenerated. Real-machine e2e
(does the shipped .node actually decode SILK?) is Phase 2.
2026-06-30 19:25:40 +08:00
DrSmoothl a7667f1cd5 feat(core,onebot): debug-console stream-invoke + upload endpoints
Phase 2 of the debug-console expansion. Two backend endpoints under the
existing /api/* bearer auth:

- POST /api/debug/invoke-stream — drive a Stream API action (#163) and
  relay every frame to the browser over an SSE body. The frontend reads
  it with fetch()+a stream reader (header auth), so it needs no SSE
  query-token allowlist entry. Frames are NEVER dropped: backpressure is
  handled by waiting for the consumer to drain, not by discarding (a lost
  chunk corrupts a transfer). Non-stream actions emit a single frame.
- POST /api/debug/upload — stream a browser-selected file to a temp path
  on THIS server (the bot runs server-side, not on the operator's
  machine), so the path can feed a send action's file/image/record/video
  param. Raw bytes in the body (no multipart buffering), ?filename= for a
  readable suffix, streamed to disk under os.tmpdir()/snowluma-debug-
  upload with a 4 GiB cap and a 24h TTL sweep.

instance.invokeStream() delegates to ApiHandler.processStreamRequest.

Pure logic (filename sanitisation, fenced size-capped disk sink, the
stream-invoke Response builder) lives in debug-tools.ts with 12 unit
tests. Adversarially reviewed: path traversal is robust (19 hostile
filenames all fenced), frames provably never dropped, auth runs before
any disk write. Fixed a High found in review — the write stream had no
'error' listener (an async ENOSPC/EIO during flush would crash the whole
process) and a late-open race could leak a partial file; both now raced
into the awaits and cleaned up after 'close'.
2026-06-30 16:19:59 +08:00
DrSmoothl f9900053b0 feat(onebot): backfill semantic roles across action params
Phase 1 of the debug-console expansion. Sweeps the 8 action files,
swapping bare coercion primitives for the role-stamped equivalents from
Phase 0 (or appending `.role()` where a `.default()`/`.optional()` field
must keep its exact coercion). Coercion is byte-for-byte unchanged; the
only intentional bound change is face_id min 1→0 (QQ face 0 is valid).

Classification (verified against each run()):
- group_id → f.groupId() everywhere.
- user_id → f.userId() for any-user / friend / stranger / private-route
  targets (send_private, friend poke, friend add/remove, stranger info,
  private file transfer, forward-to-friend, share-contact).
- user_id → f.memberId() only when it's a member of a sibling group_id
  (batch kick elements; the groupUserAction preset already injects it).
- media file/image/record + file_id → f.file()/image()/record()/fileId()
  (or .role() when defaulted/optional); message_id/timestamp/duration via
  the constructor or .role() hatch as coercion requires.

Polymorphic ids left as bare uint on purpose (no single role can honestly
describe them): mark_msg_as_read.target_id (group# or uin), bot_appid,
msg_seq, fileset_id, folder_id, chunk indices, stream_id.

Catalog regenerated: 71 group_id / 25 user_id / 9 member_id / 19
message_id / 11 file_id / 7 image / 6 file roles surfaced. Done by 4
parallel agents; adversarially reviewed — zero coercion regressions,
zero member/user misclassifications.
2026-06-30 16:00:21 +08:00
DrSmoothl 14a61f4ce8 feat(onebot): add semantic role field + stream flag to action metadata
Phase 0 of the debug-console expansion. Introduces a closed `FieldRole`
union (group_id/user_id/member_id/message_id/file_id/file/image/record/
video/duration/timestamp/face_id) orthogonal to `type` (which governs
coercion), so the WebUI debug console can render semantic pickers instead
of forcing hand-written JSON.

- FieldDoc gains `role?`; Field gains a `.role()` modifier (survives
  optional/default/describe). toJsonSchema emits it as `x-role`.
- Semantic constructors f.groupId/userId/memberId/fileId/file/image/
  record/video/duration/timestamp/faceId wrap the coercion primitives and
  stamp a role (messageId backfilled). Media sources reject '' to preserve
  the empty-string guard they replace. faceId allows 0 (valid QQ face id).
- Extracted stringCore so f.string() and string-valued roles share it.
- ActionDoc gains `stream?`; defineStreamAction sets stream:true.
- Presets: groupAction injects f.groupId(); groupUserAction injects
  f.groupId() + f.memberId() (a group action's user_id is a member of
  that group). Backfills role onto 56 group_id / 7 member_id sites.
- Regenerated MCP catalog (79 x-role, 5 stream).

Adversarially reviewed: no coercion regression, member_id stamping has
zero false positives across all 7 groupUserAction sites, x-role is inert
to MCP consumers.
2026-06-30 15:42:25 +08:00
DrSmoothl 7285db1e37 feat(onebot,mcp): catalog the Stream API actions (#163 phase 4)
Surface the six Stream API actions in the self-generated docs catalog under
a new 流式接口 category: export each module's specs as an `actions` array
(register now iterates it) and widen the doc collector's spec type to anything
carrying describe() so defineStreamAction results qualify alongside
defineAction. Regenerated the MCP catalog snapshot.

End-to-end verified on a live account over HTTP: test_download_stream (10
frames + terminal), an upload_file_stream round-trip (200 KB chunked in →
sent as a c2c file → download_file_stream back out, byte- and sha256-exact),
and the SSRF guard rejecting a cloud-metadata URL.
2026-06-30 14:40:39 +08:00
DrSmoothl 369dea582c feat(onebot): download stream actions (#163 phase 3)
NapCat-compatible server-push download: one request answered by a file_info
header, N base64 file_chunk frames, then a terminal file_complete. Bytes come
from a local file under the stream temp root, an http(s) URL, or a cached
image/voice id resolved to its QQ CDN URL. test_download_stream pushes 10
canned frames so a client can validate the transport without touching QQ.

Actions: download_file_stream / download_file_image_stream /
download_file_record_stream / test_download_stream.

Hardened beyond the NapCat original (which streams any local path and follows
redirects to anywhere), per three adversarial review passes:
- arbitrary-file-read: local reads are fenced inside the stream temp root,
  realpath-resolved so a symlink can't point out.
- SSRF: every URL (incl. each redirect hop, followed manually) is guarded —
  http(s) only, and neither the literal host nor any resolved address may be
  private/loopback/link-local; IPv6 is byte-parsed so normalized v4-mapped
  literals (::ffff:a9fe:a9fe) can't slip past. (DNS rebinding remains a
  documented residual — needs connect-time peer-IP validation.)
- robustness: TTFB-only connect timeout (doesn't cut a large body mid-stream)
  plus a per-chunk idle watchdog that aborts a stalled source so a hung
  upstream can't pin a socket; total size capped; non-2xx bodies cancelled;
  client disconnect aborts via the sink.

501 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl 4f0a0f89ae feat(onebot): upload_file_stream + clean_stream_temp_file (#163 phase 2)
NapCat-compatible chunked upload: a client pushes a file in base64 chunks
across repeated upload_file_stream calls keyed by stream_id; the bot
reassembles them into a local temp file and returns its path for a normal
send. Sidesteps the 2 MB HTTP body cap and the shared-filesystem assumption
of file:// sends.

Reassembly streams chunk-by-chunk to disk (no whole-file Buffer.concat) so
an arbitrarily large upload won't OOM. clean_stream_temp_file wipes only the
stream temp dirs.

Hardened well past the NapCat original (which has all of these holes), per
two adversarial review passes:
- stream_id is allowlist-validated + every derived path fenced inside the
  upload dir — no path traversal (the original lets stream_id write/delete
  arbitrary paths).
- total_chunks / concurrent streams / per-chunk + per-stream bytes are all
  bounded — no single-request OOM or disk/fd exhaustion.
- chunk indices are claimed synchronously and only counted complete once
  flushed — no double-count race, no truncated-read-on-concurrent-complete.
- state + temp dirs are namespaced per account.

494 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl 01ef98abb6 feat(onebot): Stream API transport plumbing (#163 phase 1)
Foundation for NapCat-compatible Stream API actions (chunked file
upload/download): a single request answered by many response frames.

- streaming.ts: StreamSink + frame wrappers (wrapStreamFrame /
  wrapStreamTerminal) matching NapCat's wire — each frame an OB11 envelope
  with stream:'stream-action', data.type ∈ stream/response/error, and
  message mirrored into wording.
- ApiHandler: registerStreamAction / isStreamAction; handle() threads a
  sink; processStreamRequest drives WS multi-frame dispatch with optional
  liveness-based abort; dead processRequest removed.
- action-kit: defineStreamAction (sink-aware run, registers as a stream
  action) reusing defineAction's parse/describe.
- adapters: HTTP server streams chunked \r\n\r\n-delimited frames (no
  Content-Length, no false application/json), aborting on client
  disconnect; WS server/client use a backpressure-aware safeSendAsync and
  abort a stream once the socket closes.

No stream actions are registered yet — those land in the next phases.
Verified by two adversarial review passes. 480 onebot tests green.
2026-06-30 14:40:39 +08:00
Airline233 62eb8fd763 feat: Qzone支持上传图片(发说说、评论附图) (#152)
* feat(core,onebot,protocol): support publish shuoshuo and comment with image

* Fix: Accidentally changed notes
2026-06-30 01:47:21 +08:00
DrSmoothl 547640bbfd fix(onebot): route oversized videos to the file path up front (#145)
A video larger than MAX_VIDEO_SIZE (~100 MB, QQ's video-resource cap)
uploads "successfully" — the server accepts the Highway bytes — but the
receiver sees 视频已过期 because no valid video resource is ever produced.

The existing large-video → file fallback only fired from the send catch
block, i.e. when the upload threw. An oversized upload doesn't throw, so
the fallback never triggered. Add a proactive split before the send: any
video whose source size is known to exceed MAX_VIDEO_SIZE is re-routed to
the file pipeline up front (mirrored for private and group sends). Smaller
videos (verified up to ~49 MB) are unaffected and still send as videos.

This pairs with the c2c-file fix (f8caa92): the re-routed video now rides
the now-working offline-file path and downloads correctly.
2026-06-30 01:24:00 +08:00
DrSmoothl 053137669a fix(protocol): drop the ineffective video force-full-on-fast-path retry (#145)
forceFullOnFastPath re-issued the NTV2 upload with tryFastUploadCompleted:
false to try to refresh a possibly-expired video resource. Real-machine
testing on a live account + RE of the QQ NT kernel (wrapper.node) proved it
never works:
- the server's fast-path is driven by md5-metadata existence and ignores
  the flag (proton omits a false bool anyway); the retry re-fast-paths
- the kernel itself does no validity check — HandleRspUploadV3 trusts the
  response's fileExist and goes straight to SendUploadSuccFTN

So an expired-but-still-indexed video resource is a platform-level
limitation, not something the upload flow can refresh. Removing the retry
drops two wasted OIDB round-trips per cached-video re-send. The underlying
#145 (receiver '资源已过期' for a server-expired resource) remains a
platform issue, tracked separately.

Tests updated to assert the single-request behaviour.
2026-06-29 15:32:57 +08:00
DrSmoothl 7ec74f2928 chore(release): v1.10.4 2026-06-28 22:48:00 +08:00