Compare commits

..
18 Commits
Author SHA1 Message Date
手瓜一十雪 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-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
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-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 .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-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
* 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-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 .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
28 changed files with 712 additions and 90 deletions

No files matched your search

-10
View File
@@ -1,16 +1,6 @@
# {VERSION}
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
NapCat.Shell.Windows.OneKey.zip (无头)
启动后可自动化部署一键包,教程参考使用文档安装部分
## 警告
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
+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}`);
+43 -15
View File
@@ -9,8 +9,8 @@ on:
permissions: write-all
env:
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
OPENROUTER_MODEL: "deepseek-v3.2-chat"
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "stepfun/step-3.5-flash:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -218,11 +218,11 @@ 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 }}
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
run: |
@@ -395,20 +395,19 @@ jobs:
BODY=$(jq -n \
--arg system "$SYSTEM_PROMPT" \
--arg user "$USER_CONTENT" \
--arg model "$OPENROUTER_MODEL" \
--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 "=== parsed response ==="
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
echo "$RESPONSE" | jq .
else
@@ -419,7 +418,7 @@ 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
@@ -436,18 +435,19 @@ jobs:
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:
tag_name: ${{ github.ref_name }}
name: NapCat ${{ github.ref_name }}
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.NAPCAT_BUILD }}
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: Update apifox
@@ -478,3 +478,31 @@ jobs:
--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="${GITHUB_REF#refs/tags/}"
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
+15 -1
View File
@@ -14,7 +14,18 @@ English | [简体中文](./docs/README_zh-CN.md) | [繁體中文](./docs/README_
---
## Notice
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested. No public community groups will be established during this period, but NapCat will continue to receive regular updates.
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested.
### Community Groups
You can get the join password directly from the **About** page of the WebUI.
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
> Note: The join key is only valid for the latest 100 versions, and requires NapCat version >= 4.17.31. If it fails, please update.
## Welcome
@@ -50,6 +61,9 @@ Download the latest version from the [Release](https://github.com/NapNeko/NapCat
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ Groups | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> Please do not mention this project in other communities (including other protocol-side or related application-side projects) to avoid disputes. If you have suggestions, please discuss them in the official group or submit a PR.
## Thanks
+13 -1
View File
@@ -16,7 +16,16 @@ _إطار عمل حديث على جانب البروتوكول مبني على N
---
## إعلان
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com. لن يتم إنشاء مجموعات مجتمع عامة خلال هذه الفترة، لكن NapCat يضمن استمرار التحديثات المنتظمة.
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com.
### مجموعات المجتمع
يمكنك الحصول على كلمة مرور الانضمام مباشرةً من **صفحة "حول" في WebUI**:
- [NapCat Family] Happy Family 1090875633:https://qm.qq.com/q/VwpnklcXqo
- [NapCat Family] Royal Relatives 1059714215:https://qm.qq.com/q/gq18RH7o7S
- [NapCat Family] Loving Family 1085662710:https://qm.qq.com/q/XyiyGPqa42
- [NapCat Family] Joyful Family 1085359803:https://qm.qq.com/q/E4nfkGD6oK
## مرحباً
@@ -52,6 +61,9 @@ _إطار عمل حديث على جانب البروتوكول مبني على N
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| مجموعات QQ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> يرجى عدم ذكر هذا المشروع في مجتمعات أخرى (بما في ذلك مشاريع البروتوكول الأخرى / مشاريع التطبيقات ذات الصلة) لتجنب الخلافات. إذا كانت لديك اقتراحات، يرجى مناقشتها في المجموعة الرسمية أو تقديم PR.
## شكر وتقدير
+15 -1
View File
@@ -14,7 +14,18 @@ _NTQQをベースにした最新のプロトコル側フレームワーク._
---
## お知らせ
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。この期間中、公開コミュニティグループは設立しませんが、NapCat は通常通りの更新を保証します。
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。
### コミュニティグループ
**WebUI の「について」ページ** から参加パスワードを直接取得できます:
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
> 注意:入会キーは最新の100バージョンにのみ有効で、NapCatバージョン >= 4.17.31 が必要です。エラーが発生した場合は更新してください。
## ようこそ
@@ -50,6 +61,9 @@ NapCat は現在、新しいメインメンテナーを募集しています。n
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ グループ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> 他のコミュニティでこのプロジェクト(他のプロトコル側/関連アプリケーション側のプロジェクトを含む)に言及して論争を引き起こさないでください。提案がある場合は、公式交流グループで議論するか、PRを提出してください。
## 謝辞
+13 -1
View File
@@ -14,8 +14,17 @@ _NTQQ 기반으로 구현된 최신 프로토콜 사이드 프레임워크._
---
## 공지
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요. 이 기간 동안 공개 커뮤니티 그룹은 만들어지지 않지만, NapCat은 정기적인 업데이트를 보장합니다.
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요.
### 커뮤니티 그룹
**WebUI 의 「정보」페이지** 에서 입장 비밀번호를 바로 확인할 수 있습니다:
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
> 참고: 가입 키는 최신 100개 버전에서만 유효하며, NapCat 버전 >= 4.17.31이 필요합니다. 오류가 발생하면 업데이트하세요.
## 환영합니다
- NapCatQQ는 NTQQ를 기반으로 한 최신 Bot 프로토콜 구현체입니다
@@ -50,6 +59,9 @@ NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeo
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ 그룹 | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> 다른 커뮤니티에서 이 프로젝트(다른 프로토콜 측/관련 애플리케이션 측 프로젝트 포함)를 언급하여 논쟁을 일으키지 마세요. 제안이 있으시면 공식 그룹에서 토론하거나 PR을 제출해 주세요.
## 감사의 말
+15 -1
View File
@@ -14,7 +14,18 @@ _Современный фреймворк на стороне протокол
---
## Объявление
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com. В этот период публичные группы сообщества создаваться не будут, но NapCat гарантирует регулярные обновления.
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com.
### Группы сообщества
Пароль для вступления можно получить прямо на **странице «О программе» в WebUI**:
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
> Примечание: Ключ для входа действителен только для последних 100 версий и требует версию NapCat >= 4.17.31. Если возникает ошибка, пожалуйста, обновитесь.
## Добро пожаловать
@@ -50,6 +61,9 @@ NapCat в настоящее время ищет нового основного
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ группы | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> Пожалуйста, не упоминайте данный проект (включая другие протокольные/прикладные проекты) в других сообществах во избежание споров. Если у вас есть предложения, обсуждайте их в официальной группе или отправляйте PR.
## Благодарности
+15 -1
View File
@@ -14,7 +14,18 @@ _基于 NTQQ 实现的现代化协议端框架._
---
## 公告
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com ,在此期不会建立任何公开社区交流群,Napcat会保证此期间的正常更新。
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com 。
### 交流群
可直接在 **WebUI 关于页面** 获取入群密码:
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群号(1090875633)
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群号(1059714215)
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群号(1085662710)
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群号(1085359803)
> 注意:入群密钥只适合最新的100个版本,且 NapCat 版本需 >= 4.17.31,如果不符合请更新。
## 欢迎
@@ -50,6 +61,9 @@ NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ 群 | [欢乐一家亲](https://qm.qq.com/q/VwpnklcXqo) | [皇亲国戚](https://qm.qq.com/q/gq18RH7o7S) | [相亲相爱一家人](https://qm.qq.com/q/XyiyGPqa42) | [开心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
## 致谢
+15 -1
View File
@@ -14,7 +14,18 @@ _基於 NTQQ 實現的現代化協議端框架._
---
## 公告
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。在此期間不會建立任何公開社群交流群,NapCat 會保證此期間的正常更新。
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。
### 交流群
可直接在 **WebUI 關於頁面** 取得入群密碼:
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群號(1090875633)
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群號(1059714215)
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群號(1085662710)
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群號(1085359803)
> 注意:入群密鑰只適用於最新的100個版本,且 NapCat 版本需 >= 4.17.31,如果錯誤請更新。
## 歡迎
@@ -50,6 +61,9 @@ NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanae
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| QQ 群 | [歡樂一家親](https://qm.qq.com/q/VwpnklcXqo) | [皇親國戚](https://qm.qq.com/q/gq18RH7o7S) | [相親相愛一家人](https://qm.qq.com/q/XyiyGPqa42) | [開心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|:-:|:-:|:-:|:-:|:-:|
> 請不要在其他社群提及本專案(包括其他協議端/相關應用端專案)以免引發爭論。如有建議,請到官方交流群討論或提交 PR。
## 致謝
+2 -2
View File
@@ -330,10 +330,10 @@ export class NTQQWebApi {
return (hash & 0x7FFFFFFF).toString();
}
async getAlbumListByNTQQ (gc: string) {
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',
@@ -230,8 +230,8 @@ export class PacketOperationContext {
}
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.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return 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);
@@ -312,6 +312,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);
@@ -1,3 +1,4 @@
import * as crypto from 'node:crypto';
import * as zlib from 'node:zlib';
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
import {
@@ -665,11 +666,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 +680,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')),
]),
},
}];
@@ -1,19 +1,20 @@
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(
+4 -2
View File
@@ -67,8 +67,10 @@ export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer |
decrypted.copy(output, 16);
// 修正 page_size 字段 (offset 16-17, big-endian)
output.writeUInt16BE(PAGE_SIZE, 16);
// 清零 reserved space 标志 (offset 20)
output[20] = 0;
// 保留原始 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);
+217 -9
View File
@@ -84,16 +84,27 @@ export async function NCoreInitFramework (
// 初始化 FFmpeg 服务
await FFmpegService.init(pathWrapper.binaryPath, logger);
// 提前启动 WebUI,使其在登录前可用,支持通过 WebUI 操控登录过程
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
// 直到登录成功后,执行下一步
// const selfInfo = {
// uid: 'u_FUSS0_x06S_9Tf4na_WpUg',
// uin: '3684714082',
// nick: '',
// online: true
// }
const selfInfo = await new Promise<SelfInfo>((resolve) => {
const loginContext = { isLogined: false };
const loginListener = new NodeIKernelLoginListener();
loginListener.onUserLoggedIn = (userid: string) => {
const tips = `当前账号(${userid})已登录,无法重复登录`;
logger.logError(tips);
WebUiDataRuntime.setQQLoginError(tips);
};
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
await new Promise<void>(resolve => {
registerInitCallback(() => resolve());
});
@@ -104,6 +115,47 @@ export async function NCoreInitFramework (
online: true,
});
};
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!loginContext.isLogined) {
logger.logError('[NapCat] [Framework] [Login] QRCode Session Failed, ErrType:', errType, 'ErrCode:', errCode);
if (errType === 1 && errCode === 3) {
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
}
}
};
loginListener.onLoginFailed = (...args) => {
const errInfo = JSON.stringify(args);
logger.logError('[NapCat] [Framework] [Login] Login Failed, ErrInfo:', errInfo);
WebUiDataRuntime.setQQLoginError(`登录失败: ${errInfo}`);
};
loginListener.onLoginConnected = () => {
logger.log('[NapCat] [Framework] 登录服务已连接');
// 注册 WebUI 登录操作回调
registerWebUiLoginCallbacks(loginService, loginContext, logger);
// 获取历史登录列表供 WebUI 使用
loginService.getLoginList().then((res) => {
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
};
loginListener.onQRCodeSessionUserScaned = () => {
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
};
loginListener.onPasswordLoginFailed = (...args) => {
logger.logError('[NapCat] [Framework] 密码登录失败:', ...args);
};
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
});
// 过早进入会导致addKernelMsgListener等Listener添加失败
@@ -116,10 +168,8 @@ export async function NCoreInitFramework (
}
await loaderObject.core.initCore();
// 启动WebUi
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
// 登录成功后设置数据路径
WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath);
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
// // 测试 DatabaseApi
// if (dbPassphrase) {
@@ -147,6 +197,164 @@ export async function NCoreInitFramework (
}
}
function registerWebUiLoginCallbacks (
loginService: NodeIKernelLoginService,
loginContext: { isLogined: boolean; },
logger: LogWrapper
) {
// 刷新二维码
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
loginService.getQRCodePicture();
});
// 快速登录
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
return await new Promise((resolve) => {
if (!uin) {
return resolve({ result: false, message: '快速登录失败' });
}
logger.log('[NapCat] [Framework] 正在快速登录', uin);
loginService.quickLoginWithUin(uin).then(res => {
const success = res.result === '0' && !res.loginErrorInfo?.errMsg;
if (!success) {
const errMsg = res.loginErrorInfo?.errMsg || `快速登录失败,错误码: ${res.result}`;
WebUiDataRuntime.setQQLoginError(errMsg);
resolve({ result: false, message: errMsg });
} else {
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
resolve({ result: true, message: '' });
}
}).catch((e) => {
logger.logError('[NapCat] [Framework] 快速登录异常:', e);
WebUiDataRuntime.setQQLoginError('快速登录发生错误');
resolve({ result: false, message: '快速登录发生错误' });
});
});
});
// 密码登录
WebUiDataRuntime.setPasswordLoginCall(async (uin: string, passwordMd5: string) => {
return await new Promise((resolve) => {
if (!uin || !passwordMd5) {
return resolve({ result: false, message: '密码登录失败:参数不完整' });
}
logger.log('[NapCat] [Framework] 正在密码登录', uin);
loginService.passwordLogin({
uin,
passwordMd5,
step: 0,
newDeviceLoginSig: new Uint8Array(),
proofWaterSig: new Uint8Array(),
proofWaterRand: new Uint8Array(),
proofWaterSid: new Uint8Array(),
unusualDeviceCheckSig: new Uint8Array(),
}).then(res => {
if (res.result === '140022008') {
const proofWaterUrl = res.loginErrorInfo?.proofWaterUrl || '';
resolve({ result: false, message: '需要验证码', needCaptcha: true, proofWaterUrl });
} else if (res.result === '140022010' || res.result === '140022011') {
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
} else if (res.result !== '0') {
const errMsg = res.loginErrorInfo?.errMsg || '密码登录失败';
WebUiDataRuntime.setQQLoginError(errMsg);
resolve({ result: false, message: errMsg });
} else {
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
resolve({ result: true, message: '' });
}
}).catch((e) => {
logger.logError('[NapCat] [Framework] 密码登录异常:', e);
WebUiDataRuntime.setQQLoginError('密码登录发生错误');
resolve({ result: false, message: '密码登录发生错误' });
});
});
});
// 验证码登录(密码登录需要验证码时的第二步)
WebUiDataRuntime.setCaptchaLoginCall(async (uin: string, passwordMd5: string, ticket: string, randstr: string, sid: string) => {
return await new Promise((resolve) => {
if (!uin || !passwordMd5 || !ticket) {
return resolve({ result: false, message: '验证码登录失败:参数不完整' });
}
logger.log('[NapCat] [Framework] 正在验证码登录', uin);
loginService.passwordLogin({
uin,
passwordMd5,
step: 1,
newDeviceLoginSig: new Uint8Array(),
proofWaterSig: new TextEncoder().encode(ticket),
proofWaterRand: new TextEncoder().encode(randstr),
proofWaterSid: new TextEncoder().encode(sid),
unusualDeviceCheckSig: new Uint8Array(),
}).then(res => {
if (res.result === '140022010' || res.result === '140022011') {
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
} else if (res.result !== '0') {
const errMsg = res.loginErrorInfo?.errMsg || '验证码登录失败';
WebUiDataRuntime.setQQLoginError(errMsg);
resolve({ result: false, message: errMsg });
} else {
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
resolve({ result: true, message: '' });
}
}).catch((e) => {
logger.logError('[NapCat] [Framework] 验证码登录异常:', e);
WebUiDataRuntime.setQQLoginError('验证码登录发生错误');
resolve({ result: false, message: '验证码登录发生错误' });
});
});
});
// 新设备验证登录(密码登录需要新设备验证时的第二步)
WebUiDataRuntime.setNewDeviceLoginCall(async (uin: string, passwordMd5: string, newDevicePullQrCodeSig: string) => {
return await new Promise((resolve) => {
if (!uin || !passwordMd5 || !newDevicePullQrCodeSig) {
return resolve({ result: false, message: '新设备验证登录失败:参数不完整' });
}
logger.log('[NapCat] [Framework] 正在新设备验证登录', uin);
loginService.passwordLogin({
uin,
passwordMd5,
step: 2,
newDeviceLoginSig: new TextEncoder().encode(newDevicePullQrCodeSig),
proofWaterSig: new Uint8Array(),
proofWaterRand: new Uint8Array(),
proofWaterSid: new Uint8Array(),
unusualDeviceCheckSig: new Uint8Array(),
}).then(res => {
if (res.result === '140022011') {
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
const sig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
resolve({ result: false, message: '异常设备需要验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig: sig });
} else if (res.result !== '0') {
const errMsg = res.loginErrorInfo?.errMsg || '新设备验证登录失败';
WebUiDataRuntime.setQQLoginError(errMsg);
resolve({ result: false, message: errMsg });
} else {
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
resolve({ result: true, message: '' });
}
}).catch((e) => {
logger.logError('[NapCat] [Framework] 新设备验证登录异常:', e);
WebUiDataRuntime.setQQLoginError('新设备验证登录发生错误');
resolve({ result: false, message: '新设备验证登录发生错误' });
});
});
});
}
export class NapCatFramework {
public core: NapCatCore;
context: InstanceContext;
@@ -1,17 +1,22 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { NTQQWebApi } from 'napcat-core/apis';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
attach_info: Type.String({ default: '', description: '附加信息(用于分页,从上一次返回结果中获取)' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Array(Type.Any(), { description: '群相册列表' });
const ReturnSchema = Type.Object({
album_list: Type.Array(Type.Any(), { description: '群相册列表' }),
attach_info: Type.String({ description: '分页附加信息,传入下一次请求以获取更多数据' }),
has_more: Type.Boolean({ description: '是否有更多数据' }),
}, { description: '群相册列表响应' });
type GetQunAlbumListReturn = Awaited<globalThis.ReturnType<NTQQWebApi['getAlbumListByNTQQ']>>['response']['album_list'];
type GetQunAlbumListReturn = Static<typeof ReturnSchema>;
export class GetQunAlbumList extends OneBotAction<PayloadType, GetQunAlbumListReturn> {
override actionName = ActionName.GetQunAlbumList;
@@ -19,19 +24,29 @@ export class GetQunAlbumList extends OneBotAction<PayloadType, GetQunAlbumListRe
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
attach_info: '',
};
override returnExample = {
album_list: [
{
album_id: 'album_1',
album_name: '测试相册',
cover_url: 'http://example.com/cover.jpg',
create_time: 1734567890
}
],
attach_info: '',
has_more: false,
};
override returnExample = [
{
album_id: 'album_1',
album_name: '测试相册',
cover_url: 'http://example.com/cover.jpg',
create_time: 1734567890
}
];
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<GetQunAlbumListReturn> {
return (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id)).response.album_list;
const resp = (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id, payload.attach_info)).response;
return {
album_list: resp.album_list,
attach_info: resp.attach_info,
has_more: resp.has_more,
};
}
}
@@ -3,6 +3,7 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { QuickAction, QuickActionEvent } from '@/napcat-onebot/types';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message';
const SenderSchema = Type.Object({
user_id: Type.String({ description: '用户ID' }),
@@ -16,7 +17,7 @@ const SenderSchema = Type.Object({
// 定义 QuickAction 的详细 Schema
const QuickActionSchema = Type.Object({
reply: Type.Optional(Type.String({ description: '回复内容' })),
reply: Type.Optional(OB11MessageMixTypeSchema),
auto_escape: Type.Optional(Type.Boolean({ description: '是否作为纯文本发送' })),
at_sender: Type.Optional(Type.Boolean({ description: '是否 @ 发送者' })),
delete: Type.Optional(Type.Boolean({ description: '是否撤回该消息' })),
+36 -4
View File
@@ -215,11 +215,11 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
uuid?: string,
packetMsg: PacketMsg[],
deleteAfterSentFiles: string[],
innerPacketMsg?: Array<{ uuid: string, packetMsg: PacketMsg[]; }>;
innerPacketMsg?: Array<{ uuid: string, packetMsg?: PacketMsg[], actionMsgBody?: UploadForwardMsgParams['actionMsgBody']; }>;
} | null> {
const packetMsg: PacketMsg[] = [];
const delFiles: string[] = [];
const innerMsg: Array<{ uuid: string, packetMsg: PacketMsg[]; }> = new Array();
const innerMsg: Array<{ uuid: string, packetMsg?: PacketMsg[], actionMsgBody?: UploadForwardMsgParams['actionMsgBody']; }> = new Array();
for (const node of messageNodes) {
if (dp >= 3) {
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
@@ -240,7 +240,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
if (uploadReturnData?.uuid) {
innerMsg.push({ uuid: uploadReturnData.uuid, packetMsg: uploadReturnData.packetMsg });
uploadReturnData.innerPacketMsg?.forEach(m => {
innerMsg.push({ uuid: m.uuid, packetMsg: m.packetMsg });
innerMsg.push(m);
});
}
@@ -274,6 +274,37 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
const msgCache = await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
delFiles.push(...msgCache);
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
// 检测嵌套合并转发消息,拉取内层protobuf数据
for (const element of msg.elements) {
let resId: string | undefined;
let uuid: string | undefined;
if (element.multiForwardMsgElement?.resId) {
resId = element.multiForwardMsgElement.resId;
uuid = element.multiForwardMsgElement.fileName;
} else if (element.arkElement?.bytesData) {
try {
const json = JSON.parse(element.arkElement.bytesData);
if (json.app === 'com.tencent.multimsg') {
resId = json.meta?.detail?.resid;
uuid = json.meta?.detail?.uniseq || json.extra?.filename;
}
} catch { /* not a valid json */ }
}
if (resId && uuid) {
try {
const rawActions = await this.core.apis.PacketApi.pkt.operation.FetchForwardMsgRaw(resId);
for (const action of rawActions) {
if (action.actionCommand === 'MultiMsg') {
innerMsg.push({ uuid, actionMsgBody: action.actionData.msgBody });
} else {
innerMsg.push({ uuid: action.actionCommand, actionMsgBody: action.actionData.msgBody });
}
}
} catch (e) {
this.core.context.logger.logError(`获取合并转发内层消息失败: ${(e as Error)?.stack}`);
}
}
}
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
packetMsg.push(transformedMsg);
}
@@ -289,10 +320,11 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
actionCommand: 'MultiMsg',
actionMsg: packetMsg,
}];
innerMsg.forEach(({ uuid, packetMsg: msg }) => {
innerMsg.forEach(({ uuid, packetMsg: msg, actionMsgBody: raw }) => {
uploadMsgData.push({
actionCommand: uuid,
actionMsg: msg,
actionMsgBody: raw,
});
});
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsgV2(uploadMsgData, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
+6 -6
View File
@@ -1,12 +1,12 @@
import { OB11BaseMetaEvent } from '@/napcat-onebot/event/meta/OB11BaseMetaEvent';
import { OB11BaseNoticeEvent } from '@/napcat-onebot/event/notice/OB11BaseNoticeEvent';
import { OB11Message } from '@/napcat-onebot/types/message';
import { OB11Message, OB11MessageMixType } from '@/napcat-onebot/types/message';
export type QuickActionEvent = OB11Message | OB11BaseMetaEvent | OB11BaseNoticeEvent;
export type PostEventType = OB11Message | OB11BaseMetaEvent | OB11BaseNoticeEvent;
export interface QuickActionPrivateMessage {
reply?: string;
reply?: OB11MessageMixType;
auto_escape?: boolean;
}
@@ -30,7 +30,7 @@ export interface QuickActionGroupRequest {
}
export type QuickAction =
QuickActionPrivateMessage
& QuickActionGroupMessage
& QuickActionFriendRequest
& QuickActionGroupRequest;
QuickActionPrivateMessage
& QuickActionGroupMessage
& QuickActionFriendRequest
& QuickActionGroupRequest;
+14 -3
View File
@@ -67,6 +67,7 @@ export class MessageTransport implements RpcTransport {
resolve: (response: RpcResponse) => void;
reject: (error: Error) => void;
}>();
private callbackHandler?: (callbackId: string, args: SerializedValue[]) => Promise<SerializedValue>;
private sendMessage: (message: string) => void | Promise<void>;
@@ -113,15 +114,25 @@ export class MessageTransport implements RpcTransport {
}
async send (request: RpcRequest): Promise<RpcResponse> {
return new Promise((resolve, reject) => {
this.pendingRequests.set(request.id, { resolve, reject });
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, _reject) => {
const id = request.id;
const reject = (error: any) => {
this.pendingRequests.delete(id);
_reject(error);
};
this.pendingRequests.set(id, { resolve, reject });
const message = JSON.stringify({
type: 'request',
request,
});
Promise.resolve(this.sendMessage(message)).catch(reject);
try {
await this.sendMessage(message);
} catch (error) {
reject(error);
}
});
}
@@ -1,11 +1,14 @@
import { RequestHandler } from 'express';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { WebUiConfig } from '@/napcat-webui-backend/index';
import { sendSuccess, sendError } from '@/napcat-webui-backend/src/utils/response';
import { WebUiConfig, webUiPathWrapper } from '@/napcat-webui-backend/index';
import { getLatestTag, getAllTags, compareSemVer } from 'napcat-common/src/helper';
import { getLatestActionArtifacts, getMirrorConfig } from '@/napcat-common/src/mirror';
import { NapCatCoreWorkingEnv } from '@/napcat-webui-backend/src/types';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
export const GetNapCatVersion: RequestHandler = (_, res) => {
const data = WebUiDataRuntime.GetNapCatVersion();
@@ -178,3 +181,14 @@ export const GetMirrorsHandler: RequestHandler = (_, res) => {
const config = getMirrorConfig();
sendSuccess(res, { mirrors: config.fileMirrors });
};
export const GetNapCatFileHashHandler: RequestHandler = (_, res) => {
try {
const filePath = path.join(webUiPathWrapper.binaryPath, 'napcat.mjs');
const fileBuffer = fs.readFileSync(filePath);
const hash = crypto.createHash('sha512').update(fileBuffer).digest('hex');
sendSuccess(res, { hash, file: 'napcat.mjs', algorithm: 'sha512' });
} catch (error) {
sendError(res, `无法计算 napcat.mjs 的 hash:${(error as Error).message}`);
}
};
@@ -3,6 +3,7 @@ import store from 'napcat-common/src/store';
import type { WebUiCredentialJson, WebUiCredentialInnerJson } from '@/napcat-webui-backend/src/types';
export class AuthHelper {
private static readonly secretKey = process.env['NAPCAT_WEBUI_JWT_SECRET_KEY'] || Math.random().toString(36).slice(2);
private static readonly MAX_CREDENTIAL_VALID_SECONDS = 3600;
public static getSecretKey (): string {
return AuthHelper.secretKey;
@@ -15,7 +16,8 @@ export class AuthHelper {
*/
public static signCredential (hash: string): WebUiCredentialJson {
const innerJson: WebUiCredentialInnerJson = {
CreatedTime: Date.now(),
// 统一使用秒级时间戳,避免与校验逻辑出现单位不一致
CreatedTime: Math.floor(Date.now() / 1000),
HashEncoded: hash,
};
const jsonString = JSON.stringify(innerJson);
@@ -59,10 +61,11 @@ export class AuthHelper {
return false;
}
const currentTime = Date.now() / 1000;
const createdTime = credentialJson.Data.CreatedTime;
const timeDifference = currentTime - createdTime;
return timeDifference <= 3600 && credentialJson.Data.HashEncoded === AuthHelper.generatePasswordHash(token);
const currentTimeSeconds = Math.floor(Date.now() / 1000);
const createdTimeSeconds = Math.floor(Number(credentialJson.Data.CreatedTime));
const timeDifferenceSeconds = currentTimeSeconds - createdTimeSeconds;
const isWithinOneHour = timeDifferenceSeconds >= 0 && timeDifferenceSeconds <= AuthHelper.MAX_CREDENTIAL_VALID_SECONDS;
return isWithinOneHour && credentialJson.Data.HashEncoded === AuthHelper.generatePasswordHash(token);
}
/**
@@ -1,5 +1,5 @@
import { Router } from 'express';
import { GetThemeConfigHandler, GetNapCatVersion, QQVersionHandler, SetThemeConfigHandler, getLatestTagHandler, getAllReleasesHandler, GetMirrorsHandler } from '../api/BaseInfo';
import { GetThemeConfigHandler, GetNapCatVersion, QQVersionHandler, SetThemeConfigHandler, getLatestTagHandler, getAllReleasesHandler, GetMirrorsHandler, GetNapCatFileHashHandler } from '../api/BaseInfo';
import { StatusRealTimeHandler } from '@/napcat-webui-backend/src/api/Status';
import { GetProxyHandler } from '../api/Proxy';
@@ -14,5 +14,6 @@ router.get('/GetSysStatusRealTime', StatusRealTimeHandler);
router.get('/proxy', GetProxyHandler);
router.get('/Theme', GetThemeConfigHandler);
router.post('/SetTheme', SetThemeConfigHandler);
router.get('/GetNapCatFileHash', GetNapCatFileHashHandler);
export { router as BaseRouter };
@@ -84,7 +84,13 @@ class TerminalManager {
ws.on('message', (data) => {
if (instance) {
const result = JSON.parse(data.toString());
let text: string;
if (Array.isArray(data)) {
text = Buffer.concat(data).toString();
} else {
text = data.toString();
}
const result = JSON.parse(text);
if (result.type === 'input') {
instance.pty.write(result.data);
}
@@ -340,4 +340,11 @@ export default class WebUIManager {
);
return data.data;
}
public static async GetNapCatFileHash () {
const { data } = await serverRequest.get<ServerResponse<{ hash: string; file: string; algorithm: string; }>>(
'/base/GetNapCatFileHash'
);
return data.data;
}
}
@@ -3,8 +3,12 @@ import { Chip } from '@heroui/chip';
import { Divider } from '@heroui/divider';
import { Image } from '@heroui/image';
import { Link } from '@heroui/link';
import { Select, SelectItem } from '@heroui/select';
import { Snippet } from '@heroui/snippet';
import { Spinner } from '@heroui/spinner';
import { Tooltip } from '@heroui/tooltip';
import { useRequest } from 'ahooks';
import { useEffect, useState } from 'react';
import {
BsCodeSlash,
BsCpu,
@@ -16,7 +20,10 @@ import {
} from 'react-icons/bs';
import { IoDocument, IoRocketSharp } from 'react-icons/io5';
import CryptoJS from 'crypto-js';
import logo from '@/assets/images/logo.png';
import QQManager from '@/controllers/qq_manager';
import WebUIManager from '@/controllers/webui_manager';
function VersionInfo () {
@@ -38,6 +45,113 @@ function VersionInfo () {
);
}
function NapCatFileHash () {
const { data: hashData, loading: hashLoading, error: hashError } = useRequest(WebUIManager.GetNapCatFileHash);
const { data: loginList, loading: listLoading, error: listError } = useRequest(QQManager.getQQQuickLoginListNew);
const { data: loginData, loading: loginLoading, error: loginError } = useRequest(QQManager.getQQLoginInfo);
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const loading = hashLoading || listLoading || loginLoading;
const error = hashError || listError || loginError;
// 优先使用 getLoginList 返回的账号列表,回退到当前登录账号
const accounts: { uin: string; label: string; }[] = [];
// 添加 LoginList 账号
if (loginList && loginList.length > 0) {
loginList.forEach(item => {
accounts.push({
uin: item.uin,
label: item.nickName ? `${item.nickName}(${item.uin})` : item.uin,
});
});
}
// 确保当前登录账号也在列表中
// 注意:API 返回的 uin 类型可能不一致(string/number),做一次转换比较
if (loginData?.uin) {
const isLoginAccountInList = accounts.some(acc => String(acc.uin) === String(loginData.uin));
if (!isLoginAccountInList) {
accounts.push({
uin: String(loginData.uin),
label: loginData.nick ? `${loginData.nick}(${loginData.uin})` : String(loginData.uin)
});
}
}
// 自动选择第一个账号
useEffect(() => {
if (accounts.length > 0) {
const isSelectedValid = selectedUin && accounts.some(acc => acc.uin === selectedUin);
if (!isSelectedValid) {
if (loginData?.uin && accounts.some((acc) => acc.uin == loginData.uin)) {
setSelectedUin(loginData.uin);
} else {
setSelectedUin(accounts[0].uin);
}
}
}
}, [accounts, selectedUin, loginData]);
const currentAccount = accounts.find((acc) => acc.uin === selectedUin) || accounts[0];
const password = (hashData && currentAccount)
? CryptoJS.SHA512(hashData.hash + currentAccount.uin).toString().substring(0, 7)
: null;
return (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm font-medium text-default-700">
<span>入群密码</span>
{loading && <Spinner size="sm" color="default" />}
</div>
{error ? (
<Chip color="warning" variant="flat" size="sm">无法计算:{(error as Error).message}</Chip>
) : loading ? null : accounts.length > 0 ? (
<div className="space-y-3">
{accounts.length > 1 && (
<Select
label="选择账号"
size="sm"
selectedKeys={selectedUin ? [selectedUin] : []}
onChange={(e) => setSelectedUin(e.target.value)}
className="max-w-full"
>
{accounts.map((acc) => (
<SelectItem key={acc.uin} textValue={acc.label}>
{acc.label}
</SelectItem>
))}
</Select>
)}
{password && (
<div className="space-y-1">
{accounts.length === 1 && <p className="text-xs text-default-500">{currentAccount.label}</p>}
<Tooltip content={`使用 ${currentAccount.label} 申请入群,以此值作为入群密码`} placement="top">
<Snippet
size="sm"
variant="flat"
symbol=""
codeString={password}
className="w-full"
classNames={{
pre: 'text-xs break-all whitespace-pre-wrap font-mono',
}}
>
{password}
</Snippet>
</Tooltip>
</div>
)}
<p className="text-xs text-warning-500">入群密钥绑定QQ,使用对应QQ申请入群即可。</p>
</div>
) : null}
</div>
);
}
export default function AboutPage () {
const features = [
{
@@ -69,8 +183,10 @@ export default function AboutPage () {
const links = [
{ icon: <BsGithub />, name: 'GitHub', href: 'https://github.com/NapNeko/NapCatQQ' },
{ icon: <BsTelegram />, name: 'Telegram', href: 'https://t.me/napcatqq' },
{ icon: <BsTencentQq />, name: 'QQ 群 1', href: 'https://qm.qq.com/q/F9cgs1N3Mc' },
{ icon: <BsTencentQq />, name: 'QQ 群 2', href: 'https://qm.qq.com/q/hSt0u9PVn' },
{ icon: <BsTencentQq />, name: '交流群 欢乐一家亲', href: 'https://qm.qq.com/q/VwpnklcXqo' },
{ icon: <BsTencentQq />, name: '交流群 皇亲国戚', href: 'https://qm.qq.com/q/gq18RH7o7S' },
{ icon: <BsTencentQq />, name: '交流群 相亲相爱一家人', href: 'https://qm.qq.com/q/XyiyGPqa42' },
{ icon: <BsTencentQq />, name: '交流群 开心家族', href: 'https://qm.qq.com/q/E4nfkGD6oK' },
{ icon: <IoDocument />, name: '文档', href: 'https://napcat.napneko.icu/' },
];
@@ -139,7 +255,8 @@ export default function AboutPage () {
<CardHeader className="pb-0 pt-4 px-4">
<h2 className="text-lg font-bold">相关资源</h2>
</CardHeader>
<CardBody className="py-4">
<CardBody className="py-4 space-y-4">
<NapCatFileHash />
<div className="flex flex-col gap-2">
{links.map((link, idx) => (
<Link
+1 -1
View File
@@ -1,2 +1,2 @@
packages:
- 'packages/*'
- packages/*