Compare commits

...
200 Commits
Author SHA1 Message Date
手瓜一十雪 b31e1c0f0c fix(packet): extend QQ build coverage from 40768 to 53644
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 22:15:24 +08:00
手瓜一十雪 83c1d1d596 fix(packet): support QQ 53644 and missing recent builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 20:19:36 +08:00
Shxiao 05feca9a2c fix(onebot): get_group_files_by_folder 不再丢弃子文件夹 (#2095)
该接口的 returnSchema 声明了 folders(文件夹列表),actionDescription
也写着「获取指定群文件夹下的文件及子文件夹列表」,但 _handle 把 folders
硬编码成空数组。

它调用的 MsgApi.getGroupFileList 与 get_group_root_files 相同,返回项
既可能带 fileInfo 也可能带 folderInfo;兄弟实现 GetGroupRootFiles 把
两类都映射了出来。后果是进入某个子目录后无法继续往下遍历,调用方永远
只能拿到空的 folders。

改为按兄弟接口的方式映射 folderInfo。
2026-10-07 22:05:51 +08:00
Shxiao f750d95545 fix(onebot): 恢复 set_group_leave 的 is_dismiss 解散群聊支持 (#2094)
payloadSchema 声明了 is_dismiss(是否解散),该字段也会出现在 build:openapi
生成的接口文档中,但 _handle 始终只调用 quitGroup:群主传 is_dismiss=true
期望解散群聊时,实际只把账号退出群聊——群没解散,账号却已经不在群里。

同一问题曾在 #1694(deae7fd4)修复过。该 PR 随后被 #1701(e6f646837,
2026-03-13)整包回滚,54 个文件全部撤销;触发原因记录在 #1700(v4.17.48
无法正常发送 JSON 卡片消息),回滚后 v4.17.49 确认修复。回滚一并删掉了
destroyGroup 与 is_dismiss 分支,本次只恢复这一条分支。

本补丁不触碰任何 schema、描述与示例字段。
2026-10-07 22:05:16 +08:00
手瓜一十雪 ec6aadaeea fix(shell): support QQ 9.9.36 Windows file query aliases
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-07 00:07:42 +08:00
手瓜一十雪 463d3ea5b1 fix(test): use typed spawn options for Windows batch regression
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-06 18:08:08 +08:00
手瓜一十雪 0d6ce7f509 fix(ci): sync typescript dependency in workspace lockfile 2026-10-06 18:07:06 +08:00
手瓜一十雪 4f1401da78 fix(types): preserve complete nested types during post-processing
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Use the TypeScript parser instead of a regex that truncates nested generics and function types. Validate generated syntax and add a regression test. Include workspace aliases and PTY ambient declarations. The full type package build still reports six errors in third-party node-pty source; this commit does not claim to resolve that remaining issue.
2026-10-06 17:51:21 +08:00
手瓜一十雪 9109b8cfe2 fix: repair Windows release dependencies and loader paths
Bundle required crypto and SSL DLLs and gate releases on a Windows native-load smoke test. Resolve loader paths independently of the working directory and encode file URLs correctly. Include the quick-login launcher built from Windows-Boot 0ff70ce10e34ac26411f9e6bcedaedfacc1e74f0. Validated builds, five path regressions, and live Shell and Windows Node startup to QR login.
2026-10-06 17:51:21 +08:00
手瓜一十雪 297133a1b1 fix(shell): update Windows hook for native file information queries
Include the x64 Release hook built from NapCat-Windows-Boot commit 789e6cce00be40d02659e1aca992f8cd928b790a. SHA256: 7C48E7D10D77E2C3936E5D190AEB0DDEE353D55FD06DE81C714F2740112B94B1.

Related to #2091. The replacement passes 10 independent Win32 checks; the reported QQ crash remains to be verified in the reporter's environment.
2026-10-06 16:54:12 +08:00
sj817 454cc0eda2 ci(release): 下游 AppImage 用的 QQ 换成 3.2.32-52194
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
原来的 3.2.30-50969 链接已经 404,v4.18.29 发版时 AppImage、NodeLoader 的构建都因此失败。
2026-10-05 13:50:01 +08:00
sj817 435cb7cf52 fix(core): Windows Server 缺少媒体基础组件时给出明确提示
QQNT.dll 静态依赖 mf.dll / mfplat.dll / mfreadwrite.dll,Windows Server 默认不安装
「媒体基础」,加载 wrapper.node 时系统只报 The specified module could not be found(#2069)。
现在 Windows 下加载失败且找不到 mfplat.dll 时,直接提示安装媒体基础的方法。
2026-10-05 13:37:07 +08:00
sj817 8005afebd2 fix: 静默离线等 60 秒再重启 Worker,被踢下线不受影响
静默离线(#2080)原来和被踢下线一样 3.5 秒后就重启 Worker。网络短暂断开时 QQ
也可能报离线,这样一次网络抖动就会把整个 Worker 重启掉。现在静默离线先等 60 秒,
期间恢复在线就不重启;等待期间收到被踢通知则不再等,按原来的 3.5 秒重启。

Shell 和 Framework 里重复的下线处理抽成 createOfflineRecovery,并补上测试。
2026-10-05 13:23:32 +08:00
xboHodx a8f6a57311 feat: 群相册支持多图同批次上传与视频上传,分片上传改为并发 (#2081)
- 新增 upload_images_to_qun_album:多张图片共用一个批次,相册里显示为同一条
- 新增 upload_video_to_qun_album:上传视频并自动抽取首帧作为封面
- 分片大小改用服务端返回的 slice_size,分片并发上传,最后一片等其它分片传完再发
- 摘要改为流式计算,分片按需读取,不再把整个文件读进内存
- 批次号同一秒内递增,避免两次上传被并成一条
2026-10-05 13:21:38 +08:00
sj817 c0fd089539 chore(release): 发布说明换成仍可下载的 QQ 官方 CDN 链接
原来的 9.9.26-44343 / 3.2.23-44343 / Mac 40990 链接已经全部 404。
换成 Windows 9.9.33-52230 和 Linux 3.2.32-52194 的官方 CDN 链接并标注,
附上 GitHub 镜像作为备用,MacOS 写明暂不支持。
2026-10-05 12:45:34 +08:00
sj817 88643854a0 fix(core): 新入群拉不到成员列表时群消息不再整条丢失
- getGroupMember 在群成员缓存刷新失败时 members 为 undefined,
  直接 members!.values() 抛 TypeError,整条群消息上报失败;
  现在返回 undefined,拉取失败的结果也不再写进缓存
- 未缓存的群刚刷新过就不再重复强制拉取,群消息处理里也去掉重复查询
- 临时会话按来源群号查成员,之前误把对方 QQ 号当群号去拉成员列表
- uin 转 uid 在 NT 接口都查不到时,先从已缓存的群成员里找

Refs #2070
2026-10-05 12:39:05 +08:00
Shxiao 9a06abbbbd fix: 静默离线(无 KickedOffLine 通知)后自动恢复登录 (#2080)
服务端静默断开会话时不会下发 KickedOffLine,onSelfStatusChanged 仅把
selfInfo.online 置为 false 并打一行日志,没有任何消费者:进程与 WS 连接
继续存活,下游 OneBot 客户端长时间收不到任何事件。

- core 在 在线 -> 离线 的跳变上广播新的 SelfOffline 事件(重复的 status=20
  不重复触发,未登录时不触发)
- framework/shell 复用 #2030 已建立的下线恢复链路:同步 WebUI -> 重启 Worker
  -> 快速登录
- 静默离线可能是临时状态,重启前重新确认仍未恢复,避免误重启 Worker

Closes #2071
2026-10-05 12:06:22 +08:00
sj817 8371359677 fix(webui): Firefox 下关闭卡片倾斜效果,修复登录页内容不显示
Firefox 里 backdrop-filter 和 3D transform 作用在同一个元素上时,卡片里
带层叠上下文的元素(标题、输入框、按钮)不会被绘制,登录页只剩一行提示文字。
报告者在 macOS 的 Firefox 157 上确认:去掉 transform 或 backdrop-filter
任意一个都能恢复,只去掉 transform 时鼠标移上去重新倾斜又会消失。

倾斜只是装饰,保留毛玻璃效果,Firefox 下不再设置 transform 和 will-change,
鼠标光晕照常显示。其他浏览器行为不变。

Closes #2083
2026-10-05 11:46:26 +08:00
sj817 651c15aa61 fix(native): 更新 MoeHoo,修复收到空包时 QQ 进程段错误
QQ 在网络未就绪、连接异常等情况下会以空包调用收发函数,MoeHoo 的
recv_hook/send_hook 不判空直接解引用,导致 QQ 进程 SIGSEGV(#2060、#1668,
崩溃点为 recv_hook+34)。Docker 部署启动后几秒内崩溃就是这个原因。

MoeHoo-NapCat new-test@ff1e937:空包直接交给原函数,不再解引用。
二进制来自该提交的 CI(run 37260275360),更新 linux.x64、linux.arm64、win32.x64。
darwin.arm64 现有二进制与 CI 产物不是同一套实现(54 KB / 1.1 MB),且无法在 Mac 上验证,
本次不更新。

验证:用伪造的 wrapper.node 在 Linux x64 上让 MoeHoo 挂钩同签名函数,
旧二进制在空包、空 src、空指针参数、发送空包时都会段错误,新二进制都正常返回,
正常包的回调内容(uin、cmd、seq、数据)与旧版一致。
2026-10-05 11:44:48 +08:00
sj817 00729e4807 feat(onebot): 群文件夹返回最后修改时间与修改者
get_group_root_files 返回的文件夹新增 modify_time、modifier、modifier_name,
取自 NT 原始数据 folderInfo 的 modifyTime / modifyUin / modifyName,
命名与群文件已有的 modify_time 保持一致。

Closes #1964
2026-10-05 11:07:59 +08:00
sj817 5ef4f6cb7c fix(webui): Passkey 检查不再阻塞 Token 登录
在电脑端注册 Passkey 后用手机打开 WebUI,本机没有对应 Passkey 时
navigator.credentials.get 可能一直不返回,而检查期间 Token 输入框和回车登录
都被禁用,页面就卡在「正在检查Passkey」。

- 检查 Passkey 期间不再禁用 Token 输入框和回车登录
- credentials.get 加 30 秒超时和 AbortController
- 提交 Token 或离开页面时取消仍在等待的 Passkey 验证

Closes #2076
2026-10-05 11:07:59 +08:00
sj817 13a8a2b8dd fix(onebot): get_group_notice 返回「发给新成员」公告
get_t_list 会把「发给新成员」类公告单独放在 inst 数组里,之前只遍历 feeds,
这类公告(群规通常发在这里)完全拿不到。现在把 inst 条目追加在 feeds 之后返回,
已有条目的顺序不变,并按 fid 去重。

新增字段:
- send_to_new_member:是否为「发给新成员」公告
- pinned:由 inst 条目的 settings.inst_no_pinned 映射(0 = 置顶),
  feeds 条目读不到置顶状态,不带该字段

Closes #2082
2026-10-05 11:07:42 +08:00
手瓜一十雪 8d69a8e086 feat
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-04 20:24:08 +08:00
Shxiao 26d7533e0f fix: get_friend_msg_history 未透传 quick_reply 参数 (#2073)
payload schema 声明了 quick_reply,但 _handle 调用 parseMessage 时
没有传入,字段被静默忽略;与 get_group_msg_history 行为不一致。
将 payload.quick_reply 作为第 5 个参数透传,并补充回归测试。
2026-09-29 15:18:10 +08:00
风澪 870a6060b8 fix(onebot): 私聊引用丢失 reply 段——按 clientSeq 反查被引用消息 (#2016)
私聊被引用时,引用元素里的 replayMsgSeq 常为 0(客户端未填序号),
replyElement 的三条 seq 查询与协议兜底都会落空,最终返回 null;null 段
被 parseMessageSegments 过滤掉,于是事件里没有 reply 段、也没有报错(#1508)。

同一元素携带的 replyMsgClientSeq / replyMsgTime 在这种场景下依然准确,而
NapCat 已有按 (peer, clientSeq, time) 查询的 getMsgByClientSeqAndTime
(此前无调用点)。这里在 seq 查询链失败之后用它反查被引用消息,命中即用
真实的 msgId 构造 reply 段。

新路径仅在 seq 链失败后追加,群聊与带真实序号的私聊行为不变。

实测(NapCat 4.18.28 / OneBot 私聊):
- 日志复现「方法1/2/3 查询失败,序号: 0」→「所有查找方法均失败」
- 修复后 reply 段的 id 等于被引用消息自身事件里的 message_id,
  get_msg 可反查,带 reply 段回发引用正常

注:本 PR 先前版本改为直用 records.msgId,实测证伪——那是每次事件一份的
快照 id,get_msg 查不到、回发引用会被静默丢弃,已放弃该方案。
2026-09-29 15:18:04 +08:00
Shxiao 0b4cfe65ed fix: set_qq_profile 无法将性别设置为 0(未知) (#2065) 2026-09-23 16:52:24 +08:00
Shxiao 46e505f4ba fix: 移出精华消息时 msg_random 与 msg_seq 参数顺序错误 (#2064) 2026-09-23 10:08:42 +08:00
手瓜一十雪 2049e64260 Add newer QQ appids and arch-aware lookup
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Updated the external QQ appid, native, and packet tables for newer Linux and Windows builds, including architecture-specific Linux AppID entries. QQBasicInfoWrapper now prefers the matching x64/arm64 AppID before falling back to version-only lookups, and regression tests cover Linux/Windows version resolution and fallback behavior.
2026-09-14 12:36:00 +08:00
手瓜一十雪 7a35ef035a Pin Windows QQ package for release build
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
The Windows release workflow now uses a fixed QQ installer URL and SHA256 hash, verifies the downloaded installer before packaging, and makes the download cache key sensitive to the selected QQ URL, hash, and Node version. The workflow also switches QQ downloads to curl with retries for transient HTTP errors and centralizes the Node version variable to keep the build config consistent.
2026-09-14 12:01:24 +08:00
五加一5plus1 c75d2f7f86 fix(webui): recover QR login after forced logout (#2030)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-09-14 11:46:32 +08:00
手瓜一十雪 fa3fe9fdb2 Use pnpm setup in release workflow
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
The release publishing workflow now installs pnpm via pnpm/action-setup instead of globally via npm, and applies the same improvement to the APIFox update job. This keeps the workflow consistent and avoids relying on the environment's global pnpm installation.
2026-09-14 11:43:29 +08:00
手瓜一十雪 464bc3d4a7 Revert "Disable npm install scripts"
This reverts commit 3c03b162f5.
2026-09-14 11:38:46 +08:00
手瓜一十雪 3c03b162f5 Disable npm install scripts
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add a project-level .npmrc so npm does not skip package lifecycle scripts during installation. This ensures dependency setup and initialization continue to run as expected.
2026-09-14 11:03:09 +08:00
Shxiao 4079214dc5 fix: Rkey 服务响应缺少必要字段时输出明确错误 (#2044)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
部分内置 Rkey 服务返回 HTTP 200 但响应缺少 group_rkey/private_rkey,
refreshRkey 直接执行 temp.group_rkey.slice(6) 触发
TypeError: Cannot read properties of undefined (reading 'slice'),
报错信息看不出是服务返回结构变化。

在解析前校验响应结构:非对象响应(如 JSON null)不再走 'retcode' in
temp 的原始 TypeError 路径;group_rkey/private_rkey 须为可截去 6 字符
前缀的非空字符串,expired_time 须为正数,无效时按现有失败计数逻辑
禁用该 URL 并抛出明确错误,与其他服务的异常路径保持一致。

Fixes #2010
2026-09-14 10:54:08 +08:00
Shxiao 109d0c1dff fix: 仅当 fork 子进程完整引导 Chromium 时注入 --no-sandbox (#2045)
纯 Node 环境(如 NapCat.Shell.Windows.Node)下 child_process.fork 的
execArgv 会直接传给 node.exe;--no-sandbox 是 Chromium 开关,Node 不识别,
Worker 以退出码 9 (bad option) 启动失败并触发三次重启后主进程退出。

#1984 在非 Electron 路径无条件注入该参数,同样影响以 ELECTRON_RUN_AS_NODE
驱动 Electron 二进制的容器环境:node 模式与上游 Node 一致拒绝未知开关
(该变量存在即触发 node 模式,与取值无关)。

将注入条件从 !isElectron 收窄为「fork 路径 && 宿主为 Electron 二进制 &&
未设 ELECTRON_RUN_AS_NODE」:QQNT 主进程 fork 出的子进程不带
ELECTRON_RUN_AS_NODE、完整引导 Chromium,由 Chromium 解析该参数以规避
proot 沙箱 SIGSEGV,#1984 行为保持不变;纯 Node 路径不再传入,Worker
正常启动,并恢复 fork 对 process.execArgv 的默认继承。

Fixes #2040
2026-09-09 13:38:46 +08:00
Shxiao 96de2314b0 style: 修复主分支现存的 ESLint 错误 (#2046)
- 修复 7 个文件中全部 21 个 ESLint 错误(缩进、注释空格、引号、函数括号空格、三元表达式换行、JSX 缩进)
- dashboard/config/index.tsx 中写在 JSX children 里的 // 注释会被当作文本节点渲染到 WebUI 配置页,改为 JSX 注释
- 验证:npx eslint . 退出码 0;pnpm run typecheck 全部包通过
2026-09-08 18:18:46 +08:00
Darf eecb02140f feat: add get_group_share_link action (NTQQ getJoinGroupLink) (#2041) 2026-09-04 19:25:36 +08:00
yibai 3ac54c181b 更换稳定签名服务器 (#2034)
更换稳定签名服务器,这次更新就不会再动了

Signed-off-by: yibai <160130578+yibainb@users.noreply.github.com>
2026-08-29 21:16:50 +08:00
yibai 0c4c371eee fix: Update music card signature URL
由于思思的音卡签名可能出现问题,测试时已无法使用,特此自建签名api并替换。同时加入备选思思api逻辑

Signed-off-by: yibai <160130578+yibainb@users.noreply.github.com>
2026-08-27 03:48:52 +08:00
手瓜一十雪 af07479351 Add missing QQ face config entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
This update adds the missing QQ face definitions for QSid 450-484 (EMCode 10450-10484) to the external face configuration. It covers newer emoji entries such as /撇嘴, /微笑, /无语, and /学习, aligning the config with the current face set.
2026-08-14 18:58:40 +08:00
手瓜一十雪 c59a47a5a7 Add 9.9.32-55230 appid and napi2native entries
Add support for release 9.9.32-55230: update packages/napcat-core/external/appid.json with Windows appid 537379411 and QUA, and add x64 send/recv mappings to packages/napcat-core/external/napi2native.json to support the new Win x64 build.
2026-08-14 18:36:05 +08:00
手瓜一十雪 49ea8d5624 Strip control & ANSI sequences from logs && fix #1961
Sanitize formatted log messages by removing control characters and ANSI escape sequences when creating the message. Consolidates ANSI/control stripping into the initial message and removes the redundant replace in the file-only logging branch to prevent control/ANSI codes from polluting console or file logs.
2026-08-14 18:25:21 +08:00
DogeCN fe7a1f053a fix: 修复 WebUI 白屏与 arm64/proot 下 Worker SIGSEGV (#1984)
* fix(webui): 合并 react/react-dom/scheduler 到 react-vendor chunk

codemirror-core chunk 从 react-dom chunk 导入 forwardRef(r),
但 react-dom 被 manualChunks 单独拆块后未导出该绑定,
forwardRef 为 undefined 导致 React 初始化崩溃、整页白屏。

将 react/react-dom/scheduler 合并为 react-vendor 块,
消除 React 19 下 chunk 间 forwardRef 跨块断裂。

* fix: Worker 改走 child_process.fork 并传 --no-sandbox(arm64/proot 下避免 UtilityProcess SIGSEGV)

- process-api.ts: ProcessOptions 增加 execArgv 选项;isElectron 增加 NAPCAT_FORCE_NODE_PROCESS 环境变量判断,可强制走 Node 进程管理器
- napcat.ts: Node 进程路径下为 Worker 注入 execArgv: ['--no-sandbox'],规避 arm64/proot 环境 Electron UtilityProcess 崩溃(退出码 11)
- 注:未包含原 commit 中 scripts/install.sh 的 Termux 特定补丁(该文件为 fork 私有,上游不存在)
2026-08-10 11:15:04 +08:00
手瓜一十雪 0fcd0e80e0 Revert "添加自动登录 | feat(login): automatically restore last logged-in account (#1980)"
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
This reverts commit 31c45bf18e.
2026-08-07 17:47:00 +08:00
Chace 624ecf5b9a fix: restore PNG thumbnails for direct video sends (#2000) 2026-08-07 17:47:00 +08:00
叫我饼干ちゃん 63a349d119 添加自动登录 | feat(login): automatically restore last logged-in account (#1980)
* feat(login): automatically restore last logged-in account

* docs(shell): correct quick login argument examples
2026-08-07 17:47:00 +08:00
Leslie Lau 56549cd0f2 fix: report non-latest private message recalls (#1998) 2026-08-07 17:47:00 +08:00
Zizheng Guo ead24423b5 feat(group): add group management APIs (#1996) 2026-08-07 17:46:59 +08:00
Chace f0e045df35 fix: 修复合并转发视频过期及移动端延迟显示问题 (#1983)
* fix: 修复合并转发视频过期问题

* fix: 修复移动端合并转发内容延迟显示问题

* fix: 同步 ffmpegAddon 视频封面处理产物
2026-08-07 17:46:59 +08:00
Airline233 33ee94ab0f feat(qzone): add QQ space message deletion functionality (#1978)
- Add deleteQzoneMsg API method to NTQQWebApi for deleting Qzone posts by tid
- Implement buildQzoneDeleteBody to construct form-encoded request payload
- Implement parseQzoneDeleteResponse to validate deletion API response
- Add QzoneDeleteResponse and QzoneDeleteParams type definitions
- Create DeleteQzoneMsg OneBot action handler with payload validation
- Register delete_qzone_msg action in router and action handlers
- Add example payload and response for DeleteQzoneMsg action
- Add comprehensive unit tests for delete body construction and response parsing
- Fix indentation inconsistency in createAlbumCommentRequest call
2026-08-07 17:46:59 +08:00
Airline233 cbec362ed1 feat(qzone): add QQ space message publishing and image upload (#1965)
- Add QzonePublishResponse interface and parsing logic for publish API responses
- Add buildQzonePublishBody function to construct publish request parameters
- Add buildQzoneUploadImageBody function to construct image upload request parameters
- Add parseQzoneUploadImageResponseText function to parse upload API responses
- Add toQzoneRichval function to format image data for publish requests
- Add publishQzoneMsg method to NTQQWebApi for publishing space messages with optional images
- Add uploadImageToQzone method to NTQQWebApi for uploading images to QQ space
- Add getQzoneAuth private method to retrieve authentication tokens (skey, pskey, g_tk)
- Add SendQzoneMsg action handler to expose QQ space publishing via OneBot API
- Add comprehensive unit tests for all Qzone data construction and parsing functions
- Update action router to register SendQzoneMsg action
- Update action examples to demonstrate Qzone publishing usage
2026-08-07 17:46:58 +08:00
手瓜一十雪 766ca6e071 Update QQNT release download URLs
Refresh the downstream release workflow to use the newer QQNT 3.2.30-50969 AppImage URLs for both x86_64 and arm64 builds.

Update release note prompt and AI model

Clarifies the release note prompt to require strict output format without wrapping the result in a code block. Also updates the release publish workflow to use `google/gemma-4-26b-a4b-it:free` instead of the previous OpenAI model endpoint setting.

Update QQNT installer URL in release workflow

Switches the release publish workflow to download a newer QQNT x64 installer (9.9.32.50969) from the updated qqdl.gtimg.cn source instead of the previous dldir1v6.qq.com link.

Add mappings for QQ 50969 builds

Add appid/QUA entries and native/packet send-recv offsets for the new 9.9.32-50969 Windows build and 3.2.30-50969 Linux x64/arm64 builds. Also normalize the existing 3.2.30-50828 x64 native recv offset format by removing the leading zero.
2026-08-07 17:46:36 +08:00
colGem 7c2514be6c fix: 将显式 group_id 优先级提升至 getTempChatInfo 缓存之前 (#1963)
## 问题
调用 send_private_msg 时,即使显式传入了 group_id 参数以指定通过某个群发起临时会话,由于 createContext() 中 getTempChatInfo(查询旧的临时会话缓存)的优先级高于显式 group_id,导致实际使用的是旧缓存所在群,而非调用方指定的群。

当缓存所在群不允许临时会话时(QQ 错误码 103),即使传入的 group_id 对应的群已开启临时会话,消息发送仍然失败。

## 根因
createContext() 的判断顺序为:
  1. 是好友 → C2C
  2. 不是好友 → getTempChatInfo 命中缓存 → 用缓存群
  3. 缓存未命中且传了 group_id → 用显式群

第 2 步应该在第 3 步之后:调用方显式指定的 group_id 是主动意图,应优先于内部缓存。

## 修复
将 if (payload.group_id) 判断移至 getTempChatInfo 之前,使优先级变为:
  1. 是好友 → C2C
  2. 不是好友且传了 group_id → 用显式群
  3. 缓存命中 → 用缓存群(兜底)

未传入 group_id 时的行为完全不变。

## 测试

已通过 patch 编译产物 napcat.mjs 在生产环境验证,确认 group_id 参数现在可以
正确指定临时会话来源群。

Signed-off-by: colGem <62532175+colGem-ga@users.noreply.github.com>
2026-07-19 20:20:11 +08:00
738e272d2c fix(onebot): 引用回复解析中 quick_reply 形参未解构导致 reply 段丢失 (#1952)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* fix(onebot): destructure quick_reply in replyElement converter

parseMessageSegments passes the whole RecvMessageContext object as the
4th argument to element converters, but replyElement declared the
parameter as `quick_reply` without destructuring. The object is always
truthy, so every reply element took the quick-reply branch and skipped
lookup methods 2/3 whenever method 1 found no match, dropping the reply
segment from the reported OneBot message (it degrades to at + text).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(onebot): fall back to msgSeq match when msgRandom mismatches in reply lookup

All three reply lookup methods matched candidates only by msgRandom
whenever records.msgRandom was present. When the recorded msgRandom is
stale or inconsistent with the message database, the quoted message
returned by a seq-based query was discarded even though its msgSeq
matched exactly. Match by msgRandom first and fall back to an exact
msgSeq match.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: xulang <xuxiaolang2003@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 09:46:59 +08:00
Yahoo f7edbfd8d9 fix(onebot): relax packet status check for send poke (#1945) 2026-07-06 12:41:49 +08:00
墨梓柒 74dc33fee6 fix: return real used_space/total_space for get_group_file_system_info (#1944)
The action hardcoded used_space=0 and total_space=10GiB. The kernel's
getGroupFileList call already returns the group's space usage in its
groupSpaceResult, so read it (a single-item fetch) instead of the
placeholders. Falls back to the previous constants when the field is
absent, so there is no regression.

Also relax the empty-count guard from `!groupFileCount` to `=== undefined`
so a group with zero files is not mistaken for "Group not found".
2026-07-05 11:10:44 +08:00
mitsukina c95dd3d030 Add mappings for 9.9.32 and 3.2.30 builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Update external version metadata to support new QQ releases. Added appid/qua entries for 9.9.32-50828 and 3.2.30-50828, plus corresponding send/recv native and packet offsets across x64 and arm64 targets.
2026-07-03 19:21:27 +08:00
Bluemangoo 68e6a9bff9 fix: 修复如[CQ:face,id=*,raw=[object Object]]的问题。 (#1932) 2026-06-24 15:38:47 +08:00
手瓜一十雪 5c18a62530 add .claude to gitignore 2026-06-20 12:46:49 +08:00
手瓜一十雪 a82a5d5203 chore: .claude delete 2026-06-20 12:46:08 +08:00
手瓜一十雪 93efce86ca feat: re
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-06-20 12:41:32 +08:00
Ryokuryuneko 091c012427 feat(webui): 添加双重登录验证(2FA)功能 (#1920)
* feat(webui): 添加双重登录验证(2FA)功能

* fix: 修复 store.delete 类型错误,添加完整项目文件

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证
- 后端:添加 enable2FA 和 totpSecret 配置项
- 后端:登录处理器支持 2FA 验证
- 前端:添加 2FA 登录流程和配置页面

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证 (TotpHelper.ts)
- 后端:添加 enable2FA 和 totpSecret 配置项 (config.ts)
- 后端:登录处理器支持 2FA 验证,添加 2FA 管理 API (Auth.ts)
- 后端:注册 2FA 相关路由 (auth.ts)
- 前端:登录页面添加 2FA 验证步骤 (web_login.tsx)
- 前端:添加 2FA 相关 API 调用方法 (webui_manager.ts)
- 前端:添加 2FA 配置页面 (webui.tsx)

* fix: 更新 AuthResponse 类型定义以支持 2FA

* fix: 修复 setLocalToken 类型错误

* fix: 修复 TotpHelper.ts 类型错误

* fix: address PR review feedback

- Remove database files from tracking
- Use local QRCodeSVG instead of third-party API
- Remove unused verify2FACode method
- Remove IP-based challenge storage (password already validated)
- Require TOTP code to disable 2FA
- Remove duplicate loginWithTokenAndTotp method
- Remove unused generateTotp method
- Use consistent English error messages

* fix: remove unused store import

* chore: translate 2FA UI to Chinese
2026-06-20 09:56:54 +08:00
tzhd427 8a3faf64f9 对WebUI布局的修改 (#1906)
* 把“系统设置-修改密码”移动到“系统设置-WebUI配置”中

* 修正语法错误

* 把修改密码移动到上方
2026-06-17 01:01:10 +08:00
cc10143 fbd70bbb04 fix: reset QQLoginStatus on KickedOffLine to prevent WebUI re-login block (#1896)
When QQ kicks the bot offline, the WebUI incorrectly shows the account as still
logged in, blocking users from re-login via QR code or password until NapCat is
restarted.

Root cause: The KickedOffLine event handlers in both the shell (base.ts) and
framework (napcat.ts) only set the error message without resetting
QQLoginStatus. The QQGetQRcodeHandler and other login endpoints check
getQQLoginStatus() and reject all re-login attempts when it remains true.

Fix: Set QQLoginStatus to false in both event handlers, ensuring the WebUI
state syncs with the actual account status when kicked offline.

Two changes:
- napcat-shell/base.ts: add setQQLoginStatus(false) before setQQLoginError()
- napcat-framework/napcat.ts: register a KickedOffLine listener that resets
  the login status (the framework previously had no KickedOffLine listener)

Fixes: #508, #1818
2026-06-11 14:43:16 +08:00
MliKiowa c405b6d0a4 docs: 社区进一步限制
Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-06-09 23:45:19 +08:00
手瓜一十雪 3a4b335062 feat
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-06-08 20:01:03 +08:00
Qiao 9aa11fd7c4 fix: 校验群名片设置结果 (#1880) 2026-06-04 23:56:45 +08:00
手瓜一十雪 8ae11bfdca Add 49738 build metadata to external JSONs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Register new builds and architecture-specific offsets/IDs for 9.9.31-49738 and 3.2.29-49738. Updated packages/napcat-core/external/appid.json to add appid/qua entries, and napi2native.json and packet.json to add send/recv offsets for x64 (and arm64 where applicable). These additions track the new builds and their native mappings.
2026-06-03 12:13:20 +08:00
Qiao 6acf350613 feat(onebot): add custom face management actions (#1879) 2026-06-02 22:51:27 +08:00
liuwanwan 0af6445d5a fix: 修复 lint 校验失败 (#1867) 2026-05-28 14:14:50 +08:00
liuwanwan a716a1a185 fix: correct HTTP method case comparison in httpApiRequest (#1865)
Express req.method returns uppercase strings ('GET', 'POST', etc.),
so `req.method === 'get'` never matches. This caused GET requests
to fall through to the else-if branch instead of directly using
req.query as the payload.

Closes NapNeko/NapCatQQ#1864
2026-05-26 22:41:33 +08:00
手瓜一十雪 8c9fc7edf4 README: suggest SnowLuma as GUI replacement
Replace the previous "New Feature" section with a short suggestion to try SnowLuma as a NapCat GUI alternative. Removes the v4.8.115+ notes about Stream API and recommending string IDs, simplifying the README and pointing users to the SnowLuma GitHub repository.
2026-05-26 18:23:23 +08:00
idranme 1abad76ac9 feat: 新增获取群组今日打卡列表功能 (#1855)
* feat: add group signed list API and OneBot action

* feat: register GetGroupSignedList action handler
2026-05-24 20:16:14 +08:00
手瓜一十雪 484c181050 Set rootDir in package tsconfigs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add compilerOptions.rootDir = ".." to tsconfig.json for napcat-onebot, napcat-shell, and napcat-webui-backend to ensure the TypeScript compiler uses the monorepo package root for source resolution. Also remove an extraneous blank line in theme.tsx near FileManager.uploadWebUIFont (minor formatting cleanup).
2026-05-22 22:31:11 +08:00
手瓜一十雪 9d652be35d fix: #1774 2026-05-22 22:27:19 +08:00
手瓜一十雪 f226c83595 Skip pnpm install scripts; defer QR code fetch & fix #1804
CI: use `pnpm i --ignore-scripts` in release-publish workflow to avoid running package install scripts during CI.

Shell: defer showing the QR code until after attempting WebUi quick-login/password fallback. Adds checks for NAPCAT_QUICK_ACCOUNT and quick-password env vars (and WebUi quick-login list), runs WebUi quick config, and only calls getQRCodePicture() if no fallback was attempted and the user is not logged in. Includes error handling for the quick-login attempt.
2026-05-22 22:23:45 +08:00
手瓜一十雪 b565f876c5 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2026-05-22 22:12:05 +08:00
手瓜一十雪 19a5febb1a fix: #1827 2026-05-22 22:06:00 +08:00
Copilotandsj817 bbf822035f fix: restart HTTP server when host changes (#1836)
* Initial plan

* fix: restart HTTP server when host changes

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/0ead0c47-df0d-4666-8877-775c9c641ed8

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-22 22:05:23 +08:00
手瓜一十雪 a2b0ac10a0 fix: #1843 2026-05-22 22:02:38 +08:00
手瓜一十雪 279b3ea4eb Add 9.9.30 & 9.9.31 x64 external entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add external mappings for Windows x64 versions 9.9.30-48762 and 9.9.31-49599 across appid, napi2native, and packet files. appid.json: add appid 537352525 (9.9.30-48762) and 537355779 (9.9.31-49599) with QUA strings. napi2native.json: add send/recv hashes for 9.9.30-48762-x64 (0A9B1BC / 1F0324D) and 9.9.31-49599-x64 (0AF885C / 20058E1). packet.json: add send/recv offsets for 9.9.30-48762-x64 (2F3B960 / 2F3EEE0) and 9.9.31-49599-x64 (3082C40 / 30861C8).
2026-05-22 21:58:30 +08:00
手瓜一十雪 33cc11ba84 Update tsconfig: bundler resolution & path mappings
Switch moduleResolution to "bundler" in base and package tsconfigs and consolidate path aliases for monorepo packages. Remove several package-level baseUrl entries and update package paths to reference ../../packages/* (add explicit napcat-common/src and napcat-image-size/src mappings). Also add a rootDir override for napcat-core. These changes unify module resolution and path aliases so TypeScript and bundlers resolve workspace packages consistently.
2026-05-21 19:16:44 +08:00
手瓜一十雪 b058604077 PR build: add dispatch script & secure workflow
Introduce a safe PR build dispatch flow and related helpers.

- Add GitHubAPI.createWorkflowDispatch to .github/scripts/lib/github.ts and tighten getRepository nullability.
- Add .github/scripts/pr-build-dispatch.ts to dispatch an untrusted workflow_run (workflow_dispatch) for PR builds.
- Rewrite .github/workflows/build-pr.yml to split privileged checks (pull_request_target / issue_comment) from untrusted execution (workflow_dispatch):
  - Add workflow_dispatch inputs for PR metadata.
  - Ensure privileged jobs only check conditions, post comments and dispatch the untrusted build.
  - Untrusted build jobs (framework/shell/publish) run under workflow_dispatch, checkout PR code into a separate workspace, clear GITHUB_TOKEN in build steps, and set stricter permissions and persist-credentials:false where appropriate.
  - Adjust concurrency, outputs, and inter-job dependencies to work with inputs rather than passing sensitive data between privileged and untrusted contexts.
- Update trigger-docker and result-comment flows to rely on workflow_dispatch inputs and only run in the untrusted run where appropriate.

- Change packages/napcat-vite/vite-plugin-version.js to read NAPCAT_GITHUB_TOKEN (instead of GITHUB_TOKEN) to avoid exposing Actions write tokens in untrusted builds.

These changes aim to improve security by preventing execution of PR-controlled code with elevated repo permissions and by isolating token usage.
2026-05-19 15:52:47 +08:00
H3CoF6 1c703a60ed fix(album): refactor group album like payload and implement cancel like action (#1844) 2026-05-19 09:54:15 +08:00
时瑾 285ba9cf2d ci: pin pnpm to v9 via pnpm/action-setup
pnpm 10 exits non-zero on [ERR_PNPM_IGNORED_BUILDS] by default, which
broke CI after the global pnpm version on GitHub runners bumped.

Replace ad-hoc `npm i -g pnpm` calls with pnpm/action-setup@v4 pinned to
version 9 across build-ci.yml, build-pr.yml, and drop the redundant
Install pnpm step from pr-build-run.ts.
2026-05-16 14:07:11 +08:00
Copilotandsj817 b253fd82c4 Fix WebUI login page stuck when navigating via token URL (#1835)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* Initial plan

* Fix: set isPasskeyLoading=false when token is in URL to prevent permanently disabled input on login failure

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/fa88593a-3466-40e5-80ff-82c47e1c56e6

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-13 10:34:26 +08:00
Ventiの酒 8996b35dd1 fix: enable wss connections and add certificate verification toggle in WebSocket Client (#1823)
* fix: enable wss connections and add certificate verification toggle in WebSocket Client

Previous behavior: the WebSocket Client only supported unencrypted ws:// connections; wss:// URLs were not handled and would fail to connect, providing no option to disable TLS certificate validation for development or self-signed certificates.
Fixed behavior: secure WebSocket connections (wss://) are now fully supported. A verifyCertificate configuration option has been introduced, defaulting to true. When set to false, certificate errors (e.g., self-signed certificates) are ignored, enabling safe local testing while maintaining strict validation by default for production.

* fix: improve wss certificate verification and add tests

Previous behavior: wsOptions used 'any' type without type safety, verifyCertificate was added to napcat-protocol without implementation, and no tests existed for the new config option.

Fixed behavior: wsOptions now uses proper WebSocket.ClientOptions type for compile-time safety, verifyCertificate removed from napcat-protocol (no WebSocket client implementation exists there), and comprehensive tests added to validate config loading and default values.
2026-05-13 10:33:47 +08:00
Bluemangoo 25db6f0835 add ptt to text (#1837) 2026-05-13 10:31:07 +08:00
手瓜一十雪 2c8f9743da Add 9.9.30-48517 appid and napi2native entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add mappings for version 9.9.30-48517: update packages/napcat-core/external/appid.json with appid 537352474 and qua "V1_WIN_NQ_9.9.30_48517_GW_B", and update packages/napcat-core/external/napi2native.json with the x64 mapping (send: "0A9B1BC", recv: "1F0324D"). These entries add support for the new 9.9.30-48517 release.
2026-04-26 18:10:40 +08:00
手瓜一十雪 fc26077283 fix: #1793 2026-04-26 17:26:53 +08:00
手瓜一十雪 e9bbc82f37 fix: #1801 2026-04-26 17:21:16 +08:00
时瑾 600f2a4518 fix: replace nclatest proxy with ghfast.top, add dual install commands 2026-04-18 01:29:58 +08:00
时瑾 abf57e688c feat: add proxy prefix to install URL, change TTL to 5 days
- comment.ts: Add PROXY_BASE constant (https://nclatest.znin.net);
  install curl command now uses proxy URL for CN users;
  '24小时' -> '5天'; Docker '7天' -> '5天'
- pr-publish-release.ts: Import PROXY_BASE, use proxy URL in release body,
  '24小时' -> '5天'
2026-04-18 00:31:40 +08:00
时瑾 d92a4cff8d fix: zip absolute path, publish failure comment, pass publish_status
- pr-publish-release.ts: Use resolve() for releaseDir to get absolute path;
  zip command runs with cwd=artifactDir so relative path was resolving wrong
- build-pr.yml: Expose steps.publish.outcome as publish_status job output;
  pass PUBLISH_STATUS env to update-comment-result job
- pr-build-result.ts: Read PUBLISH_STATUS, pass publishFailed to comment
- comment.ts: Show '⚠️ Release 发布失败' section in PR comment when
  publish failed but installInfo is absent
2026-04-18 00:18:46 +08:00
时瑾 e195aee5d2 fix: remove TS overloads incompatible with --experimental-strip-types, fix 204 response, fix retention-days
- lib/github.ts: Remove getEnv overload signatures (Node.js experimental-strip-types
  does not support TS function overloads, causes SyntaxError at parse time)
- lib/github.ts: Handle 204 No Content in request<T> (DELETE returns 204,
  calling response.json() on empty body throws)
- build-pr.yml: retention-days 7->5 (repo max is 5)
2026-04-18 00:08:12 +08:00
时瑾 014a32533d feat: add PR release publish, Docker dispatch and comment system 2026-04-17 23:51:30 +08:00
Airline233andCopilot fa97d15c66 Fix: /get_cookies under the QZone domain returned bkn unexpectedly (#1762)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* Fix: QZone's g_tk(bkn)

Signed-off-by: Airline233 <airline233@gmail.com>

* Add getBknFromPSKey method to webapi

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix variable declaration for BKN in GetCookies

a stupid error...

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix typo in method name for BKN retrieval

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix getBknFromPSKey function call syntax

Signed-off-by: Airline233 <airline233@gmail.com>

* Update packages/napcat-core/apis/webapi.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Airline233 <airline233@gmail.com>

* Update packages/napcat-onebot/action/user/GetCookies.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Airline233 <airline233@gmail.com>

---------

Signed-off-by: Airline233 <airline233@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-16 07:11:31 +08:00
Copilotandsj817 285632f463 fix: preserve user napcat.json config across updates (#1765)
* Initial plan

* fix: prevent o3HookMode from being reset to enabled after NapCat updates

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/98ea8e7d-4ee4-43c1-ac33-2714fba480e3

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* fix: restore o3HookMode default to 1, harden updater against path traversal

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/53b58325-1685-4961-803e-93091dd8b1c4

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-16 07:08:54 +08:00
xboHodx 6d63da4fa0 feat: 新增群待办完成和取消功能 (#1764)
- 添加CompleteGroupTodo和CancelGroupTodo方法
- 重构SetGroupTodo使用BaseGroupTodoAction基类
- 更新相关测试用例和依赖配置

Signed-off-by: xboHodx <2679933924@qq.com>
2026-04-16 07:08:07 +08:00
时瑾 d849188ef2 feat: Add hourly server time synchronization 2026-04-13 19:49:06 +08:00
Copilotandsj817 45966f072e fix(get_msg): return error immediately for recalled messages instead of hanging (#1731)
* Initial plan

* fix: add timeout to getMsgsByMsgId in GetMsg to handle recalled messages

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/15e050cc-734a-4cd5-acb1-69624f6e0978

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* Update GetMsg.ts

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-13 19:30:51 +08:00
c235c92ce9 feat: set_group_ban fails when admin attempts to ban another admin (#1742)
* Initial plan

* feat: set_group_ban returns failed when admin tries to ban another admin

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/5c497921-6acb-41fd-a8d3-ad84f59a0eb8

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* Update SetGroupBan.ts

* Update packages/napcat-onebot/action/group/SetGroupBan.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: 时瑾 <shijinn520@gmail.com>

---------

Signed-off-by: 时瑾 <shijinn520@gmail.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
Co-authored-by: 时瑾 <shijinn520@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-13 19:26:57 +08:00
Copilotandsj817 a62c9298ac fix: accept NAPCAT_DISABLE_MULTIPROCESSING as alias for NAPCAT_DISABLE_MULTI_PROCESS (#1757)
* Initial plan

* fix: accept NAPCAT_DISABLE_MULTIPROCESSING as alias for NAPCAT_DISABLE_MULTI_PROCESS

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/1f67b134-2798-41ad-9d26-b9b82f5adb7d

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-13 19:18:57 +08:00
手瓜一十雪 c5bc48da1f Remove NAPCAT_BUILD token from workflow
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Remove the explicit `token: ${{ secrets.NAPCAT_BUILD }}` line from the release-publish GitHub Actions workflow. This stops passing the custom NAPCAT_BUILD secret to the release step, allowing the action to use the default authentication mechanism or another configured token and reducing exposure of the custom secret.
2026-04-05 20:31:17 +08:00
006lp 4edb3385e4 feat(appid,napi2native,packet): add early support for QQ client version 47354 (#1743)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* feat(appid): add support for QQ client versions 47354

Add appid and qua configurations for new QQ client versions:

QQ 3.2.27-47354-x64 (Linux)

QQ 9.9.29-47354-x64 (Windows)

QQ 6.9.93-47354-arm64 (macOS)

* Update napi2native version keys to 47354 (win-x64,linux-x64/arm64)

* Update napi2native version keys to 47354 (mac-arm64)

* Update napi2native version keys to 47354 (mac-x64)

* feat(packet): add support for QQ client version 47354
2026-04-05 20:29:06 +08:00
手瓜一十雪 10f961c552 Update OPENAI_MODEL in release workflow
Change the OPENAI_MODEL environment variable in .github/workflows/release-publish.yml from "openrouter/hunter-alpha" to "z-ai/glm-4.5-air:free" so the release-publish job uses the new model endpoint for OpenAI API calls. No other workflow changes.
2026-03-22 15:19:40 +08:00
手瓜一十雪 0baf800d21 Add mappings for 46928 and 9.9.28 builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Update packages/napcat-core/external/napi2native.json and packet.json to include send/recv offsets for 3.2.26-46928 (x64 and arm64) and 9.9.28-46928-x64. Arm64 entries reuse the same offsets as 3.2.26-46494-arm64; new x64 offsets were added for both files.
2026-03-22 12:25:58 +08:00
Rinandrin 5c0fac7de6 feat: 群公告/精华等接口引入 psKey 缓存 (#1716)
* fix: 群公告/精华等接口的 psKey 缓存优化

- 在 NTQQGroupApi 中新增 _qunPskeyCache 缓存字段(TTL 4分钟)
- 新增 getQunPskey() 私有方法,统一管理 qun.qq.com 域名的 psKey 获取
- fetchGroupEssenceList、deleteGroupBulletin、uploadGroupBulletinPic、publishGroupBulletin
  共 4 处调用改为共享缓存,避免每次请求都独立拉取 psKey,减少 HTTP 请求次数
- 缓存过期后自动刷新,无需手动管理

* fix: 改用滑动 TTL + 惰性删除管理 psKey 缓存

- TTL 从硬编码 4 分钟改为 60 秒滑动窗口
- 每次访问顺延过期时间(滑动 TTL),避免频繁刷新
- 过期后惰性删除,下次访问时直接覆盖,无主动清理开销
- 回应 reviewer 建议:滑动窗口比固定 TTL 更适合偶发调用场景

---------

Co-authored-by: rin <rin@rin.red>
2026-03-22 12:19:39 +08:00
手瓜一十雪 c7109e20ad Use GITHUB_TOKEN for downstream trigger
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Replace secrets.NAPCAT_BUILD with the built-in secrets.GITHUB_TOKEN in the release-publish workflow to authenticate triggering downstream release workflows. This removes dependency on a custom secret and uses the repo-scoped Actions token for simpler, more secure automation.
2026-03-14 12:51:00 +08:00
手瓜一十雪 d61433f2a4 Update OPENAI_MODEL in release workflow
Update the OPENAI_MODEL env var in .github/workflows/release-publish.yml from "stepfun/step-3.5-flash:free" to "openrouter/hunter-alpha" so the release publish job uses the new model for API calls. No other workflow changes.
2026-03-13 22:58:03 +08:00
手瓜一十雪 0ae05ccb8d Use default duration if getDuration fails
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add a fallback for video duration by including this.getDuration(videoPath).catch(() => 60) in the Promise.all alongside fileTypeFromFile. This prevents Promise.all from rejecting when duration retrieval fails and supplies a sensible default (60s) for downstream processing (e.g., thumbnail generation).
2026-03-13 19:48:31 +08:00
手瓜一十雪 973ccaebed Throw on invalid ffprobe duration, remove prefetch
Remove prefetching of video duration from the initial Promise.all and change getDuration to stop swallowing errors: it now throws when ffprobe returns a non-numeric duration (including the raw stdout in the error) instead of returning a default 60s. This prevents silently masking ffprobe failures — callers should handle or catch errors from getDuration.
2026-03-13 19:48:14 +08:00
手瓜一十雪 59bd457a97 Refactor GitHub Actions workflows
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Rework CI/CD by replacing and reorganizing GitHub Actions workflows. Added build-ci.yml (typecheck/test + matrix builds), release-downstream.yml (dispatch downstream releases), and release-tag.yml (tag validation + trigger). Renamed pr-build.yml → build-pr.yml and release.yml → release-publish.yml to use input-driven release flows. Removed deprecated workflows (auto-release.yml, build.yml) and deleted locale README files under docs (README_ar/ja/ko/ru/zh-CN/zh-TW). Changes include artifact matrix builds, caching and optimized Windows assembly steps, OpenAPI schema publishing to NapCatDocs, and explicit downstream workflow dispatching on release.
2026-03-13 19:22:00 +08:00
手瓜一十雪 d70e06a4f5 Update napi2native version keys to 46494 & fix #1699
Replace three entries in packages/napcat-core/external/napi2native.json that used the '-46949' suffix with '-46494' for versions 9.9.28-x64 and 3.2.26 (x64 and arm64). send/recv hashes are unchanged; this corrects the version/build identifiers in the mapping.
2026-03-13 18:12:50 +08:00
时瑾 e6f6468377 Revert "fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)" (#1701)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
This reverts commit deae7fd467.
2026-03-13 15:26:53 +08:00
MliKiowa 9d5f0ee604 Revise README with new feature details and groups
Updated README to include new features and community group information.

Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-03-12 23:19:40 +08:00
手瓜一十雪 07d4d80ab7 Add isLocal flag to uriToLocalFile and use it
Expose an isLocal boolean from uriToLocalFile to indicate user-owned files vs temporary downloads/decodes, and update callers to avoid deleting or cleaning up user local files. Update OneBot file APIs to accept the isLocal hint (including createValidSendFileElement/createValidSendPicElement/createValidSendVideoElement) and adjust temp-file handling for videos: local files are copied into the NapCat temp dir with a random UUID filename to avoid polluting user directories, while temporary files get an added extension in-place. Also adjust deleteAfterSentFiles usage, image/video thumb handling, and numeric parsing fallbacks for element fileSize to be more robust. Minor imports (randomUUID) and related callsites were updated accordingly.
2026-03-12 15:36:44 +08:00
手瓜一十雪 7a974d38d4 Use element.fileSize fields to calc totalSize
Remove filesystem stat calls and the node:fs/promises import; replace the async size calculation with a synchronous reduce that sums parseInt(fileSize) from each send element (falls back to 0 on parse failure). This avoids runtime I/O, simplifies the logic, and still provides a totalSize used to compute message timeout.
2026-03-12 15:07:44 +08:00
手瓜一十雪 e9b74138d1 Add configurable timeout calculation for transfers
Introduce timeout configuration and automatic timeout estimation for uploads/downloads. Added TimeoutConfig to OneBot config with baseTimeout, upload/downloadSpeedKBps and maxTimeout, plus calculateTimeout and capTimeout helpers. Applied estimation to FileApi.downloadFileById calls (GetFile, BaseDownloadStream) and to message sending (OneBotMsgApi) to compute timeouts from total payload size; sendMsg now accepts an optional timeout override which is capped by maxTimeout. Updated SendMsg payload schema to allow a custom timeout, and updated web UI store, types and config form to expose timeout settings and defaults.
2026-03-12 15:01:34 +08:00
手瓜一十雪 df0795f2c5 Update GitHub Actions to newer versions
Upgrade workflow action versions across .github/workflows: actions/checkout@v4 -> @v5, actions/setup-node@v4 -> @v6, actions/upload-artifact@v4 -> @v6, and actions/download-artifact@v4 -> @v7. Changes touch auto-release.yml, build.yml, pr-build.yml, and release.yml to keep CI tooling current and compatible with newer runner features; also add a missing newline at end of auto-release.yml.
2026-03-12 14:04:00 +08:00
手瓜一十雪 85b56e52ac fix: #1697
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-03-12 13:51:54 +08:00
时瑾 77c89d0923 lint: eslint
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-03-12 09:09:26 +08:00
时瑾 58b36cd331 fix: 优化Passkey在非安全场景下无法使用的提示 #1680 2026-03-12 09:08:47 +08:00
吴天一 deae7fd467 fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)
* fix: make defaulted request fields optional

* fix: align onebot schemas with runtime behavior

* fix: tighten schema and unsupported action metadata

* fix: reject empty forward reference ids

* fix: update GoCQHTTPSendForwardMsg to handle messages correctly and adjust payload schema

* fix: refactor message handling in GoCQHTTPSendForwardMsg and add test for message normalization

* fix: update compatibility actions to return appropriate responses and align schemas with runtime behavior

* fix: ensure payload properties are non-null with default values in action handlers

* fix: update StreamStatus comments for clarity and enforce nickname as required in message schema

* fix: integrate sleep function in GetOnlineClient and update tests to verify API call

* fix: add production test checklist for OneBot schema alignment and message handling

* fix: remove outdated production test checklist for OneBot schema alignment
2026-03-12 01:54:33 +08:00
吴天一 8b2207e109 fix: make album attach_info optional (#1690) 2026-03-09 20:01:43 +08:00
手瓜一十雪 f3b76e8b3a Add new version mappings in external JSON
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add send/recv offsets for several new builds to packages/napcat-core/external/napi2native.json and packages/napcat-core/external/packet.json. Entries added: 9.9.27-46949-x64 and 3.2.26-46949-(x64, arm64) in napi2native.json; 3.2.26-46494-(x64, arm64) and 9.9.28-46494-x64 in packet.json. These register offsets for newly encountered builds.
2026-03-08 19:39:27 +08:00
006lp 466d9a3c4f feat(appid): add support for QQ client versions 46494 (#1681)
Add appid and qua configurations for new QQ client versions:
- QQ 3.2.26-46494 (Linux)
- QQ 9.9.28-46494 (Windows)
- QQ 6.9.90-46494 (macOS)
2026-03-08 19:28:28 +08:00
MliKiowa 4af49c5761 chore: remove manifest.json from
Removed manifest.json from the copy targets in the Vite configuration.

Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-03-06 22:47:23 +08:00
手瓜一十雪 442ad4f9a3 feat: 正式中断插件注入启动模式 2026-03-06 22:33:27 +08:00
手瓜一十雪 7ee2f1c40d Fix imports and formatting in packages
Small cleanup across multiple packages: adjust TypeBox imports (add TSchema) and reorder imports in napcat-core/helper/config.ts; normalize indentation and type formatting in napcat-protobuf/NapProto.ts; add missing trailing commas and minor object formatting fixes in tests (packages/napcat-test/schema.test.ts); remove an extra blank line in external-shims.d.ts; and remove an unnecessary blank line in post-build.mjs. These are whitespace/formatting and minor import fixes to satisfy linting and type checks.
2026-03-06 10:54:31 +08:00
手瓜一十雪 7380665cc2 Notify log subscription only when logger exists
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Move logSubscription.notify into the branch that calls this.logger.log and remove the previous external call. This ensures the subscription is notified only when the configured logger is used, avoiding redundant or spurious notifications.
2026-03-06 10:48:03 +08:00
手瓜一十雪 2c57faf117 Disable file logs by default; lazy-init transport
Set file logging off by default and defer creation of the File transport until file logging is enabled. Store logPath and fileLogLevel (with fileTransportAdded flag) so the file transport can be added later with the correct filename and level. Remove the eager File transport from the constructor, update setFileAndConsoleLogLevel to persist fileLogLevel, and add the transport in setFileLogEnabled(true). Improve _log to only format messages when needed and notify subscribers once. Replace some direct logger.* calls with wrapper methods for consistent handling when deleting/reading old log files.
2026-03-06 10:47:09 +08:00
手瓜一十雪 8b0d186625 Remove napcat-onebot test_schema.ts
Delete packages/napcat-onebot/test_schema.ts — a standalone script that compiled and validated OB11 TypeBox schemas and performed a sample validation. This file appeared to be a local test/diagnostic harness and was removed as part of cleanup to avoid keeping ad-hoc test scripts in the package source.
2026-03-06 10:32:48 +08:00
手瓜一十雪 3ba1bd9565 Replace Value.Default/Convert with Value.Parse
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Use Value.Parse from @sinclair/typebox/value instead of the previous Value.Default + Value.Convert sequence across the codebase. Updated config loaders, OneBot action handling, tests and web UI helpers to rely on Value.Parse so schema defaults and coercion are applied consistently and errors surface in a single Parse call. Added two scratch files (scratch.ts, scratch2.ts) to inspect Parse error structure and boolean coercion behavior, and adjusted a test type annotation in test_schema.ts.
2026-03-06 10:23:01 +08:00
手瓜一十雪 8aec6aec1b Use RTT midpoint to adjust Date.now
Measure local time before and after fetching server time and compute offset using the midpoint (compensates for network latency). Round the calculated offset and lower the adjustment threshold from 5000ms to 500ms to avoid applying small corrections. Also rename timing variables for clarity.
2026-03-06 09:57:12 +08:00
手瓜一十雪 36ae7bf923 Replace AJV with TypeBox validation
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Migrate schema validation from AJV to @sinclair/typebox across the monorepo. Key changes:

- Core validation: ConfigBase now uses TypeCompiler/Value (TypeBox) for compile/defaults/coercion and replaces Ajv usage.
- OneBot & Protocol: loadConfig functions and related config loaders updated to use Value.Default/Convert and TypeCompiler.Compile with improved error reporting.
- OneBot action validation: OneBotAction now compiles TypeBox schemas, applies defaults/conversions and returns TypeBox errors.
- Web UI backend: use TypeBox Value/TypeCompiler to fetch and validate defaults for Napcat/Web UI configs.
- Types/scripts: removed AJV type shims and adjusted post-build script to stop special-casing AJV types.
- Dependencies: removed ajv from several package.json files and added/normalized @sinclair/typebox usage; updated pnpm-lock accordingly.
- Tests/tools: added schema validation test utilities and tests (packages/napcat-onebot/test_schema.ts and packages/napcat-test/schema.test.ts) to validate schema compilation, coercion, and defaults.

This change standardizes on TypeBox for runtime schema compilation, default population and type coercion, simplifying validation logic and improving default handling across packages.
2026-03-06 09:46:12 +08:00
手瓜一十雪 4ed4dfd450 Remove no-op voids and add explicit SW return
Remove a pointless `void options.callbackTimeout;` no-op in napcat-rpc client. In the service worker template, add `/* eslint-disable no-undef */` and an explicit `return undefined;` in the cache cleanup callback to make the return value explicit and satisfy linters. In the OneBot debug UI, call `sendRequest(value)` without the leading `void` so the returned promise is not intentionally ignored.
2026-03-05 18:57:30 +08:00
手瓜一十雪 b15d02535e refactor: minor lint and consistency fixes
Apply a collection of small code cleanups across the repo for consistency and lint-safety. Changes include:

- Use strict equality (===) where appropriate (GetEmojiLikes, about page checks).
- Replace Array.map used for side effects with Array.forEach (GetMsg).
- Rename unused catch parameters to underscore-prefixed names to avoid lint warnings (multiple backend/middleware files).
- Replace void with undefined in an actions.call invocation (builtin plugin index).
- Remove an unused loadedCount variable when reading .env (napcat-shell).
- Rename promise resolver parameter to `resolve` for clarity in tests and keep setTimeout usage (rpc.test.ts).
- Strengthen external shims types by changing generic parameter names to _T and update inversify ServiceIdentifier generic param (external-shims.d.ts).
- Simplify post-build script imports and comment out an external-type mapping block; fix a regex character class bug (post-build.mjs).
- Prefix several unused test stub variables with underscore to indicate intentional unused status (test-dist.ts).
- Minor JSX formatting/indentation fixes in password_login component and UI text indentation in system_info.
- Misc: SSE/config and plugin config handlers adjusted to consistent catch parameter naming; update mirror/download error catch variable name.

These edits are non-functional refactors focused on code style, lint compliance and small robustness/clarity improvements.
2026-03-05 18:53:58 +08:00
手瓜一十雪 974528fe7e Apply formatting and minor style fixes across repo
Normalize code style across multiple packages: whitespace cleanup, consistent commas and trailing commas in arrays/enums/objects, fix table markdown lines in CI comment template, ensure newline at EOF, normalize header/object property quoting and spacing, remove stray blank lines and minor non-functional comment tweaks. These are formatting-only changes and small type/annotation spacing adjustments; no functional behavior changes intended.
2026-03-05 18:45:50 +08:00
手瓜一十雪 d2d0b258bc Add per-UIN NapCat config and core UI
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Backend: add per-UIN config support (napcat_{uin}.json) with read/write helpers, handlers (GetUinConfig/SetUinConfig) and router entries; handlers check login status via WebUiDataRuntime and fall back to napcat.json when needed. Frontend: add QQManager methods to get/set per-UIN config, new CoreConfigCard React component for core settings (autoTimeSync, fileLog, consoleLog) and register it in the config page tabs. Types: expose autoTimeSync in NapCatConfig type. Config writes create config directory and merge updates with existing per-UIN config.
2026-03-05 16:35:51 +08:00
手瓜一十雪 2dcba633ba Add configurable automatic time sync
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add autoTimeSync (default: true) to the Napcat config and honor NAPCAT_DISABLE_TIME_SYNC=1 or autoTimeSync=false to disable automatic time synchronization. When enabled, time sync is attempted via getServerTime with errors logged; warning threshold for significant drift increased from 1s to 5s. Adds informational log when auto time sync is disabled.
2026-03-05 15:38:36 +08:00
手瓜一十雪 53ceb85801 Add server time sync hook and integration
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduce helper server-time.ts that preserves the original Date.now and provides hookGlobalDateNow(getServerTimeFn) to compute an offset from a server timestamp and override Date.now when the offset is significant. The function parses a server time string, returns the computed offset, and only patches Date.now if |offset| > 5000ms. Export the helper and call it in NapCatCore startup using session.getMSFService().getServerTime(), logging synchronization results (info for small offsets, warning for >1s) and catching errors. Improves global time consistency with server-provided time.
2026-03-05 15:27:40 +08:00
手瓜一十雪 dbba6b3ffe Add protocol fallback to fetch quoted messages
When existing lookup methods fail to find a referenced/reply message, try a protocol-level fallback using PacketApi. If PacketApi.packetStatus is available, attempt FetchGroupMessage or FetchC2CMessage by sequence, match by contentHead.sequence, and use contentHead.newId as the message id to build reply data. Log warnings on success/not-found and errors on exceptions.
2026-03-05 15:09:58 +08:00
手瓜一十雪 03dd89add0 Disable file logging in main process
Prevent the main process from writing logs to file when running in multi-process mode. base.ts and napcat.ts now disable file logging unless the process is a worker or multi-process mode is disabled (checks NAPCAT_WORKER_PROCESS / NAPCAT_DISABLE_MULTI_PROCESS and ENV.isWorkerProcess / ENV.isMultiProcessDisabled). This reduces duplicate log output and disk I/O by ensuring only worker processes write log files.
2026-03-05 14:56:33 +08:00
手瓜一十雪 7fc70bc5ce Use Type.Omit(..., []) in schema intersections & fix: #1674
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Replace direct schema references inside Type.Intersect with Type.Omit(schema, []) in two places (OB11MessageSchema and OB11MessageImageSchema). This avoids reusing the original schema metadata/$id when intersecting, preventing duplicate-id or type-merging issues with TypeBox/OpenAPI generation.
2026-03-05 14:36:48 +08:00
手瓜一十雪 6758825895 feat: 聊天记录对聊天记录合并转发修复 & fix #1673
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-03-05 13:40:16 +08:00
手瓜一十雪 ae53d27313 Integrate WebUI login flow and callbacks
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Start the WebUI earlier and integrate it with the login process. Initialize WebUI before user login so the UI can control and display login status; set working environment and start InitWebUi asynchronously. Add login listener handlers to update WebUiDataRuntime for QR updates, session failures, login errors, connection events and history. Introduce registerWebUiLoginCallbacks to expose refresh QR, quick login, password/captcha/new-device login flows to the WebUI and update loginContext and UI state accordingly. Also set QQ data path after successful login.
2026-03-05 13:04:57 +08:00
手瓜一十雪 86884b6ba2 Remove onlyBuiltDependencies from pnpm workspace
Remove the onlyBuiltDependencies section from pnpm-workspace.yaml to simplify the workspace configuration. The removed list included '@heroui/shared-utils', '@homebridge/node-pty-prebuilt-multiarch', '@swc/core', esbuild, sharp, ttf2woff2, and unrs-resolver; the file now only declares packages: - packages/*.
2026-03-05 09:22:10 +08:00
手瓜一十雪 776cc8cefd Use NAPCAT_BUILD secret for release
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Switch the release workflow to use the NAPCAT_BUILD secret instead of the default GITHUB_TOKEN. This allows the release job to run with a dedicated token (e.g., with different scopes or credentials) when creating tags, changelogs, and uploading release artifacts.
2026-03-05 09:16:46 +08:00
手瓜一十雪 66542eda26 fix: #1672 2026-03-05 09:15:21 +08:00
手瓜一十雪 34a699c568 Remove Windows one-click package section
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Delete the 'Windows 一键包' section from .github/prompt/default.md, removing the lightweight one-click deployment instructions, reference to NapCat.Shell.Windows.OneKey.zip, and related tutorial notes. Keeps the version header and warning section intact.
2026-03-04 22:22:58 +08:00
手瓜一十雪 2a06688479 Remove SHA512 debug log output
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Remove console.log statements that printed the computed SHA512 hashes for the shell and framework in .github/scripts/publish-release-hash.mjs. This reduces log noise and prevents potentially sensitive hash values from appearing in CI logs while retaining the hash computation logic.
2026-03-04 21:59:00 +08:00
手瓜一十雪 976331af94 Use NAPCAT_BUILD secret in release workflow
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Update .github/workflows/release.yml to set GH_TOKEN from secrets.NAPCAT_BUILD instead of secrets.GH_TOKEN when publishing the release hash. This switches the workflow to use the new/rotated secret name for release publishing.
2026-03-04 21:50:16 +08:00
手瓜一十雪 46b0532f84 Set up gh auth in release workflow
Invoke `gh auth setup-git` in the release GitHub Actions workflow before cloning the hash repo so git is configured to use the GitHub CLI authentication. This prevents authentication issues when running `gh repo clone` and subsequent git operations in CI.
2026-03-04 21:41:17 +08:00
手瓜一十雪 819f76afbf Use gh CLI to clone hash repo in workflow
In the release workflow, replace the token-based git clone URL with the GitHub CLI command. Removed the CLONE_URL variable and now run `gh repo clone NapNeko/napcat-release-hash hash-repo`, avoiding embedding GH_TOKEN in the clone URL and relying on gh authentication for a cleaner, more secure clone.
2026-03-04 21:38:32 +08:00
手瓜一十雪 938074c654 Support selecting account for join key
Add account selection to About page so users can generate the group-join password for different QQ accounts. about.tsx: fetch quick-login list (QQManager.getQQQuickLoginListNew), track selectedUin with useState/useEffect, build account list (including current login as fallback), compute password per selected account (SHA512(hash + uin).substring(0,7)), and render a Select control and updated Snippet/Tooltip UI; also add a binding notice. README and translated docs: add note that the join key is only valid for the latest 100 versions and prompt users to update if it fails.
2026-03-04 21:28:38 +08:00
手瓜一十雪 d16f493136 Publish GitHub release instead of draft
Update the release workflow to publish releases immediately by setting the softprops/action-gh-release step's draft flag to false. Also adjust the step name to "Create Release and Upload Artifacts" to reflect the change so CI will create a published release and upload artifacts instead of leaving a draft.
2026-03-04 21:00:13 +08:00
手瓜一十雪 4c8419d5ab Add release hash script and NapCat file-hash UI
Add a new .github/scripts/publish-release-hash.mjs to compute SHA512 for Shell/Framework napcat.mjs, maintain a release.json (keep last 100 entries) and write it to a separate hash repo. Wire the script into .github/workflows/release.yml to clone NapNeko/napcat-release-hash and publish hashes on release. Backend: expose GET /base/GetNapCatFileHash to compute napcat.mjs SHA512. Frontend: add WebUIManager.GetNapCatFileHash and show a join-password snippet on About page by combining file hash and user UIN (hashed with CryptoJS); update About page links to QQ groups. Update README and localized docs to list community QQ groups. Error handling and basic logging added.
2026-03-04 20:57:53 +08:00
手瓜一十雪 fbba3d5ade fix #1670 2026-03-04 19:27:05 +08:00
水化 cf80c787c3 fix: callbacks cleanup and credential timestamp validation (#1669)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
* fix(rpc): clean callbacks when sending failed

* chore: format

* fix(pty): handle ws message properly

* fix(webui-backend): unify credential timestamp validation

Store credential CreatedTime in seconds and validate expiry using the same unit. Keep backward compatibility for legacy millisecond timestamps.

* chore: format

* Revert "chore: format"

This reverts commit 6f2e9f1b53b55e8f4bf4a747ed7b05a0d6e4dbb4.

* fix: naming

Rename ONE_HOUR_SECONDS to MAX_CREDENTIAL_VALID_SECONDS for clearer intent. Simplify CreatedTime parsing by using Math.floor(Number(...)) and remove the legacy millisecond-to-second conversion branch. Update the time-difference check to use the new constant name.
2026-03-04 19:03:21 +08:00
手瓜一十雪 7b58681b2b feat: 修复database disk image is malforme
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-03-04 15:33:55 +08:00
手瓜一十雪 7c2eacf0dc Switch release workflow to OpenAI endpoint
Update .github/workflows/release.yml to use the OpenRouter/OpenAI public endpoint and standardized env names. Replaced custom API URL and model with OPENAI_API_URL=https://openrouter.ai/api/v1/chat/completions and OPENAI_MODEL="stepfun/step-3.5-flash:free", renamed variables (OPENROUTER_* → OPENAI_*), adjusted the job step name and log messages, and updated the curl request and response handling to use the new env vars. Kept existing behavior for generating release notes and the fallback to the default template when the LLM output is empty.
2026-03-04 12:01:11 +08:00
手瓜一十雪 e09c3c1146 Upgrade release action to v2 and set tag_name
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Update .github/workflows/release.yml to use softprops/action-gh-release@v2 and add the tag_name input mapped to github.ref_name so the created draft release uses the current ref as the release tag. Other release settings (name, token, body_path) are preserved.
2026-03-04 11:50:26 +08:00
手瓜一十雪 cec011bdfa Include node:sqlite and bump napcat-types version
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add 'node:sqlite' to nodeModules in packages/napcat-schema/vite.config.ts so sqlite imports (node:sqlite) are recognized as builtins/externals. Also bump napcat-types package version from 0.0.16 to 0.0.17 in packages/napcat-types/package.public.json.
2026-03-04 11:26:54 +08:00
手瓜一十雪 9cbaafe806 Comment out DatabaseApi test code
Commented out temporary DatabaseApi test blocks in packages/napcat-framework/napcat.ts and packages/napcat-shell/base.ts. These changes disable the runtime test/read of nt_msg.db (previously guarded by dbPassphrase checks) while keeping the code as commented reference to avoid noisy logs or unintended DB access during initialization.
2026-03-04 11:08:40 +08:00
手瓜一十雪 0ddf21a2f5 Add DatabaseHandle and DB utilities, integrate API
Introduce a DatabaseHandle wrapper and helper functions for opening and decrypting NTQQ SQLite DBs (openDatabase, decryptAndOpen) in napcat-database; expose them from the package index. Add typed query/execute helpers and SQLInputValue typing. Extend NTQQDatabaseApi in napcat-core to provide high-level methods (openDecryptedDb, openDatabase, query, queryOne, execute) and export DatabaseHandle. Replace disabled inline test blocks with runtime DatabaseApi usage in napcat-framework and napcat-shell to test/read nt_msg.db via the new API. Misc: small cleanup of imports and comments.
2026-03-04 11:02:21 +08:00
手瓜一十雪 b9dcedacf5 Add napcat-database and DatabaseApi support
Introduce a new napcat-database package that implements SQLCipher/NTQQ DB handling (constants, key derivation, page decryption, file-level decrypt, and a reader that can list tables using node:sqlite). Add NTQQDatabaseApi to napcat-core (APIs export, NapCatCore field & container) to expose high-level helpers (isSqliteAvailable, readDatabase, scanDatabases, decryptDatabase, formatResults). Add protobuf definitions for OidbSvcTrpcTcp.0xcde_2 and hook packet handlers in framework and shell to capture the DB passphrase and set core.dbPassphrase. Update package.json files and vite configs to include napcat-database/napcat-protobuf and allow node:sqlite, and update pnpm-lock accordingly.
2026-03-04 10:56:18 +08:00
bietiaop b42b6c3cf0 docs(README): update multi-language README.md 2026-02-28 12:32:48 +08:00
手瓜一十雪 740d2118f1 Comment out plugin import UI and handlers
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Temporarily disable the local plugin import flow: remove the unused useRef import, comment out the FiUpload import, fileInputRef declaration, and the related handlers (handleImportClick and handleFileChange). Keeps the rest of the plugin page (loading, modal and plugin list logic) intact so the import feature can be re-enabled later.
2026-02-22 13:34:03 +08:00
手瓜一十雪 77bdcfd249 Disable local plugin import and upload handling
Commented out ImportLocalPluginHandler import and the multer upload configuration (50MB limit and .zip file filter). Temporarily disables local plugin .zip uploads, likely for debugging or while refactoring the upload/import flow; can be re-enabled when upload handling is restored.
2026-02-22 13:33:06 +08:00
手瓜一十雪 896e1c209a Disable plugin upload feature
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Comment out the backend import route and corresponding frontend upload UI to disable plugin uploads. Backend: commented out POST /Import route in packages/napcat-webui-backend/src/router/Plugin.ts. Frontend: removed (commented) the upload Button and hidden file input in packages/napcat-webui-frontend/src/pages/dashboard/plugin.tsx. This temporarily prevents users from uploading plugins.
2026-02-22 13:15:42 +08:00
手瓜一十雪 cff07c7ce5 Revise README for new maintainer notice
Updated the README to replace the 'New Feature' section with a 'Notice' about seeking new maintainers and removed outdated information.

Signed-off-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-02-21 19:22:07 +08:00
手瓜一十雪 5c04b799a6 feat: 提高超时检测等待
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-02-21 16:21:31 +08:00
ud2 1fc4655ae1 refactor(onebot): 精简 WebSocket 适配器实现 (#1644)
* refactor(onebot): 移除 `async-mutex` 依赖

* fix(onebot): 避免重复发送 WebSocket pong
2026-02-21 15:59:12 +08:00
Eric-Terminaland手瓜一十雪 eb07cdb715 feat: 自动登录失败后回退密码登录并补充独立配置 (#1638)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
* feat: 自动登录失败后回退密码登录并补充独立配置

改动文件:
- packages/napcat-webui-backend/src/helper/config.ts
- packages/napcat-webui-backend/src/utils/auto_login.ts
- packages/napcat-webui-backend/src/utils/auto_login_config.ts
- packages/napcat-webui-backend/index.ts
- packages/napcat-webui-backend/src/api/QQLogin.ts
- packages/napcat-webui-backend/src/router/QQLogin.ts
- packages/napcat-webui-frontend/src/controllers/qq_manager.ts
- packages/napcat-webui-frontend/src/pages/dashboard/config/login.tsx
- packages/napcat-test/autoPasswordFallback.test.ts

目的:
- 在启动阶段将自动登录流程从“仅快速登录”扩展为“快速登录失败后自动回退密码登录”,并保持二维码兜底。
- 在 WebUI 登录配置页新增独立的自动回退账号/密码配置,密码仅提交与存储 MD5,不回显明文。

效果:
- 后端配置新增 autoPasswordLoginAccount 与 autoPasswordLoginPasswordMd5 字段,并提供读取、更新(空密码不覆盖)和清空能力。
- 新增 QQLogin API:GetAutoPasswordLoginConfig / SetAutoPasswordLoginConfig / ClearAutoPasswordLoginConfig。
- WebUI 登录配置页新增自动回退密码登录区块,支持保存、刷新、清空及“留空不修改密码”交互。
- 新增自动登录回退逻辑单测与配置补丁构造单测,覆盖快速成功、回退成功、回退失败、无密码兜底等场景。

* feat: 精简为环境变量驱动的快速登录失败密码回退

改动目的:
- 按维护者建议将方案收敛为后端环境变量驱动,不新增 WebUI 配置与路由
- 保留“快速登录失败 -> 密码回退 -> 二维码兜底”核心能力
- 兼容快速启动参数场景,降低评审复杂度

主要改动文件:
- packages/napcat-webui-backend/index.ts
- packages/napcat-shell/base.ts
- packages/napcat-webui-backend/src/api/QQLogin.ts
- packages/napcat-webui-backend/src/helper/config.ts
- packages/napcat-webui-backend/src/router/QQLogin.ts
- packages/napcat-webui-frontend/src/controllers/qq_manager.ts
- packages/napcat-webui-frontend/src/pages/dashboard/config/login.tsx
- 删除:packages/napcat-webui-backend/src/utils/auto_login.ts
- 删除:packages/napcat-webui-backend/src/utils/auto_login_config.ts
- 删除:packages/napcat-test/autoPasswordFallback.test.ts

实现细节:
1. WebUI 启动自动登录链路
- 保留 NAPCAT_QUICK_ACCOUNT 优先逻辑
- 快速登录失败后触发密码回退
- 回退密码来源优先级:
  a) NAPCAT_QUICK_PASSWORD_MD5(32 位 MD5)
  b) NAPCAT_QUICK_PASSWORD(运行时自动计算 MD5)
- 未配置回退密码时保持二维码兜底,并输出带 QQ 号的引导日志

2. Shell 快速登录链路
- quickLoginWithUin 失败判定统一基于 result 码 + errMsg
- 覆盖历史账号不存在、凭证失效、快速登录异常等场景
- 失败后统一进入同一密码回退逻辑,再兜底二维码

3. 文案与可运维性
- 日志明确推荐优先使用 ACCOUNT + NAPCAT_QUICK_PASSWORD
- NAPCAT_QUICK_PASSWORD_MD5 作为备用方式

效果:
- 满足自动回退登录需求,且改动面显著缩小
- 不修改 napcat-docker 仓库代码,直接兼容现有容器启动参数
- 便于上游快速审阅与合并

* fix: 修复 napcat-framework 未使用变量导致的 CI typecheck 失败

改动文件:
- packages/napcat-framework/napcat.ts

问题背景:
- 上游代码中声明了变量 bypassEnabled,但后续未使用
- 在 CI 的全量 TypeScript 检查中触发 TS6133(声明但未读取)
- 导致 PR Build 机器人评论显示构建失败(Type check failed)

具体修复:
- 将以下语句从“赋值后未使用”改为“直接调用”
- 原:const bypassEnabled = napi2nativeLoader.nativeExports.enableAllBypasses?.(bypassOptions);
- 现:napi2nativeLoader.nativeExports.enableAllBypasses?.(bypassOptions);

影响与效果:
- 不改变运行时行为(仍会执行 enableAllBypasses)
- 消除 TS6133 报错,恢复 typecheck 可通过

本地验证:
- pnpm run typecheck:通过
- pnpm run build:framework:通过
- pnpm run build:shell:通过

---------

Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-02-21 14:18:34 +08:00
手瓜一十雪 964fd98914 Add spinner during captcha verification
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Show a loading spinner and message while captcha is being verified. Imported Spinner and added an optional captchaVerifying prop to PasswordLogin to toggle between the TencentCaptchaModal and a waiting state. In qq_login.tsx introduced captchaVerifying state, set it true before the captcha login request and reset it in finally, and passed the prop down to the PasswordLogin component.
2026-02-21 13:39:35 +08:00
手瓜一十雪 f9764c9559 Improve new-device QR handling and bypass init
Refactor new-device QR flow and streamline bypass init:

- napcat-shell: stop verbose logging and removed check of enableAllBypasses return value; just invoke native enableAllBypasses when not disabled by env.
- backend (QQLogin): simplify extraction of tokens from jumpUrl (use sig and uin-token), return an error if missing, and send oidbRequest directly (removed nested try/catch and regex fallback).
- frontend (new_device_verify): accept result.str_url without requiring bytes_token and pass an empty string to polling when bytes_token is absent.
- frontend (password_login): change render order to show captcha modal before new-device verification UI.
- frontend (qq_manager): normalize GetNewDeviceQRCode response — derive bytes_token from str_url's str_url query param (base64) when bytes_token is missing, and preserve extra status/error fields in the returned object.

These changes improve robustness when OIDB responses omit bytes_token, reduce noisy logs, and ensure the UI and polling still function.
2026-02-21 13:24:56 +08:00
手瓜一十雪 b71a4913eb Add captcha & new-device QQ login flows
Introduce multi-step QQ password login support (captcha and new-device verification) and related OIDB QR handling.

- Change login signature fields in NodeIKernelLoginService to binary (Uint8Array) and add unusualDeviceCheckSig.
- Update shell base to handle additional result codes (captcha required, new-device, abnormal-device), set login status on success, and register three callbacks: captcha, new-device, and password flows. Use TextEncoder for encoding ticket/randstr/sid and newDevicePullQrCodeSig.
- Extend backend WebUiDataRuntime (types and runtime) with set/request methods for captcha and new-device login calls and adjust LoginRuntime types to return richer metadata (needCaptcha, proofWaterUrl, needNewDevice, jumpUrl, newDevicePullQrCodeSig).
- Add backend API handlers: CaptchaLogin, NewDeviceLogin, GetNewDeviceQRCode and PollNewDeviceQR; add oidbRequest helper using https to query oidb.tim.qq.com for QR generation and polling.
- Wire new handlers into QQLogin router and return structured success responses when further steps are required.
- Add frontend components and pages for captcha and new-device verification (new files: 1.html, new_device_verify.tsx, tencent_captcha.tsx) and update existing frontend controllers/pages to integrate the new flows.
- Improve error logging and user-facing messages for the new flows.

This change enables handling of password-login scenarios requiring captcha or device attestation and provides endpoints to obtain and poll OIDB QR codes for new-device verification.
2026-02-21 13:03:40 +08:00
手瓜一十雪 f961830836 Inline plugin icon helper into PluginCard
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Move getPluginIconUrl from utils/plugin_icon.ts into plugin_card.tsx and remove the now-unused util file. The function behavior is unchanged: it reads webui_token from localStorage and appends it as a query parameter to plugin icon URLs so authenticated icon endpoints can be used as img src.
2026-02-20 23:36:45 +08:00
手瓜一十雪 dd8b5f84a6 Simplify plugin avatar logic
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Remove getAuthorAvatar and related homepage/repository parsing. Rely on getPluginIconUrl(icon) (backend-provided URL with token) and fall back to Vercel avatar. Update prop destructuring to drop homepage/repository and streamline avatar selection, removing fragile favicon/GitHub parsing logic.
2026-02-20 23:35:49 +08:00
手瓜一十雪 48ffd5597a Add plugin icon support and caching
Introduce support for plugin icons across backend and frontend. Updates include:

- napcat-onebot: add optional `icon` field to PluginPackageJson.
- Backend (api/Plugin, PluginStore, router): add handlers/utilities to locate and serve plugin icons (`GetPluginIconHandler`, getPluginIconUrl, findPluginIconPath) and wire the route `/api/Plugin/Icon/:pluginId`.
- Cache logic: implement `cachePluginIcon` to fetch GitHub user avatars and store as `data/icon.png` when package.json lacks an icon; invoked after plugin install (regular and SSE flows).
- Frontend: add `icon` to PluginItem, prefer backend-provided icon URL in plugin card (via new getPluginIconUrl util that appends webui_token query param), and add the util to handle token-based image requests.
- Plugin store UI: add a Random category (shuffled), client-side pagination, and reset page on tab/search changes.

These changes let the UI display plugin icons (falling back to author/avatar or Vercel avatars) and cache icons for better UX, while handling auth by passing the token as a query parameter for img src requests.
2026-02-20 23:32:57 +08:00
手瓜一十雪 1b73d68cbf Refactor extension tabs layout and styles
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Remove the overflow wrapper around extension tabs and move max-w/full styling to the Tabs component. Simplify classNames (tabList, cursor) and clean up shrinking/truncation classes on tab items and plugin name to improve responsiveness and layout, while preserving the openInNewWindow click behavior.
2026-02-20 23:05:20 +08:00
手瓜一十雪 5fec649425 Load napcat.json, use o3HookMode & bypass
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add loadNapcatConfig helper that reads napcat.json (json5), validates with Ajv and fills defaults for early pre-login use. Change NativePacketHandler.init signature to accept an o3HookMode flag and forward it to native initHook. Update framework and shell to use loadNapcatConfig (remove duplicated file-reading logic) and pass configured o3HookMode and bypass options into Napi2NativeLoader/native packet initialization. Clean up imports (Ajv, path, fs, json5) and remove the old loadBypassConfig helper.
2026-02-20 21:49:19 +08:00
手瓜一十雪 052e7fa2b3 Init nativePacketHandler after loading wrapper && fix #1633
Delay initialization of nativePacketHandler until after loadQQWrapper so that wrapper.node is loaded before initializing hooks. Moved the await nativePacketHandler.init(...) call below loadQQWrapper and added an explanatory comment to ensure native hooks are set up only after the native module is available.
2026-02-20 21:39:50 +08:00
叫我饼干ちゃん 04e425d17a update:汉化 (#1641) 2026-02-20 20:31:36 +08:00
Rinne cbe0506577 fix(webui): properly center plus icon in add button row (#1642)
Add `flex items-center justify-center` to the plus icon wrapper in `AddButton` so the icon is vertically and horizontally centered. This improves visual alignment and keeps the “新建网络配置” button content consistent.
2026-02-20 20:31:22 +08:00
手瓜一十雪 32ec097f51 Update native binaries for napi2native
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Rebuild native artifacts: updated ffmpeg.dll and napi2native Node addons for linux (arm64, x64) and win32 x64. These are binary-only updates (no source changes), likely to refresh builds for compatibility or toolchain/dependency updates.
2026-02-20 19:56:24 +08:00
手瓜一十雪 53f27ea9e2 Refactor Bypass layout and UI text
Wrap Bypass SwitchCard controls in a responsive grid for better layout and spacing. Rename the Config tab title from 'Bypass配置' to '反检测'. Clean up WebUI button/label text by removing emoji prefixes (removed 📥, 🔐, ✅) for a cleaner UI. Files changed: bypass.tsx (layout), index.tsx (tab title), webui.tsx (text cleanup).
2026-02-20 17:11:58 +08:00
手瓜一十雪 41d94cd5e2 Refactor bypass defaults and crash handling
Set bypass defaults to disabled and simplify loading: napcat.json default bypass flags changed to false and code now reads bypass options without merging a prior "all enabled" default. Removed the progressive bypass-disable logic and related environment variable usage, and added a log when Napi2NativeLoader enables bypasses. Web UI/backend adjustments: default NapCat config is now generated from the AJV schema; the bypass settings UI defaults to false, adds an o3HookMode toggle, and submits o3HookMode as 0/1. UX fixes: extension tabs made horizontally scrollable with fixed tab sizing, and plugin uninstall flow updated to a single confirmation dialog with an optional checkbox to remove plugin config. Overall changes aim to use safer defaults, simplify crash/restart behavior, and improve configuration and UI clarity.
2026-02-20 16:36:16 +08:00
手瓜一十雪 285d352bc8 Downgrade json5 in napcat-framework
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Update packages/napcat-framework/package.json to use json5@^2.2.3 (was ^3.2.2). This change pins json5 to the v2 line, likely for compatibility with other workspace packages or tooling that require the older major version.
2026-02-18 22:21:55 +08:00
手瓜一十雪 a3b3836b8a Add process bypass option and update bypass fields
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduce a new 'process' bypass option and remove the old 'maps' key, updating all related schemas, types, defaults and validation. Adjusted napcat.json ordering and NapcatConfig defaults, updated BypassOptions schema and TypeScript interfaces, backend validation keys, loader/default parsing logic, and the web UI form mappings/labels to reflect the new field set and ordering.
2026-02-18 22:14:31 +08:00
手瓜一十雪 b9f61cc0ee Add configurable bypass options and UI
Introduce granular "bypass" configuration to control Napi2Native bypass features and expose it in the WebUI.

Key changes:
- Add bypass defaults to packages/napcat-core/external/napcat.json and BypassOptionsSchema in napcat-core helper config.
- Extend Napi2NativeLoader types: enableAllBypasses now accepts BypassOptions.
- Framework & Shell: load napcat.json (via json5), pass parsed bypass options to native loader, and log the applied config. Add json5 dependency.
- Shell: implement loadBypassConfig with a crash-recovery override (NAPCAT_BYPASS_DISABLE_LEVEL) and add master<->worker IPC (login-success) plus progressive bypass-disable strategy to mitigate repeated crashes before login.
- WebUI backend: add GET/Set endpoints for NapCat config (NapCatConfigRouter) with validation and JSON5-aware defaults.
- WebUI frontend: add BypassConfig page, types, and controller methods to get/set bypass config.
- Update package.json to include json5 and update pnpm lockfile; native binaries (.node / ffmpeg.dll) also updated.

This enables operators to tune bypass behavior per-installation and to have an in-UI control for toggling anti-detection features; it also adds progressive fallback behavior to help recover from crashes caused by bypasses.
2026-02-18 22:09:27 +08:00
手瓜一十雪 9998207346 Move plugin data to config path; improve uninstall UI
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Change plugin data storage to use core.context.pathWrapper.configPath/plugins/<id> instead of pluginPath/data across OB11 plugin managers. Ensure plugin config directory is created when building the plugin context, use the central path for cleanup/uninstall, and update getPluginDataPath accordingly. Update web UI uninstall flow to prompt for cleaning configuration files using dialog.confirm (showing the config path) and performUninstall helper instead of window.confirm. Also include rebuilt native binaries (napi2native) for Linux x64 and arm64.
2026-02-18 16:49:43 +08:00
手瓜一十雪 4f47af233f Update napi2native Linux native binaries
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Replace prebuilt napi2native native modules for Linux (arm64 and x64) with updated binaries. These updated artifacts ensure the native addon is rebuilt and compatible with current Node/N-API/ABI or dependency changes, restoring compatibility and performance on Linux platforms.
2026-02-16 15:39:44 +08:00
手瓜一十雪 6aadc2402d Enable o3HookMode and update Win32 native binary
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Set o3HookMode to 1 in packages/napcat-core/external/napcat.json to enable O3 hook mode. Replace the prebuilt napi2native.win32.x64.node binary in packages/napcat-native/napi2native to include corresponding native changes for Win32 x64.
2026-02-16 14:58:06 +08:00
手瓜一十雪 eb937b29e4 Enable native verbose logging via env var
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Read NAPCAT_ENABLE_VERBOSE_LOG at startup and call napi2nativeLoader.nativeExports.setVerbose(true) (if available) right after loading the wrapper so native verbose logging can be enabled via environment. Also includes an updated native .node binary.
2026-02-13 19:33:48 +08:00
手瓜一十雪 f44aca9a2f Update napi2native Windows x64 binary
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Replace the compiled napi2native.win32.x64.node binary for the Windows x64 build. This updates the native addon artifact (likely rebuilt due to code or build environment changes) so consumers get the latest native implementation.
2026-02-13 19:06:12 +08:00
手瓜一十雪 c34812bc9c Update napi2native Windows x64 binary
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Replace the compiled napi2native.win32.x64.node binary in packages/napcat-native/napi2native. This updates the Windows x64 native addon (rebuild/bugfix or dependency-linked binary update); no JS/source changes are included in this diff.
2026-02-13 19:01:37 +08:00
手瓜一十雪 d93b430034 Revert "Enable native verbose logging"
This reverts commit cad567dc3f.
2026-02-13 18:12:11 +08:00
手瓜一十雪 c91e1378cf Increase OpenRouter max_tokens to 5000
Update .github/workflows/release.yml to raise the OpenRouter request max_tokens from 1500 to 5000. This allows the model to generate longer responses during the release workflow; be aware this may increase token usage and cost.
2026-02-13 18:01:36 +08:00
436 changed files with 15344 additions and 4560 deletions

No files matched your search

+8 -16
View File
@@ -1,26 +1,18 @@
# {VERSION}
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
NapCat.Shell.Windows.OneKey.zip (无头)
启动后可自动化部署一键包,教程参考使用文档安装部分
## 警告
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
+10 -8
View File
@@ -24,7 +24,7 @@
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
```
# {VERSION}
@@ -44,12 +44,14 @@ NapCat.Shell.Windows.OneKey.zip (无头)
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
@@ -76,7 +78,7 @@ NapCat.Shell.Windows.OneKey.zip (无头)
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
- QQ 版本号和下载链接保持不变(40990 版本)
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
## 重要约束
+192 -6
View File
@@ -3,6 +3,16 @@
*/
export const COMMENT_MARKER = '<!-- napcat-pr-build -->';
export const DOCKER_COMMENT_MARKER = '<!-- napcat-pr-docker -->';
// 默认代理前缀(加速中国大陆访问 GitHub Release)
// 格式:https://ghfast.top/{full-github-url}
export const PROXY_BASE = 'https://gh.llkk.cc';
/** 将 GitHub 直链转换为 ghfast.top 加速链接 */
export function toProxyUrl (directUrl: string): string {
return `${PROXY_BASE}/${directUrl}`;
}
export type BuildStatus = 'success' | 'failure' | 'cancelled' | 'pending' | 'unknown';
@@ -84,8 +94,8 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
'',
'## 📋 构建信息',
'',
`| 项目 | 值 |`,
`| :--- | :--- |`,
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🕐 开始时间 | ${time} |`,
'',
@@ -105,12 +115,19 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
// ============== 构建结果评论 ==============
export interface InstallInfo {
installUrl: string;
releaseUrl: string;
}
export function generateResultComment (
targets: BuildTarget[],
prSha: string,
runId: string,
repository: string,
version?: string
version?: string,
installInfo?: InstallInfo,
publishFailed?: boolean
): string {
const runUrl = `https://github.com/${repository}/actions/runs/${runId}`;
const shortSha = formatSha(prSha);
@@ -165,21 +182,56 @@ export function generateResultComment (
'',
'## 📋 构建信息',
'',
`| 项目 | 值 |`,
`| :--- | :--- |`,
'| 项目 | 值 |',
'| :--- | :--- |',
...(version ? [`| 🏷️ 版本号 | \`${version}\` |`] : []),
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 构建日志 | [查看详情](${runUrl}) |`,
`| 🕐 完成时间 | ${time} |`,
];
// 添加快速安装命令
if (installInfo) {
const directUrl = installInfo.installUrl;
const proxyInstallUrl = toProxyUrl(directUrl);
lines.push(
'',
'---',
'',
'## 🚀 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
`> 📦 [查看 Release 页面](${installInfo.releaseUrl})`,
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。'
);
} else if (publishFailed) {
lines.push(
'',
'---',
'',
'## ⚠️ Release 发布失败',
'',
'> ❌ PR Release 发布过程中出现错误,无法提供快速安装命令。',
`> 🔗 [查看构建日志](${runUrl}) 了解详情。`
);
}
// 添加错误详情
const failedTargets = targets.filter(t => t.status === 'failure' && t.error);
if (failedTargets.length > 0) {
lines.push('', '---', '', '## ⚠️ 错误详情', '');
for (const target of failedTargets) {
lines.push(
`<details>`,
'<details>',
`<summary>🔴 <b>${target.name}</b> 构建错误</summary>`,
'',
'```',
@@ -229,3 +281,137 @@ export function generateResultComment (
return lines.join('\n');
}
// ============== Docker 构建评论 ==============
export function generateDockerBuildingComment (prNumber: string, prSha: string): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
'# 🐳 Docker 测试镜像构建中',
'',
'![Building](https://img.shields.io/badge/Docker-构建中-yellow?style=for-the-badge&logo=docker&logoColor=white)',
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 触发时间 | ${time} |`,
'',
'---',
'',
'<div align="center">',
'',
'> ⏳ **Docker 镜像正在构建中,请稍候...**',
'>',
'> 构建完成后将自动更新此评论',
'',
'</div>',
];
return lines.join('\n');
}
export function generateDockerResultComment (
prNumber: string,
prSha: string,
success: boolean,
dockerImage?: string,
error?: string
): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const statusBadge = success
? '![Success](https://img.shields.io/badge/Docker-构建成功-success?style=for-the-badge&logo=docker&logoColor=white)'
: '![Failed](https://img.shields.io/badge/Docker-构建失败-critical?style=for-the-badge&logo=docker&logoColor=white)';
const headerTitle = success ? '# ✅ Docker 测试镜像就绪' : '# ❌ Docker 测试镜像构建失败';
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
headerTitle,
'',
statusBadge,
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 完成时间 | ${time} |`,
];
if (success && dockerImage) {
lines.push(
'',
'---',
'',
'## 🚀 快速使用',
'',
'```bash',
`docker pull ${dockerImage}`,
'```',
'',
'> ⚠️ 此为 PR 测试镜像,保留 5 天后自动清理。'
);
}
if (!success && error) {
lines.push(
'',
'---',
'',
'<details>',
'<summary>🔴 <b>错误详情</b></summary>',
'',
'```',
escapeCodeBlock(error),
'```',
'',
'</details>'
);
}
lines.push('', '---', '');
if (success) {
lines.push(
'<div align="center">',
'',
'> 🎉 **Docker 测试镜像已就绪!**',
'>',
'> 使用上方命令拉取镜像进行测试',
'',
'</div>'
);
} else {
lines.push(
'<div align="center">',
'',
'> ⚠️ **Docker 镜像构建失败**',
'>',
'> 请检查错误详情',
'',
'</div>'
);
}
return lines.join('\n');
}
+135 -3
View File
@@ -31,6 +31,21 @@ export interface Artifact {
archive_download_url: string;
}
export interface Release {
id: number;
tag_name: string;
name: string;
upload_url: string;
html_url: string;
created_at: string;
}
export interface ReleaseAsset {
id: number;
name: string;
browser_download_url: string;
}
// ============== GitHub API Client ==========================
export class GitHubAPI {
@@ -56,6 +71,11 @@ export class GitHubAPI {
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
// 204 No Content(DELETE 等)不解析 body
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
@@ -150,6 +170,119 @@ export class GitHubAPI {
console.log('✓ Created new comment');
}
}
// ============== Release API ==============
async getReleaseByTag (owner: string, repo: string, tag: string): Promise<Release | null> {
try {
return await this.request<Release>(`/repos/${owner}/${repo}/releases/tags/${tag}`);
} catch {
return null;
}
}
async deleteRelease (owner: string, repo: string, releaseId: number): Promise<void> {
await this.request(`/repos/${owner}/${repo}/releases/${releaseId}`, { method: 'DELETE' });
}
async deleteRef (owner: string, repo: string, ref: string): Promise<void> {
try {
await this.request(`/repos/${owner}/${repo}/git/refs/${ref}`, { method: 'DELETE' });
} catch {
// ref may not exist, ignore
}
}
async createRelease (
owner: string,
repo: string,
tag: string,
name: string,
body: string,
prerelease = true
): Promise<Release> {
return this.request<Release>(`/repos/${owner}/${repo}/releases`, {
method: 'POST',
body: JSON.stringify({ tag_name: tag, name, body, prerelease }),
headers: { 'Content-Type': 'application/json' },
});
}
async uploadReleaseAsset (
uploadUrl: string,
fileName: string,
data: Buffer,
contentType = 'application/octet-stream'
): Promise<ReleaseAsset> {
const url = uploadUrl.replace(/\{[^}]*\}/g, '') + `?name=${encodeURIComponent(fileName)}`;
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'Content-Type': contentType,
'X-GitHub-Api-Version': '2022-11-28',
},
body: data,
});
if (!response.ok) {
throw new Error(`Upload ${fileName} failed: ${response.status} ${response.statusText}`);
}
return response.json() as Promise<ReleaseAsset>;
}
// ============== Dispatch API ==============
async repositoryDispatch (
owner: string,
repo: string,
eventType: string,
clientPayload: Record<string, string>
): Promise<void> {
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/dispatches`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/json',
},
body: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
});
if (!response.ok && response.status !== 204) {
throw new Error(`Dispatch failed: ${response.status} ${response.statusText}`);
}
}
async createWorkflowDispatch (
owner: string,
repo: string,
workflowFile: string,
ref: string,
inputs: Record<string, string>
): Promise<void> {
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/actions/workflows/${workflowFile}/dispatches`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/json',
},
body: JSON.stringify({ ref, inputs }),
});
if (!response.ok && response.status !== 204) {
throw new Error(`Workflow dispatch failed: ${response.status} ${response.statusText}`);
}
}
// ============== Release Cleanup API ==============
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
return this.request<Release[]>(
`/repos/${owner}/${repo}/releases?per_page=${perPage}&page=${page}`
);
}
}
// ============== Output 工具 ==============
@@ -172,8 +305,7 @@ export function setMultilineOutput (name: string, value: string): void {
// ============== 环境变量工具 ==============
export function getEnv (name: string, required: true): string;
export function getEnv (name: string, required?: false): string | undefined;
// Note: 不使用函数重载——Node.js --experimental-strip-types 不支持 TS overload signatures
export function getEnv (name: string, required = false): string | undefined {
const value = process.env[name];
if (required && !value) {
@@ -183,7 +315,7 @@ export function getEnv (name: string, required = false): string | undefined {
}
export function getRepository (): { owner: string, repo: string; } {
const repository = getEnv('GITHUB_REPOSITORY', true);
const repository = getEnv('GITHUB_REPOSITORY', true)!;
const [owner, repo] = repository.split('/');
return { owner, repo };
}
+50
View File
@@ -0,0 +1,50 @@
/**
* PR Build - Dispatch untrusted build workflow
*
* 环境变量:
* - GITHUB_TOKEN: GitHub API Token
* - PR_NUMBER: PR 编号
* - PR_SHA: PR HEAD SHA
* - PR_HEAD_REPO: PR 源仓库
* - PR_HEAD_REF: PR 源分支
* - WORKFLOW_FILE: 工作流文件名,默认 build-pr.yml
* - DISPATCH_REF: 触发分支,默认当前分支
*/
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
declare const process: { exit(code?: number): never; };
async function main (): Promise<void> {
console.log('🚀 Dispatching PR build workflow\n');
const token = getEnv('GITHUB_TOKEN', true)!;
const prNumber = getEnv('PR_NUMBER', true)!;
const prSha = getEnv('PR_SHA', true)!;
const prHeadRepo = getEnv('PR_HEAD_REPO', true)!;
const prHeadRef = getEnv('PR_HEAD_REF') || '';
const workflowFile = getEnv('WORKFLOW_FILE') || 'build-pr.yml';
const dispatchRef = getEnv('DISPATCH_REF') || getEnv('GITHUB_REF_NAME') || 'main';
const { owner, repo } = getRepository();
console.log(`PR: #${prNumber}`);
console.log(`SHA: ${prSha}`);
console.log(`Head repo: ${prHeadRepo}`);
console.log(`Workflow: ${workflowFile}`);
console.log(`Ref: ${dispatchRef}\n`);
const github = new GitHubAPI(token);
await github.createWorkflowDispatch(owner, repo, workflowFile, dispatchRef, {
pr_number: prNumber,
pr_sha: prSha,
pr_head_repo: prHeadRepo,
pr_head_ref: prHeadRef,
});
console.log('✅ Dispatch created');
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+19 -2
View File
@@ -11,11 +11,13 @@
* - FRAMEWORK_ERROR: Framework 构建错误信息
* - SHELL_STATUS: Shell 构建状态
* - SHELL_ERROR: Shell 构建错误信息
* - INSTALL_URL: PR Release 安装脚本 URL (可选)
* - RELEASE_URL: PR Release 页面 URL (可选)
*/
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
import { generateResultComment, COMMENT_MARKER } from './lib/comment.ts';
import type { BuildTarget, BuildStatus } from './lib/comment.ts';
import type { BuildTarget, BuildStatus, InstallInfo } from './lib/comment.ts';
function parseStatus (value: string | undefined): BuildStatus {
if (value === 'success' || value === 'failure' || value === 'cancelled') {
@@ -46,6 +48,21 @@ async function main (): Promise<void> {
console.log(`Framework: ${frameworkStatus}${frameworkError ? ` (${frameworkError})` : ''}`);
console.log(`Shell: ${shellStatus}${shellError ? ` (${shellError})` : ''}\n`);
// PR Release 信息(由 publish-pr-release job 传入)
const installUrl = getEnv('INSTALL_URL');
const releaseUrl = getEnv('RELEASE_URL');
const publishStatus = getEnv('PUBLISH_STATUS'); // 'success' | 'failure' | 'skipped' | ''
const installInfo: InstallInfo | undefined =
installUrl && releaseUrl ? { installUrl, releaseUrl } : undefined;
const publishFailed = publishStatus === 'failure';
if (installInfo) {
console.log(`Install URL: ${installUrl}`);
console.log(`Release URL: ${releaseUrl}\n`);
} else if (publishFailed) {
console.log('Publish status: FAILED\n');
}
const github = new GitHubAPI(token);
const repository = `${owner}/${repo}`;
@@ -79,7 +96,7 @@ async function main (): Promise<void> {
},
];
const comment = generateResultComment(targets, prSha, runId, repository, version);
const comment = generateResultComment(targets, prSha, runId, repository, version, installInfo, publishFailed);
await github.createOrUpdateComment(owner, repo, prNumber, comment, COMMENT_MARKER);
}
+1 -5
View File
@@ -22,11 +22,7 @@ interface BuildStep {
function getCommonSteps (): BuildStep[] {
return [
{
name: 'Install pnpm',
command: 'npm i -g pnpm',
errorMessage: 'Failed to install pnpm',
},
// pnpm 已通过 GitHub Action (pnpm/action-setup) 预安装并固定 v9, 此处无需再次安装
{
name: 'Install dependencies',
command: 'pnpm i',
+69
View File
@@ -0,0 +1,69 @@
/**
* PR Build - 触发 NapCat-Docker 仓库构建 PR 测试镜像
*
* 功能:
* 1. 在 PR 中创建 Docker 构建中评论
* 2. 触发 NapCat-Docker 仓库的 repository_dispatch 事件
*
* 环境变量:
* DISPATCH_PAT - 具备目标仓库 dispatch 权限的 PAT
* GITHUB_TOKEN - GitHub API Token (用于写 PR 评论)
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* PR_HEAD_REPO - PR 源仓库 (owner/repo)
* SOURCE_REPO - 当前仓库 (默认 NapNeko/NapCatQQ)
* RELEASE_REPO - PR release 仓库 (默认 NapNeko/napcat-pr-release)
* TARGET_REPO - Docker 仓库 (默认 NapNeko/NapCat-Docker)
*/
import { GitHubAPI, getEnv } from './lib/github.ts';
import { generateDockerBuildingComment, DOCKER_COMMENT_MARKER } from './lib/comment.ts';
async function main (): Promise<void> {
console.log('🐳 Dispatching Docker build\n');
const token = getEnv('DISPATCH_PAT', true);
const githubToken = getEnv('GITHUB_TOKEN', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const prHeadRepo = getEnv('PR_HEAD_REPO') || '';
const sourceRepo = getEnv('SOURCE_REPO') || 'NapNeko/NapCatQQ';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const targetRepo = getEnv('TARGET_REPO') || 'NapNeko/NapCat-Docker';
const [targetOwner, targetRepoName] = targetRepo.split('/');
const [sourceOwner, sourceRepoName] = sourceRepo.split('/');
const shortSha = prSha.substring(0, 7);
console.log(` PR: #${prNumber}`);
console.log(` SHA: ${shortSha}`);
console.log(` Target: ${targetRepo}`);
console.log(` Release: ${releaseRepo}\n`);
// 在 PR 中创建 Docker 构建中评论
console.log('💬 Creating Docker building comment...');
const prGithub = new GitHubAPI(githubToken);
const dockerComment = generateDockerBuildingComment(prNumber, prSha);
await prGithub.createOrUpdateComment(
sourceOwner, sourceRepoName, parseInt(prNumber, 10), dockerComment, DOCKER_COMMENT_MARKER
);
// 触发 Docker 仓库构建
const github = new GitHubAPI(token);
await github.repositoryDispatch(targetOwner, targetRepoName, 'napcatqq-pr-build', {
pr_number: prNumber,
pr_sha: prSha,
pr_short_sha: shortSha,
pr_head_repo: prHeadRepo,
source_repo: sourceRepo,
release_repo: releaseRepo,
});
console.log('✅ Dispatch succeeded');
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+173
View File
@@ -0,0 +1,173 @@
/**
* PR Build - 发布构建产物到 napcat-pr-release 仓库
*
* 功能:
* 1. 将 CI 构建产物(Framework / Shell)打包为 zip
* 2. 从 NapCat-Installer 仓库拉取 install.sh 并替换下载链接
* 3. 发布到 napcat-pr-release 仓库的 GitHub Release
*
* 环境变量:
* RELEASE_PAT - 具备目标仓库 release 写权限的 PAT
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* NAPCAT_VERSION - 构建版本号
* ARTIFACTS_DIR - 构建产物目录 (默认 ./artifacts)
* RELEASE_REPO - 发布仓库 (默认 NapNeko/napcat-pr-release)
* INSTALLER_REPO - 安装脚本仓库 (默认 NapNeko/NapCat-Installer)
* INSTALLER_BRANCH - 安装脚本分支 (默认 main)
*/
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
import { toProxyUrl } from './lib/comment.ts';
interface AssetEntry {
name: string;
path: string;
contentType: string;
}
async function main (): Promise<void> {
console.log('📦 PR Release Publisher\n');
const token = getEnv('RELEASE_PAT', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const version = getEnv('NAPCAT_VERSION') || 'unknown';
const artifactsDir = getEnv('ARTIFACTS_DIR') || './artifacts';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const installerRepo = getEnv('INSTALLER_REPO') || 'NapNeko/NapCat-Installer';
const installerBranch = getEnv('INSTALLER_BRANCH') || 'main';
const [releaseOwner, releaseRepoName] = releaseRepo.split('/');
const shortSha = prSha.substring(0, 7);
const tag = `pr-${prNumber}-${shortSha}`;
const releaseName = `PR #${prNumber} (${shortSha})`;
const downloadBase = `https://github.com/${releaseRepo}/releases/download/${tag}`;
console.log(` Tag: ${tag}`);
console.log(` Repo: ${releaseRepo}`);
console.log(` Version: ${version}`);
console.log(` SHA: ${shortSha}\n`);
const github = new GitHubAPI(token);
const releaseDir = resolve('./release-assets'); // 使用绝对路径,避免 zip cwd 切换后相对路径解析错误
mkdirSync(releaseDir, { recursive: true });
// ---- 打包构建产物 ----
const artifacts = ['NapCat.Framework', 'NapCat.Shell'];
for (const name of artifacts) {
const dir = join(artifactsDir, name);
if (existsSync(dir)) {
const zipPath = join(releaseDir, `${name}.zip`);
console.log(`📦 Packing ${name}...`);
execSync(`zip -qr "${zipPath}" .`, { cwd: dir, stdio: 'inherit' });
console.log(` ✓ ${name}.zip\n`);
} else {
console.log(` ⚠ ${name} 目录不存在,跳过\n`);
}
}
// ---- 拉取并修改安装脚本 ----
console.log('📜 Fetching install.sh...');
const scriptUrl = `https://raw.githubusercontent.com/${installerRepo}/${installerBranch}/script/install.sh`;
try {
const response = await fetch(scriptUrl);
if (response.ok) {
let script = await response.text();
// 替换下载链接(保留代理前缀 ${target_proxy:+${target_proxy}/})
const shellUrl = `${downloadBase}/NapCat.Shell.zip`;
const originalScript = script;
script = script.replace(
/napcat_download_url="\$\{target_proxy:\+\$\{target_proxy\}\/\}https:\/\/github\.com\/NapNeko\/NapCatQQ\/releases\/latest\/download\/NapCat\.Shell\.zip"/g,
`napcat_download_url="\${target_proxy:+\${target_proxy}/}${shellUrl}"`
);
if (script === originalScript) {
console.log(' ⚠ Warning: URL replacement did not match - install.sh format may have changed');
}
const scriptPath = join(releaseDir, 'install.sh');
writeFileSync(scriptPath, script, { mode: 0o755 });
console.log(` ✓ Patched download URL -> ${shellUrl}\n`);
} else {
console.log(` ⚠ Failed to fetch install.sh: ${response.status}\n`);
}
} catch (e) {
console.log(` ⚠ Failed to fetch install.sh: ${(e as Error).message}\n`);
}
// ---- 收集所有要上传的文件 ----
const assets: AssetEntry[] = [];
for (const file of readdirSync(releaseDir)) {
const ext = file.split('.').pop()?.toLowerCase();
const contentType = ext === 'zip' ? 'application/zip' : ext === 'sh' ? 'application/x-sh' : 'application/octet-stream';
assets.push({ name: file, path: join(releaseDir, file), contentType });
}
console.log(`📋 Assets to upload: ${assets.map(a => a.name).join(', ')}\n`);
// ---- 删除旧 release ----
console.log('🗑️ Checking for existing release...');
const existing = await github.getReleaseByTag(releaseOwner, releaseRepoName, tag);
if (existing) {
console.log(` Deleting existing release (id=${existing.id})...`);
await github.deleteRelease(releaseOwner, releaseRepoName, existing.id);
await github.deleteRef(releaseOwner, releaseRepoName, `tags/${tag}`);
console.log(' ✓ Deleted\n');
} else {
console.log(' No existing release\n');
}
// ---- 创建 Release ----
const directInstallUrl = `${downloadBase}/install.sh`;
const proxyInstallUrl = toProxyUrl(directInstallUrl);
const releaseBody = [
`## NapCat PR #${prNumber} 测试版本`,
'',
`- **版本**: \`${version}\``,
`- **提交**: \`${prSha}\``,
`- **来源**: [NapCatQQ PR #${prNumber}](https://github.com/NapNeko/NapCatQQ/pull/${prNumber})`,
'',
'### 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directInstallUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。',
].join('\n');
console.log('🚀 Creating release...');
const release = await github.createRelease(
releaseOwner, releaseRepoName, tag, releaseName, releaseBody, true
);
console.log(` ✓ Release created: ${release.html_url}\n`);
// ---- 上传资产 ----
console.log('📤 Uploading assets...');
for (const asset of assets) {
const data = readFileSync(asset.path);
const uploaded = await github.uploadReleaseAsset(
release.upload_url, asset.name, data, asset.contentType
);
console.log(` ✓ ${asset.name} -> ${uploaded.browser_download_url}`);
}
console.log(`\n✅ Release published: ${release.html_url}`);
// 输出供后续 job 使用
setOutput('release_url', release.html_url);
setOutput('release_tag', tag);
setOutput('install_url', `${downloadBase}/install.sh`);
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+80
View File
@@ -0,0 +1,80 @@
/**
* publish-release-hash.mjs
*
* 读取 release.json(不存在则创建),追加新版本的 Shell/Framework napcat.mjs SHA512,
* 保留最近 100 条后写回文件。
*
* 用法:
* node .github/scripts/publish-release-hash.mjs \
* --version v4.9.0 \
* --shell ./artifacts/NapCat.Shell/napcat.mjs \
* --framework ./artifacts/NapCat.Framework/napcat.mjs \
* --file ./hash-repo/release.json
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
// ─── CLI 参数解析 ────────────────────────────────────────────────────────────
function parseArgs () {
const args = process.argv.slice(2);
const result = {};
for (let i = 0; i < args.length; i += 2) {
result[args[i].replace(/^--/, '')] = args[i + 1];
}
return result;
}
const { version, shell: shellPath, framework: frameworkPath, file: outputFile } = parseArgs();
if (!version || !shellPath || !frameworkPath || !outputFile) {
console.error('Usage: node publish-release-hash.mjs --version <v> --shell <path> --framework <path> --file <path>');
process.exit(1);
}
// ─── 工具函数 ────────────────────────────────────────────────────────────────
function sha512File (filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
const buf = fs.readFileSync(filePath);
return crypto.createHash('sha512').update(buf).digest('hex');
}
// ─── 主逻辑 ──────────────────────────────────────────────────────────────────
const MAX_ENTRIES = 100;
// 1. 计算哈希
console.log(`Computing SHA512 for Shell: ${shellPath}`);
const shellHash = sha512File(shellPath);
console.log(`Computing SHA512 for Framework: ${frameworkPath}`);
const frameworkHash = sha512File(frameworkPath);
// 2. 读取现有 release.json,不存在则创建空数组
let entries = [];
if (fs.existsSync(outputFile)) {
entries = JSON.parse(fs.readFileSync(outputFile, 'utf-8'));
console.log(`Loaded existing ${outputFile} with ${entries.length} entries.`);
} else {
console.log(`${outputFile} not found, will create it.`);
}
// 3. 追加新条目,去除同版本旧条目,滚动保留最近 MAX_ENTRIES 条
const newEntry = {
version,
shell: { sha512: shellHash },
framework: { sha512: frameworkHash },
updatedAt: new Date().toISOString(),
};
const updated = [
...entries.filter(e => e.version !== version),
newEntry,
].slice(-MAX_ENTRIES);
// 4. 写回文件
fs.writeFileSync(outputFile, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
console.log(`✅ Written ${updated.length} entries to ${outputFile}`);
@@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.20)
project(NapCatWindowsLoaderTest LANGUAGES CXX)
add_executable(windows-loader-test probe.cpp)
+96
View File
@@ -0,0 +1,96 @@
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using QueryByName = BOOL(WINAPI *)(PCWSTR, FILE_INFO_BY_NAME_CLASS, PVOID, ULONG);
int wmain(int argumentCount, wchar_t **arguments)
{
if (argumentCount != 3)
return 2;
const wchar_t *providers[] = {L"kernel32.dll", L"kernelbase.dll", L"api-ms-win-core-file-l2-1-4.dll"};
HMODULE providerModules[3]{};
QueryByName nativeQueries[3]{};
unsigned char nativeCode[3][12]{};
unsigned char nativeInfo[3][4][1024]{};
BOOL nativeResults[3][4]{};
DWORD nativeErrors[3][4]{};
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
providerModules[providerIndex] = LoadLibraryW(providers[providerIndex]);
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
if (!query)
return 3;
nativeQueries[providerIndex] = query;
std::memcpy(nativeCode[providerIndex], reinterpret_cast<void *>(query), sizeof(nativeCode[providerIndex]));
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
SetLastError(ERROR_SUCCESS);
nativeResults[providerIndex][infoClass] = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), nativeInfo[providerIndex][infoClass], sizeof(nativeInfo[providerIndex][infoClass]));
nativeErrors[providerIndex][infoClass] = GetLastError();
}
}
FILE_STAT_BASIC_INFORMATION expected{};
if (!nativeQueries[0](arguments[2], FileStatBasicByNameInfo, &expected, sizeof(expected)))
return 4;
if (_wputenv_s(L"NAPCAT_LOAD_PATH", arguments[2]) || _wputenv_s(L"NAPCAT_PATCH_PACKAGE", arguments[2]))
return 5;
if (!LoadLibraryW(arguments[1]))
{
std::printf("LoadLibrary failed: %lu\n", GetLastError());
return 6;
}
const std::wstring missingRoot = L"C:\\napcat-loader-test-" + std::to_wstring(GetCurrentProcessId());
const std::wstring loaderPath = missingRoot + L"\\loadNapCat.js";
const std::wstring packagePath = missingRoot + L"\\resources\\app\\package.json";
const std::wstring unrelatedPath = missingRoot + L"\\unrelated.txt";
const wchar_t *redirectedPaths[] = {loaderPath.c_str(), packagePath.c_str()};
int failures = 0;
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
bool preserved = std::memcmp(nativeCode[providerIndex], reinterpret_cast<void *>(nativeQueries[providerIndex]), sizeof(nativeCode[providerIndex])) == 0;
std::wprintf(L"%ls native code preserved: %ls\n", providers[providerIndex], preserved ? L"PASS" : L"FAIL");
failures += !preserved;
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
unsigned char actual[1024]{};
SetLastError(ERROR_SUCCESS);
BOOL result = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), actual, sizeof(actual));
DWORD error = GetLastError();
bool passed = result == nativeResults[providerIndex][infoClass] &&
(result ? std::memcmp(actual, nativeInfo[providerIndex][infoClass], sizeof(actual)) == 0 : error == nativeErrors[providerIndex][infoClass]);
std::wprintf(L"%ls information class %d native parity: %ls\n", providers[providerIndex], infoClass, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
for (const auto *redirectedPath : redirectedPaths)
{
FILE_STAT_BASIC_INFORMATION actual{};
BOOL result = query(redirectedPath, FileStatBasicByNameInfo, &actual, sizeof(actual));
bool passed = result && actual.EndOfFile.QuadPart == expected.EndOfFile.QuadPart &&
actual.FileId.QuadPart == expected.FileId.QuadPart && actual.FileAttributes == expected.FileAttributes;
std::wprintf(L"%ls redirect %ls: %ls\n", providers[providerIndex], redirectedPath, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION missing{};
SetLastError(ERROR_SUCCESS);
BOOL nativeResult = nativeQueries[providerIndex](unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
DWORD nativeError = GetLastError();
SetLastError(ERROR_SUCCESS);
BOOL result = query(unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
bool passed = !result && result == nativeResult && GetLastError() == nativeError;
std::wprintf(L"%ls unrelated missing file: %ls\n", providers[providerIndex], passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION direct{};
BOOL result = GetFileInformationByName(loaderPath.c_str(), FileStatBasicByNameInfo, &direct, sizeof(direct));
bool passed = result && direct.FileId.QuadPart == expected.FileId.QuadPart && direct.EndOfFile.QuadPart == expected.EndOfFile.QuadPart;
std::printf("static import redirection: %s\n", passed ? "PASS" : "FAIL");
failures += !passed;
return failures ? 1 : 0;
}
-153
View File
@@ -1,153 +0,0 @@
name: Auto Release Docker
on:
release:
types: [published]
jobs:
publish-schema:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Get Version
id: get_version
run: |
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
version=${latest_tag#v}
echo "version=${version}" >> $GITHUB_ENV
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
echo "Debug: Version is ${version}"
- name: Install Dependencies
run: pnpm install --frozen-lockfile
- name: Build napcat-schema
run: |
cd packages/napcat-schema
pnpm run build:openapi
- name: Checkout NapCatDocs
uses: actions/checkout@v4
with:
repository: NapNeko/NapCatDocs
token: ${{ secrets.NAPCAT_BUILD }}
path: napcat-docs
- name: Copy OpenAPI Schema
run: |
mkdir -p napcat-docs/src/api/${{ env.version }}
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
- name: Commit and Push
run: |
cd napcat-docs
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add src/api/${{ env.version }}/openapi.json
git commit -m "chore: update OpenAPI schema for version ${{ env.version }}" || echo "No changes to commit"
git push
shell-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
framework-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Framework-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
-d '{"ref":"main"}'
appimage-shell-docker:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Get Latest NapCat Version
id: get_version
run: |
# 获取当前仓库的最新 tag
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
# 输出调试信息
echo "Debug: Latest NapCat Version is ${latest_tag}"
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_version_x86_64=${QQ_VERSION_X86_64}, qq_version_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${QQ_VERSION_X86_64}\",\"qq_version_arm64\":\"${QQ_VERSION_ARM64}\"}}"
node-shell-docker:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Get Latest NapCat Version
id: get_version
run: |
# 获取当前仓库的最新 tag
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
# 输出调试信息
echo "Debug: Latest NapCat Version is ${latest_tag}"
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
+111
View File
@@ -0,0 +1,111 @@
name: Build NapCat Artifacts
on:
workflow_dispatch:
push:
branches:
- main
permissions: write-all
jobs:
windows-loader-test:
name: Windows Loader Test
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell
path: shell-dist
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/shell-dist/NapCatWinBootHook.dll" "$pwd/shell-dist/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
typecheck-and-test:
name: Type Check & Test
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Install Dependencies
run: pnpm i
- name: Type Check
run: pnpm run typecheck
- name: Run Tests
run: pnpm test
build:
name: Build NapCat.${{ matrix.target.name }}
needs: typecheck-and-test
runs-on: ubuntu-latest
strategy:
matrix:
target:
- name: Framework
build_cmd: build:framework
src_dir: packages/napcat-framework/dist
dist_dir: framework-dist
- name: Shell
build_cmd: build:shell
src_dir: packages/napcat-shell/dist
dist_dir: shell-dist
steps:
- name: Clone Main Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Generate Version
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
pnpm --filter napcat-plugin-builtin run build || exit 1
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v6
with:
name: NapCat.${{ matrix.target.name }}
path: ${{ matrix.target.dist_dir }}
+424
View File
@@ -0,0 +1,424 @@
# =============================================================================
# PR 构建工作流
# =============================================================================
# 安全模型:
# 1. pull_request_target / issue_comment 入口只读取元数据、检查权限、更新评论并触发构建。
# 2. 真正执行 PR 代码的构建流程只在 workflow_dispatch 中运行。
# 3. 构建流程不具备写仓库/写评论/读 secrets 权限,显式清空 GITHUB_TOKEN,不持久化 checkout 凭据。
# 4. 版本号在 Action 中提前生成,通过 NAPCAT_VERSION 传给 Vite 插件,插件无需 GitHub token。
# 5. 发布 Release、触发 Docker 等可信操作只消费构建 artifact,不执行 PR artifact 中的代码。
# =============================================================================
name: Build PR
on:
pull_request_target:
types: [opened, synchronize, reopened]
issue_comment:
types: [created]
workflow_dispatch:
inputs:
pr_number:
description: PR 编号
required: true
type: string
pr_sha:
description: PR HEAD SHA
required: true
type: string
pr_head_repo:
description: PR 源仓库
required: true
type: string
pr_head_ref:
description: PR 源分支
required: false
type: string
permissions:
contents: read
concurrency:
group: pr-build-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
cancel-in-progress: true
jobs:
# ---------------------------------------------------------------------------
# 特权入口:只检查条件、写入“构建中”评论、触发无权限构建
# ---------------------------------------------------------------------------
check-build:
if: github.event_name != 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: write
outputs:
should_build: ${{ steps.check.outputs.should_build }}
pr_number: ${{ steps.check.outputs.pr_number }}
pr_sha: ${{ steps.check.outputs.pr_sha }}
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }}
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }}
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Check trigger condition
id: check
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
update-comment-building:
needs: check-build
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Update building comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
dispatch-build:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Dispatch untrusted build
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
PR_HEAD_REF: ${{ needs.check-build.outputs.pr_head_ref }}
WORKFLOW_FILE: build-pr.yml
DISPATCH_REF: ${{ github.event.repository.default_branch }}
run: node --experimental-strip-types .github/scripts/pr-build-dispatch.ts
# ---------------------------------------------------------------------------
# 无权限构建:只由 workflow_dispatch 执行 PR 代码
# ---------------------------------------------------------------------------
build-framework:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
status: ${{ steps.build.outcome }}
error: ${{ steps.build.outputs.error }}
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
persist-credentials: false
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ inputs.pr_head_repo }}
ref: ${{ inputs.pr_sha }}
path: workspace
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Generate Version
id: version
working-directory: workspace
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ''
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
continue-on-error: true
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 5
build-shell:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
status: ${{ steps.build.outcome }}
error: ${{ steps.build.outputs.error }}
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
persist-credentials: false
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ inputs.pr_head_repo }}
ref: ${{ inputs.pr_sha }}
path: workspace
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Generate Version
id: version
working-directory: workspace
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ''
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
continue-on-error: true
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 5
# ---------------------------------------------------------------------------
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
# ---------------------------------------------------------------------------
publish-pr-release:
needs: [build-framework, build-shell]
if: always() && github.event_name == 'workflow_dispatch' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
runs-on: ubuntu-latest
permissions:
contents: read
actions: read
outputs:
release_url: ${{ steps.publish.outputs.release_url }}
release_tag: ${{ steps.publish.outputs.release_tag }}
install_url: ${{ steps.publish.outputs.install_url }}
publish_status: ${{ steps.publish.outcome }}
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Download Framework artifact
if: needs.build-framework.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Framework
path: ./artifacts/NapCat.Framework
- name: Download Shell artifact
if: needs.build-shell.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Shell
path: ./artifacts/NapCat.Shell
- name: Publish release
id: publish
continue-on-error: true
env:
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
ARTIFACTS_DIR: ./artifacts
run: |
if [ -z "${RELEASE_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 PR Release 发布"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-publish-release.ts
- name: Upload install script as artifact
if: steps.publish.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: install-script
path: ./release-assets/install.sh
retention-days: 5
if-no-files-found: ignore
update-comment-result:
needs: [build-framework, build-shell, publish-pr-release]
if: always() && github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
actions: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Update result comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
RUN_ID: ${{ github.run_id }}
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
trigger-docker:
needs: [build-shell, publish-pr-release]
if: github.event_name == 'workflow_dispatch' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Dispatch docker build
continue-on-error: true
env:
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
PR_HEAD_REPO: ${{ inputs.pr_head_repo }}
SOURCE_REPO: ${{ github.repository }}
RELEASE_REPO: NapNeko/napcat-pr-release
run: |
if [ -z "${DISPATCH_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 Docker 测试镜像构建"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-docker-dispatch.ts
-96
View File
@@ -1,96 +0,0 @@
name: Build NapCat Artifacts
on:
workflow_dispatch:
push:
branches:
- main
permissions: write-all
jobs:
Build-Framework:
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Use Node.js 20.X
uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Generate Version
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.Framework
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm run typecheck || exit 1
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Framework
path: framework-dist
Build-Shell:
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Use Node.js 20.X
uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Generate Version
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.Shell
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm run typecheck || exit 1
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Shell
path: shell-dist
-303
View File
@@ -1,303 +0,0 @@
# =============================================================================
# PR 构建工作流
# =============================================================================
# 功能:
# 1. 在 PR 提交时自动构建 Framework 和 Shell 包
# 2. 支持通过 /build 命令手动触发构建(仅协作者/组织成员)
# 3. 在 PR 中发布构建状态评论,并持续更新(不会重复创建)
# 4. 支持 Fork PR 的构建(使用 pull_request_target 获取写权限)
#
# 安全说明:
# - 使用 pull_request_target 事件,在 base 分支上下文运行
# - 构建脚本始终从 base 分支 checkout,避免恶意 PR 篡改脚本
# - PR 代码单独 checkout 到 workspace 目录
# =============================================================================
name: PR Build
# =============================================================================
# 触发条件
# =============================================================================
on:
# PR 事件:打开、同步(新推送)、重新打开时触发
# 注意:使用 pull_request_target 而非 pull_request,以便对 Fork PR 有写权限
pull_request_target:
types: [opened, synchronize, reopened]
# Issue 评论事件:用于响应 /build 命令
issue_comment:
types: [created]
# =============================================================================
# 权限配置
# =============================================================================
permissions:
contents: read # 读取仓库内容
pull-requests: write # 写入 PR 评论
issues: write # 写入 Issue 评论(/build 命令响应)
actions: read # 读取 Actions 信息(获取构建日志链接)
# =============================================================================
# 并发控制
# =============================================================================
# 同一 PR 的多次构建会取消之前未完成的构建,避免资源浪费
# 注意:只有在 should_build=true 时才会进入实际构建流程,
# issue_comment 事件如果不是 /build 命令,会在 check-build 阶段快速退出,
# 不会取消正在进行的构建(因为 cancel-in-progress 只影响同 group 的后续任务)
concurrency:
# 使用不同的 group 策略:
# - pull_request_target: 使用 PR 号
# - issue_comment: 只有确认是 /build 命令时才使用 PR 号,否则使用 run_id(不冲突)
group: pr-build-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
cancel-in-progress: true
# =============================================================================
# 任务定义
# =============================================================================
jobs:
# ---------------------------------------------------------------------------
# Job 1: 检查构建条件
# ---------------------------------------------------------------------------
# 判断是否应该触发构建:
# - pull_request_target 事件:总是触发
# - issue_comment 事件:检查是否为 /build 命令,且用户有权限
# ---------------------------------------------------------------------------
check-build:
runs-on: ubuntu-latest
outputs:
should_build: ${{ steps.check.outputs.should_build }} # 是否应该构建
pr_number: ${{ steps.check.outputs.pr_number }} # PR 编号
pr_sha: ${{ steps.check.outputs.pr_sha }} # PR 最新提交 SHA
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }} # PR 源仓库(用于 Fork)
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }} # PR 源分支
steps:
# 仅 checkout 脚本目录,加快速度
- name: Checkout scripts
uses: actions/checkout@v4
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
# 使用 Node.js 24 以支持原生 TypeScript 执行
- name: Setup Node.js 24
uses: actions/setup-node@v4
with:
node-version: 24
# 执行检查脚本,判断是否触发构建
- name: Check trigger condition
id: check
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
# ---------------------------------------------------------------------------
# Job 2: 更新评论为"构建中"状态
# ---------------------------------------------------------------------------
# 在 PR 中创建或更新评论,显示构建正在进行中
# ---------------------------------------------------------------------------
update-comment-building:
needs: check-build
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v4
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v4
with:
node-version: 24
# 更新 PR 评论,显示构建中状态
- name: Update building comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
# ---------------------------------------------------------------------------
# Job 3: 构建 Framework 包
# ---------------------------------------------------------------------------
# 执行 napcat-framework 的构建流程
# ---------------------------------------------------------------------------
build-framework:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
outputs:
status: ${{ steps.build.outcome }} # 构建结果:success/failure
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
version: ${{ steps.version.outputs.version }} # 构建版本号
steps:
# 【安全】先从 base 分支 checkout 构建脚本
# 这样即使 PR 中修改了脚本,也不会被执行
- name: Checkout scripts from base
uses: actions/checkout@v4
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v4
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v4
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- name: Generate Version
id: version
working-directory: workspace
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
continue-on-error: true # 允许失败,后续更新评论时处理
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 7 # 保留 7 天
# ---------------------------------------------------------------------------
# Job 4: 构建 Shell 包
# ---------------------------------------------------------------------------
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
# ---------------------------------------------------------------------------
build-shell:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
outputs:
status: ${{ steps.build.outcome }} # 构建结果:success/failure
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
version: ${{ steps.version.outputs.version }} # 构建版本号
steps:
# 【安全】先从 base 分支 checkout 构建脚本
- name: Checkout scripts from base
uses: actions/checkout@v4
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v4
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v4
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- name: Generate Version
id: version
working-directory: workspace
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
# 执行构建
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
continue-on-error: true
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 7 # 保留 7 天
# ---------------------------------------------------------------------------
# Job 5: 更新评论为构建结果
# ---------------------------------------------------------------------------
# 汇总所有构建结果,更新 PR 评论显示最终状态
# 使用 always() 确保即使构建失败/取消也会执行
# ---------------------------------------------------------------------------
update-comment-result:
needs: [check-build, update-comment-building, build-framework, build-shell]
if: always() && needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v4
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v4
with:
node-version: 24
# 更新评论,显示构建结果和下载链接
- name: Update result comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
RUN_ID: ${{ github.run_id }}
# 构建版本号
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
# 获取构建状态,如果 job 被跳过则标记为 cancelled
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
+153
View File
@@ -0,0 +1,153 @@
name: Release Downstream
on:
workflow_dispatch:
inputs:
tag_name:
description: 'Release tag name (e.g., v4.10.7)'
required: true
type: string
env:
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.AppImage'
jobs:
get-version:
runs-on: ubuntu-latest
outputs:
latest_tag: ${{ steps.get_version.outputs.latest_tag }}
version: ${{ steps.get_version.outputs.version }}
steps:
- name: Checkout Repository
uses: actions/checkout@v5
- name: Get Latest NapCat Version
id: get_version
run: |
if [ -n "${{ inputs.tag_name }}" ]; then
latest_tag="${{ inputs.tag_name }}"
else
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
fi
version=${latest_tag#v}
echo "Debug: Latest NapCat Version is ${latest_tag}, version is ${version}"
echo "latest_tag=${latest_tag}" >> $GITHUB_OUTPUT
echo "version=${version}" >> $GITHUB_OUTPUT
publish-schema:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install Dependencies
run: pnpm install --frozen-lockfile
- name: Build napcat-schema
run: |
cd packages/napcat-schema
pnpm run build:openapi
- name: Checkout NapCatDocs
uses: actions/checkout@v5
with:
repository: NapNeko/NapCatDocs
token: ${{ secrets.NAPCAT_BUILD }}
path: napcat-docs
- name: Copy OpenAPI Schema
run: |
VERSION="${{ needs.get-version.outputs.version }}"
mkdir -p napcat-docs/src/api/${VERSION}
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${VERSION}/openapi.json
echo "OpenAPI schema copied to napcat-docs/src/api/${VERSION}/openapi.json"
- name: Commit and Push
run: |
VERSION="${{ needs.get-version.outputs.version }}"
cd napcat-docs
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add src/api/${VERSION}/openapi.json
git commit -m "chore: update OpenAPI schema for version ${VERSION}" || echo "No changes to commit"
git push
shell-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
framework-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Framework-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
-d '{"ref":"main"}'
appimage:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat AppImage build workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
run: |
echo "Debug: Triggering NapCat AppImage with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_version_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
node-shell:
needs: get-version
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
steps:
- name: Trigger NapCat NodeLoader release workflow
run: |
echo "Debug: Triggering NapCat NodeLoader release with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
- name: Trigger NapCat NodeLoader docker workflow
run: |
echo "Debug: Triggering NapCat NodeLoader docker with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
@@ -1,115 +1,83 @@
name: Release NapCat
name: Release Publish
on:
workflow_dispatch:
push:
tags:
- 'v*'
inputs:
version:
description: 'Release version tag (e.g., v4.10.7)'
required: true
type: string
permissions: write-all
env:
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
OPENROUTER_MODEL: "glm-4.7"
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
RELEASE_NAME: "NapCat"
jobs:
# 验证版本号格式
validate-version:
runs-on: ubuntu-latest
outputs:
valid: ${{ steps.check.outputs.valid }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Validate semantic version
id: check
run: |
TAG="${GITHUB_REF#refs/tags/}"
echo "Checking tag: $TAG"
# 语义化版本正则表达式
# 支持: v1.0.0, v1.0.0-beta, v1.0.0-rc.1, v1.0.0-alpha.1+build.123
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
echo "✅ Valid semantic version: $TAG"
echo "valid=true" >> $GITHUB_OUTPUT
echo "version=$TAG" >> $GITHUB_OUTPUT
else
echo "❌ Invalid version format: $TAG"
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
echo "valid=false" >> $GITHUB_OUTPUT
exit 1
fi
Build-Framework:
needs: validate-version
if: needs.validate-version.outputs.valid == 'true'
build:
name: Build NapCat.${{ matrix.target.name }}
runs-on: ubuntu-latest
strategy:
matrix:
target:
- name: Framework
build_cmd: build:framework
src_dir: packages/napcat-framework/dist
dist_dir: framework-dist
- name: Shell
build_cmd: build:shell
src_dir: packages/napcat-shell/dist
dist_dir: shell-dist
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
- name: Use Node.js 20.X
uses: actions/setup-node@v4
uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Build NapCat.Framework
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ inputs.version }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm run ${{ matrix.target.build_cmd }}
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: framework-dist
name: NapCat.${{ matrix.target.name }}
path: ${{ matrix.target.dist_dir }}
Build-Shell:
needs: validate-version
if: needs.validate-version.outputs.valid == 'true'
assemble-windows-node:
needs: build
runs-on: ubuntu-latest
env:
# QQ 9.9.31.49738; SHA256 matches the microsoft/winget-pkgs installer manifest.
QQ_URL: https://github.com/Rodert/qq-versions/releases/download/qq-packages-20260528-3e8913a2/QQ_9.9.31_260528_x64_01.exe
QQ_SHA256: 0beb5cb4ff776cba822caa0abadbd53f5892f12628a86dabea1b372c82c086bc
NODE_VERSION: '22.11.0'
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
- name: Use Node.js 20.X
uses: actions/setup-node@v4
- uses: actions/checkout@v5
with:
node-version: 20.x
- name: Build NapCat.Shell
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Shell
path: shell-dist
Download-QNX64:
needs: Build-Shell
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
ref: ${{ inputs.version }}
- name: Download Artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v7
with:
path: ./artifacts
@@ -118,35 +86,59 @@ jobs:
sudo apt update
sudo apt install -y aria2 unzip zip p7zip-full curl jq
- name: Download and Assemble NapCat.Shell.Windows.Node.zip
- name: Generate download cache key
id: download-cache-key
run: |
DOWNLOAD_HASH=$(printf '%s\n' "$QQ_URL" "$QQ_SHA256" "$NODE_VERSION" | sha256sum | cut -d ' ' -f 1)
echo "key=napcat-downloads-v2-$DOWNLOAD_HASH" >> "$GITHUB_OUTPUT"
- name: Cache QQ and Node.js downloads
id: cache-downloads
uses: actions/cache@v4
with:
path: /tmp/napcat-downloads
key: ${{ steps.download-cache-key.outputs.key }}
- name: Download QQ and Node.js
if: steps.cache-downloads.outputs.cache-hit != 'true'
run: |
set -euo pipefail
mkdir -p /tmp/napcat-downloads
cd /tmp/napcat-downloads
echo "Downloading QQ installer..."
# Retry download errors, including HTTP 404 responses.
curl --fail --location --retry 5 --retry-all-errors --retry-delay 5 \
--connect-timeout 30 --max-time 600 --user-agent "Mozilla/5.0" \
--output "QQ_x64.exe" "$QQ_URL"
NODE_URL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-win-x64.zip"
echo "Downloading Node.js $NODE_VERSION..."
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
- name: Verify QQ installer
run: |
echo "$QQ_SHA256 /tmp/napcat-downloads/QQ_x64.exe" | sha256sum --check --strict -
- name: Assemble NapCat.Shell.Windows.Node.zip
run: |
set -euo pipefail
TMPDIR=$(mktemp -d)
cd "$TMPDIR"
CACHE_DIR="/tmp/napcat-downloads"
# -----------------------------
# 1) 下载 QQ x64
# 1) 解压 QQ x64
# -----------------------------
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
QQ_ZIP="$(basename "$NT_URL")"
echo "Downloading QQ installer: $QQ_ZIP"
aria2c -x16 -s16 -k1M -o "$QQ_ZIP" "$NT_URL"
QQ_EXTRACT="$TMPDIR/qq_extracted"
mkdir -p "$QQ_EXTRACT"
7z x -y -o"$QQ_EXTRACT" "$QQ_ZIP" >/dev/null
7z x -y -o"$QQ_EXTRACT" "$CACHE_DIR/QQ_x64.exe" >/dev/null
# -----------------------------
# 2) 下载 Node.js Windows x64 zip 22.11.0
# 2) 解压 Node.js Windows x64
# -----------------------------
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
NODE_ZIP="node-v$NODE_VER-win-x64.zip"
aria2c -x1 -s1 -k1M -o "$NODE_ZIP" "$NODE_URL"
NODE_EXTRACT="$TMPDIR/node_extracted"
mkdir -p "$NODE_EXTRACT"
unzip -q "$NODE_ZIP" -d "$NODE_EXTRACT"
unzip -q "$CACHE_DIR/node-win-x64.zip" -d "$NODE_EXTRACT"
# -----------------------------
# 3) 创建输出目录
@@ -162,9 +154,14 @@ jobs:
# -----------------------------
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
# -----------------------------
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "crypto.dll" "ssl.dll" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
for name in "${QQ_TARGETS[@]}"; do
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
source_file=$(find "$QQ_EXTRACT" -type f -iname "$name" -print -quit)
if [ -z "$source_file" ]; then
echo "Missing required QQ file: $name" >&2
exit 1
fi
cp -a "$source_file" "$OUT_DIR/"
done
# -----------------------------
@@ -180,29 +177,60 @@ jobs:
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/napcat.bat" "$OUT_DIR/" || true
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/index.js" "$OUT_DIR/" || true
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/QQNT.dll" "$OUT_DIR/" || true
# -----------------------------
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
# -----------------------------
NODE_VER="22.11.0"
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
cp -a "$NODE_EXTRACT/node-v$NODE_VERSION-win-x64/node.exe" "$OUT_DIR/" || true
- name: Upload Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell.Windows.Node
path: NapCat.Shell.Windows.Node
validate-windows-node:
needs: assemble-windows-node
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell.Windows.Node
path: windows-node
- name: Verify bundled Node and QQ native dependencies
shell: pwsh
working-directory: windows-node
run: |
& .\node.exe --check .\index.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\node.exe -e "const wrapper = require('./wrapper.node'); if (!wrapper.NodeQQNTWrapperUtil) throw new Error('Missing NodeQQNTWrapperUtil'); console.log('wrapper.node native-load PASS'); process.exit(0);"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/windows-node/napcat/NapCatWinBootHook.dll" "$pwd/windows-node/napcat/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
release-napcat:
needs: [Build-Framework, Build-Shell, Download-QNX64]
needs: [build, assemble-windows-node, validate-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
fetch-depth: 0
- name: Download Artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v7
with:
path: ./artifacts
@@ -218,18 +246,18 @@ jobs:
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
cd ..
- name: Generate release note via OpenRouter
- name: Generate release note
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
OPENROUTER_API_URL: ${{ env.OPENROUTER_API_URL }}
OPENROUTER_MODEL: ${{ env.OPENROUTER_MODEL }}
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
GITHUB_OWNER: "NapNeko"
GITHUB_REPO: "NapCatQQ"
run: |
set -euo pipefail
# 当前 tag
CURRENT_TAG="${GITHUB_REF#refs/tags/}"
CURRENT_TAG="${{ inputs.version }}"
echo "Current tag: $CURRENT_TAG"
# 从 GitHub API 获取 tag 列表
@@ -248,7 +276,7 @@ jobs:
done
if [ -z "$PREV_TAG" ]; then
echo "⚠️ Could not find previous tag for $CURRENT_TAG, using first commit"
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
fi
@@ -259,7 +287,6 @@ jobs:
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
# 获取 commit,使用更清晰的格式
# 格式: <type>: <subject> (<hash>)
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
@@ -268,15 +295,15 @@ jobs:
# 获取文件变化统计
echo "Getting file change statistics..."
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
# 获取总体统计(最后一行)
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
echo "Summary: $SUMMARY_LINE"
# 获取每个文件的变化(去掉最后一行汇总)
# 截断过长的输出(最多50个文件,每行最多80字符)
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
# 如果文件变化太多,进一步精简:只保留主要目录的变化
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
if [ "$FILE_COUNT" -gt 50 ]; then
@@ -289,28 +316,27 @@ jobs:
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
$DIR_STATS"
fi
echo "File changes:"
echo "$FILE_CHANGES"
# 获取具体代码变化(关键文件的diff)
echo "Getting code diff for key files..."
# 定义关键目录(优先展示这些目录的变化)
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
# 获取变更的关键文件列表(排除测试、配置等)
# 使用 || true 防止 grep 无匹配时返回非零退出码
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
grep -E "\.(ts|js)$" || true | \
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
head -15) || true
CODE_DIFF=""
DIFF_CHAR_LIMIT=6000 # 总diff字符限制
DIFF_CHAR_LIMIT=6000
CURRENT_CHARS=0
if [ -n "$KEY_FILES" ]; then
for file in $KEY_FILES; do
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
@@ -318,21 +344,19 @@ jobs:
[... 更多文件变化已截断 ...]"
break
fi
# 获取单个文件的diff,限制每个文件最多50行
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
FILE_DIFF_LEN=${#FILE_DIFF}
# 如果单个文件diff超过1500字符,截断
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
FILE_DIFF="$FILE_DIFF
[... 文件 $file 变化已截断 ...]"
fi
if [ -n "$FILE_DIFF" ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
@@ -341,19 +365,19 @@ jobs:
fi
done
fi
# 如果没有关键文件变化,获取前5个变更文件的diff
if [ -z "$CODE_DIFF" ]; then
echo "No key files changed, getting top changed files..."
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "\.(ts|js|yml|md)$" | head -5) || true
if [ -n "$TOP_FILES" ]; then
for file in $TOP_FILES; do
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
@@ -362,12 +386,12 @@ jobs:
done
fi
fi
# 如果仍然没有代码变化,添加说明
if [ -z "$CODE_DIFF" ]; then
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
fi
echo "Code diff preview:"
echo "$CODE_DIFF" | head -50
@@ -378,16 +402,16 @@ jobs:
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
USER_CONTENT="当前版本: $CURRENT_TAG
上一版本: $PREV_TAG
## 提交列表
$COMMITS
## 文件变化统计
$SUMMARY_LINE
## 变更文件列表
$FILE_CHANGES
## 关键代码变化
$CODE_DIFF"
@@ -395,20 +419,19 @@ jobs:
BODY=$(jq -n \
--arg system "$SYSTEM_PROMPT" \
--arg user "$USER_CONTENT" \
--arg model "$OPENROUTER_MODEL" \
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:1500}')
--arg model "$OPENAI_MODEL" \
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
echo "=== OpenRouter request body ==="
echo "=== request body ==="
echo "$BODY" | jq .
# 调用 OpenRouter
if RESPONSE=$(curl -s -X POST "$OPENROUTER_API_URL" \
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
-H "Authorization: Bearer $OPENAI_KEY" \
-H "Content-Type: application/json" \
-d "$BODY"); then
echo "=== raw response ==="
echo "$RESPONSE"
echo "=== OpenRouter raw response ==="
echo "$RESPONSE"
echo "=== parsed response ==="
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
echo "$RESPONSE" | jq .
else
@@ -419,46 +442,47 @@ jobs:
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
if [ -z "$RELEASE_BODY" ]; then
echo "❌ OpenRouter failed to generate release note, using default.md"
# 替换默认模板中的版本占位符
echo "LLM failed to generate release note, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
else
# 后处理:确保版本号正确,并添加比较链接
echo -e "$RELEASE_BODY" > CHANGELOG.md
# 替换可能的占位符
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
fi
else
echo "❌ Curl failed, using default.md"
echo "Curl failed, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
fi
echo "=== generated release note ==="
cat CHANGELOG.md
- name: Create Release Draft and Upload Artifacts
uses: softprops/action-gh-release@v1
- name: Create Release and Upload Artifacts
uses: softprops/action-gh-release@v2
with:
name: NapCat ${{ github.ref_name }}
token: ${{ secrets.GITHUB_TOKEN }}
tag_name: ${{ inputs.version }}
name: NapCat ${{ inputs.version }}
body_path: CHANGELOG.md
files: |
NapCat.Shell.Windows.Node.zip
NapCat.Framework.zip
NapCat.Shell.zip
NapCat.Shell.Windows.OneKey.zip
draft: true
draft: false
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Update apifox
env:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm i --ignore-scripts
pnpm run build:openapi
# 使用 jq 安全地构建大型 JSON 数据并保存到文件
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
'{
input: $input,
@@ -471,10 +495,48 @@ jobs:
}
}' > apifox_payload.json
# 通过文件形式发送数据,避免命令行长度限制
curl --location -g --request POST 'https://api.apifox.com/v1/projects/5348325/import-openapi?locale=zh-CN' \
--header 'X-Apifox-Api-Version: 2024-03-28' \
--header "Authorization: Bearer $APIFOX_TOKEN" \
--header 'Content-Type: application/json' \
--data-binary @apifox_payload.json
- name: Publish release hash
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
set -euo pipefail
VERSION="${{ inputs.version }}"
HASH_REPO="NapNeko/napcat-release-hash"
gh auth setup-git
gh repo clone "$HASH_REPO" hash-repo
node .github/scripts/publish-release-hash.mjs \
--version "$VERSION" \
--shell "./artifacts/NapCat.Shell/napcat.mjs" \
--framework "./artifacts/NapCat.Framework/napcat.mjs" \
--file "./hash-repo/release.json"
cd hash-repo
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add release.json
if git diff --cached --quiet; then
echo "No changes to commit"
else
git commit -m "chore: update release hash for ${VERSION}"
git push origin HEAD:main || git push origin HEAD:master
fi
- name: Trigger downstream release workflows
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ inputs.version }}
run: |
echo "Triggering release-downstream workflow with tag_name=${VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-downstream.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"tag_name\":\"${VERSION}\"}}"
+53
View File
@@ -0,0 +1,53 @@
name: Release Tag
on:
workflow_dispatch:
push:
tags:
- 'v*'
permissions: write-all
jobs:
validate-version:
runs-on: ubuntu-latest
outputs:
valid: ${{ steps.check.outputs.valid }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Validate semantic version
id: check
run: |
TAG="${GITHUB_REF#refs/tags/}"
echo "Checking tag: $TAG"
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
echo "Valid semantic version: $TAG"
echo "valid=true" >> $GITHUB_OUTPUT
echo "version=$TAG" >> $GITHUB_OUTPUT
else
echo "Invalid version format: $TAG"
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
echo "valid=false" >> $GITHUB_OUTPUT
exit 1
fi
trigger-release:
needs: [validate-version]
if: needs.validate-version.outputs.valid == 'true'
runs-on: ubuntu-latest
steps:
- name: Trigger release-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
VERSION: ${{ needs.validate-version.outputs.version }}
run: |
echo "Triggering release-publish workflow with version=${VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"version\":\"${VERSION}\"}}"
+1
View File
@@ -21,3 +21,4 @@ tests/run/
guild1.db-wal
guild1.db-shm
packages/napcat-develop/config/.env
.claude
+1 -1
View File
@@ -6,7 +6,7 @@
"vite.config.ts": "vite*.ts",
"README.md": "CODE_OF_CONDUCT.md, RELEASES.md, CONTRIBUTING.md, CHANGELOG.md, SECURITY.md",
"tsconfig.json": "tsconfig.*.json, env.d.ts",
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, logo.png, .gitignore, LICENSE"
},
"css.customData": [
".vscode/tailwindcss.json"
+8 -10
View File
@@ -11,15 +11,9 @@ _Modern protocol-side framework implemented based on NTQQ._
---
## New Feature
## New Framework ?
在 v4.8.115+ 版本开始
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
可以试试更新更好用的 [SnowLuma](https://github.com/SnowLuma/SnowLuma) 作为NapCat Gui替代品。
## Welcome
@@ -53,7 +47,7 @@ _Modern protocol-side framework implemented based on NTQQ._
| Docs | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| QQ Group | [![QQ Group#4](https://img.shields.io/badge/QQ%20Group%234-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#3](https://img.shields.io/badge/QQ%20Group%233-Join-blue)](https://qm.qq.com/q/8zJMLjqy2Y) | [![QQ Group#2](https://img.shields.io/badge/QQ%20Group%232-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#1](https://img.shields.io/badge/QQ%20Group%231-Join-blue)](https://qm.qq.com/q/I6LU87a0Yq) |
| QQ Group | [![NapCat Family Group 4](https://img.shields.io/badge/NapCat%20Family%20Group%204-Join-blue)](https://qm.qq.com/q/E4nfkGD6oK) | [![NapCat Family Group 3](https://img.shields.io/badge/NapCat%20Family%20Group%203-Join-blue)](https://qm.qq.com/q/XyiyGPqa42) | [![NapCat Family Group 2](https://img.shields.io/badge/NapCat%20Family%20Group%202-Join-blue)](https://qm.qq.com/q/gq18RH7o7S) | [![NapCat Family Group 1](https://img.shields.io/badge/NapCat%20Family%20Group%201-Join-blue)](https://qm.qq.com/q/VwpnklcXqo) |
|:-:|:-:|:-:|:-:|:-:|
| Telegram | [![Telegram](https://img.shields.io/badge/Telegram-napcatqq-blue)](https://t.me/napcatqq) |
@@ -62,7 +56,11 @@ _Modern protocol-side framework implemented based on NTQQ._
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
社区相关日后会进一步加强审核,并严格限制一定时间的入群人数,请具备一定编程基础和问题解决能力再申请入群。
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
## Thanks
-1
View File
@@ -16,7 +16,6 @@
}
},
"dependencies": {
"ajv": "^8.13.0",
"file-type": "^21.0.0"
},
"devDependencies": {
+30 -30
View File
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
proxy?: string;
}
type Uri2LocalRes = {
export type Uri2LocalRes = {
success: boolean,
errMsg: string,
fileName: string,
path: string;
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
};
// 定义一个异步函数来检查文件是否存在
@@ -151,7 +152,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
const isTargetHttps = targetUrl.protocol === 'https:';
const proxyPort = parseInt(proxyUrl.port) || (proxyUrl.protocol === 'https:' ? 443 : 80);
// 代理认证头
const proxyAuthHeader = proxyUrl.username && proxyUrl.password
? { 'Proxy-Authorization': 'Basic ' + Buffer.from(`${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`).toString('base64') }
@@ -165,7 +166,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
method: 'CONNECT',
path: `${targetUrl.hostname}:${targetUrl.port || 443}`,
headers: {
'Host': `${targetUrl.hostname}:${targetUrl.port || 443}`,
Host: `${targetUrl.hostname}:${targetUrl.port || 443}`,
...proxyAuthHeader,
},
});
@@ -179,7 +180,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
// 在隧道上建立 TLS 连接
const tlsSocket = tls.connect({
socket: socket,
socket,
servername: targetUrl.hostname,
rejectUnauthorized: true,
}, () => {
@@ -187,14 +188,14 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
const requestPath = targetUrl.pathname + targetUrl.search;
const requestHeaders = {
...headers,
'Host': targetUrl.hostname,
'Connection': 'close',
Host: targetUrl.hostname,
Connection: 'close',
};
const headerLines = Object.entries(requestHeaders)
.map(([key, value]) => `${key}: ${value}`)
.join('\r\n');
const httpRequest = `GET ${requestPath} HTTP/1.1\r\n${headerLines}\r\n\r\n`;
tlsSocket.write(httpRequest);
});
@@ -209,19 +210,19 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
tlsSocket.on('data', (chunk: Buffer) => {
responseData = Buffer.concat([responseData, chunk]);
if (!headersParsed) {
const headerEndIndex = responseData.indexOf('\r\n\r\n');
if (headerEndIndex !== -1) {
headersParsed = true;
const headerStr = responseData.subarray(0, headerEndIndex).toString();
const headerLines = headerStr.split('\r\n');
// 解析状态码
const statusLine = headerLines[0];
const statusMatch = statusLine?.match(/HTTP\/\d\.\d\s+(\d+)/);
statusCode = statusMatch ? parseInt(statusMatch[1]!) : 0;
// 解析响应头
for (const line of headerLines.slice(1)) {
const [key, ...valueParts] = line.split(':');
@@ -232,7 +233,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
redirectLocation = value;
}
}
bodyData = responseData.subarray(headerEndIndex + 4);
}
} else {
@@ -243,18 +244,18 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
tlsSocket.on('end', () => {
// 处理重定向
if (statusCode >= 300 && statusCode < 400 && redirectLocation) {
const redirectUrl = redirectLocation.startsWith('http')
? redirectLocation
const redirectUrl = redirectLocation.startsWith('http')
? redirectLocation
: `${targetUrl.protocol}//${targetUrl.host}${redirectLocation}`;
httpDownloadWithProxy(redirectUrl, headers, proxy).then(resolve).catch(reject);
return;
}
if (statusCode !== 200) {
reject(new Error(`下载失败: ${statusCode}`));
return;
}
// 处理 chunked 编码
if (isChunked) {
resolve(parseChunkedBody(bodyData));
@@ -282,7 +283,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
path: url, // 完整 URL
headers: {
...headers,
'Host': targetUrl.hostname,
Host: targetUrl.hostname,
...proxyAuthHeader,
},
}, (response) => {
@@ -304,26 +305,26 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
function parseChunkedBody (data: Buffer): Buffer {
const chunks: Buffer[] = [];
let offset = 0;
while (offset < data.length) {
// 查找 chunk 大小行的结束
const lineEnd = data.indexOf('\r\n', offset);
if (lineEnd === -1) break;
const sizeStr = data.subarray(offset, lineEnd).toString().split(';')[0]; // 忽略 chunk 扩展
const chunkSize = parseInt(sizeStr!, 16);
if (chunkSize === 0) break; // 最后一个 chunk
const chunkStart = lineEnd + 2;
const chunkEnd = chunkStart + chunkSize;
if (chunkEnd > data.length) break;
chunks.push(data.subarray(chunkStart, chunkEnd));
offset = chunkEnd + 2; // 跳过 chunk 数据后的 \r\n
}
return Buffer.concat(chunks);
}
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
case FileUriType.Local: {
const fileExt = path.extname(HandledUri);
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
const tempFilePath = path.join(dir, filename + fileExt);
fs.copyFileSync(HandledUri, tempFilePath);
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
// 直接返回原始路径,不复制,避免不必要的 IO
return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
}
case FileUriType.Remote: {
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
fs.writeFileSync(filePath, buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
}
case FileUriType.Base64: {
const base64 = HandledUri.replace(/^base64:\/\//, '');
const base64Buffer = Buffer.from(base64, 'base64');
fs.writeFileSync(filePath, base64Buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
}
default:
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '', isLocal: false };
}
}
-1
View File
@@ -253,7 +253,6 @@ export async function getAllTags (mirror?: string): Promise<{ tags: string[], mi
return getAllTagsFromMirror('NapNeko', 'NapCatQQ', mirror);
}
export async function getLatestTag (mirror?: string): Promise<string> {
const { tags } = await getAllTags(mirror);
+1 -1
View File
@@ -21,4 +21,4 @@ export interface ILogWrapper {
logWarn (...args: any[]): void;
logFatal (...args: any[]): void;
logMessage (msg: unknown, selfInfo: unknown): void;
}
}
+8 -12
View File
@@ -1,7 +1,7 @@
/**
* GitHub 镜像配置模块
* 提供统一的镜像源管理,支持复杂网络环境
*
*
* 镜像源测试时间: 2026-01-03
* 测试通过: 55/61 完全可用
*/
@@ -17,7 +17,7 @@ import { PromiseTimer } from './helper';
* GitHub 文件加速镜像
* 用于加速 release assets 下载
* 按延迟排序,优先使用快速镜像
*
*
* 测试时间: 2026-01-03
* 镜像支持 301/302 重定向
* 懒加载测速:首次使用时自动测速,缓存 30 分钟
@@ -74,7 +74,7 @@ export const GITHUB_FILE_MIRRORS = [
* GitHub API 镜像
* 用于访问 GitHub API(作为备选方案)
* 注:优先使用非 API 方法,减少对 API 的依赖
*
*
* 经测试,大部分代理镜像不支持 API 转发
* 建议使用 getLatestReleaseTag 等方法避免 API 调用
*/
@@ -271,8 +271,6 @@ async function performMirrorTest (): Promise<string[]> {
.sort((a, b) => a.latency - b.latency)
.map(r => r.mirror);
// 至少返回原始 URL
if (successfulMirrors.length === 0) {
return [''];
@@ -287,7 +285,6 @@ async function performMirrorTest (): Promise<string[]> {
export function clearMirrorCache (): void {
cachedFastMirrors = null;
cacheTimestamp = 0;
}
/**
@@ -664,7 +661,7 @@ export function buildReleaseDownloadUrl (
/**
* 获取 GitHub release 信息(优先使用非 API 方法)
*
*
* 策略:
* 1. 先通过 git refs 获取 tags
* 2. 直接构建下载 URL,不依赖 API
@@ -725,7 +722,7 @@ export async function getGitHubRelease (
const response = await PromiseTimer(
RequestUtil.HttpGetJson<any>(url, 'GET', undefined, {
'User-Agent': 'NapCat',
'Accept': 'application/vnd.github.v3+json',
Accept: 'application/vnd.github.v3+json',
}),
currentConfig.timeout
);
@@ -958,7 +955,7 @@ async function getWorkflowRunsFromHtml (
allRuns.push({
id,
created_at: timeMatch[1],
title: title.trim()
title: title.trim(),
});
}
}
@@ -994,7 +991,7 @@ async function getWorkflowRunsFromHtml (
/**
* 通过 API 获取最新的 workflow runs,然后直接拼接 nightly.link 下载链接
* 无需解析 HTML,直接使用固定的 URL 格式
*
*
* 策略:
* 1. 优先使用 GitHub API
* 2. API 失败时,从 GitHub Actions HTML 页面解析
@@ -1042,7 +1039,6 @@ async function getArtifactsFromNightlyLink (
}
}
return { artifacts, mirror: runsMirror };
} catch {
return { artifacts: [], mirror: '' };
}
@@ -1051,7 +1047,7 @@ async function getArtifactsFromNightlyLink (
/**
* 获取 GitHub Action 最新运行的 artifacts
* 用于下载 nightly/dev 版本
*
*
* 策略:
* 1. 检查缓存(10分钟有效)
* 2. 优先尝试从 nightly.link 获取(无需认证,更稳定)
@@ -3,4 +3,4 @@ export interface ISubscription {
subscribe (listener: LogListener): void;
unsubscribe (listener: LogListener): void;
notify (msg: string): void;
}
}
+8 -3
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2021",
"module": "ESNext",
"moduleResolution": "Node",
"moduleResolution": "bundler",
"lib": [
"ES2021"
],
@@ -34,10 +34,15 @@
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"napcat-common/src/*": [
"../../packages/napcat-common/src/*"
],
"napcat-image-size/src/*": [
"../../packages/napcat-image-size/src/*"
],
"@/*": [
"../*"
"../../packages/*"
]
},
"skipLibCheck": true,
+201
View File
@@ -0,0 +1,201 @@
import path from 'node:path';
import { InstanceContext, NapCatCore } from '@/napcat-core/index';
import {
checkSqliteAvailable,
DatabaseHandle,
openDatabase,
decryptAndOpen,
readSingleDatabase,
scanAllDatabases,
formatScanResults,
decryptDatabaseFile,
type DatabaseScanResult,
type DatabaseReadOptions,
type TableInfo,
} from 'napcat-database';
type SQLInputValue = import('node:sqlite').SQLInputValue;
export class NTQQDatabaseApi {
context: InstanceContext;
core: NapCatCore;
constructor (context: InstanceContext, core: NapCatCore) {
this.context = context;
this.core = core;
}
/** node:sqlite 是否可用 */
async isSqliteAvailable (): Promise<boolean> {
return checkSqliteAvailable();
}
/** 获取当前账号的 nt_db 目录 */
getNtDbDir (): string {
return path.resolve(this.core.dataPath, this.core.selfInfo.uin, 'nt_qq', 'nt_db');
}
/**
* 获取解密缓存目录
* 默认: <NapCatDataPath>/db_<uin>/
* 可通过 customDir 完全自定义
*/
getDefaultCacheDir (customDir?: string): string {
if (customDir) return customDir;
return path.resolve(this.core.NapCatDataPath, `db_${this.core.selfInfo.uin}`);
}
/** 当前是否已获取到数据库 passphrase */
hasPassphrase (): boolean {
return !!this.core.dbPassphrase;
}
/** 获取 passphrase Buffer,未获取时返回 null */
getPassphraseBuffer (): Buffer | null {
return this.core.dbPassphrase ? Buffer.from(this.core.dbPassphrase) : null;
}
// ======================== SQLite 数据库操作 ========================
/**
* 打开一个已解密的 SQLite 数据库文件
* @param filePath 解密后 .db 文件路径
* @param readOnly 是否只读 (默认 true)
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
*/
openDecryptedDb (filePath: string, readOnly = true): DatabaseHandle {
return openDatabase(filePath, readOnly);
}
/**
* 解密并打开一个 NTQQ 加密数据库
* @param dbName 数据库文件名 (如 'nt_msg.db') 或完整路径
* @param readOnly 是否只读 (默认 true)
* @param cacheDir 自定义缓存目录,默认 db_<uin>
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
*/
openDatabase (dbName: string, readOnly = true, cacheDir?: string): DatabaseHandle | null {
const passphrase = this.getPassphraseBuffer();
if (!passphrase) return null;
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
return decryptAndOpen(dbPath, passphrase, resolvedCacheDir, readOnly);
}
/**
* 对加密数据库执行查询并自动关闭连接
* @param dbName 数据库文件名或完整路径
* @param sql SQL 查询语句
* @param params 绑定参数
* @returns 查询结果行数组,passphrase 不可用时返回 null
*/
query<T = Record<string, unknown>> (
dbName: string,
sql: string,
params?: SQLInputValue[] | Record<string, SQLInputValue>
): T[] | null {
const db = this.openDatabase(dbName);
if (!db) return null;
try {
return db.query<T>(sql, params);
} finally {
db.close();
}
}
/**
* 对加密数据库执行查询,仅返回第一行
* @param dbName 数据库文件名或完整路径
* @param sql SQL 查询语句
* @param params 绑定参数
*/
queryOne<T = Record<string, unknown>> (
dbName: string,
sql: string,
params?: SQLInputValue[] | Record<string, SQLInputValue>
): T | undefined | null {
const db = this.openDatabase(dbName);
if (!db) return null;
try {
return db.queryOne<T>(sql, params);
} finally {
db.close();
}
}
/**
* 对加密数据库执行非查询 SQL (INSERT/UPDATE/DELETE 等) 并自动关闭
* @param dbName 数据库文件名或完整路径
* @param sql SQL 语句
* @param params 绑定参数
*/
execute (
dbName: string,
sql: string,
params?: SQLInputValue[] | Record<string, SQLInputValue>
): { changes: number | bigint; lastInsertRowid: number | bigint; } | null {
const db = this.openDatabase(dbName, false);
if (!db) return null;
try {
return db.execute(sql, params);
} finally {
db.close();
}
}
// ======================== 批量扫描 ========================
/**
* 读取单个加密数据库的表信息
* @param dbName 数据库文件名 (如 'nt_msg.db'),或完整路径
* @param cacheDir 自定义缓存目录,默认 db_<uin>
* @param options 其他选项
*/
readDatabase (dbName: string, cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult | null {
const passphrase = this.getPassphraseBuffer();
if (!passphrase) return null;
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
return readSingleDatabase(dbPath, passphrase, { cacheDir: resolvedCacheDir, ...options });
}
/**
* 扫描所有加密数据库
* @param cacheDir 自定义缓存目录,默认 db_<uin>
* @param options 其他选项
*/
scanDatabases (cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult[] {
const passphrase = this.getPassphraseBuffer();
if (!passphrase) return [];
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
return scanAllDatabases(this.getNtDbDir(), passphrase, { cacheDir: resolvedCacheDir, ...options });
}
/**
* 仅解密数据库文件(不读取表信息,不需要 node:sqlite)
* @param dbName 数据库文件名或完整路径
* @param outputPath 输出路径,默认保存到 db_<uin>/<dbName>
*/
decryptDatabase (dbName: string, outputPath?: string): string | null {
const passphrase = this.getPassphraseBuffer();
if (!passphrase) return null;
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
const outPath = outputPath ?? path.resolve(this.getDefaultCacheDir(), path.basename(dbName));
return decryptDatabaseFile(dbPath, passphrase, outPath);
}
/** 格式化扫描结果为可读字符串 */
formatResults (results: DatabaseScanResult[]): string {
return formatScanResults(results);
}
}
export { DatabaseHandle };
export type { DatabaseScanResult, DatabaseReadOptions, TableInfo };
+1 -1
View File
@@ -33,7 +33,7 @@ export class NTQQFileApi {
'http://ss.xingzhige.com/music_card/rkey',
'https://secret-service.bietiaop.com/rkeys',
],
this.context.logger
this.context.logger
);
}
+132 -11
View File
@@ -12,11 +12,17 @@ import {
ShutUpGroupMember,
Peer,
ChatType,
GroupManagementSettings,
} from '@/napcat-core/index';
import { isNumeric, solveAsyncProblem } from 'napcat-common/src/helper';
import { LimitedHashTable } from 'napcat-common/src/message-unique';
import { CancelableTask, TaskExecutor } from 'napcat-common/src/cancel-task';
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
import {
createGroupDetailInfoV2Param,
createGroupExtFilter,
createGroupExtInfo,
createGroupManagementRequests,
} from '../data';
import { NTEventWrapper } from '../helper/event';
export class NTQQGroupApi {
@@ -24,12 +30,28 @@ export class NTQQGroupApi {
core: NapCatCore;
groupMemberCache: Map<string, Map<string, GroupMember>> = new Map<string, Map<string, GroupMember>>();
essenceLRU = new LimitedHashTable<number, string>(1000);
// psKey 滑动缓存,TTL 60 秒,惰性删除(不主动清理,等下次访问检测到过期再刷新)
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
constructor (context: InstanceContext, core: NapCatCore) {
this.context = context;
this.core = core;
}
/** 获取 qun.qq.com 域名的 psKey,滑动 TTL 60 秒(每次访问顺延) */
private async getQunPskey (): Promise<string> {
const now = Date.now();
if (this._qunPskeyCache && this._qunPskeyCache.expireAt > now) {
// 滑动 TTL:每次访问都顺延过期时间
this._qunPskeyCache.expireAt = now + 60 * 1000;
return this._qunPskeyCache.value;
}
// 过期或为空,惰性删除旧值(直接覆盖)并重新获取
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
this._qunPskeyCache = { value: psKey, expireAt: now + 60 * 1000 };
return psKey;
}
async setGroupRemark (groupCode: string, remark: string) {
return this.context.session.getGroupService().modifyGroupRemark(groupCode, remark);
}
@@ -75,7 +97,7 @@ export class NTQQGroupApi {
}
async fetchGroupEssenceList (groupCode: string) {
const pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const pskey = await this.getQunPskey();
return this.context.session.getGroupService().fetchGroupEssenceList({
groupCode,
pageStart: 0,
@@ -152,6 +174,54 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
}
async setGroupMemberInvitePolicy (
groupCode: string,
policy: NonNullable<GroupManagementSettings['memberInvite']>
) {
return this.modifyGroupManagementSettings(groupCode, { memberInvite: policy });
}
async setGroupMemberPermissions (
groupCode: string,
permissions: Pick<
GroupManagementSettings,
'allowMemberUploadAlbum' | 'allowMemberTemporarySession' | 'allowMemberCreateGroup'
>
) {
return this.modifyGroupManagementSettings(groupCode, permissions);
}
async setGroupNewMemberHistoryVisibility (groupCode: string, visible: boolean) {
return this.modifyGroupManagementSettings(groupCode, { newMembersSeeRecentHistory: visible });
}
private async modifyGroupManagementSettings (groupCode: string, settings: GroupManagementSettings) {
const results: Array<{ setting: string, result: GeneralCallResult; }> = [];
const changesKnownFlags = settings.memberInvite !== undefined ||
settings.allowMemberUploadAlbum !== undefined ||
settings.allowMemberTemporarySession !== undefined ||
settings.allowMemberCreateGroup !== undefined ||
settings.newMembersSeeRecentHistory !== undefined;
const currentDetail = changesKnownFlags ? await this.fetchGroupDetail(groupCode) : undefined;
for (const request of createGroupManagementRequests(
groupCode,
settings,
currentDetail?.privilegeFlag,
currentDetail?.groupFlagExt4
)) {
results.push({
setting: request.setting,
result: await this.context.session.getGroupService().modifyGroupDetailInfoV2(
request.param,
request.operationType
),
});
}
return results;
}
async setGroupSearch (groupCode: string, option: {
noCodeFingerOpenFlag?: number;
noFingerOpenFlag?: number;
@@ -227,6 +297,9 @@ export class NTQQGroupApi {
const updateCache = async () => {
try {
const members = await this.getGroupMemberAll(groupCode, true);
if (!members?.result?.infos) {
throw new Error(`errCode: ${members?.errCode}, errMsg: ${members?.errMsg}`);
}
this.groupMemberCache.set(groupCode, members.result.infos);
} catch (e) {
this.context.logger.logError(`刷新群成员缓存失败, 群号: ${groupCode}, 错误: ${e}`);
@@ -256,31 +329,57 @@ export class NTQQGroupApi {
// 获取群成员缓存
let members = this.groupMemberCache.get(groupCodeStr);
const cached = !!members;
if (!members) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
}
// 刚入的群可能拉不到成员列表,这时 members 为空,不能直接抛错,否则整条群消息都上报不出去
const getMember = () => {
if (!members) {
return undefined;
}
if (isNumeric(memberUinOrUidStr)) {
return Array.from(members!.values()).find(member => member.uin === memberUinOrUidStr);
return Array.from(members.values()).find(member => member.uin === memberUinOrUidStr);
} else {
return members!.get(memberUinOrUidStr);
return members.get(memberUinOrUidStr);
}
};
let member = getMember();
// 如果缓存中不存在该成员,尝试刷新缓存
if (!member) {
// 缓存里没有该成员(比如新入群),刷新一次;上面刚刷新过就不再重复拉取
if (!member && cached) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
member = getMember();
}
return member;
}
// 从已缓存的群成员里按 QQ 号找 uid,供 uin 转 uid 兜底
getUidFromMemberCache (uin: string) {
for (const members of this.groupMemberCache.values()) {
for (const [uid, member] of members) {
if (member.uin === uin) {
return uid;
}
}
}
return undefined;
}
async getGroupRecommendContactArkJson (groupCode: string) {
return this.context.session.getGroupService().getGroupRecommendContactArkJson(groupCode);
}
async getJoinGroupLink (groupCode: string, needShortUrl = true, srcId = 73, additionalParam = '') {
return this.context.session.getGroupService().getJoinGroupLink({
groupCode,
srcId,
needShortUrl,
additionalParam,
});
}
async creatGroupFileFolder (groupCode: string, folderName: string) {
return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
}
@@ -319,7 +418,7 @@ export class NTQQGroupApi {
}
async deleteGroupBulletin (groupCode: string, noticeId: string) {
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const psKey = await this.getQunPskey();
return this.context.session.getGroupService().deleteGroupBulletin(groupCode, psKey, noticeId);
}
@@ -414,6 +513,24 @@ export class NTQQGroupApi {
return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
}
// getGroupFileList also carries the group's used/total space in its call
// result's `groupSpaceResult`; a single-item fetch is enough to read it.
async getGroupFileSpace (groupCode: string) {
const [result] = await this.core.eventWrapper.callNormalEventV2(
'NodeIKernelRichMediaService/getGroupFileList',
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
[
groupCode,
{ sortType: 1, fileCount: 1, startIndex: 0, sortOrder: 1, showOnlinedocFolder: 0 },
],
() => true,
() => true,
1,
5000
);
return result?.groupSpaceResult;
}
async getArkJsonGroupShare (groupCode: string) {
const ret = await this.core.eventWrapper.callNoListenerEvent(
'NodeIKernelGroupService/getGroupRecommendContactArkJson',
@@ -423,7 +540,7 @@ export class NTQQGroupApi {
}
async uploadGroupBulletinPic (groupCode: string, imageurl: string) {
const _Pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const _Pskey = await this.getQunPskey();
return this.context.session.getGroupService().uploadGroupBulletinPic(groupCode, _Pskey, imageurl);
}
@@ -445,6 +562,10 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().quitGroup(groupCode);
}
async destroyGroup (groupCode: string) {
return this.context.session.getGroupService().destroyGroup(groupCode);
}
async kickMember (groupCode: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason);
}
@@ -466,8 +587,8 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
}
async setGroupName (groupCode: string, groupName: string) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
async setGroupName (groupCode: string, groupName: string, isNormalMember: boolean = false) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, isNormalMember);
}
async publishGroupBulletin (groupCode: string, content: string, picInfo: {
@@ -475,7 +596,7 @@ export class NTQQGroupApi {
width: number,
height: number;
} | undefined = undefined, pinned: number = 0, confirmRequired: number = 0) {
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com');
const psKey = await this.getQunPskey();
// text是content内容url编码
const data = {
text: encodeURI(content),
+1
View File
@@ -9,3 +9,4 @@ export * from './packet';
export * from './file';
export * from './online';
export * from './flash';
export * from './database';
+12
View File
@@ -67,6 +67,18 @@ export class NTQQMsgApi {
return this.context.session.getMsgService().fetchFavEmojiList('', num, true, true);
}
async addFavEmoji (req: Parameters<NodeIKernelMsgService['addFavEmoji']>[0]) {
return this.context.session.getMsgService().addFavEmoji(req);
}
async deleteFavEmoji (ids: string[]) {
return this.context.session.getMsgService().deleteFavEmoji(ids);
}
async modifyFavEmojiDesc (items: Parameters<NodeIKernelMsgService['modifyFavEmojiDesc']>[0]) {
return this.context.session.getMsgService().modifyFavEmojiDesc(items);
}
async queryMsgsWithFilterExWithSeq (peer: Peer, msgSeq: string) {
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
chatInfo: peer,
+1 -1
View File
@@ -114,7 +114,7 @@ export class NTQQOnlineApi {
fileElement: {
fileName: actualFolderName,
filePath: folderPath,
fileSize: "",
fileSize: '',
},
};
+18 -3
View File
@@ -36,7 +36,7 @@ export class NTQQPacketApi {
})
.catch((err) => {
this.logger.logError(err);
this.errStack.push(err);
this.pushError(err);
return false;
})) && this.pkt?.available;
}
@@ -46,7 +46,15 @@ export class NTQQPacketApi {
}
get clientLogStack () {
return this.pkt?.clientLogStack + '\n' + this.errStack.join('\n');
return [this.pkt?.clientLogStack, ...this.errStack].filter(Boolean).join('\n');
}
private pushError (error: unknown) {
if (error instanceof Error) {
this.errStack.push(error.stack || error.message);
return;
}
this.errStack.push(String(error));
}
async InitSendPacket (qqVer: string) {
@@ -67,10 +75,17 @@ export class NTQQPacketApi {
}
this.pkt = new PacketClientSession(this.core);
await this.pkt.init(process.pid, table.recv, table.send);
if (!this.pkt.available) {
const err = '[Core] [Packet] NativePacketClient 初始化失败,PacketBackend 发包能力不可用!';
this.logger.logError(err);
this.errStack.push(err);
return false;
}
try {
await this.pkt.operation.FetchRkey(1500);
await this.pkt.operation.FetchRkey(3000);
} catch (error) {
this.logger.logError('测试Packet状态异常', error);
this.pushError(error);
return false;
}
return true;
+1
View File
@@ -198,6 +198,7 @@ export class NTQQUserApi {
.add(() => this.context.session.getUixConvertService().getUid([uin]).then((data) => data.uidInfo.get(uin)))
.add(() => this.context.session.getProfileService().getUidByUin('FriendsServiceImpl', [uin]).get(uin))
.add(() => this.context.session.getGroupService().getUidByUins([uin]).then((data) => data.uids.get(uin)))
.add(() => this.core.apis.GroupApi.getUidFromMemberCache(uin))
.add(() => this.getUserDetailInfoByUin(uin).then((data) => data.detail.uid));
const uid = await fallback.run().catch(() => '');
+382 -48
View File
@@ -8,11 +8,25 @@ import {
WebHonorType, NapCatCore,
} from '@/napcat-core/index';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { basename } from 'node:path';
import { qunAlbumControl } from '../data/webapi';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { open, unlink, writeFile, type FileHandle } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
import { basename, join } from 'node:path';
import { qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl, QunAlbumBatch, nextQunAlbumBatchId } from '../data/webapi';
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
import { FFmpegService } from '../helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '../helper/ffmpeg/video';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
QzoneDeleteResponse,
QzonePublishResponse,
} from '../data/qzone';
export interface SetNoticeRetSuccess {
ec: number;
em: string;
@@ -24,6 +38,34 @@ export interface SetNoticeRetSuccess {
srv_code: number;
}
// 群相册分片上传的并发数
const QUN_ALBUM_SLICE_CONCURRENCY = 8;
// 服务端没给分片大小时的下限,以及防止异常值的上限
const QUN_ALBUM_SLICE_MIN = 16384;
const QUN_ALBUM_SLICE_MAX = 4 * 1024 * 1024;
// 流式计算文件摘要,避免为了算 MD5/SHA1 把整个文件读进内存(视频可能有几十上百 MB)
function hashFile (path: string, algorithm: 'md5' | 'sha1'): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash(algorithm);
createReadStream(path)
.on('data', chunk => hash.update(chunk))
.on('end', () => resolve(hash.digest('hex')))
.on('error', reject);
});
}
// 按需读取单个分片:并发上传时的内存占用只有「并发数 × 分片大小」
async function readSlice (handle: FileHandle, offset: number, length: number): Promise<Buffer> {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, offset);
// 读不满说明文件在上传过程中被改短了,继续传只会传上去一段补零的数据
if (bytesRead !== length) {
throw new Error(`读取分片失败: offset=${offset} 预期 ${length} 字节,实际 ${bytesRead} 字节`);
}
return buffer;
}
export class NTQQWebApi {
context: InstanceContext;
core: NapCatCore;
@@ -164,8 +206,6 @@ export class NTQQWebApi {
imgWidth: number = 540,
imgHeight: number = 300
) {
const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com');
try {
@@ -330,10 +370,14 @@ export class NTQQWebApi {
return (hash & 0x7FFFFFFF).toString();
}
async getAlbumListByNTQQ (gc: string) {
public getBknFromPSKey (psKey: string) {
return this.getBknFromSKey(psKey);
}
async getAlbumListByNTQQ (gc: string, attach_info: string = '') {
return await this.context.session.getAlbumService().getAlbumList({
qun_id: gc,
attach_info: '',
attach_info,
seq: 3331,
request_time_line: {
request_invoke_time: '0',
@@ -369,9 +413,11 @@ export class NTQQWebApi {
return response.data.album;
}
async createQunAlbumSession (gc: string, sAlbumID: string, sAlbumName: string, path: string, skey: string, pskey: string, img_md5: string, uin: string) {
const img = readFileSync(path);
const img_size = img.length;
async createQunAlbumSession (
gc: string, sAlbumID: string, sAlbumName: string, path: string,
skey: string, pskey: string, img_md5: string, uin: string, batch?: QunAlbumBatch
) {
const img_size = statSync(path).size;
const img_name = basename(path);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
@@ -384,42 +430,76 @@ export class NTQQWebApi {
img_name,
sAlbumName,
sAlbumID,
// 同批多图共用 batchId,并按「第几张 / 共几张」上报,相册里才会合并成同一条
batchId: batch?.batchId,
batchIndex: batch?.index,
photo_num: batch?.count,
batch_num: batch?.count,
});
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
const post = await RequestUtil.HttpGetJson<{ data: { session: string; }, ret: number, msg: string; }>(api, 'POST', body, {
const post = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 16384。
private resolveQunAlbumSliceSize (raw: unknown) {
const value = Number(raw);
if (!Number.isFinite(value) || value < QUN_ALBUM_SLICE_MIN) return QUN_ALBUM_SLICE_MIN;
return Math.min(value, QUN_ALBUM_SLICE_MAX);
}
async uploadQunAlbumSlice (
path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number,
options: { appid?: string, cmd?: string; } = {}
) {
const appid = options.appid ?? 'qun';
const cmd = options.cmd ?? 'FileUpload';
const img_size = statSync(path).size;
let seq = 0;
let offset = 0;
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const stream = createReadStream(path, { highWaterMark: slice_size });
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 MB 的图上要几十秒)
const slices: { seq: number, offset: number, end: number; }[] = [];
let seq = 0;
let offset = 0;
while (offset < img_size) {
const end = Math.min(offset + slice_size, img_size);
slices.push({ seq, offset, end });
offset = end;
seq++;
}
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
// 视频分片响应里会带 sVid,封面二段上传要靠它把封面挂到视频上
let sVid: string | undefined;
const handle = await open(path, 'r');
const uploadSlice = async (slice: { seq: number, offset: number, end: number; }) => {
const chunk = await readSlice(handle, slice.offset, slice.end - slice.offset);
const form = new FormData();
form.append('uin', uin);
form.append('appid', 'qun');
form.append('appid', appid);
form.append('session', session);
form.append('offset', offset.toString());
form.append('offset', slice.offset.toString());
form.append('data', new Blob([chunk], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('seq', slice.seq.toString());
form.append('end', slice.end.toString());
form.append('cmd', cmd);
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${GTK}`;
// 分片路径必须与 cmd 一致:视频走 /sliceUpload/FileUploadVideo,
// 否则服务端按图片处理,分片会「成功」但响应里没有 sVid
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${cmd}?seq=${slice.seq}&retry=0&offset=${slice.offset}&end=${slice.end}&total=${img_size}&type=form&g_tk=${GTK}`;
const response = await fetch(api, {
method: 'POST',
headers: {
@@ -432,24 +512,153 @@ export class NTQQWebApi {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string; }; if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
const post = await response.json() as { ret: number, msg: string, data?: { biz?: { sVid?: string; }; }; };
if (post.ret !== 0) {
throw new Error(`分片 ${slice.seq} 上传失败: ${post.msg}`);
}
offset += chunk.length;
seq++;
if (!sVid && typeof post.data?.biz?.sVid === 'string' && post.data.biz.sVid) {
sVid = post.data.biz.sVid;
}
};
try {
// 最后一片要等前面的全部传完再发:服务端收到最后一片就认为文件传完了,
// 并发时它可能比前面的分片先到
const lastSlice = slices.pop();
let next = 0;
let failure: { error: unknown; } | undefined;
// 固定数量的 worker 各自领下一片,慢的分片不会拖住整批
const worker = async () => {
while (!failure) {
const slice = slices[next++];
if (!slice) break;
try {
await uploadSlice(slice);
} catch (error) {
if (!failure) failure = { error };
}
}
};
await Promise.all(Array.from({ length: Math.min(QUN_ALBUM_SLICE_CONCURRENCY, slices.length) }, worker));
if (failure) throw failure.error;
if (lastSlice) await uploadSlice(lastSlice);
} finally {
await handle.close();
}
return { success: true, message: '上传完成' };
return { success: true, message: '上传完成', sVid };
}
// 多张图片一次上传:共用同一个 batchId,相册里显示为同一条
async uploadImagesToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, paths: string[]) {
if (!paths.length) throw new Error('上传列表为空');
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const uin = this.core.selfInfo.uin || '10001';
const batchId = nextQunAlbumBatchId();
const count = paths.length.toString();
for (const [index, path] of paths.entries()) {
const img_md5 = await hashFile(path, 'md5');
const post = await this.createQunAlbumSession(
gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin,
{ batchId, count, index: index.toString() }
);
if (!post.data?.session) throw new Error(`创建群相册会话失败: ${post.msg || post.ret}`);
await this.uploadQunAlbumSlice(path, post.data.session, skey, pskey, uin, this.resolveQunAlbumSliceSize(post.data.slice_size));
}
}
async uploadImageToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
await this.uploadImagesToQunAlbum(gc, sAlbumID, sAlbumName, [path]);
}
/**
* 上传视频到群相册。
*
* 分三步:
* 1. 建视频会话:appid=video_qun / cmd=FileUploadVideo / SHA1 校验,此时不带相册
* 2. 分片上传视频,从分片响应里拿 sVid
* 3. 按图片上传封面并用 vid 关联视频,相册和批次号在这一步带上,视频随封面进相册
*/
async uploadVideoToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const img_md5 = createHash('md5').update(readFileSync(path)).digest('hex');
const uin = this.core.selfInfo.uin || '10001';
const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
if (!session) throw new Error('创建群相册会话失败');
await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const video_sha1 = await hashFile(path, 'sha1');
// 时长:ffmpeg 不可用时上报 0
let playTime = 0;
try {
playTime = Math.max(0, Math.round(await FFmpegService.getDuration(path)));
} catch (e) {
this.context.logger.logWarn('获取视频时长失败,iPlayTime 上报 0', e);
}
// 1) 视频主体(不带相册,只传成素材)
const videoSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${video_sha1}?g_tk=${GTK}`, 'POST', qunAlbumVideoControl({
uin,
group_id: gc,
pskey,
video_sha1,
video_size: statSync(path).size,
play_time: playTime,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!videoSession.data?.session) throw new Error(`创建群相册视频会话失败: ${videoSession.msg || videoSession.ret}`);
const uploaded = await this.uploadQunAlbumSlice(path, videoSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(videoSession.data.slice_size), { appid: 'video_qun', cmd: 'FileUploadVideo' });
if (!uploaded.sVid) throw new Error('视频上传完成但未取得 sVid,无法挂进相册');
// 2) 封面:抽首帧,失败(含 ffmpeg 不可用)回落内置默认封面
// 用 .png:Native Addon 路径产出的就是 png(日志里可见 Detected format: png),
// 而命令行路径会按扩展名编码,两条路都能得到真正的 PNG
const coverPath = join(this.core.NapCatTempPath, `${randomUUID()}.png`);
try {
try {
await FFmpegService.extractThumbnail(path, coverPath);
} catch (e) {
this.context.logger.logWarn('提取视频封面失败,使用默认封面', e);
await writeFile(coverPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
// 3) 封面二段上传:这一步才带相册和批次号,视频靠它进相册
const cover_md5 = await hashFile(coverPath, 'md5');
const coverSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${cover_md5}?g_tk=${GTK}`, 'POST', qunAlbumVideoCoverControl({
uin,
group_id: gc,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size: statSync(coverPath).size,
vid: uploaded.sVid,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!coverSession.data?.session) throw new Error(`创建群相册视频封面会话失败: ${coverSession.msg || coverSession.ret}`);
await this.uploadQunAlbumSlice(coverPath, coverSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(coverSession.data.slice_size));
} finally {
if (existsSync(coverPath)) {
await unlink(coverPath);
}
}
}
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
@@ -477,10 +686,10 @@ export class NTQQWebApi {
const client_key = Date.now() * 1000;
return await this.context.session.getAlbumService().doQunComment(
random_seq, {
map_info: [],
map_bytes_info: [],
map_user_account: [],
},
map_info: [],
map_bytes_info: [],
map_user_account: [],
},
qunId,
2,
createAlbumMediaFeed(uin, albumId, lloc),
@@ -505,20 +714,145 @@ export class NTQQWebApi {
async doAlbumMediaLikeByNTQQ (
qunId: string,
albumId: string,
lloc: string,
id: string) {
batchId: string,
lloc: string | undefined,
isLike: boolean
) {
const random_seq = Math.floor(Math.random() * 9000) + 1000;
const uin = this.core.selfInfo.uin || '10001';
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${qunId}|${albumId}|${batchId}^||^421_1_0_${qunId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${qunId}|${albumId}|${batchId}`;
}
return await this.context.session.getAlbumService().doQunLike(
random_seq, {
map_info: [],
map_bytes_info: [],
map_user_account: [],
}, {
id,
status: 1,
},
createAlbumFeedPublish(qunId, uin, albumId, lloc)
random_seq,
{
map_info: [],
map_bytes_info: [],
map_user_account: [],
},
type,
{
id,
status,
},
createAlbumFeedPublish(qunId, uin, albumId, batchId)
);
}
private async getQzoneAuth () {
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const uin = this.core.selfInfo.uin || '10001';
const g_tk = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
return { skey, pskey, uin, g_tk, cookie };
}
/**
* 上传图片到 QQ 空间相册, 返回可用于发说说的 richval 字符串
* @param base64 图片Base64编码内容(不带data:前缀)
*/
async uploadImageToQzone (base64: string): Promise<string> {
const { skey, pskey, uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneUploadImageBody({ uin, skey, pskey, g_tk, base64 });
const api = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const resultText = await RequestUtil.HttpGetText(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
});
const parsed = parseQzoneUploadImageResponseText(resultText);
if (parsed.code !== undefined && parsed.code !== 0) {
throw new Error(parsed.msg || `QQ空间图片上传失败, code=${parsed.code}`);
}
if (!parsed.data) {
throw new Error('QQ空间图片上传失败, 响应缺少data字段');
}
return toQzoneRichval(parsed.data);
}
/**
* 发表QQ空间说说
* @param content 说说正文
* @param richvals 每张图片对应的richval数组, 为空表示纯文字说说
* @param ugcRight 查看权限 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见
* @param targetUins 权限作用QQ号数组, ugcRight为16/128时使用
*/
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: number[]) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const richval = richvals.length > 0 ? richvals.join('\t') : undefined;
const allowUins = targetUins && targetUins.length > 0 ? targetUins.join('|') : undefined;
const body = buildQzonePublishBody({
hostuin: uin,
content,
richval,
ugcRight,
allowUins,
});
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzonePublishResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzonePublishResponse(result);
}
/**
* 删除QQ空间说说
* @param tid 说说Tid, 来自 publishQzoneMsg 的返回值
*/
async deleteQzoneMsg (tid: string) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneDeleteBody({ hostuin: uin, tid });
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzoneDeleteResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzoneDeleteResponse(result);
}
async getDaySignedList (groupCode: string) {
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const selfUin = this.core.selfInfo.uin;
const cookie = `p_uin=o${selfUin}; p_skey=${pSkey}; uin=o${selfUin}`;
const post = await RequestUtil.HttpGetJson<{
retCode: number,
costTime: number,
response: {
ret?: {
code: string,
msg: string,
},
page?: {
infos?: {
uid: string,
uidGroupNick: string,
signedTimeStamp: string,
signInRank: number,
}[],
offset: number,
total: number,
}[],
},
funcCode: number,
}>(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${this.getBknFromPSKey(pSkey)}`, 'POST', {
dayYmd: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
}, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
}
+8 -17
View File
@@ -163,14 +163,14 @@ export interface AlbumFeedLikePublish {
};
cell_media: {
album_id: string;
batch_id: number;
media_items: Array<{
batch_id: string | number;
media_items?: {
type: number;
image: {
lloc: string;
sloc: string;
};
}>;
}[];
};
cell_qun_info: {
qun_id: string;
@@ -182,21 +182,19 @@ export interface AlbumFeedLikePublish {
* @param qunId 群号
* @param uin 用户QQ号
* @param albumId 相册ID
* @param lloc 信息
* @param sloc 信息(可选,默认与lloc相同)
* @param batchId 批次ID
* @returns 动态发布请求参数对象
*/
export function createAlbumFeedPublish (
qunId: string,
uin: string,
albumId: string,
lloc: string,
sloc?: string
): AlbumFeedLikePublish {
batchId: string
) {
return {
cell_common: {
time: Date.now(),
feed_id: '',
feed_id: `422_0_${batchId}`, // 需要补全feed_id
},
cell_user_info: {
user: {
@@ -205,14 +203,7 @@ export function createAlbumFeedPublish (
},
cell_media: {
album_id: albumId,
batch_id: 0,
media_items: [{
type: 0,
image: {
lloc,
sloc: sloc || lloc,
},
}],
batch_id: batchId,
},
cell_qun_info: {
qun_id: qunId,
+3 -3
View File
@@ -212,7 +212,7 @@ export enum UploadSceneType {
KUPLOADSCENEH5LAUNCHCLIENTSHORTCUTKEYCTRLCV,
KUPLOADSCENEAIODRAG,
KUPLOADSCENEAIOFILESELECTOR,
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
}
export interface StartFlashTaskRequests {
screen: number; // 1 PC-QQ
@@ -237,7 +237,7 @@ export interface StartFlashTaskRequests {
}
export enum BusiScene {
KBUSISCENEINVALID,
KBUSISCENEFLASHSCENE
KBUSISCENEFLASHSCENE,
}
export interface FileListInfoRequests {
seq: number, // 0
@@ -274,7 +274,7 @@ export enum DownloadSceneType {
KDOWNLOADSCENELINKOTHERINQQ,
KDOWNLOADSCENESCANQRCODE,
KDWONLOADSCENEFLASHTRANSFERCENTERCLIENT,
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA,
}
export interface FlashFileSetInfo {
fileSetId: string,
+139 -1
View File
@@ -1,4 +1,142 @@
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter, GroupManagementSettings } from '../types';
const MEMBER_INVITE_PRIVILEGE_MASK = 0x06100000;
const MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK = 0x1;
const MEMBER_CREATE_GROUP_FLAG = 0x8000;
const MEMBER_TEMPORARY_SESSION_FLAG = 0x10000;
const NEW_MEMBER_RECENT_HISTORY_FLAG = 0x4;
function mergeMaskedFlag (currentFlag: number, requestedFlag: number, maskValue: number): number {
const mask = BigInt(maskValue);
return Number((BigInt(currentFlag) & ~mask) | (BigInt(requestedFlag) & mask));
}
export function applyGroupManagementSettings (
param: GroupDetailInfoV2Param,
settings: GroupManagementSettings
): boolean {
let changed = false;
if (settings.memberInvite !== undefined) {
const privilegeByPolicy = {
disabled: 0x04000000,
require_approval: 0,
no_approval: 0x00100000,
no_approval_under_100: 0x02000000,
} satisfies Record<NonNullable<GroupManagementSettings['memberInvite']>, number>;
param.filter.allowMemberInvite = 1;
param.modifyInfo.allowMemberInvite = settings.memberInvite === 'disabled' ? 0 : 1;
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_INVITE_PRIVILEGE_MASK;
param.modifyInfo.appPrivilegeFlag |= privilegeByPolicy[settings.memberInvite];
changed = true;
}
if (settings.allowMemberUploadAlbum !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
if (!settings.allowMemberUploadAlbum) param.modifyInfo.appPrivilegeFlag |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
changed = true;
}
if (settings.allowMemberTemporarySession !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_TEMPORARY_SESSION_FLAG;
if (!settings.allowMemberTemporarySession) param.modifyInfo.appPrivilegeFlag |= MEMBER_TEMPORARY_SESSION_FLAG;
changed = true;
}
if (settings.allowMemberCreateGroup !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_CREATE_GROUP_FLAG;
if (!settings.allowMemberCreateGroup) param.modifyInfo.appPrivilegeFlag |= MEMBER_CREATE_GROUP_FLAG;
changed = true;
}
if (settings.newMembersSeeRecentHistory !== undefined) {
param.filter.groupFlagExt4 = 1;
param.filter.groupFlagExt4Mask = 1;
param.modifyInfo.groupFlagExt4Mask |= NEW_MEMBER_RECENT_HISTORY_FLAG;
if (settings.newMembersSeeRecentHistory) param.modifyInfo.groupFlagExt4 |= NEW_MEMBER_RECENT_HISTORY_FLAG;
changed = true;
}
return changed;
}
export function createGroupManagementRequests (
groupCode: string,
settings: GroupManagementSettings,
initialAppPrivilegeFlag = 0,
initialGroupFlagExt4 = 0
) {
const requests: Array<{ setting: string, param: GroupDetailInfoV2Param, operationType: number; }> = [];
const requestSettings: Array<{
setting: string,
value: GroupManagementSettings,
operationType: number;
}> = [
{ setting: 'member_invite', value: { memberInvite: settings.memberInvite }, operationType: 0 },
{
setting: 'new_members_see_recent_history',
value: { newMembersSeeRecentHistory: settings.newMembersSeeRecentHistory },
operationType: 0,
},
{
setting: 'allow_member_upload_album',
value: { allowMemberUploadAlbum: settings.allowMemberUploadAlbum },
operationType: 8,
},
{
setting: 'allow_member_temporary_session',
value: { allowMemberTemporarySession: settings.allowMemberTemporarySession },
operationType: 8,
},
{
setting: 'allow_member_create_group',
value: { allowMemberCreateGroup: settings.allowMemberCreateGroup },
operationType: 8,
},
];
let currentAppPrivilegeFlag = initialAppPrivilegeFlag;
let currentGroupFlagExt4 = initialGroupFlagExt4;
for (const requestSetting of requestSettings) {
const param = createGroupDetailInfoV2Param(groupCode);
if (applyGroupManagementSettings(param, requestSetting.value)) {
if (param.filter.appPrivilegeFlag) {
const nextAppPrivilegeFlag = mergeMaskedFlag(
currentAppPrivilegeFlag,
param.modifyInfo.appPrivilegeFlag,
param.modifyInfo.appPrivilegeMask
);
if (requestSetting.operationType === 8 && nextAppPrivilegeFlag === currentAppPrivilegeFlag) continue;
currentAppPrivilegeFlag = nextAppPrivilegeFlag;
// Linux NTQQ's wrapper builds this field from the current complete privilege value.
// Supplying only the targeted bit makes zero-valued clears get acknowledged but ignored.
param.modifyInfo.appPrivilegeFlag = currentAppPrivilegeFlag;
}
if (param.filter.groupFlagExt4) {
const nextGroupFlagExt4 = mergeMaskedFlag(
currentGroupFlagExt4,
param.modifyInfo.groupFlagExt4,
param.modifyInfo.groupFlagExt4Mask
);
if (nextGroupFlagExt4 === currentGroupFlagExt4) continue;
currentGroupFlagExt4 = nextGroupFlagExt4;
param.modifyInfo.groupFlagExt4 = currentGroupFlagExt4;
}
requests.push({ setting: requestSetting.setting, param, operationType: requestSetting.operationType });
}
}
return requests;
}
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
return {
+199
View File
@@ -0,0 +1,199 @@
/**
* QQ空间(Qzone)发说说/上传图片相关的纯数据构造与解析函数
* 不发起任何网络请求,方便单独测试
*/
export interface QzoneUploadImageParams {
uin: string;
skey: string;
pskey: string;
g_tk: string;
base64: string;
}
/**
* 构造上传图片到 QQ 空间的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image
*/
export function buildQzoneUploadImageBody (params: QzoneUploadImageParams): string {
const { uin, skey, pskey, g_tk, base64 } = params;
const backUrls = `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const query = new URLSearchParams({
filename: 'filename',
uin,
skey,
zzpaneluin: uin,
p_uin: uin,
p_skey: pskey,
uploadtype: '1',
albumtype: '7',
exttype: '0',
refer: 'shuoshuo',
output_type: 'jsonhtml',
charset: 'utf-8',
output_charset: 'utf-8',
upload_hd: '1',
hd_width: '2048',
hd_height: '10000',
hd_quality: '96',
backUrls,
base64: '1',
jsonhtml_callback: 'callback',
picfile: base64,
qzreferrer: `https://user.qzone.qq.com/${uin}/main`,
});
return query.toString();
}
export interface QzoneUploadImageData {
albumid: string;
lloc: string;
type: string;
height: string;
width: string;
url?: string;
}
export interface QzoneUploadImageRawResponse {
code?: number;
msg?: string;
data?: QzoneUploadImageData;
}
/**
* 解析上传图片接口返回的 `frameElement.callback({...});</script>` 包裹响应
*/
export function parseQzoneUploadImageResponseText (raw: string): QzoneUploadImageRawResponse {
const startTag = 'frameElement.callback';
const endTag = '</script>';
const startIdx = raw.indexOf(startTag);
const endIdx = raw.indexOf(endTag);
if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
throw new Error('QQ空间图片上传响应格式异常');
}
const segment = raw.slice(startIdx + startTag.length, endIdx);
const jsonStart = segment.indexOf('(');
const jsonEnd = segment.lastIndexOf(')');
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
throw new Error('QQ空间图片上传响应解析失败');
}
const jsonText = segment.slice(jsonStart + 1, jsonEnd);
try {
return JSON.parse(jsonText) as QzoneUploadImageRawResponse;
} catch {
throw new Error('QQ空间图片上传响应JSON解析失败');
}
}
/**
* 依据上传图片返回数据拼接 richval 字段
* 格式: ,albumid,lloc,sloc,type,height,width,,height,width (sloc 与 lloc 一致)
*/
export function toQzoneRichval (data: QzoneUploadImageData): string {
const { albumid, lloc, type, height, width } = data;
return `,${albumid},${lloc},${lloc},${type},${height},${width},,${height},${width}`;
}
export interface QzonePublishParams {
hostuin: string;
content: string;
/** 多张图片使用 \t 拼接后的 richval,无图时不传 */
richval?: string;
ugcRight: number;
/** ugc_right 为 16/128 时必填,多个QQ号使用 | 拼接 */
allowUins?: string;
}
/**
* 构造发表说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6
*/
export function buildQzonePublishBody (params: QzonePublishParams): string {
const { hostuin, content, richval, ugcRight, allowUins } = params;
const fields: Record<string, string> = {
syn_tweet_verson: '1',
paramstr: '1',
con: content,
feedversion: '1',
ver: '1',
ugc_right: String(ugcRight),
to_sign: '0',
hostuin,
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}/main`,
};
if (richval) {
fields['richtype'] = '1';
fields['richval'] = richval;
}
if (allowUins) {
fields['allow_uins'] = allowUins;
fields['who'] = '1';
}
return new URLSearchParams(fields).toString();
}
export interface QzonePublishResponse {
subcode?: number;
code?: number;
tid?: string;
t1_tid?: string;
message?: string;
msg?: string;
}
/**
* 解析发表说说接口返回的 JSON, 提取 tid
*/
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
}
const tid = json.t1_tid || json.tid;
if (!tid) {
throw new Error('QQ空间发说说失败, 未返回tid');
}
return { tid };
}
export interface QzoneDeleteParams {
hostuin: string;
tid: string;
}
/**
* 构造删除说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6
*/
export function buildQzoneDeleteBody (params: QzoneDeleteParams): string {
const { hostuin, tid } = params;
const fields: Record<string, string> = {
hostuin,
tid,
t1_source: '1',
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
};
return new URLSearchParams(fields).toString();
}
export interface QzoneDeleteResponse {
subcode?: number;
code?: number;
message?: string;
msg?: string;
}
/**
* 解析删除说说接口返回的 JSON
*/
export function parseQzoneDeleteResponse (json: QzoneDeleteResponse): { success: true; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间删说说失败, subcode=${subcode}`);
}
return { success: true };
}
+265 -55
View File
@@ -18,20 +18,64 @@ export interface BizReq {
iBatchID: number;
iBitmap: number;
iDistinctUse: number;
iNeedFeeds: number;
iNeedFeeds?: number;
iPicHight: number;
iPicWidth: number;
iUploadTime: number;
iUploadType: number;
iUpPicType: number;
iWaterType: number;
mapExt: MapExt;
mapExt?: MapExt;
mutliPicInfo?: MutliPicInfo;
sAlbumID: string;
sAlbumName: string;
sPicDesc: string;
sPicPath: string;
sPicTitle: string;
stExtendInfo: StExtendInfo;
stExtendInfo?: StExtendInfo;
// 视频主体上传专用
extend_info?: VideoExtendInfo;
iFlag?: number;
iIsFormatF20?: number;
iIsNew?: number;
iIsOriginalVideo?: number;
iPlayTime?: number;
sCoverUrl?: string;
sDesc?: string;
sTitle?: string;
// 视频封面二段上传专用
stExternalMapExt?: StExternalMapExt;
sExif_CameraMaker?: string;
sExif_CameraModel?: string;
sExif_Latitude?: string;
sExif_LatitudeRef?: string;
sExif_Longitude?: string;
sExif_LongitudeRef?: string;
sExif_Time?: string;
}
// 多图同批上传时描述「本批共几张 / 当前第几张」,相册里据此合并成同一条
export interface MutliPicInfo {
iBatUploadNum: string;
iCurUpload: string;
iSuccNum: number;
iFailNum: number;
}
// 视频主体上传用(视频不走 stExtendInfo.mapParams,而是这段扩展信息)
export interface VideoExtendInfo {
video_type: string;
domainid: string;
photo_num: string;
video_num: string;
batch_num: string;
qun_id: string;
}
// 视频封面二段上传用:声明这是客户端上传的封面,且与图片混合在同一条动态里
export interface StExternalMapExt {
is_client_upload_cover: string;
is_pic_video_mix_feeds: string;
}
export interface MapExt {
@@ -47,6 +91,8 @@ export interface MapParams {
batch_num: string;
photo_num: string;
video_num: string;
// 视频封面二段上传时用它把封面挂到已上传的视频上
vid?: string;
}
export interface Env {
@@ -60,6 +106,96 @@ export interface Token {
type: number;
}
// 一次上传的批次信息:同批的多张图必须共用 batchId,相册里才会显示成同一条。
export interface QunAlbumBatch {
batchId: number,
count: string,
index: string
}
let lastQunAlbumBatchId = 0;
// 批次号取秒级时间戳。同一秒里发起的两次上传要错开,不然会被相册并成同一条
export function nextQunAlbumBatchId () {
lastQunAlbumBatchId = Math.max(Math.floor(Date.now() / 1000), lastQunAlbumBatchId + 1);
return lastQunAlbumBatchId;
}
// control_req 的外层(鉴权、来源、会话),图片、视频、封面都一样
function buildQunAlbumControlReq (
{ uin, pskey, appid, checksum, check_type, file_len, refer = 'qzone', cmd }: {
uin: string,
pskey: string,
appid: string,
checksum: string,
check_type: number,
file_len: number,
refer?: string,
cmd?: string
},
biz_req: BizReq
): ControlReq {
const req: ControlReq = {
uin,
token: { type: 4, data: pskey, appid: 5 },
appid,
checksum,
check_type,
file_len,
env: { refer, deviceInfo: 'h5' },
model: 0,
biz_req,
session: '',
asy_upload: 0,
};
if (cmd) req.cmd = cmd;
return req;
}
// biz_req 里三种上传都要带的基础字段
function buildQunAlbumBizBase (
{ iUploadType, sAlbumName = '', sAlbumID = '', iBatchID = 0, sPicTitle = '' }: {
iUploadType: number,
sAlbumName?: string,
sAlbumID?: string,
iBatchID?: number,
sPicTitle?: string
}
): BizReq {
return {
sPicTitle,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType,
iUpPicType: 0,
iBatchID,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iUploadTime: Math.floor(Date.now() / 1000),
};
}
// 进相册的那一步(图片、视频封面)要带的群与批次信息
function buildQunAlbumFeedFields (group_id: string, mapParams: MapParams, batchIndex: string) {
return {
iNeedFeeds: 1,
mapExt: { appid: 'qun', userid: group_id },
stExtendInfo: { mapParams },
mutliPicInfo: {
iBatUploadNum: mapParams.batch_num,
iCurUpload: batchIndex,
iSuccNum: 0,
iFailNum: 0,
},
};
}
export function qunAlbumControl ({
uin,
group_id,
@@ -72,6 +208,8 @@ export function qunAlbumControl ({
photo_num = '1',
video_num = '0',
batch_num = '1',
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
}: {
uin: string,
group_id: string,
@@ -83,64 +221,21 @@ export function qunAlbumControl ({
sAlbumID: string,
photo_num?: string,
video_num?: string,
batch_num?: string
batch_num?: string,
batchId?: number,
batchIndex?: string
}
): {
control_req: ControlReq[]
} {
const timestamp = Math.floor(Date.now() / 1000);
return {
control_req: [
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
{
uin,
token: {
type: 4,
data: pskey,
appid: 5,
},
appid: 'qun',
checksum: pic_md5,
check_type: 0,
file_len: img_size,
env: {
refer: 'qzone',
deviceInfo: 'h5',
},
model: 0,
biz_req: {
sPicTitle: img_name,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: {
appid: 'qun',
userid: group_id,
},
stExtendInfo: {
mapParams: {
photo_num,
video_num,
batch_num,
},
},
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
}
)],
};
}
@@ -174,3 +269,118 @@ export function createStreamUpload (
},
};
}
/**
* 视频主体上传的控制体。
*
* 视频这一步不进相册(相册留空,iBatchID 为 0),只是先把视频传成素材;
* 分片响应里拿到 sVid 后,再由封面上传(qunAlbumVideoCoverControl)把视频挂进相册。
*/
export function qunAlbumVideoControl ({
uin,
group_id,
pskey,
video_sha1,
video_size,
play_time = 0,
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
video_sha1: string,
video_size: number,
play_time?: number,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'video_qun', checksum: video_sha1, check_type: 1, file_len: video_size, cmd: 'FileUploadVideo' },
{
...buildQunAlbumBizBase({ iUploadType: 3 }),
sTitle: '',
sDesc: '',
sCoverUrl: '',
iFlag: 0,
iPlayTime: play_time,
iIsNew: 111,
iIsOriginalVideo: 0,
iIsFormatF20: 0,
extend_info: {
video_type: '3',
domainid: '5',
photo_num,
video_num,
batch_num,
qun_id: group_id,
},
}
)],
};
}
/**
* 视频封面上传的控制体。
*
* 按图片上传,但 iUploadType 为 2,并用 mapParams.vid 指向已上传的视频。
* 相册和批次号只在这一步出现,视频是靠封面进的相册。
*/
export function qunAlbumVideoCoverControl ({
uin,
group_id,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size,
vid,
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
sAlbumName: string,
sAlbumID: string,
cover_md5: string,
cover_size: number,
vid: string,
batchId?: number,
batchIndex?: string,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: cover_md5, check_type: 0, file_len: cover_size, refer: 'huodong' },
{
...buildQunAlbumBizBase({ iUploadType: 2, sAlbumName, sAlbumID, iBatchID: batchId }),
...buildQunAlbumFeedFields(group_id, { vid, photo_num, video_num, batch_num }, batchIndex),
// 标明封面由客户端上传,且允许和图片出现在同一条动态里
stExternalMapExt: {
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
},
sExif_CameraMaker: '',
sExif_CameraModel: '',
sExif_Time: '',
sExif_LatitudeRef: '',
sExif_Latitude: '',
sExif_LongitudeRef: '',
sExif_Longitude: '',
}
)],
};
}
+258 -14
View File
@@ -395,12 +395,16 @@
"appid": 537319840,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"3.2.20-40768-arm64": {
"appid": 537319841,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"9.9.22-40768": {
"appid": 537319804,
"qua": "V1_WIN_NQ_9.9.22_40768_GW_B"
},
"6.9.82-40768": {
"appid": 537319829,
"appid": 537319828,
"qua": "V1_MAC_NQ_6.9.82_40768_GW_B"
},
"3.2.20-40824": {
@@ -416,23 +420,27 @@
"qua": "V1_MAC_NQ_6.9.82_40824_GW_B"
},
"6.9.82-40990": {
"appid": 537319880,
"appid": 537319879,
"qua": "V1_MAC_NQ_6.9.82_40990_GW_B"
},
"9.9.22-40990": {
"appid": 537319855,
"qua": "V1_WIN_NQ_9.9.22.40990_GW_B"
"qua": "V1_WIN_NQ_9.9.22_40990_GW_B"
},
"3.2.20-40990": {
"appid": 537319891,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"3.2.20-40990-arm64": {
"appid": 537319892,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"9.9.23-41679": {
"appid": 537320110,
"qua": "V1_WIN_NQ_9.9.23_41679_GW_B"
},
"6.9.83-41679": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41679_GW_B"
},
"9.9.23-41785": {
@@ -440,7 +448,7 @@
"qua": "V1_WIN_NQ_9.9.23_41785_GW_B"
},
"6.9.83-41785": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41785_GW_B"
},
"9.9.23-41857": {
@@ -451,20 +459,28 @@
"appid": 537320197,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"3.2.21-41857-arm64": {
"appid": 537320198,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"6.9.83-41857": {
"appid": 537320186,
"appid": 537320185,
"qua": "V1_MAC_NQ_6.9.83_41857_GW_B"
},
"3.2.21-42086": {
"appid": 537320248,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"3.2.21-42086-arm64": {
"appid": 537320249,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"9.9.23-42086": {
"appid": 537320212,
"qua": "V1_WIN_NQ_9.9.23_42086_GW_B"
},
"6.9.85-42086": {
"appid": 537320237,
"appid": 537320236,
"qua": "V1_MAC_NQ_6.9.85_42086_GW_B"
},
"9.9.23-42430": {
@@ -473,30 +489,34 @@
},
"9.9.25-42744": {
"appid": 537328470,
"qua": "V1_WIN_NQ_9.9.23_42744_GW_B"
"qua": "V1_WIN_NQ_9.9.25_42744_GW_B"
},
"6.9.86-42744": {
"appid": 537328495,
"qua": "V1_MAC_NQ_6.9.85_42744_GW_B"
"appid": 537328494,
"qua": "V1_MAC_NQ_6.9.86_42744_GW_B"
},
"9.9.25-42905": {
"appid": 537328521,
"qua": "V1_WIN_NQ_9.9.25_42905_GW_B"
},
"6.9.86-42905": {
"appid": 537328546,
"appid": 537328545,
"qua": "V1_MAC_NQ_6.9.86_42905_GW_B"
},
"3.2.22-42941": {
"appid": 537328659,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"3.2.22-42941-arm64": {
"appid": 537328660,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"9.9.25-42941": {
"appid": 537328623,
"qua": "V1_WIN_NQ_9.9.25_42941_GW_B"
},
"6.9.86-42941": {
"appid": 537328648,
"appid": 537328647,
"qua": "V1_MAC_NQ_6.9.86_42941_GW_B"
},
"9.9.26-44175": {
@@ -511,6 +531,14 @@
"appid": 537336639,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"3.2.23-44343-arm64": {
"appid": 537336640,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"6.9.87-44343": {
"appid": 537336627,
"qua": "V1_MAC_NQ_6.9.87_44343_GW_B"
},
"9.9.26-44498": {
"appid": 537337416,
"qua": "V1_WIN_NQ_9.9.26_44498_GW_B"
@@ -524,15 +552,231 @@
"qua": "V1_WIN_NQ_9.9.27_45627_GW_B"
},
"6.9.88-44725": {
"appid": 537337594,
"appid": 537337593,
"qua": "V1_MAC_NQ_6.9.88_44725_GW_B"
},
"3.2.25-45758": {
"appid": 537340249,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"3.2.25-45758-arm64": {
"appid": 537340250,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"6.9.89-45758": {
"appid": 537340237,
"qua": "V1_MAC_NQ_6.9.89_45758_GW_B"
},
"9.9.27-45758": {
"appid": 537340213,
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
},
"3.2.26-46494": {
"appid": 537345891,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"3.2.26-46494-arm64": {
"appid": 537345892,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"9.9.28-46494": {
"appid": 537345855,
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
},
"6.9.90-46494": {
"appid": 537345879,
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
},
"3.2.26-46928": {
"appid": 537345993,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"3.2.26-46928-arm64": {
"appid": 537345994,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"6.9.91-46928": {
"appid": 537345981,
"qua": "V1_MAC_NQ_6.9.91_46928_GW_B"
},
"9.9.28-46928": {
"appid": 537345957,
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
},
"3.2.27-47256": {
"appid": 537346857,
"qua": "V1_LNX_NQ_3.2.27_47256_GW_B"
},
"3.2.27-47354": {
"appid": 537346908,
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
},
"9.9.29-47354": {
"appid": 537346872,
"qua": "V1_WIN_NQ_9.9.29_47354_GW_B"
},
"6.9.93-47354": {
"appid": 537346896,
"qua": "V1_MAC_NQ_6.9.93_47354_GW_B"
},
"9.9.30-48517": {
"appid": 537352474,
"qua": "V1_WIN_NQ_9.9.30_48517_GW_B"
},
"3.2.28-48517": {
"appid": 537352510,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"3.2.28-48517-arm64": {
"appid": 537352511,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"6.9.95-48517": {
"appid": 537352498,
"qua": "V1_MAC_NQ_6.9.95_48517_GW_B"
},
"9.9.30-48762": {
"appid": 537352525,
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
},
"9.9.31-49599": {
"appid": 537355779,
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
},
"9.9.31-49738": {
"appid": 537355830,
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
},
"3.2.29-49738": {
"appid": 537355866,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"3.2.29-49738-arm64": {
"appid": 537355867,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"6.9.96-49738": {
"appid": 537355854,
"qua": "V1_MAC_NQ_6.9.96_49738_GW_B"
},
"9.9.32-50828": {
"appid": 537358739,
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
},
"3.2.30-50828": {
"appid": 537358775,
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
},
"3.2.30-50828-arm64": {
"appid": 537358776,
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
},
"9.9.32-50969": {
"appid": 537376308,
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
},
"3.2.30-50969": {
"appid": 537376344,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.30-50969-arm64": {
"appid": 537376345,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.31-51102": {
"appid": 537376497,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"3.2.31-51102-arm64": {
"appid": 537376498,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"6.9.98-51102": {
"appid": 537376485,
"qua": "V1_MAC_NQ_6.9.98_51102_GW_B"
},
"9.9.32-51246": {
"appid": 537376512,
"qua": "V1_WIN_NQ_9.9.32_51246_GW_B"
},
"3.2.32-51728": {
"appid": 537376803,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51728-arm64": {
"appid": 537376804,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51802": {
"appid": 537376854,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"3.2.32-51802-arm64": {
"appid": 537376855,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"6.9.99-51802": {
"appid": 537376842,
"qua": "V1_MAC_NQ_6.9.99_51802_GW_B"
},
"9.9.33-51802": {
"appid": 537376818,
"qua": "V1_WIN_NQ_9.9.33_51802_GW_B"
},
"9.9.33-52230": {
"appid": 537379411,
"qua": "V1_WIN_NQ_9.9.33_52230_GW_B"
},
"3.2.32-52194": {
"appid": 537379447,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"3.2.32-52194-arm64": {
"appid": 537379448,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"7.0.0-52194": {
"appid": 537379435,
"qua": "V1_MAC_NQ_7.0.0_52194_GW_B"
},
"9.9.35-52804": {
"appid": 537382717,
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
},
"9.9.35-52892": {
"appid": 537382819,
"qua": "V1_WIN_NQ_9.9.35_52892_GW_B"
},
"9.9.36-53489": {
"appid": 537391475,
"qua": "V1_WIN_NQ_9.9.36_53489_GW_B"
},
"3.2.33-52892": {
"appid": 537382855,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"3.2.33-52892-arm64": {
"appid": 537382856,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"7.0.1-52892": {
"appid": 537382843,
"qua": "V1_MAC_NQ_7.0.1_52892_GW_B"
},
"3.2.34-53644": {
"appid": 537391664,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"3.2.34-53644-arm64": {
"appid": 537391665,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"7.0.2-53644": {
"appid": 537391652,
"qua": "V1_MAC_NQ_7.0.2_53644_GW_B"
},
"9.9.36-53644": {
"appid": 537391628,
"qua": "V1_WIN_NQ_9.9.36_53644_GW_B"
}
}
}
+165
View File
@@ -2593,6 +2593,171 @@
"AniStickerType": 1,
"AniStickerPackId": "1",
"AniStickerId": "59"
},
{
"QSid": "450",
"QDes": "/撇嘴",
"EMCode": "10450"
},
{
"QSid": "451",
"QDes": "/色",
"EMCode": "10451"
},
{
"QSid": "452",
"QDes": "/微笑",
"EMCode": "10452"
},
{
"QSid": "453",
"QDes": "/发呆",
"EMCode": "10453"
},
{
"QSid": "454",
"QDes": "/得意",
"EMCode": "10454"
},
{
"QSid": "455",
"QDes": "/害羞",
"EMCode": "10455"
},
{
"QSid": "456",
"QDes": "/闭嘴",
"EMCode": "10456"
},
{
"QSid": "457",
"QDes": "/睡",
"EMCode": "10457"
},
{
"QSid": "458",
"QDes": "/我吗",
"EMCode": "10458"
},
{
"QSid": "459",
"QDes": "/优雅",
"EMCode": "10459"
},
{
"QSid": "460",
"QDes": "/硬撑",
"EMCode": "10460"
},
{
"QSid": "461",
"QDes": "/宕机",
"EMCode": "10461"
},
{
"QSid": "462",
"QDes": "/无语",
"EMCode": "10462"
},
{
"QSid": "463",
"QDes": "/新年快乐",
"EMCode": "10463"
},
{
"QSid": "464",
"QDes": "/马上到",
"EMCode": "10464"
},
{
"QSid": "465",
"QDes": "/拆红包",
"EMCode": "10465"
},
{
"QSid": "466",
"QDes": "/羞羞哒",
"EMCode": "10466"
},
{
"QSid": "467",
"QDes": "/摇花手",
"EMCode": "10467"
},
{
"QSid": "468",
"QDes": "/失眠",
"EMCode": "10468"
},
{
"QSid": "469",
"QDes": "/坚毅",
"EMCode": "10469"
},
{
"QSid": "470",
"QDes": "/马到成功",
"EMCode": "10470"
},
{
"QSid": "472",
"QDes": "/心动",
"EMCode": "10472"
},
{
"QSid": "474",
"QDes": "/给你一拳",
"EMCode": "10474"
},
{
"QSid": "475",
"QDes": "/干饭",
"EMCode": "10475"
},
{
"QSid": "476",
"QDes": "/不是吧",
"EMCode": "10476"
},
{
"QSid": "477",
"QDes": "/你懂的",
"EMCode": "10477"
},
{
"QSid": "478",
"QDes": "/对的对的",
"EMCode": "10478"
},
{
"QSid": "479",
"QDes": "/不对不对",
"EMCode": "10479"
},
{
"QSid": "480",
"QDes": "/散味儿",
"EMCode": "10480"
},
{
"QSid": "481",
"QDes": "/学习",
"EMCode": "10481"
},
{
"QSid": "482",
"QDes": "/热化了",
"EMCode": "10482"
},
{
"QSid": "483",
"QDes": "/略",
"EMCode": "10483"
},
{
"QSid": "484",
"QDes": "/比爱心",
"EMCode": "10484"
}
],
"emoji": [
+9 -1
View File
@@ -5,5 +5,13 @@
"consoleLogLevel": "info",
"packetBackend": "auto",
"packetServer": "",
"o3HookMode": 0
"o3HookMode": 1,
"bypass": {
"hook": false,
"window": false,
"module": false,
"process": false,
"container": false,
"js": false
}
}
+228 -4
View File
@@ -64,7 +64,7 @@
"recv": "1D19FF9"
},
"6.9.83-41857-arm64": {
"send": "0815774",
"send": "23B41F0",
"recv": "0958B3C"
},
"3.2.21-41857-x64": {
@@ -85,7 +85,7 @@
},
"6.9.85-42086-arm64": {
"send": "23B0330",
"recv": "0957648"
"recv": "9556B8"
},
"3.2.21-42086-arm64": {
"send": "3D6D98C",
@@ -103,7 +103,7 @@
"send": "0A0D104",
"recv": "1D3E7F9"
},
"6.9.85-42744-arm64": {
"6.9.86-42744-arm64": {
"send": "23DFEF0",
"recv": "095FD80"
},
@@ -147,6 +147,10 @@
"send": "59A27B0",
"recv": "2FFBE90"
},
"6.9.87-44343-arm64": {
"send": "2311B68",
"recv": "9673A4"
},
"9.9.26-44498-x64": {
"send": "0A1051C",
"recv": "1D3BC0D"
@@ -175,8 +179,228 @@
"send": "3EB6554",
"recv": "149AF0C"
},
"6.9.89-45758-arm64": {
"send": "2425228",
"recv": "9B6770"
},
"9.9.27-45758-x64": {
"send": "0A6A6BC",
"recv": "1E87EC1"
},
"9.9.28-46494-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.26-46494-x64": {
"send": "5D30910",
"recv": "31814B0"
},
"3.2.26-46494-arm64": {
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.90-46494-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"3.2.26-46928-x64": {
"send": "5D30910",
"recv": "31814B0"
},
"3.2.26-46928-arm64": {
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.91-46928-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"9.9.28-46928-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.27-47256-x64": {
"send": "5D389C0",
"recv": "318D090"
},
"3.2.27-47354-x64": {
"send": "5D38930",
"recv": "318D090"
},
"3.2.27-47354-arm64": {
"send": "3EE8B24",
"recv": "14D422C"
},
"9.9.29-47354-x64": {
"send": "0A70B3C",
"recv": "1EAFD51"
},
"6.9.93-47354-arm64": {
"send": "244066C",
"recv": "09BCCF8"
},
"6.9.93-47354-x64": {
"send": "28ADE46",
"recv": "0A8FD5A"
},
"9.9.30-48517-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
},
"3.2.28-48517-x64": {
"send": "5E41890",
"recv": "3216D10"
},
"3.2.28-48517-arm64": {
"send": "3F9C7E4",
"recv": "14E1AA8"
},
"6.9.95-48517-arm64": {
"send": "25120A8",
"recv": "9DB00C"
},
"9.9.30-48762-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
},
"9.9.31-49599-x64": {
"send": "0AF885C",
"recv": "20058E1"
},
"9.9.31-49738-x64": {
"send": "0AF9FCC",
"recv": "2007901"
},
"3.2.29-49738-x64": {
"send": "6234600",
"recv": "33D89D0"
},
"3.2.29-49738-arm64": {
"send": "426AA04",
"recv": "1596254"
},
"6.9.96-49738-arm64": {
"send": "2785BB8",
"recv": "A29880"
},
"9.9.32-50828-x64": {
"send": "0B245CC",
"recv": "2073D65"
},
"3.2.30-50828-x64": {
"send": "6340530",
"recv": "346DA50"
},
"3.2.30-50828-arm64": {
"send": "4327764",
"recv": "15e3184"
},
"9.9.32-50969-x64": {
"send": "0B2E2AC",
"recv": "209C709"
},
"3.2.30-50969-x64": {
"send": "63F47B0",
"recv": "34B9E30"
},
"3.2.30-50969-arm64": {
"send": "43A4804",
"recv": "1608CC8"
},
"3.2.31-51102-x64": {
"send": "63F4910",
"recv": "34B9F90"
},
"3.2.31-51102-arm64": {
"send": "43A48E4",
"recv": "1608D98"
},
"6.9.98-51102-arm64": {
"send": "2849378",
"recv": "A66CFC"
},
"9.9.32-51246-x64": {
"send": "B2E37C",
"recv": "209C7D9"
},
"3.2.32-51728-arm64": {
"send": "48CA8F8",
"recv": "17D5A78"
},
"3.2.32-51728-x64": {
"send": "6B9ADD0",
"recv": "38F5F30"
},
"3.2.32-51802-x64": {
"send": "6B9B790",
"recv": "38F68F0"
},
"3.2.32-51802-arm64": {
"send": "48CB078",
"recv": "17D620C"
},
"6.9.99-51802-arm64": {
"send": "2B0B384",
"recv": "B4526C"
},
"9.9.33-51802-x64": {
"send": "BDE15F",
"recv": "237BC91"
},
"9.9.33-52230-x64": {
"send": "BF2B5F",
"recv": "23BB4DD"
},
"3.2.32-52194-x64": {
"send": "6C45D20",
"recv": "393DE00"
},
"3.2.32-52194-arm64": {
"send": "493FAD8",
"recv": "17EA1DC"
},
"7.0.0-52194-arm64": {
"send": "2B3FBA4",
"recv": "B4E85C"
},
"9.9.35-52804-x64": {
"send": "C3614F",
"recv": "246F481"
},
"9.9.35-52892-x64": {
"send": "C361DF",
"recv": "246F3A1"
},
"9.9.36-53489-x64": {
"send": "C3ED0F",
"recv": "24A6235"
},
"3.2.33-52892-x64": {
"send": "6DDB4C0",
"recv": "39DA860"
},
"3.2.33-52892-arm64": {
"send": "4A5D658",
"recv": "1813A34"
},
"7.0.1-52892-arm64": {
"send": "2B3FBCC",
"recv": "B64170"
},
"3.2.34-53644-x64": {
"send": "6E5AB20",
"recv": "3A12CD0"
},
"3.2.34-53644-arm64": {
"send": "4AABA5C",
"recv": "182C534"
},
"7.0.2-53644-arm64": {
"send": "2B82DEC",
"recv": "B71088"
},
"9.9.36-53644-x64": {
"send": "C3EE2F",
"recv": "24A6355"
}
}
}
+235 -7
View File
@@ -528,8 +528,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40768-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.22-40824-x64": {
"send": "31C1838",
@@ -540,8 +540,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40824-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"3.2.20-40990-x64": {
"send": "B69CFE0",
@@ -556,8 +556,8 @@
"recv": "31C4FDC"
},
"6.9.82-40990-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.23-41679-x64": {
"send": "2C94520",
@@ -603,6 +603,10 @@
"send": "6B13038",
"recv": "6B169C8"
},
"6.9.85-42086-arm64": {
"send": "3D6D028",
"recv": "3D6F938"
},
"9.9.23-42430-x64": {
"send": "2C9A4A0",
"recv": "2C9DA20"
@@ -655,6 +659,10 @@
"send": "6926F60",
"recv": "692A910"
},
"6.9.87-44343-arm64": {
"send": "3D74F50",
"recv": "3D77860"
},
"9.9.26-44498-x64": {
"send": "2CDAE40",
"recv": "2CDE3C0"
@@ -686,5 +694,225 @@
"3.2.25-45758-arm64": {
"send": "6D6F9A0",
"recv": "6D73350"
},
"6.9.89-45758-arm64": {
"send": "3F9BD68",
"recv": "3F9E678"
},
"3.2.26-46494-x64": {
"send": "AB341C0",
"recv": "AB37C60"
},
"9.9.28-46494-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.26-46494-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
},
"6.9.90-46494-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"3.2.26-46928-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
},
"3.2.26-46928-x64": {
"send": "AB341C0",
"recv": "AB37C60"
},
"6.9.91-46928-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"9.9.28-46928-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.27-47256-x64": {
"send": "AB6A7E0",
"recv": "AB6E280"
},
"3.2.27-47354-x64": {
"send": "AB6A6C0",
"recv": "AB6E160"
},
"3.2.27-47354-arm64": {
"send": "6DE1438",
"recv": "6DE4DE8"
},
"9.9.29-47354-x64": {
"send": "2E84920",
"recv": "2E87EA0"
},
"6.9.93-47354-arm64": {
"send": "3FD1E98",
"recv": "3FD47A8"
},
"6.9.93-47354-x64": {
"send": "47CD940",
"recv": "47D04F0"
},
"3.2.28-48517-x64": {
"send": "AD7C280",
"recv": "AD7FD20"
},
"9.9.30-48517-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
},
"3.2.28-48517-arm64": {
"send": "6F48B70",
"recv": "6F4C520"
},
"6.9.95-48517-arm64": {
"send": "40A0438",
"recv": "40A2D48"
},
"9.9.30-48762-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
},
"9.9.31-49599-x64": {
"send": "3082C40",
"recv": "30861C8"
},
"9.9.31-49738-x64": {
"send": "3086C80",
"recv": "308A208"
},
"3.2.29-49738-x64": {
"send": "B3B20A0",
"recv": "B3B5B40"
},
"3.2.29-49738-arm64": {
"send": "7342800",
"recv": "73461B0"
},
"6.9.96-49738-arm64": {
"send": "428B660",
"recv": "428DF70"
},
"9.9.32-50828-x64": {
"send": "3155200",
"recv": "3158788"
},
"3.2.30-50828-arm64": {
"send": "74C3070",
"recv": "74C6A20"
},
"3.2.30-50828-x64": {
"send": "B5D0FC0",
"recv": "B5D4A60"
},
"9.9.32-50969-x64": {
"send": "31994E0",
"recv": "319CA68"
},
"3.2.30-50969-x64": {
"send": "B7394C0",
"recv": "B73CF60"
},
"3.2.30-50969-arm64": {
"send": "75BD1D0",
"recv": "75C0B80"
},
"3.2.31-51102-x64": {
"send": "B739780",
"recv": "B73D220"
},
"3.2.31-51102-arm64": {
"send": "75BD390",
"recv": "75C0D40"
},
"6.9.98-51102-arm64": {
"send": "4419468",
"recv": "441BD78"
},
"9.9.32-51246-x64": {
"send": "3199680",
"recv": "319CC08"
},
"3.2.32-51728-arm64": {
"send": "8009330",
"recv": "800CCE0"
},
"3.2.32-51728-x64": {
"send": "C6860E0",
"recv": "C689B80"
},
"3.2.32-51802-x64": {
"send": "C687460",
"recv": "C68AF00"
},
"3.2.32-51802-arm64": {
"send": "800A230",
"recv": "800DBE0"
},
"6.9.99-51802-arm64": {
"send": "499CF40",
"recv": "499FA40"
},
"9.9.33-51802-x64": {
"send": "360A0D8",
"recv": "360D88C"
},
"9.9.33-52230-x64": {
"send": "367FE18",
"recv": "36835CC"
},
"3.2.32-52194-x64": {
"send": "C7DBF80",
"recv": "C7DFA20"
},
"3.2.32-52194-arm64": {
"send": "80F36D0",
"recv": "80F7080"
},
"7.0.0-52194-arm64": {
"send": "4A05FB0",
"recv": "4A08AB0"
},
"9.9.35-52804-x64": {
"send": "37C3298",
"recv": "37C6A4C"
},
"9.9.35-52892-x64": {
"send": "37C30D8",
"recv": "37C688C"
},
"9.9.36-53489-x64": {
"send": "38253B0",
"recv": "3828BF0"
},
"3.2.33-52892-x64": {
"send": "CB06D60",
"recv": "CB0A800"
},
"3.2.33-52892-arm64": {
"send": "832ECA0",
"recv": "8332650"
},
"7.0.1-52892-arm64": {
"send": "4B1E4B8",
"recv": "4B20FB8"
},
"3.2.34-53644-x64": {
"send": "CBF25A0",
"recv": "CBF60E0"
},
"3.2.34-53644-arm64": {
"send": "83D1BD0",
"recv": "83D5610"
},
"7.0.2-53644-arm64": {
"send": "4BA3870",
"recv": "4BA6388"
},
"9.9.36-53644-x64": {
"send": "38255F0",
"recv": "3828E30"
}
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: Lo
return {
converted: true,
path: pttPath,
duration: duration,
duration,
};
} else {
let duration = 0;
+20 -10
View File
@@ -2,22 +2,24 @@ import path from 'node:path';
import fs from 'node:fs';
import type { NapCatCore } from '@/napcat-core';
import json5 from 'json5';
import Ajv, { AnySchema, ValidateFunction } from 'ajv';
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { TSchema } from '@sinclair/typebox';
export abstract class ConfigBase<T> {
name: string;
core: NapCatCore;
configPath: string;
configData: T = {} as T;
ajv: Ajv;
validate: ValidateFunction<T>;
configSchema: TSchema;
validate: TypeCheck<TSchema>;
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: AnySchema) {
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: TSchema) {
this.name = name;
this.core = core;
this.configPath = configPath;
this.ajv = new Ajv({ useDefaults: true, coerceTypes: true });
this.validate = this.ajv.compile<T>(ConfigSchema);
this.configSchema = ConfigSchema;
this.validate = TypeCompiler.Compile(ConfigSchema);
fs.mkdirSync(this.configPath, { recursive: true });
this.read();
}
@@ -43,8 +45,12 @@ export abstract class ConfigBase<T> {
private loadConfig (configPath: string): T {
try {
const newConfigData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
this.validate(newConfigData);
this.configData = newConfigData;
let data: unknown = newConfigData;
data = Value.Parse(this.configSchema, data);
if (!this.validate.Check(data)) {
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
}
this.configData = data as T;
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
return this.configData;
} catch (e: unknown) {
@@ -55,8 +61,12 @@ export abstract class ConfigBase<T> {
save (newConfigData: T = this.configData): void {
const configPath = this.getConfigPath(this.core.selfInfo.uin);
this.validate(newConfigData);
this.configData = newConfigData;
let data: unknown = newConfigData;
data = Value.Parse(this.configSchema, data);
if (!this.validate.Check(data)) {
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
}
this.configData = data as T;
try {
fs.writeFileSync(configPath, JSON.stringify(this.configData, null, 2));
} catch (e: unknown) {
+37 -3
View File
@@ -1,7 +1,21 @@
import { ConfigBase } from '@/napcat-core/helper/config-base';
import { NapCatCore } from '@/napcat-core/index';
import { Type, Static } from '@sinclair/typebox';
import { AnySchema } from 'ajv';
import { Type, Static, TSchema } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
import path from 'node:path';
import fs from 'node:fs';
import json5 from 'json5';
export const BypassOptionsSchema = Type.Object({
hook: Type.Boolean({ default: true }),
window: Type.Boolean({ default: true }),
module: Type.Boolean({ default: true }),
process: Type.Boolean({ default: true }),
container: Type.Boolean({ default: true }),
js: Type.Boolean({ default: true }),
});
export const NapcatConfigSchema = Type.Object({
fileLog: Type.Boolean({ default: false }),
@@ -11,12 +25,32 @@ export const NapcatConfigSchema = Type.Object({
packetBackend: Type.String({ default: 'auto' }),
packetServer: Type.String({ default: '' }),
o3HookMode: Type.Number({ default: 0 }),
autoTimeSync: Type.Boolean({ default: true }),
bypass: Type.Optional(BypassOptionsSchema),
});
export type NapcatConfig = Static<typeof NapcatConfigSchema>;
/**
* 从指定配置目录读取 napcat.json,按 NapcatConfigSchema 校验并填充默认值
* 用于登录前(无 NapCatCore 实例时)的早期配置读取
*/
export function loadNapcatConfig (configPath: string): NapcatConfig {
let data: Record<string, unknown> = {};
try {
const configFile = path.join(configPath, 'napcat.json');
if (fs.existsSync(configFile)) {
data = json5.parse(fs.readFileSync(configFile, 'utf-8'));
}
} catch {
// 读取失败时使用 schema 默认值
}
data = Value.Parse(NapcatConfigSchema, data) as Record<string, unknown>;
return data as NapcatConfig;
}
export class NapCatConfigLoader extends ConfigBase<NapcatConfig> {
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
super('napcat', core, configPath, schema);
}
}
@@ -21,13 +21,13 @@ export interface VideoInfo {
/** Video duration in seconds */
duration: number;
/** Container format name (e.g., "mp4", "mkv", "avi") */
/** Generated thumbnail image format */
format: string;
/** Video codec name (e.g., "h264", "hevc", "vp9") */
videoCodec: string;
/** First frame thumbnail as BMP image buffer */
/** First frame thumbnail as JPEG image buffer */
image: Buffer;
}
@@ -101,7 +101,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
// 获取文件大小和类型
const [fileType, duration] = await Promise.all([
fileTypeFromFile(videoPath).catch(() => null),
this.getDuration(videoPath),
this.getDuration(videoPath).catch(() => 60),
]);
// 创建临时缩略图路径
@@ -136,22 +136,24 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
}
/**
* 获取时长
*/
* 获取时长
*/
async getDuration (filePath: string): Promise<number> {
try {
const { stdout } = await execFileAsync(this.ffprobePath, [
'-v', 'error',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
filePath,
]);
const { stdout } = await execFileAsync(this.ffprobePath, [
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
]);
const duration = parseFloat(stdout.trim());
return isNaN(duration) ? 60 : duration;
} catch {
return 60; // 默认时长
const duration = parseFloat(stdout.trim());
if (isNaN(duration)) {
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
}
return duration;
}
/**
@@ -6,6 +6,7 @@ import { platform } from 'node:os';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
@@ -64,10 +65,12 @@ export class FFmpegService {
}
return this.adapter;
}
public static async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
const adapter = await this.getAdapter();
await adapter.convertToNTSilkTct(inputFile, outputFile);
}
/**
* 设置 FFmpeg 路径并更新适配器
* @deprecated 建议使用 init() 方法初始化
@@ -92,6 +95,15 @@ export class FFmpegService {
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
*/
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 转换音频文件
*/
@@ -112,11 +112,11 @@ export class ForwardMsgBuilder {
preview: m.valid ? m.toPreview() : '[该消息类型暂不支持查看]',
})),
})),
source,
news,
summary,
prompt,
uuid,
source,
news,
summary,
prompt,
uuid
);
}
}
+31 -21
View File
@@ -59,13 +59,17 @@ class Subscription {
export const logSubscription = new Subscription();
export class LogWrapper implements ILogWrapper {
fileLogEnabled = true;
fileLogEnabled = false;
consoleLogEnabled = true;
logger: winston.Logger;
private logPath: string;
private fileTransportAdded = false;
private fileLogLevel: string = LogLevel.DEBUG;
constructor (logDir: string) {
const filename = `${getFormattedTimestamp()}.log`;
const logPath = path.join(logDir, filename);
this.logPath = path.join(logDir, filename);
this.logger = winston.createLogger({
level: 'debug',
@@ -77,12 +81,6 @@ export class LogWrapper implements ILogWrapper {
})
),
transports: [
new transports.File({
filename: logPath,
level: 'debug',
maxsize: 5 * 1024 * 1024, // 5MB
maxFiles: 5,
}),
new transports.Console({
format: format.combine(
format.colorize(),
@@ -107,7 +105,7 @@ export class LogWrapper implements ILogWrapper {
this.deleteOldLogFile(filePath, oneWeekAgo);
});
}).catch((err) => {
this.logger.error('Failed to read log directory', err);
this.logError('Failed to read log directory', err);
});
}
@@ -117,21 +115,22 @@ export class LogWrapper implements ILogWrapper {
fs.unlink(filePath).catch((err) => {
if (err) {
if (err.code === 'ENOENT') {
this.logger.warn(`File already deleted: ${filePath}`);
this.logWarn(`File already deleted: ${filePath}`);
} else {
this.logger.error('Failed to delete old log file', err);
this.logError('Failed to delete old log file', err);
}
} else {
this.logger.info(`Deleted old log file: ${filePath}`);
this.log(`Deleted old log file: ${filePath}`);
}
});
}
}).catch((err) => {
this.logger.error('Failed to get file stats', err);
this.logError('Failed to get file stats', err);
});
}
setFileAndConsoleLogLevel (fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
this.fileLogLevel = fileLogLevel;
this.logger.transports.forEach((transport) => {
if (transport instanceof transports.File) {
transport.level = fileLogLevel;
@@ -148,6 +147,15 @@ export class LogWrapper implements ILogWrapper {
setFileLogEnabled (isEnabled: boolean) {
this.fileLogEnabled = isEnabled;
if (isEnabled && !this.fileTransportAdded) {
this.fileTransportAdded = true;
this.logger.add(new transports.File({
filename: this.logPath,
level: this.fileLogLevel,
maxsize: 5 * 1024 * 1024, // 5MB
maxFiles: 5,
}));
}
this.logger.transports.forEach((transport) => {
if (transport instanceof transports.File) {
transport.silent = !isEnabled;
@@ -178,16 +186,18 @@ export class LogWrapper implements ILogWrapper {
}
_log (level: LogLevel, ...args: any[]) {
const message = this.formatMsg(args);
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
if (this.consoleLogEnabled || this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
this.logger.log(level, message);
}
logSubscription.notify(JSON.stringify({ level, message }));
}
logSubscription.notify(JSON.stringify({ level, message }));
}
log (...args: any[]) {
@@ -0,0 +1,58 @@
export interface OfflineRecoveryOptions {
// 当前账号是否在线
isOnline: () => boolean;
// 刚下线:同步 WebUI 状态
onOffline: (tips: string) => void;
// 静默离线期间账号自己恢复了,不需要重启
onRecovered: () => void;
// 重启 Worker;返回 false 或抛错表示失败,之后可以再次触发
restart: (tips: string) => Promise<boolean>;
// 被踢下线后多久重启。常规状态轮询为 3 秒,留出一个轮询周期,确保浏览器先清除旧二维码
kickedDelayMs?: number;
// 静默离线后多久重启。网络短暂断开时 QQ 也可能报离线,先给它自己重连的机会,
// 不然一次网络抖动就会把整个 Worker 重启掉
selfOfflineDelayMs?: number;
}
/**
* 下线恢复:被踢下线(KickedOffLine)和静默离线(SelfOffline)共用。
* 返回的函数在每次收到下线事件时调用,allowSelfRecovery 为 true 表示静默离线。
*/
export function createOfflineRecovery ({
isOnline,
onOffline,
onRecovered,
restart,
kickedDelayMs = 3_500,
selfOfflineDelayMs = 60_000,
}: OfflineRecoveryOptions) {
let restartRequested = false;
let selfRecoveryTimer: ReturnType<typeof setTimeout> | undefined;
return (tips: string, allowSelfRecovery: boolean) => {
onOffline(tips);
if (restartRequested) {
// 被踢时离线状态可能先到:还在等静默离线自行恢复的话,不用再等了
if (allowSelfRecovery || !selfRecoveryTimer) return;
clearTimeout(selfRecoveryTimer);
}
restartRequested = true;
// 不在 RefreshQRcode 请求里直接重启 Worker,否则请求在返回前就被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE;延后调度也让前端先看到「二维码已清空、正在恢复」
const timer = setTimeout(() => {
selfRecoveryTimer = undefined;
if (allowSelfRecovery && isOnline()) {
restartRequested = false;
onRecovered();
return;
}
restart(tips).then((ok) => {
if (!ok) restartRequested = false;
}, () => {
restartRequested = false;
});
}, allowSelfRecovery ? selfOfflineDelayMs : kickedDelayMs);
selfRecoveryTimer = allowSelfRecovery ? timer : undefined;
};
}
+3 -2
View File
@@ -79,10 +79,11 @@ export class QQBasicInfoWrapper {
getAppidV2 (): { appid: string; qua: string; } {
// 通过已有表 性能好
const appidTbale = AppidTable as unknown as QQAppidTableType;
const appidTable = AppidTable as unknown as QQAppidTableType;
const fullVersion = this.getFullQQVersion();
if (fullVersion) {
const data = appidTbale[fullVersion];
// 同一 Linux 版本的 x64 和 arm64 使用不同的 AppID,优先匹配架构。
const data = appidTable[`${fullVersion}-${process.arch}`] ?? appidTable[fullVersion];
if (data) {
return data;
}
+11 -1
View File
@@ -107,10 +107,20 @@ export class RkeyManager {
for (const url of availableUrls) {
try {
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
if ('retcode' in temp) {
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
// 支持Onebot Ret风格
temp = (temp as unknown as OneBotApiRet).data;
}
if (
typeof temp?.group_rkey !== 'string' ||
typeof temp?.private_rkey !== 'string' ||
typeof temp?.expired_time !== 'number' ||
temp.group_rkey.length <= 6 ||
temp.private_rkey.length <= 6 ||
temp.expired_time <= 0
) {
throw new Error('Rkey 服务返回格式无效:group_rkey/private_rkey/expired_time 缺失或不合法');
}
this.rkeyData = {
group_rkey: temp.group_rkey.slice(6),
private_rkey: temp.private_rkey.slice(6),
@@ -0,0 +1,34 @@
/**
* 服务器时间矫正 - 全局 Hook
*
* 保留 Date.now 原始引用,启动后通过 getServerTime 计算偏移量,
* 直接覆盖 Date.now(),使全局所有调用自动获得矫正后的时间戳。
*/
/** 原始 Date.now 引用,不受 hook 影响 */
export const OriginalDateNow: () => number = Date.now.bind(Date);
/**
* 初始化全局时间矫正,覆盖 Date.now()
* @param getServerTimeFn 获取服务器时间的函数,返回毫秒级时间戳字符串
* @returns 偏移量(毫秒)
*/
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
const start = OriginalDateNow();
const serverTimeStr = getServerTimeFn();
const end = OriginalDateNow();
const serverTimeMs = parseInt(serverTimeStr, 10);
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
return 0;
}
// 补偿网络延迟:假定往返时间对称,服务器时间对应本地时间的中点 (start + end) / 2
const offsetMs = Math.round(serverTimeMs - (start + end) / 2);
if (Math.abs(offsetMs) > 5000) {
Date.now = () => OriginalDateNow() + offsetMs;
}
return offsetMs;
}
+6 -6
View File
@@ -6,13 +6,13 @@ import { NTEventWrapper } from './event';
* 创建 Service 方法的代理
* 拦截所有方法调用,通过 EventWrapper 进行调用
*/
function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
function createServiceMethodProxy<S extends keyof ServiceNamingMapping> (
serviceName: S,
originalService: ServiceNamingMapping[S],
eventWrapper: NTEventWrapper
): ServiceNamingMapping[S] {
return new Proxy(originalService as object, {
get(target, prop, receiver) {
get (target, prop, receiver) {
const originalValue = Reflect.get(target, prop, receiver);
// 如果不是函数,直接返回原始值
@@ -50,7 +50,7 @@ function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
* 第一层:拦截 getXXXService 方法
* 第二层:拦截 Service 上的具体方法调用
*/
export function createSessionProxy(
export function createSessionProxy (
session: NodeIQQNTWrapperSession,
eventWrapper: NTEventWrapper
): NodeIQQNTWrapperSession {
@@ -58,7 +58,7 @@ export function createSessionProxy(
const serviceProxyCache = new Map<string, unknown>();
return new Proxy(session, {
get(target, prop, receiver) {
get (target, prop, receiver) {
const propName = prop as string;
// 检查是否是 getXXXService 方法
@@ -105,7 +105,7 @@ export function createSessionProxy(
/**
* 检查 Service 名称是否在已知的映射中
*/
function isKnownService(serviceName: string): serviceName is keyof ServiceNamingMapping {
function isKnownService (serviceName: string): serviceName is keyof ServiceNamingMapping {
const knownServices: string[] = [
'NodeIKernelAvatarService',
'NodeIKernelBuddyService',
@@ -132,7 +132,7 @@ function isKnownService(serviceName: string): serviceName is keyof ServiceNaming
* 创建带有 EventWrapper 集成的 InstanceContext
* 这是推荐的使用方式,在创建 context 时自动代理 session
*/
export function createProxiedSession(
export function createProxiedSession (
session: NodeIQQNTWrapperSession,
eventWrapper: NTEventWrapper
): NodeIQQNTWrapperSession {
+59 -7
View File
@@ -8,6 +8,7 @@ import {
NTQQWebApi,
NTQQFlashApi,
NTQQOnlineApi,
NTQQDatabaseApi,
} from '@/napcat-core/apis';
import { NTQQCollectionApi } from '@/napcat-core/apis/collection';
import {
@@ -37,6 +38,7 @@ import { Napi2NativeLoader } from './packet/handler/napi2nativeLoader';
import { container, ReceiverServiceRegistry } from './packet/handler/serviceRegister';
import { appEvent } from './packet/handler/eventList';
import { TypedEventEmitter } from './packet/handler/typeEvent';
import { hookGlobalDateNow } from './helper/server-time';
export * from './wrapper';
export * from './types/index';
export * from './services/index';
@@ -49,6 +51,7 @@ export * from './helper/config';
export * from './helper/config-base';
export * from './helper/proxy-handler';
export * from './helper/session-proxy';
export * from './helper/server-time';
export enum NapCatCoreWorkingEnv {
Unknown = 0,
@@ -56,12 +59,30 @@ export enum NapCatCoreWorkingEnv {
Framework = 2,
}
function dlopenWrapper (wrapperPath: string): WrapperNodeApi {
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
try {
process.dlopen(nativemodule, wrapperPath);
} catch (error) {
// QQNT.dll 依赖媒体基础(mfplat.dll 等),Windows Server 默认不装这个组件。
// 缺了它系统只会报 The specified module could not be found,看不出缺的是什么
const mfplatPath = path.join(process.env['SystemRoot'] || 'C:\\Windows', 'System32', 'mfplat.dll');
if (os.platform() === 'win32' && !fs.existsSync(mfplatPath)) {
throw new Error(
'加载 wrapper.node 失败:系统缺少「媒体基础」组件(找不到 mfplat.dll),Windows Server 默认不安装它。' +
'请在服务器管理器的「添加角色和功能」里勾选「媒体基础」,' +
'或在管理员 PowerShell 中执行 Install-WindowsFeature Server-Media-Foundation,重启后再启动。' +
`原始错误:${(error as Error).message}`
);
}
throw error;
}
return nativemodule.exports;
}
export function loadQQWrapper (execPath: string | undefined, QQVersion: string): WrapperNodeApi {
if (process.env['NAPCAT_WRAPPER_PATH']) {
const wrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperPath);
return nativemodule.exports;
return dlopenWrapper(process.env['NAPCAT_WRAPPER_PATH']);
}
if (!execPath) {
throw new Error('无法加载Wrapper,execPath未定义');
@@ -82,10 +103,9 @@ export function loadQQWrapper (execPath: string | undefined, QQVersion: string):
if (!fs.existsSync(wrapperNodePath)) {
wrapperNodePath = path.join(path.dirname(execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
}
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath);
const exports = dlopenWrapper(wrapperNodePath);
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
return nativemodule.exports;
return exports;
}
export function getMajorPath (execPath: string, QQVersion: string): string {
// major.node
@@ -118,6 +138,8 @@ export class NapCatCore {
selfInfo: SelfInfo;
util: NodeQQNTWrapperUtil;
configLoader: NapCatConfigLoader;
/** 数据库 passphrase,由 OidbSvcTrpcTcp.0xcde_2 包获取 */
dbPassphrase: string | undefined;
// 通过构造器递过去的 runtime info 应该尽量少
constructor (context: InstanceContext, selfInfo: SelfInfo) {
@@ -148,6 +170,7 @@ export class NapCatCore {
GroupApi: new NTQQGroupApi(this.context, this),
FlashApi: new NTQQFlashApi(this.context, this),
OnlineApi: new NTQQOnlineApi(this.context, this),
DatabaseApi: new NTQQDatabaseApi(this.context, this),
};
container.bind(NapCatCore).toConstantValue(this);
container.bind(TypedEventEmitter).toConstantValue(this.event);
@@ -169,6 +192,28 @@ export class NapCatCore {
if (!fs.existsSync(this.NapCatTempPath)) {
fs.mkdirSync(this.NapCatTempPath, { recursive: true });
}
// 通过 getServerTime 全局 hook Date.now() 矫正本地时间偏差
// 可通过环境变量 NAPCAT_DISABLE_TIME_SYNC=1 或配置 autoTimeSync: false 禁用
if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) {
this.context.logger.log('[ServerTime] 自动对时已禁用');
} else {
const doTimeSync = () => {
try {
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
if (Math.abs(offsetMs) > 5000) {
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
} else {
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
}
} catch (e) {
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
}
};
doTimeSync();
// 每小时定期重同步,防止长时间运行后本地时钟漂移触发风控
const syncTimer = setInterval(doTimeSync, 3600000);
syncTimer.unref();
}
// 遍历this.apis[i].initApi 如果存在该函数进行async 调用
for (const apiKey in this.apis) {
const api = this.apis[apiKey as keyof StableNTApiWrapper];
@@ -233,8 +278,14 @@ export class NapCatCore {
};
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
if (Info.status === 20) {
// 静默离线:服务端判定会话失效,但不会下发 KickedOffLine 通知。
// 仅在 在线 -> 离线 的跳变上广播一次,供上层复用下线恢复链路。
const wasOnline = this.selfInfo.online === true;
this.selfInfo.online = false;
this.context.logger.log('账号状态变更为离线');
if (wasOnline) {
this.event.emit('SelfOffline', '[SelfOffline] 账号状态变更为离线(未收到 KickedOffLine 通知)');
}
} else {
this.selfInfo.online = true;
}
@@ -330,4 +381,5 @@ export interface StableNTApiWrapper {
GroupApi: NTQQGroupApi;
FlashApi: NTQQFlashApi,
OnlineApi: NTQQOnlineApi,
DatabaseApi: NTQQDatabaseApi,
}
@@ -53,6 +53,7 @@ export class NodeIKernelLoginListener {
onLoginState (..._args: any[]): any {
}
onLoginRecordUpdate (..._args: any[]): any {
}
}
+34 -34
View File
@@ -1,38 +1,38 @@
{
"name": "napcat-core",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
"name": "napcat-core",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
},
"exports": {
".": {
"import": "./index.ts"
},
"exports": {
".": {
"import": "./index.ts"
},
"./*": {
"import": "./*"
}
},
"dependencies": {
"winston": "^3.17.0",
"json5": "^2.2.3",
"inversify": "^7.10.4",
"reflect-metadata": "^0.2.2",
"@protobuf-ts/runtime": "^2.11.1",
"ajv": "^8.13.0",
"@sinclair/typebox": "^0.34.38",
"file-type": "^21.0.0",
"compressing": "^1.10.1",
"napcat-image-size": "workspace:*",
"napcat-common": "workspace:*",
"napcat-protobuf": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.1"
},
"engines": {
"node": ">=18.0.0"
"./*": {
"import": "./*"
}
},
"dependencies": {
"@protobuf-ts/runtime": "^2.11.1",
"@sinclair/typebox": "^0.34.38",
"compressing": "^1.10.1",
"file-type": "^21.0.0",
"inversify": "^7.10.4",
"json5": "^2.2.3",
"napcat-common": "workspace:*",
"napcat-database": "workspace:*",
"napcat-image-size": "workspace:*",
"napcat-protobuf": "workspace:*",
"reflect-metadata": "^0.2.2",
"winston": "^3.17.0"
},
"devDependencies": {
"@types/node": "^22.0.1"
},
"engines": {
"node": ">=18.0.0"
}
}
@@ -39,12 +39,17 @@ export class NativePacketClient {
async init (_pid: number, recv: string, send: string): Promise<void> {
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
if (isNewQQ) {
const success = this.napi2nativeLoader.initHook(send, recv);
if (success) {
this.available = true;
}
if (!isNewQQ) {
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
return;
}
const success = this.napi2nativeLoader.initHook(send, recv);
if (success) {
this.available = true;
this.logStack.pushLogInfo(`[PacketClient] NativePacketClient Hook 初始化成功 platform=${process.platform}.${process.arch}`);
return;
}
this.logStack.pushLogError(`[PacketClient] NativePacketClient Hook 初始化失败 platform=${process.platform}.${process.arch} send=${send} recv=${recv}`);
}
async sendPacket (
@@ -19,6 +19,7 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
import { gunzipSync } from 'zlib';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
export class PacketOperationContext {
private readonly context: PacketContext;
@@ -41,6 +42,16 @@ export class PacketOperationContext {
await this.context.client.sendOidbPacket(req, true);
}
async CompleteGroupTodo (groupUin: number, msgSeq: string) {
const req = trans.CompleteGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async CancelGroupTodo (groupUin: number, msgSeq: string) {
const req = trans.CancelGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async FetchRkey (timeout: number = 10000) {
const req = trans.FetchRkey.build();
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
@@ -95,15 +106,7 @@ export class PacketOperationContext {
.filter(Boolean)
);
const res = await Promise.allSettled(reqList);
const failedCount = res.filter((r) => r.status === 'rejected').length;
if (failedCount > 0) {
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
res.forEach((result, index) => {
if (result.status === 'rejected') {
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
}
});
}
assertUploadResults(res, this.context.logger);
}
async UploadImage (img: PacketMsgPicElement) {
@@ -228,15 +231,18 @@ export class PacketOperationContext {
const res = trans.UploadForwardMsg.parse(resp);
return res.result.resId;
}
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
//await this.SendPreprocess(msg, groupUin);
// 遍历上传资源
await Promise.allSettled(msg.map(async (item) => { return await this.SendPreprocess(item.actionMsg, groupUin); }));
// 遍历上传资源(跳过已有原始数据的项)
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
await this.SendPreprocess(item.actionMsg!, groupUin);
}));
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.UploadForwardMsg.parse(resp);
return res.result.resId;
}
async MoveGroupFile (
groupUin: number,
fileUUID: string,
@@ -312,6 +318,15 @@ export class PacketOperationContext {
}
}
async FetchForwardMsgRaw (resId: string) {
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, resId);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.DownloadForwardMsg.parse(resp);
const inflate = gunzipSync(res.result.payload);
const result = new NapProtoMsg(LongMsgResult).decode(inflate);
return result.action;
}
async FetchForwardMsg (res_id: string): Promise<RawMessage[]> {
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, res_id);
const resp = await this.context.client.sendOidbPacket(req, true);
@@ -349,11 +364,39 @@ export class PacketOperationContext {
}
return element;
}
if (element.videoElement && rawElem?.commonElem?.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
const index = extra?.msgInfoBody[0]?.index;
if (!index) return element;
if (msg?.responseHead.grp !== undefined) {
element.videoElement = {
...element.videoElement,
filePath: await this.GetGroupVideoUrl(msg.responseHead.grp.groupUin ?? 0, index),
};
} else {
element.videoElement = {
...element.videoElement,
filePath: await this.GetVideoUrl(this.context.napcore.basicInfo.uid, index),
};
}
return element;
}
return element;
})
);
const isGroup = msg?.responseHead.grp !== undefined;
const peerUin = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUin ?? 0);
const peerUid = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUid ?? '');
const sendNickName = isGroup
? (msg?.responseHead.grp?.memberName ?? '')
: (msg?.responseHead.forward?.friendName ?? '');
return {
chatType: ChatType.KCHATTYPEGROUP,
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
elements,
guildId: '',
isOnlineMsg: false,
@@ -364,18 +407,18 @@ export class PacketOperationContext {
msgType: NTMsgType.KMSGTYPEMIX,
parentMsgIdList: [],
parentMsgPeer: {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
peerUid,
},
peerName: '',
peerUid: '1094950020',
peerUin: '1094950020',
peerUid,
peerUin,
recallTime: '0',
records: [],
sendNickName: msg?.responseHead.grp?.memberName ?? '',
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
senderUid: '',
senderUin: '1094950020',
sendNickName,
sendRemarkName: sendNickName,
senderUid: msg?.responseHead.fromUid ?? '',
senderUin: String(msg?.responseHead.fromUin ?? 0),
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
subMsgType: 1,
};
@@ -0,0 +1,26 @@
export interface UploadResultLogger {
warn (message: string): unknown;
error (message: string): unknown;
}
export function assertUploadResults (
results: PromiseSettledResult<unknown>[],
logger: UploadResultLogger
): void {
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failures.length === 0) return;
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
results.forEach((result, index) => {
if (result.status === 'rejected') {
const reason = result.reason instanceof Error
? result.reason.stack ?? result.reason.message
: String(result.reason);
logger.error(`上传第${index + 1}个资源失败:${reason}`);
}
});
throw new AggregateError(
failures.map(result => result.reason),
`上传转发消息资源失败:${failures.length}/${results.length}`
);
}
@@ -194,7 +194,7 @@ export class NativePacketHandler {
}
}
async init (version: string): Promise<boolean> {
async init (version: string, o3HookMode: boolean = false): Promise<boolean> {
const version_arch = version + '-' + process.arch;
try {
if (!this.loaded) {
@@ -215,7 +215,7 @@ export class NativePacketHandler {
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
this.emitPacket(type, uin, cmd, seq, hex_data);
}, true);
}, o3HookMode);
this.logger.log('[PacketHandler] 初始化成功');
return true;
} catch (error) {
@@ -3,5 +3,7 @@ import { TypedEventEmitter } from './typeEvent';
export interface AppEvents {
'event:emoji_like': { groupId: string; senderUin: string; emojiId: string, msgSeq: string, isAdd: boolean, count: number; };
KickedOffLine: string;
// 静默离线:服务端会话已失效,但没有下发 KickedOffLine 通知
SelfOffline: string;
}
export const appEvent = new TypedEventEmitter<AppEvents>();
@@ -4,10 +4,19 @@ import fs from 'fs';
import { constants } from 'node:os';
import { LogWrapper } from '../../helper/log';
export interface BypassOptions {
hook?: boolean;
window?: boolean;
module?: boolean;
process?: boolean;
container?: boolean;
js?: boolean;
}
export interface Napi2NativeExportType {
initHook?: (send: string, recv: string) => boolean;
setVerbose?: (verbose: boolean) => void; // 默认关闭日志
enableAllBypasses?: () => void;
enableAllBypasses?: (options?: BypassOptions) => boolean;
}
export class Napi2NativeLoader {
@@ -21,8 +21,11 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
import { calculateFileMD5 } from 'napcat-common/src/file';
import { randomUUID } from 'node:crypto';
import { imageSizeFallBack } from 'napcat-image-size/src/index';
export const BlockSize = 1024 * 1024;
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
interface HighwayServerAddr {
ip: string;
@@ -110,22 +113,37 @@ export class PacketHighwayContext {
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
}
// 如果缺少视频缩略图,自动生成一个
let tempThumbPath: string | null = null;
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
if (!video.thumbPath || !thumbExists) {
tempThumbPath = await this.ensureVideoThumb(video);
}
const cleanupThumbPaths: string[] = [];
try {
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
if (!shouldGenerateThumb) {
try {
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
shouldGenerateThumb = true;
}
} catch (e) {
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
shouldGenerateThumb = true;
}
}
if (shouldGenerateThumb) {
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
}
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupVideo(+peer.peerUid, video);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
@@ -134,23 +152,21 @@ export class PacketHighwayContext {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
} finally {
// 清理临时生成的缩略图文件
if (tempThumbPath) {
const thumbToClean = tempThumbPath;
fs.promises.unlink(thumbToClean)
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
.catch((e) => {
// 文件不存在时忽略错误
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
});
}
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
try {
await fs.promises.unlink(thumbToClean);
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
}
}));
}
}
/**
* 确保视频缩略图存在,如果不存在则自动生成
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
* @returns 生成的临时缩略图路径,用于后续清理
*/
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
@@ -161,9 +177,10 @@ export class PacketHighwayContext {
// 生成缩略图路径
const videoDir = path.dirname(video.filePath);
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
video.thumbPath = thumbPath;
try {
// 尝试使用 FFmpeg 提取视频缩略图
@@ -174,26 +191,36 @@ export class PacketHighwayContext {
} catch {
throw new Error('FFmpeg failed to generate thumbnail');
}
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
}
} catch (e) {
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
await this.updateVideoThumbInfo(video);
}
// 更新视频元素的缩略图信息
video.thumbPath = thumbPath;
const thumbStat = await fs.promises.stat(thumbPath);
video.thumbSize = thumbStat.size;
video.thumbMd5 = await calculateFileMD5(thumbPath);
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
if (!video.thumbWidth) video.thumbWidth = 240;
if (!video.thumbHeight) video.thumbHeight = 383;
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
return thumbPath;
}
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
if (!video.thumbPath) {
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
}
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
fs.promises.stat(video.thumbPath),
calculateFileMD5(video.thumbPath),
imageSizeFallBack(video.thumbPath),
]);
video.thumbSize = thumbStat.size;
video.thumbMd5 = thumbMd5;
video.thumbWidth = dimensions.width;
video.thumbHeight = dimensions.height;
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
}
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
@@ -296,13 +323,17 @@ export class PacketHighwayContext {
const req = trans.UploadGroupVideo.build(groupUin, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
fileUuid: videoIndex.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -324,16 +355,15 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -349,7 +379,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -361,13 +391,17 @@ export class PacketHighwayContext {
const req = trans.UploadPrivateVideo.build(peerUid, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
fileUuid: videoIndex.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -389,16 +423,15 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -414,7 +447,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -4,6 +4,8 @@ import {
MessageElement,
Peer,
RawMessage,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -15,7 +17,7 @@ import {
SendReplyElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/index';
} from '@/napcat-core/types/element';
import {
IPacketMsgElement,
PacketMsgAtElement,
@@ -158,7 +160,8 @@ export class PacketMsgConverter {
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
const converters = [PacketMsgTextElement.parseElement,
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
return msg.map((element) => {
for (const converter of converters) {
const result = converter(element);
+62 -9
View File
@@ -1,3 +1,4 @@
import * as crypto from 'node:crypto';
import * as zlib from 'node:zlib';
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
import {
@@ -19,7 +20,11 @@ import {
FaceType,
MessageElement,
NTMsgAtType,
NTVideoType,
PicType,
Peer,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -31,8 +36,7 @@ import {
SendMultiForwardMsgElement,
SendTextElement,
SendVideoElement,
Peer,
} from '@/napcat-core/index';
} from '@/napcat-core/types/element';
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
@@ -386,8 +390,10 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
if (elem?.commonElem?.serviceType === 48 &&
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
elem.commonElem.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
const msgInfoBody = extra.msgInfoBody[0];
const index = msgInfoBody?.index;
return [{
@@ -405,7 +411,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.UNKNOWN,
elementType: ElementType.PIC,
elementId: '',
}, elem];
}
@@ -445,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
fileName: string;
fileSize?: string;
filePath?: string;
fileTime: number;
fileFormat: NTVideoType;
fileWidth?: number;
fileHeight?: number;
thumbSize?: number;
thumbPath?: string;
fileMd5?: string;
@@ -455,12 +466,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
thumbSha1?: string;
thumbWidth?: number;
thumbHeight?: number;
businessType: 11 | 21 = 21;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
constructor (element: SendVideoElement) {
super(element);
this.fileName = element.videoElement.fileName;
this.fileSize = element.videoElement.fileSize;
this.filePath = element.videoElement.filePath;
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
this.fileWidth = element.videoElement.fileWidth;
this.fileHeight = element.videoElement.fileHeight;
this.thumbSize = element.videoElement.thumbSize;
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
this.fileMd5 = element.videoElement.videoMd5;
@@ -479,11 +496,45 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: 21,
businessType: this.businessType,
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType !== 48 ||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
!elem.commonElem.pbElem) {
return undefined;
}
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
const videoIndex = extra.msgInfoBody[0]?.index;
const thumbIndex = extra.msgInfoBody[1]?.index;
if (!videoIndex) return undefined;
return [{
videoElement: {
filePath: '',
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
videoMd5: videoIndex.info.fileHash,
thumbMd5: thumbIndex?.info.fileHash,
fileTime: videoIndex.info.time,
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
fileSize: String(videoIndex.info.fileSize),
fileWidth: videoIndex.info.width,
fileHeight: videoIndex.info.height,
thumbWidth: thumbIndex?.info.width,
thumbHeight: thumbIndex?.info.height,
thumbSize: thumbIndex?.info.fileSize,
thumbPath: new Map(),
fileUuid: videoIndex.fileUuid,
busiType: 0,
subBusiType: 0,
},
elementType: ElementType.VIDEO,
elementId: '',
}, elem];
};
override toPreview (): string {
return '[视频]';
}
@@ -510,14 +561,14 @@ export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
//return [];
// return [];
if (!this.msgInfo) return [];
return [{
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: 22,
}
},
}];
}
@@ -665,11 +716,13 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsgElement> {
resid: string;
message: PacketMsg[];
uuid: string;
constructor (rawElement: SendMultiForwardMsgElement, message?: PacketMsg[]) {
super(rawElement);
this.resid = rawElement.multiForwardMsgElement.resId;
this.message = message ?? [];
this.uuid = rawElement.multiForwardMsgElement.fileName || crypto.randomUUID();
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
@@ -677,7 +730,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsg
lightAppElem: {
data: Buffer.concat([
Buffer.from([0x01]),
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), 'utf-8')),
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message, undefined, undefined, undefined, undefined, this.uuid)), 'utf-8')),
]),
},
}];
@@ -0,0 +1,20 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class CancelGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
return OidbBase.build(0xF90, 3, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new CancelGroupTodo();
@@ -0,0 +1,20 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class CompleteGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
return OidbBase.build(0xF90, 2, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new CompleteGroupTodo();
@@ -5,7 +5,7 @@ import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class SetGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90_1).encode({
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
@@ -8,4 +8,6 @@ export { default as SetSpecialTitle } from './SetSpecialTitle';
export { default as ImageOCR } from './ImageOCR';
export { default as MoveGroupFile } from './MoveGroupFile';
export { default as RenameGroupFile } from './RenameGroupFile';
export { default as CompleteGroupTodo } from './CompleteGroupTodo';
export { default as CancelGroupTodo } from './CancelGroupTodo';
export { default as SetGroupTodo } from './SetGroupTodo';
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
fileName: video.fileName || 'video.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
videoFormat: video.fileFormat,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
original: 0,
},
subFileType: 0,
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
type: {
type: 1,
picFormat: 0,
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
fileName: video.fileName || 'video.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
videoFormat: video.fileFormat,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
original: 0,
},
subFileType: 0,
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
type: {
type: 1,
picFormat: 0,
@@ -1,20 +1,21 @@
import zlib from 'node:zlib';
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import { PacketMsg } from '@/napcat-core/packet/message/message';
export interface UploadForwardMsgParams {
actionCommand: string;
actionMsg: PacketMsg[];
actionMsg?: PacketMsg[];
actionMsgBody?: NapProtoEncodeStructType<typeof proto.PushMsgBody>[];
}
class UploadForwardMsgV2 extends PacketTransformer<typeof proto.SendLongMsgResp> {
build (selfUid: string, msg: UploadForwardMsgParams[], groupUin: number = 0): OidbPacket {
const reqdata = msg.map((item) => ({
actionCommand: item.actionCommand,
actionData: {
msgBody: this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg),
}
msgBody: item.actionMsgBody ?? this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg ?? []),
},
}));
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
{
@@ -2,4 +2,4 @@ export { default as UploadForwardMsg } from './UploadForwardMsg';
export { default as FetchGroupMessage } from './FetchGroupMessage';
export { default as FetchC2CMessage } from './FetchC2CMessage';
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
@@ -25,9 +25,10 @@ export * from './oidb/Oidb.0x929';
export * from './oidb/Oidb.0xE37_1200';
export * from './oidb/Oidb.0xE37_1700';
export * from './oidb/Oidb.0XE37_800';
export * from './oidb/Oidb.0xCDE_2';
export * from './oidb/Oidb.0xEB7';
export * from './oidb/Oidb.0xED3_1';
export * from './oidb/Oidb.0XFE1_2';
export * from './oidb/OidbBase';
export * from './oidb/Oidb.0xE07';
export * from './oidb/Oidb.0xf90_1';
export * from './oidb/Oidb.0xf90';
@@ -0,0 +1,11 @@
import { ProtoField, ScalarType } from 'napcat-protobuf';
// OidbSvcTrpcTcp.0xcde_2 响应体
// body.field2.field1 为目标字符串值
export const OidbSvcTrpcTcp0XCDE_2RespBodyInner = {
value: ProtoField(1, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0XCDE_2RespBody = {
inner: ProtoField(2, () => OidbSvcTrpcTcp0XCDE_2RespBodyInner),
};
@@ -1,6 +1,6 @@
import { ProtoField, ScalarType } from 'napcat-protobuf';
export const OidbSvcTrpcTcp0XF90_1 = {
export const OidbSvcTrpcTcp0XF90 = {
groupUin: ProtoField(1, ScalarType.UINT32),
msgSeq: ProtoField(2, ScalarType.UINT64),
};
@@ -88,6 +88,7 @@ export interface NodeIKernelAlbumService {
map_bytes_info: unknown[],
map_user_account: unknown[];
},
type: number, // type : number 1 取消 2 点赞
param: {
// {"id":"421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3e*KqaLVYdic!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560336594^||^1","status":1}
id: string,
@@ -32,7 +32,7 @@ export interface NodeIKernelGroupService {
getAllGroupPrivilegeFlag (troopUinList: string[], serviceType: number): Promise<unknown>;
// <---
getGroupExt0xEF0Info (enableGroupCodes: string[], bannedGroupCodes: string[], filter: GroupExt0xEF0InfoFilter, forceFetch: boolean):
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
kickMemberV2 (param: KickMemberV2Req): Promise<GeneralCallResult>;
@@ -29,10 +29,11 @@ export interface PasswordLoginArgType {
uin: string;
passwordMd5: string;// passwMD5
step: number;// 猜测是需要二次认证 参数 一次为0
newDeviceLoginSig: string;
proofWaterSig: string;
proofWaterRand: string;
proofWaterSid: string;
newDeviceLoginSig: Uint8Array;
proofWaterSig: Uint8Array;
proofWaterRand: Uint8Array;
proofWaterSid: Uint8Array;
unusualDeviceCheckSig: Uint8Array;
}
export interface LoginListItem {
@@ -341,7 +341,7 @@ export interface NodeIKernelMsgService {
getFileThumbSavePath (arg1: string, arg2: number, arg3: boolean): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): Promise<GeneralCallResult>;
setPttPlayedState (arg1: string, arg2: Peer, arg3: string): unknown;
@@ -369,7 +369,16 @@ export interface NodeIKernelMsgService {
}>;
}>;
addFavEmoji (arg: unknown): unknown;
addFavEmoji (arg: {
emojiId?: string,
packageId?: number,
emojiPath: string,
fileSize: string,
fileName: string,
md5: string,
isMarkFace?: boolean,
isOrigin?: boolean,
}): unknown;
fetchMarketEmoticonList (arg1: number, arg2: number): unknown;
@@ -397,9 +406,14 @@ export interface NodeIKernelMsgService {
downloadEmojiPic (arg1: number, arg2: Array<unknown>[], arg3: number, arg4: Map<unknown, unknown>): unknown;
deleteFavEmoji (arg: unknown): unknown;
deleteFavEmoji (arg: string[]): unknown;
modifyFavEmojiDesc (arg: unknown): unknown;
modifyFavEmojiDesc (arg: Array<{
emojiId: number,
resId: string,
md5: string,
desc: string,
}>): unknown;
queryFavEmojiByDesc (arg: unknown): unknown;
@@ -688,14 +702,14 @@ export interface NodeIKernelMsgService {
msgSeq: string;
msgRandom: string;
}>, DataMigrationResourceInfo: {
extraData: string;
filePath: string;
fileSize: string;
msgRandom: string;
msgSeq: string;
msgSubType: number;
msgType: number;
}): unknown;
extraData: string;
filePath: string;
fileSize: string;
msgRandom: string;
msgSeq: string;
msgSubType: number;
msgType: number;
}): unknown;
dataMigrationGetResourceLocalDestinyPath (arg: unknown): unknown;
@@ -24,7 +24,7 @@ export interface NodeIKernelStorageCleanService {
// "C:\\Users\\nanaeo\\AppData\\Roaming\\QQ\\Partitions\\qqnt_9212"
// ]
// ]
addCacheScanedPaths (paths: Map<`tmp` | `SilentCacheappSessionPartation9212` | `hotUpdate`, unknown>): unknown;
addCacheScanedPaths (paths: Map<'tmp' | 'SilentCacheappSessionPartation9212' | 'hotUpdate', unknown>): unknown;
addFilesScanedPaths (arg: unknown): unknown;
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
+2
View File
@@ -118,6 +118,8 @@ export interface VideoElement {
thumbSize?: number; // byte
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
fileSize?: string; // byte
fileWidth?: number;
fileHeight?: number;
thumbWidth?: number;
thumbHeight?: number;
busiType?: 0; //
+14
View File
@@ -74,6 +74,20 @@ export interface EXTInfo {
groupSquareSwitch: number;
}
export type GroupMemberInvitePolicy =
| 'disabled'
| 'require_approval'
| 'no_approval'
| 'no_approval_under_100';
export interface GroupManagementSettings {
memberInvite?: GroupMemberInvitePolicy;
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
newMembersSeeRecentHistory?: boolean;
}
export interface GroupGuildIDS {
guildIds: any[];
}
+2
View File
@@ -78,6 +78,7 @@ export interface WebApiGroupNoticeFeed {
remind_ts: number
tip_window_type: number
confirm_required: number
inst_no_pinned?: number // 仅 inst 条目有:0 = 置顶中,1 = 未置顶
};
read_num: number;
is_read: number;
@@ -92,6 +93,7 @@ export interface WebApiGroupNoticeRet {
read_only: number
role: number
feeds: WebApiGroupNoticeFeed[]
inst?: WebApiGroupNoticeFeed[] // 「发给新成员」类公告,不在 feeds 里
group: {
group_id: number
class_ext: number
+25
View File
@@ -0,0 +1,25 @@
{
"name": "napcat-database",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "src/index.ts",
"scripts": {
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
},
"exports": {
".": {
"import": "./src/index.ts"
},
"./src/*": {
"import": "./src/*"
}
},
"dependencies": {},
"devDependencies": {
"@types/node": "^22.0.1"
},
"engines": {
"node": ">=18.0.0"
}
}
+35
View File
@@ -0,0 +1,35 @@
/** 文件头部扩展区大小 */
export const EXT_HEADER_SIZE = 1024;
/** SQLCipher 页大小 */
export const PAGE_SIZE = 4096;
/** PBKDF2 salt 长度 */
export const SALT_SIZE = 16;
/** AES-256 密钥长度 */
export const KEY_SIZE = 32;
/** AES-CBC IV 长度 */
export const IV_SIZE = 16;
/** HMAC-SHA1 长度 */
export const HMAC_SIZE = 20;
/** 每页保留区大小: IV(16) + HMAC_SHA1(20) + pad(12) = 48 */
export const RESERVE_SIZE = 48;
/** PBKDF2 主密钥迭代次数 */
export const KDF_ITERATIONS = 4000;
/** PBKDF2 HMAC 密钥迭代次数 */
export const FAST_ITERATIONS = 2;
/** HMAC salt XOR 掩码 */
export const HMAC_MASK = 0x3a;
/** SQLite 加密文件头 */
export const SQLITE_HEADER = Buffer.from('SQLite header 3\0');
/** SQLite 明文文件头 */
export const SQLITE_FORMAT = Buffer.from('SQLite format 3\0');
+29
View File
@@ -0,0 +1,29 @@
/**
* 密钥派生
* enc_key = PBKDF2_HMAC_SHA512(passphrase, salt, 4000, 32)
* hmac_key = PBKDF2_HMAC_SHA512(enc_key, salt ^ 0x3a, 2, 32)
*/
import { pbkdf2Sync } from 'node:crypto';
import {
KEY_SIZE,
KDF_ITERATIONS,
FAST_ITERATIONS,
HMAC_MASK,
} from './constants';
export interface DerivedKeys {
encKey: Buffer;
hmacKey: Buffer;
}
export function deriveKeys (passphrase: Buffer, salt: Buffer): DerivedKeys {
const encKey = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, 'sha512');
const hmacSalt = Buffer.alloc(salt.length);
for (let i = 0; i < salt.length; i++) {
hmacSalt[i] = salt[i]! ^ HMAC_MASK;
}
const hmacKey = pbkdf2Sync(encKey, hmacSalt, FAST_ITERATIONS, KEY_SIZE, 'sha512');
return { encKey, hmacKey };
}
+109
View File
@@ -0,0 +1,109 @@
import { createDecipheriv } from 'node:crypto';
import fs from 'node:fs';
import {
EXT_HEADER_SIZE,
PAGE_SIZE,
SALT_SIZE,
IV_SIZE,
RESERVE_SIZE,
SQLITE_HEADER,
SQLITE_FORMAT,
} from './constants';
import { deriveKeys } from './crypto';
/**
* 解密单个 SQLCipher 页面
* @param pageData 原始页数据 (4096 字节)
* @param encKey AES-256 密钥
* @param skipSalt 页 1 需跳过前 16 字节 salt
*/
function decryptPage (pageData: Buffer, encKey: Buffer, skipSalt: number = 0): Buffer {
const data = pageData.subarray(skipSalt);
const contentLen = data.length - RESERVE_SIZE;
const encrypted = data.subarray(0, contentLen);
const iv = data.subarray(contentLen, contentLen + IV_SIZE);
const decipher = createDecipheriv('aes-256-cbc', encKey, iv);
decipher.setAutoPadding(false);
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}
/**
* 检查文件是否为 NTQQ 加密数据库
*/
export function isEncryptedNTDB (fileData: Buffer): boolean {
if (fileData.length < EXT_HEADER_SIZE + PAGE_SIZE) return false;
return fileData.subarray(0, 16).equals(SQLITE_HEADER);
}
/**
* 将加密的 NTQQ 数据库解密为标准 SQLite 数据库
* @param fileData 完整的加密数据库文件内容
* @param passphrase 服务端返回的密钥口令
* @returns 解密后的 SQLite 数据库 Buffer,失败返回 null
*/
export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer | null {
if (!isEncryptedNTDB(fileData)) return null;
const scData = fileData.subarray(EXT_HEADER_SIZE);
const totalPages = Math.floor(scData.length / PAGE_SIZE);
if (totalPages === 0) return null;
const salt = scData.subarray(0, SALT_SIZE);
const { encKey } = deriveKeys(passphrase, salt);
const output = Buffer.alloc(totalPages * PAGE_SIZE);
let offset = 0;
for (let pgno = 1; pgno <= totalPages; pgno++) {
const pageOffset = (pgno - 1) * PAGE_SIZE;
const rawPage = scData.subarray(pageOffset, pageOffset + PAGE_SIZE);
const skip = pgno === 1 ? SALT_SIZE : 0;
const decrypted = decryptPage(rawPage, encKey, skip);
if (pgno === 1) {
// 重建 Page 1: SQLite 标准文件头 + 解密内容
SQLITE_FORMAT.copy(output, 0);
decrypted.copy(output, 16);
// 修正 page_size 字段 (offset 16-17, big-endian)
output.writeUInt16BE(PAGE_SIZE, 16);
// 保留原始 reserved-bytes-per-page 值 (byte 20)
// NTQQ SQLCipher 使用 reserved=80 用于 B-tree 布局 (usable=4016)
// 即使加密保留区 (IV+HMAC) 实际只有 48 字节
// 清零会导致 SQLite 误判溢出指针,报 "database disk image is malformed"
offset = PAGE_SIZE;
} else {
decrypted.copy(output, offset);
offset += PAGE_SIZE;
}
}
return output;
}
/**
* 解密数据库文件并写入输出路径
* @param inputPath 加密数据库路径
* @param passphrase 密钥口令
* @param outputPath 输出路径 (默认: 原路径加 _decrypted 后缀)
* @returns 输出路径,失败返回 null
*/
export function decryptDatabaseFile (
inputPath: string,
passphrase: Buffer,
outputPath?: string
): string | null {
const fileData = fs.readFileSync(inputPath);
const result = decryptDatabase(fileData, passphrase);
if (!result) return null;
if (!outputPath) {
const dotIdx = inputPath.lastIndexOf('.');
outputPath = dotIdx > 0
? inputPath.substring(0, dotIdx) + '_decrypted' + inputPath.substring(dotIdx)
: inputPath + '_decrypted';
}
fs.writeFileSync(outputPath, result);
return outputPath;
}
+29
View File
@@ -0,0 +1,29 @@
export { deriveKeys, type DerivedKeys } from './crypto';
export { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
export {
checkSqliteAvailable,
DatabaseHandle,
openDatabase,
decryptAndOpen,
listTablesFromBuffer,
listTablesFromFile,
readSingleDatabase,
scanAllDatabases,
formatScanResults,
type TableInfo,
type ColumnInfo,
type DatabaseScanResult,
type DatabaseReadOptions,
} from './reader';
export {
EXT_HEADER_SIZE,
PAGE_SIZE,
SALT_SIZE,
KEY_SIZE,
IV_SIZE,
HMAC_SIZE,
RESERVE_SIZE,
KDF_ITERATIONS,
FAST_ITERATIONS,
HMAC_MASK,
} from './constants';
+425
View File
@@ -0,0 +1,425 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
type DatabaseSyncType = import('node:sqlite').DatabaseSync;
type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean; }) => DatabaseSyncType;
type SQLInputValue = import('node:sqlite').SQLInputValue;
let _DatabaseSync: DatabaseSyncCtor | null = null;
let _sqliteChecked = false;
async function loadSqlite (): Promise<DatabaseSyncCtor | null> {
if (_sqliteChecked) return _DatabaseSync;
_sqliteChecked = true;
try {
const mod = await import('node:sqlite');
_DatabaseSync = mod.DatabaseSync as unknown as DatabaseSyncCtor;
return _DatabaseSync;
} catch {
_DatabaseSync = null;
return null;
}
}
function getDatabaseSync (): DatabaseSyncCtor {
if (!_DatabaseSync) {
throw new Error(
'node:sqlite 不可用。请使用 Node.js 22+ 并添加 --experimental-sqlite 标志,' +
'或调用 checkSqliteAvailable() 检查可用性。'
);
}
return _DatabaseSync;
}
export async function checkSqliteAvailable (): Promise<boolean> {
const ctor = await loadSqlite();
return ctor !== null;
}
// ======================== 数据库连接管理 ========================
/** 数据库连接句柄,封装 DatabaseSync 实例 */
export class DatabaseHandle {
private db: DatabaseSyncType;
private _closed = false;
readonly filePath: string;
readonly readOnly: boolean;
constructor (filePath: string, readOnly = false) {
const DB = getDatabaseSync();
this.db = new DB(filePath, { readOnly });
this.filePath = filePath;
this.readOnly = readOnly;
}
/** 数据库是否已关闭 */
get closed (): boolean {
return this._closed;
}
private ensureOpen (): void {
if (this._closed) throw new Error('数据库已关闭');
}
/**
* 执行 SELECT 查询,返回所有结果行
* @param sql SQL 语句
* @param params 绑定参数 (位置参数数组 或 命名参数对象)
*/
query<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T[] {
this.ensureOpen();
const stmt = this.db.prepare(sql);
if (params) {
if (Array.isArray(params)) {
return stmt.all(...params) as T[];
}
return stmt.all(params) as T[];
}
return stmt.all() as T[];
}
/**
* 执行 SELECT 查询,仅返回第一行
* @param sql SQL 语句
* @param params 绑定参数
*/
queryOne<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T | undefined {
this.ensureOpen();
const stmt = this.db.prepare(sql);
if (params) {
if (Array.isArray(params)) {
return stmt.get(...params) as T | undefined;
}
return stmt.get(params) as T | undefined;
}
return stmt.get() as T | undefined;
}
/**
* 执行非查询 SQL (INSERT/UPDATE/DELETE/CREATE 等)
* @param sql SQL 语句
* @param params 绑定参数
* @returns 受影响的行数信息
*/
execute (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): { changes: number | bigint; lastInsertRowid: number | bigint; } {
this.ensureOpen();
const stmt = this.db.prepare(sql);
if (params) {
if (Array.isArray(params)) {
return stmt.run(...params);
}
return stmt.run(params);
}
return stmt.run();
}
/** 列出所有表的信息 */
listTables (): TableInfo[] {
this.ensureOpen();
return extractTablesInfo(this.db);
}
/** 获取指定表的列信息 */
getTableColumns (tableName: string): ColumnInfo[] {
this.ensureOpen();
const cols = this.db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
cid: number; name: string; type: string; notnull: number; pk: number;
}[];
return cols.map(col => ({
cid: col.cid,
name: col.name,
type: col.type,
notnull: col.notnull === 1,
pk: col.pk === 1,
}));
}
/** 获取表的行数 */
getRowCount (tableName: string): number {
this.ensureOpen();
const cnt = this.db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
return cnt?.cnt ?? 0;
}
/** 关闭数据库连接 */
close (): void {
if (!this._closed) {
this.db.close();
this._closed = true;
}
}
}
/**
* 打开一个已解密的 SQLite 数据库文件
* @param filePath 解密后的 .db 文件路径
* @param readOnly 是否以只读模式打开 (默认 true)
*/
export function openDatabase (filePath: string, readOnly = true): DatabaseHandle {
return new DatabaseHandle(filePath, readOnly);
}
/**
* 解密并打开一个加密的 NTQQ 数据库
* @param dbPath 加密数据库路径
* @param passphrase 密钥口令
* @param cacheDir 解密缓存目录 (可选)
* @param readOnly 是否只读 (默认 true)
*/
export function decryptAndOpen (
dbPath: string,
passphrase: Buffer,
cacheDir?: string,
readOnly = true
): DatabaseHandle {
const filename = path.basename(dbPath);
if (cacheDir) {
const cachedPath = path.join(cacheDir, filename);
// 已存在缓存直接打开
if (fs.existsSync(cachedPath)) {
return new DatabaseHandle(cachedPath, readOnly);
}
fs.mkdirSync(cacheDir, { recursive: true });
const outPath = decryptDatabaseFile(dbPath, passphrase, cachedPath);
if (!outPath) throw new Error(`解密失败: ${dbPath}`);
return new DatabaseHandle(outPath, readOnly);
}
// 无缓存目录: 解密到临时文件
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
const fileData = fs.readFileSync(dbPath);
const decryptedBuf = decryptDatabase(fileData, passphrase);
if (!decryptedBuf) throw new Error(`解密失败: ${dbPath}`);
fs.writeFileSync(tmpPath, decryptedBuf);
return new DatabaseHandle(tmpPath, readOnly);
}
/** 单个数据库表信息 */
export interface TableInfo {
name: string;
type: string; // 'table' | 'view' | ...
rowCount: number;
columns: ColumnInfo[];
}
/** 列信息 */
export interface ColumnInfo {
cid: number;
name: string;
type: string;
notnull: boolean;
pk: boolean;
}
/** 单个数据库扫描结果 */
export interface DatabaseScanResult {
/** 数据库文件名 */
filename: string;
/** 原始加密文件路径 */
sourcePath: string;
/** 解密后缓存文件路径 (仅当指定了 cacheDir 时) */
cachePath?: string;
success: boolean;
error?: string;
tables: TableInfo[];
}
/** 扫描/读取选项 */
export interface DatabaseReadOptions {
/** 解密后数据库缓存目录,不设置则使用临时文件 */
cacheDir?: string;
/** 是否跳过已存在的缓存文件 (默认 true) */
skipExistingCache?: boolean;
}
/**
* 从 DatabaseSync 对象提取表信息
*/
function extractTablesInfo (db: DatabaseSyncType): TableInfo[] {
const tables: TableInfo[] = [];
const masterRows = db.prepare(
"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY name"
).all() as { name: string; type: string; }[];
for (const { name: tableName, type: tableType } of masterRows) {
// 获取列信息
const columns: ColumnInfo[] = [];
try {
const cols = db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
cid: number; name: string; type: string; notnull: number; pk: number;
}[];
for (const col of cols) {
columns.push({
cid: col.cid,
name: col.name,
type: col.type,
notnull: col.notnull === 1,
pk: col.pk === 1,
});
}
} catch {
// PRAGMA 可能对某些表失败
}
// 获取行数
let rowCount = 0;
try {
const cnt = db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
rowCount = cnt?.cnt ?? 0;
} catch {
rowCount = -1;
}
tables.push({
name: tableName,
type: tableType,
rowCount,
columns,
});
}
return tables;
}
/**
* 打开一个解密后的 SQLite 文件,列出所有表和列信息
*/
export function listTablesFromFile (filePath: string): TableInfo[] {
const DB = getDatabaseSync();
const db = new DB(filePath, { readOnly: true });
try {
return extractTablesInfo(db);
} finally {
db.close();
}
}
export function listTablesFromBuffer (data: Buffer): TableInfo[] {
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
try {
fs.writeFileSync(tmpPath, data);
return listTablesFromFile(tmpPath);
} finally {
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
}
}
/**
* 解密并读取单个数据库文件
*
* @param dbPath 加密数据库文件路径
* @param passphrase 密钥口令
* @param options 可选配置 (缓存目录等)
* @returns 数据库扫描结果
*/
export function readSingleDatabase (
dbPath: string,
passphrase: Buffer,
options?: DatabaseReadOptions
): DatabaseScanResult {
const filename = path.basename(dbPath);
const result: DatabaseScanResult = {
filename,
sourcePath: dbPath,
success: false,
tables: [],
};
try {
// 如果指定了缓存目录,且缓存文件已存在,直接读取
if (options?.cacheDir) {
const cachedPath = path.join(options.cacheDir, filename);
result.cachePath = cachedPath;
if (options?.skipExistingCache !== false && fs.existsSync(cachedPath)) {
result.tables = listTablesFromFile(cachedPath);
result.success = true;
return result;
}
}
const fileData = fs.readFileSync(dbPath);
if (!isEncryptedNTDB(fileData)) {
result.error = 'Not an encrypted NTQQ database';
return result;
}
// 有缓存目录: 解密写入文件再读取
if (options?.cacheDir) {
fs.mkdirSync(options.cacheDir, { recursive: true });
const outPath = decryptDatabaseFile(dbPath, passphrase, result.cachePath);
if (!outPath) {
result.error = 'Decryption failed';
return result;
}
result.cachePath = outPath;
result.tables = listTablesFromFile(outPath);
} else {
// 无缓存目录: 解密到内存再用临时文件读取
const decryptedBuf = decryptDatabase(fileData, passphrase);
if (!decryptedBuf) {
result.error = 'Decryption returned null';
return result;
}
result.tables = listTablesFromBuffer(decryptedBuf);
}
result.success = true;
} catch (e) {
result.error = e instanceof Error ? e.message : String(e);
}
return result;
}
export function scanAllDatabases (
dbDir: string,
passphrase: Buffer,
options?: DatabaseReadOptions
): DatabaseScanResult[] {
const results: DatabaseScanResult[] = [];
if (!fs.existsSync(dbDir)) return results;
const files = fs.readdirSync(dbDir).filter(f => f.endsWith('.db')).sort();
for (const filename of files) {
const filePath = path.join(dbDir, filename);
const result = readSingleDatabase(filePath, passphrase, options);
results.push(result);
}
return results;
}
/**
* 格式化扫描结果为可读字符串
*/
export function formatScanResults (results: DatabaseScanResult[]): string {
const lines: string[] = [];
let totalTables = 0;
let successCount = 0;
for (const db of results) {
if (db.success) {
successCount++;
const cacheNote = db.cachePath ? ` → ${db.cachePath}` : '';
lines.push(`=== ${db.filename} (${db.tables.length} tables)${cacheNote} ===`);
for (const table of db.tables) {
totalTables++;
const colList = table.columns.map(c => `${c.name}:${c.type || '?'}`).join(', ');
lines.push(` ${table.name}: ${table.rowCount} rows [${colList}]`);
}
} else {
lines.push(`=== ${db.filename}: SKIP (${db.error}) ===`);
}
lines.push('');
}
lines.push(`Summary: ${successCount}/${results.length} databases decrypted, ${totalTables} total tables`);
return lines.join('\n');
}
Loaded 100 of 436 files, more files were not shown because too many files have changed in this diff. Show more