Compare commits

...
21 Commits
Author SHA1 Message Date
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
50 changed files with 1240 additions and 88 deletions

No files matched your search

+188 -1
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';
@@ -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);
@@ -173,6 +190,41 @@ export function generateResultComment (
`| 🕐 完成时间 | ${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) {
@@ -228,3 +280,138 @@ 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');
}
+112 -2
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,97 @@ 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}`);
}
}
// ============== 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 +283,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) {
+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);
}
+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, basename, 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);
});
+114 -3
View File
@@ -191,7 +191,7 @@ jobs:
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 7 # 保留 7 天
retention-days: 5 # 保留 5 天(仓库上限)
# ---------------------------------------------------------------------------
# Job 4: 构建 Shell 包
@@ -263,7 +263,7 @@ jobs:
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 7 # 保留 7 天
retention-days: 5 # 保留 5 天(仓库上限)
# ---------------------------------------------------------------------------
# Job 5: 更新评论为构建结果
@@ -272,7 +272,7 @@ jobs:
# 使用 always() 确保即使构建失败/取消也会执行
# ---------------------------------------------------------------------------
update-comment-result:
needs: [check-build, update-comment-building, build-framework, build-shell]
needs: [check-build, update-comment-building, build-framework, build-shell, publish-pr-release]
if: always() && needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
steps:
@@ -301,4 +301,115 @@ jobs:
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
# PR Release 信息(用于在评论中显示安装命令)
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
# ---------------------------------------------------------------------------
# Job 6: 发布 PR 构建产物到 napcat-pr-release 仓库
# ---------------------------------------------------------------------------
# 将所有构建产物打包 + 从 NapCat-Installer 拉取并修改安装脚本,
# 一起发布为 GitHub Release(公开可下载,无需登录)。
# Release 会由 napcat-pr-release 仓库的定时任务在 24h 后自动清理。
# ---------------------------------------------------------------------------
publish-pr-release:
needs: [check-build, build-framework, build-shell]
if: always() && needs.check-build.outputs.should_build == 'true' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
runs-on: ubuntu-latest
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 }} # 'success' | 'failure' | 'skipped'
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: 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: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.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
# 将修改后的安装脚本也上传为 CI artifact(自动过期)
- 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
# ---------------------------------------------------------------------------
# Job 7: 触发 NapCat-Docker 仓库的 PR 测试镜像构建
# ---------------------------------------------------------------------------
# 仅当 Shell 构建成功、且 Release 已发布时触发。
# Docker 构建从公开 Release 下载产物,无需跨仓 artifact PAT。
# ---------------------------------------------------------------------------
trigger-docker:
needs: [check-build, build-shell, publish-pr-release]
if: needs.check-build.outputs.should_build == 'true' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: 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: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
PR_HEAD_REPO: ${{ needs.check-build.outputs.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
+1 -2
View File
@@ -12,7 +12,7 @@ permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "openrouter/hunter-alpha"
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -406,7 +406,6 @@ jobs:
with:
tag_name: ${{ inputs.version }}
name: NapCat ${{ inputs.version }}
token: ${{ secrets.NAPCAT_BUILD }}
body_path: CHANGELOG.md
files: |
NapCat.Shell.Windows.Node.zip
+3 -3
View File
@@ -25,7 +25,7 @@ export class NTQQGroupApi {
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;
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
constructor (context: InstanceContext, core: NapCatCore) {
this.context = context;
@@ -482,8 +482,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: {
+4
View File
@@ -328,6 +328,10 @@ export class NTQQWebApi {
return (hash & 0x7FFFFFFF).toString();
}
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,
+20
View File
@@ -554,5 +554,25 @@
"9.9.28-46928": {
"appid": 537345957,
"qua": "V1_WIN_NQ_9.9.28_46928_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"
}
}
+32
View File
@@ -202,5 +202,37 @@
"9.9.28-46928-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"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"
}
}
+32
View File
@@ -710,5 +710,37 @@
"9.9.28-46928-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"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"
}
}
+15 -9
View File
@@ -180,16 +180,22 @@ export class NapCatCore {
if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) {
this.context.logger.log('[ServerTime] 自动对时已禁用');
} else {
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`);
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);
}
} 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) {
@@ -41,6 +41,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);
@@ -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';
@@ -31,4 +31,4 @@ 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';
@@ -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),
};
@@ -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;
@@ -11,4 +11,12 @@ export const PacketActionsExamples = {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
CompleteGroupTodo: {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
CancelGroupTodo: {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
};
@@ -3,6 +3,7 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { NTGroupMemberRole } from '@/napcat-core';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
@@ -30,7 +31,13 @@ export default class SetGroupBan extends OneBotAction<PayloadType, ReturnType> {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('uid error');
const member_role = (await this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, true))?.role;
if (member_role === 4) throw new Error('cannot ban owner');
if (member_role === undefined) throw new Error('user not in group');
if (member_role === NTGroupMemberRole.KOWNER) throw new Error('cannot ban owner');
if (member_role === NTGroupMemberRole.KADMIN) {
const self_role = (await this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), this.core.selfInfo.uid, true))?.role;
if (self_role === undefined) throw new Error('failed to fetch bot role');
if (self_role !== NTGroupMemberRole.KOWNER) throw new Error('cannot ban admin');
}
// 例如无管理员权限时 result为 120101005 errMsg为 'ERR_NOT_GROUP_ADMIN'
const ret = await this.core.apis.GroupApi.banMember(payload.group_id.toString(),
[{ uid, timeStamp: +payload.duration }]);
@@ -26,7 +26,10 @@ export default class SetGroupName extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupName.response;
async _handle (payload: PayloadType): Promise<null> {
const ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
let ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
if (ret.result.toString() === '1287') {
ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name, true);
}
if (ret.result !== 0) {
throw new Error(`设置群名称失败 ErrCode: ${ret.result} ErrMsg: ${ret.errMsg}`);
}
+6
View File
@@ -127,6 +127,8 @@ import SetGroupKickMembers from './extends/SetGroupKickMembers';
import { GetGroupDetailInfo } from './group/GetGroupDetailInfo';
import GetGroupAddRequest from './extends/GetGroupAddRequest';
import { GetCollectionList } from './extends/GetCollectionList';
import { CompleteGroupTodo } from './packet/CompleteGroupTodo';
import { CancelGroupTodo } from './packet/CancelGroupTodo';
import { SetGroupTodo } from './packet/SetGroupTodo';
import { GetQunAlbumList } from './extends/GetQunAlbumList';
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
@@ -155,6 +157,7 @@ import { CancelOnlineFile } from './file/online/CancelOnlineFile';
import { ReceiveOnlineFile } from './file/online/ReceiveOnlineFile';
import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
@@ -171,6 +174,8 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetQunAlbumList(obContext, core),
new UploadImageToQunAlbum(obContext, core),
new SetGroupTodo(obContext, core),
new CompleteGroupTodo(obContext, core),
new CancelGroupTodo(obContext, core),
new GetGroupDetailInfo(obContext, core),
new SetGroupKickMembers(obContext, core),
new SetGroupAddOption(obContext, core),
@@ -185,6 +190,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetGroupInfoEx(obContext, core),
new FetchEmojiLike(obContext, core),
new GetEmojiLikes(obContext, core),
new FetchPttText(obContext, core),
new GetFile(obContext, core),
new SetQQProfile(obContext, core),
new ShareGroupEx(obContext, core),
@@ -0,0 +1,87 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { Static, Type } from '@sinclair/typebox';
import { PromiseTimer } from '@/napcat-common/src/helper';
import { ElementType } from '@/napcat-core';
import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples';
const PayloadSchema = Type.Object({
message_id: Type.Union([Type.Number(), Type.String()], { description: '消息ID' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({ text: Type.String({ description: '得到的文本' }) });
type ReturnType = Static<typeof ReturnSchema>;
export class FetchPttText extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.FetchPttText;
override actionSummary = '获取语音转文字结果';
override actionTags = ['消息扩展'];
override payloadExample = MsgActionsExamples.FetchPttText.payload;
override returnExample = MsgActionsExamples.FetchPttText.response;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
if (!payload.message_id) {
throw Error('参数message_id不能为空');
}
const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId ?? +payload.message_id);
if (!msgIdWithPeer) {
throw new Error('消息不存在');
}
const peer = { guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
const getMsgTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
const msgRes = await PromiseTimer(
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
getMsgTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
}
throw e;
});
const msg = msgRes.msgList[0];
if (!msg) throw Error('消息不存在或已被撤回');
const pttSegment = msg.elements.find((s) =>
s.elementType === ElementType.PTT
);
if (!pttSegment) {
throw Error('消息中不包含语音');
}
const getPttTextTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
await PromiseTimer(
this.core.context.session.getMsgService().translatePtt2Text(msgIdWithPeer.MsgId, msgIdWithPeer.Peer, pttSegment),
getPttTextTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`获取语音转文字结果失败: ${e.message || String(e)}`);
}
throw e;
});
const msgRes2 = await PromiseTimer(
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
getMsgTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
}
throw e;
});
const msg2 = msgRes2.msgList[0];
if (!msg2) throw Error('消息不存在或已被撤回');
for (const s of msg2.elements) {
if (s.elementType === ElementType.PTT) {
if (s.pttElement?.text) {
return { text: s.pttElement?.text };
}
}
}
throw new Error('获取语音转文字结果失败');
}
}
+13 -2
View File
@@ -1,6 +1,7 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { PromiseTimer } from 'napcat-common/src/helper';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
@@ -49,8 +50,18 @@ class GetMsg extends OneBotAction<PayloadType, ReturnType> {
throw new Error('消息不存在');
}
const peer = { guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()])).msgList[0];
if (!msg) throw Error('消息不存在');
const getMsgTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
const msgRes = await PromiseTimer(
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
getMsgTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
}
throw e;
});
const msg = msgRes.msgList[0];
if (!msg) throw Error('消息不存在或已被撤回');
const retMsg = await this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat);
if (!retMsg) throw Error('消息为空');
retMsg.emoji_likes_list = [];
@@ -14,6 +14,12 @@ export const MsgActionsExamples = {
message: 'hello',
},
},
FetchPttText: {
payload: { message_id: 123456 },
response: {
text: 'hello',
},
},
MarkMsgAsRead: {
payload: { group_id: '123456' },
response: {},
@@ -0,0 +1,40 @@
import { MessageUnique } from 'napcat-common/src/message-unique';
import { ChatType, Peer } from 'napcat-core';
import { Static, Type } from '@sinclair/typebox';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
export const GroupTodoPayloadSchema = Type.Object({
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
message_id: Type.Optional(Type.String({ description: '消息ID' })),
message_seq: Type.Optional(Type.String({ description: '消息Seq (可选)' })),
});
export type GroupTodoPayload = Static<typeof GroupTodoPayloadSchema>;
export abstract class BaseGroupTodoAction extends GetPacketStatusDepends<GroupTodoPayload, void> {
override payloadSchema = GroupTodoPayloadSchema;
override returnSchema = Type.Null();
override actionTags = ['核心接口'];
protected abstract handleGroupTodo(groupId: number, msgSeq: string): Promise<void>;
async _handle (payload: GroupTodoPayload) {
const groupId = +payload.group_id;
if (payload.message_seq) {
return await this.handleGroupTodo(groupId, payload.message_seq.toString());
}
if (!payload.message_id) {
throw new Error('缺少参数 message_id 或 message_seq');
}
const peer: Peer = {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: payload.group_id.toString(),
};
const { MsgId, Peer } = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id) ?? { Peer: peer, MsgId: payload.message_id.toString() };
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(Peer, [MsgId])).msgList[0];
if (!msg) {
throw new Error('消息不存在');
}
await this.handleGroupTodo(groupId, msg.msgSeq);
}
}
@@ -0,0 +1,15 @@
import { ActionName } from '../router';
import { PacketActionsExamples } from '../example/PacketActionsExamples';
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
export class CancelGroupTodo extends BaseGroupTodoAction {
override actionName = ActionName.CancelGroupTodo;
override actionSummary = '取消群待办';
override actionDescription = '将指定消息对应的群待办取消';
override payloadExample = PacketActionsExamples.CancelGroupTodo.payload;
override returnExample = PacketActionsExamples.CancelGroupTodo.response;
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
await this.core.apis.PacketApi.pkt.operation.CancelGroupTodo(groupId, msgSeq);
}
}
@@ -0,0 +1,15 @@
import { ActionName } from '../router';
import { PacketActionsExamples } from '../example/PacketActionsExamples';
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
export class CompleteGroupTodo extends BaseGroupTodoAction {
override actionName = ActionName.CompleteGroupTodo;
override actionSummary = '完成群待办';
override actionDescription = '将指定消息对应的群待办标记为已完成';
override payloadExample = PacketActionsExamples.CompleteGroupTodo.payload;
override returnExample = PacketActionsExamples.CompleteGroupTodo.response;
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
await this.core.apis.PacketApi.pkt.operation.CompleteGroupTodo(groupId, msgSeq);
}
}
@@ -1,42 +1,14 @@
import { MessageUnique } from 'napcat-common/src/message-unique';
import { ChatType, Peer } from 'napcat-core';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
import { ActionName } from '../router';
import { PacketActionsExamples } from '../example/PacketActionsExamples';
export const SetGroupTodoPayloadSchema = Type.Object({
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
message_id: Type.Optional(Type.String({ description: '消息ID' })),
message_seq: Type.Optional(Type.String({ description: '消息Seq (可选)' })),
});
export type SetGroupTodoPayload = Static<typeof SetGroupTodoPayloadSchema>;
export class SetGroupTodo extends GetPacketStatusDepends<SetGroupTodoPayload, void> {
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
export class SetGroupTodo extends BaseGroupTodoAction {
override actionName = ActionName.SetGroupTodo;
override payloadSchema = SetGroupTodoPayloadSchema;
override returnSchema = Type.Null();
override actionSummary = '设置群待办';
override actionDescription = '将指定消息设置为群待办';
override actionTags = ['核心接口'];
override payloadExample = PacketActionsExamples.SetGroupTodo.payload;
override returnExample = PacketActionsExamples.SetGroupTodo.response;
async _handle (payload: SetGroupTodoPayload) {
if (payload.message_seq) {
return await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, payload.message_seq.toString());
}
if (!payload.message_id) {
throw new Error('缺少参数 message_id 或 message_seq');
}
const peer: Peer = {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: payload.group_id.toString(),
};
const { MsgId, Peer } = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id) ?? { Peer: peer, MsgId: payload.message_id.toString() };
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(Peer, [MsgId])).msgList[0];
if (!msg) throw new Error('消息不存在');
await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, msg.msgSeq);
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(groupId, msgSeq);
}
}
+3
View File
@@ -29,6 +29,8 @@ export const ActionName = {
UploadImageToQunAlbum: 'upload_image_to_qun_album',
GetQunAlbumList: 'get_qun_album_list',
SetGroupTodo: 'set_group_todo',
CompleteGroupTodo: 'complete_group_todo',
CancelGroupTodo: 'cancel_group_todo',
SetGroupKickMembers: 'set_group_kick_members',
SetGroupRobotAddOption: 'set_group_robot_add_option',
SetGroupAddOption: 'set_group_add_option',
@@ -139,6 +141,7 @@ export const ActionName = {
ForwardFriendSingleMsg: 'forward_friend_single_msg',
ForwardGroupSingleMsg: 'forward_group_single_msg',
TranslateEnWordToZn: 'translate_en2zh',
FetchPttText: 'fetch_ptt_text',
SetMsgEmojiLike: 'set_msg_emoji_like',
GoCQHTTP_SendForwardMsg: 'send_forward_msg',
MarkPrivateMsgAsRead: 'mark_private_msg_as_read',
@@ -35,7 +35,16 @@ export class GetCookies extends OneBotAction<GetCookiesPayload, GetCookiesRespon
const cookiesObject = await this.core.apis.UserApi.getCookies(payload.domain);
// 把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ');
const bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
let bkn = '';
if (payload.domain.includes('qzone.qq.com')) {
if (cookiesObject?.['p_skey']) {
bkn = this.core.apis.WebApi.getBknFromPSKey(cookiesObject['p_skey']);
} else {
bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
}
} else {
bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
}
return { cookies, bkn };
}
}
+1
View File
@@ -59,6 +59,7 @@ const WebsocketClientConfigSchema = Type.Object({
token: Type.String({ default: '' }),
debug: Type.Boolean({ default: false }),
heartInterval: Type.Number({ default: 30000 }),
verifyCertificate: Type.Optional(Type.Boolean({ default: true })),
});
const PluginConfigSchema = Type.Object({
@@ -73,7 +73,7 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
if (!this.connection && this.isEnable) {
let isClosedByError = false;
this.connection = new WebSocket(this.config.url, {
const wsOptions: WebSocket.ClientOptions = {
maxPayload: 50 * 1024 * 1024, // 50 MB
handshakeTimeout: 2000,
perMessageDeflate: false,
@@ -83,8 +83,14 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
'x-client-role': 'Universal', // 为koishi adpter适配
'User-Agent': 'OneBot/11',
},
};
});
// 如果配置了 verifyCertificate,设置 rejectUnauthorized
if (this.config.verifyCertificate !== undefined) {
wsOptions.rejectUnauthorized = this.config.verifyCertificate;
}
this.connection = new WebSocket(this.config.url, wsOptions);
this.connection.on('pong', () => {
// this.logger.logDebug('[OneBot] [WebSocket Client] 收到pong');
});
+1 -1
View File
@@ -581,7 +581,7 @@ export async function NCoreInitShell () {
console.log('NapCat Shell App Loading...');
const pathWrapper = new NapCatPathWrapper();
const logger = new LogWrapper(pathWrapper.logsPath);
if (process.env['NAPCAT_WORKER_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTI_PROCESS'] !== '1') {
if (process.env['NAPCAT_WORKER_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTI_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTIPROCESSING'] !== '1') {
logger.setFileLogEnabled(false);
}
handleUncaughtExceptions(logger);
+1 -1
View File
@@ -36,7 +36,7 @@ if (fs.existsSync(envPath)) {
// 环境变量配置
const ENV = {
isWorkerProcess: process.env['NAPCAT_WORKER_PROCESS'] === '1',
isMultiProcessDisabled: process.env['NAPCAT_DISABLE_MULTI_PROCESS'] === '1',
isMultiProcessDisabled: process.env['NAPCAT_DISABLE_MULTI_PROCESS'] === '1' || process.env['NAPCAT_DISABLE_MULTIPROCESSING'] === '1',
isPipeDisabled: process.env['NAPCAT_DISABLE_PIPE'] === '1',
} as const;
@@ -0,0 +1,60 @@
import { describe, expect, test, vi } from 'vitest';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbSvcTrpcTcpBase } from '@/napcat-core/packet/transformer/proto/oidb/OidbBase';
import { OidbSvcTrpcTcp0XF90 } from '@/napcat-core/packet/transformer/proto/oidb/Oidb.0xf90';
vi.mock('@/napcat-core/packet/transformer/base', () => ({
PacketTransformer: class PacketTransformer {
protected msgBuilder: unknown;
constructor () {
this.msgBuilder = undefined;
}
},
PacketBufBuilder: (str: Uint8Array) => Buffer.from(str),
}));
import SetGroupTodo from '@/napcat-core/packet/transformer/action/SetGroupTodo';
import CompleteGroupTodo from '@/napcat-core/packet/transformer/action/CompleteGroupTodo';
import CancelGroupTodo from '@/napcat-core/packet/transformer/action/CancelGroupTodo';
const decodePacket = (data: Buffer) => {
const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(data);
const body = new NapProtoMsg(OidbSvcTrpcTcp0XF90).decode(base.body);
return { base, body };
};
describe('Group todo packet builder', () => {
test('builds OIDB 0xF90 subCommand 1 for set', () => {
const packet = SetGroupTodo.build(123456, '789');
const { base, body } = decodePacket(packet.data);
expect(packet.cmd).toBe('OidbSvcTrpcTcp.0xF90_1');
expect(base.command).toBe(0xF90);
expect(base.subCommand).toBe(1);
expect(body.groupUin).toBe(123456);
expect(body.msgSeq).toBe('789');
});
test('builds OIDB 0xF90 subCommand 2 for complete', () => {
const packet = CompleteGroupTodo.build(123456, '789');
const { base, body } = decodePacket(packet.data);
expect(packet.cmd).toBe('OidbSvcTrpcTcp.0xF90_2');
expect(base.command).toBe(0xF90);
expect(base.subCommand).toBe(2);
expect(body.groupUin).toBe(123456);
expect(body.msgSeq).toBe('789');
});
test('builds OIDB 0xF90 subCommand 3 for cancel', () => {
const packet = CancelGroupTodo.build(123456, '789');
const { base, body } = decodePacket(packet.data);
expect(packet.cmd).toBe('OidbSvcTrpcTcp.0xF90_3');
expect(base.command).toBe(0xF90);
expect(base.subCommand).toBe(3);
expect(body.groupUin).toBe(123456);
expect(body.msgSeq).toBe('789');
});
});
+2 -1
View File
@@ -15,6 +15,7 @@
"napcat-core": "workspace:*",
"napcat-image-size": "workspace:*",
"napcat-onebot": "workspace:*",
"napcat-rpc": "workspace:*"
"napcat-rpc": "workspace:*",
"napcat-protobuf": "workspace:*"
}
}
+51
View File
@@ -97,6 +97,57 @@ describe('NapCat Configuration Loaders', () => {
expect(loaded.musicSignUrl).toBe('');
});
test('OneBotConfig websocketClients should apply verifyCertificate default', () => {
const partialConfig: Partial<OneBotConfig> = {
network: {
httpServers: [],
httpSseServers: [],
httpClients: [],
websocketServers: [],
websocketClients: [{
name: 'test-ws-client',
enable: true,
url: 'wss://example.com',
messagePostFormat: 'array',
reportSelfMessage: false,
reconnectInterval: 5000,
token: '',
debug: false,
heartInterval: 30000,
}],
plugins: [],
},
};
const loaded = loadOneBotConfig(partialConfig);
expect(loaded.network.websocketClients[0]?.verifyCertificate).toBe(true);
});
test('OneBotConfig websocketClients should preserve explicit verifyCertificate false', () => {
const partialConfig: Partial<OneBotConfig> = {
network: {
httpServers: [],
httpSseServers: [],
httpClients: [],
websocketServers: [],
websocketClients: [{
name: 'test-ws-client',
enable: true,
url: 'wss://example.com',
messagePostFormat: 'array',
reportSelfMessage: false,
reconnectInterval: 5000,
token: '',
debug: false,
heartInterval: 30000,
verifyCertificate: false,
}],
plugins: [],
},
};
const loaded = loadOneBotConfig(partialConfig);
expect(loaded.network.websocketClients[0]?.verifyCertificate).toBe(false);
});
test('NapcatConfig should compile and apply defaults', () => {
let compiled: ReturnType<typeof TypeCompiler.Compile> | undefined;
expect(() => {
+4 -1
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
@@ -8,4 +11,4 @@
"node_modules",
"dist"
]
}
}
+2
View File
@@ -13,6 +13,8 @@ export default defineConfig({
'@/napcat-test': resolve(__dirname, '.'),
'@/napcat-common': resolve(__dirname, '../napcat-common'),
'@/napcat-core': resolve(__dirname, '../napcat-core'),
'@/napcat-onebot': resolve(__dirname, '../napcat-onebot'),
'napcat-protobuf': resolve(__dirname, '../napcat-protobuf/NapProto.ts'),
},
},
});
@@ -42,6 +42,13 @@ const SKIP_UPDATE_FILES = [
'NapCatWinBootHook.dll',
];
// 更新时若文件已存在则保留(不覆盖)的用户配置文件(使用相对路径精确匹配)
// 这些文件保存了用户的自定义设置,更新时应予以保留;
// 新增的配置项将在运行时通过 TypeBox schema 默认值自动填充,用户不会错过新配置选项。
const PRESERVE_USER_CONFIG_RELATIVE_PATHS = new Set([
path.normalize('config/napcat.json'),
]);
/**
* 递归扫描目录中的所有文件
*/
@@ -59,9 +66,12 @@ function scanFilesRecursively (dirPath: string, basePath: string = dirPath): Arr
for (const item of items) {
const fullPath = path.join(dirPath, item);
const relativePath = path.relative(basePath, fullPath);
const stat = fs.statSync(fullPath);
const stat = fs.lstatSync(fullPath);
if (stat.isDirectory()) {
if (stat.isSymbolicLink()) {
// 跳过符号链接,避免潜在的路径穿越风险
continue;
} else if (stat.isDirectory()) {
// 递归扫描子目录
files.push(...scanFilesRecursively(fullPath, basePath));
} else if (stat.isFile()) {
@@ -263,8 +273,16 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
}> = [];
// 先尝试直接替换文件
const resolvedBinaryPath = path.resolve(webUiPathWrapper.binaryPath);
for (const fileInfo of allFiles) {
const targetFilePath = path.join(webUiPathWrapper.binaryPath, fileInfo.relativePath);
// 防止路径穿越攻击:确保目标路径严格位于 binaryPath 子目录内
const targetFilePath = path.resolve(webUiPathWrapper.binaryPath, fileInfo.relativePath);
if (!targetFilePath.startsWith(resolvedBinaryPath + path.sep)) {
webUiLogger?.logWarn(`[NapCat Update] Skipping suspicious path: ${fileInfo.relativePath}`);
continue;
}
const normalizedRelativePath = path.normalize(fileInfo.relativePath);
// 跳过指定的文件
if (SKIP_UPDATE_FILES.includes(path.basename(fileInfo.relativePath))) {
@@ -272,6 +290,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
continue;
}
// 保留已存在的用户配置文件,避免覆盖用户设置
if (PRESERVE_USER_CONFIG_RELATIVE_PATHS.has(normalizedRelativePath) && fs.existsSync(targetFilePath)) {
webUiLogger?.log(`[NapCat Update] Preserving existing user config: ${fileInfo.relativePath}`);
continue;
}
try {
// 确保目标目录存在
const targetDir = path.dirname(targetFilePath);
@@ -20,7 +20,7 @@ export default function Hitokoto () {
error,
loading,
run,
} = useRequest(() => request.get<IHitokoto>('https://hitokoto.152710.xyz/'), {
} = useRequest(() => request.get<IHitokoto>('https://hi.logacg.com/'), {
throttleWait: 1000,
});
const backupData = {
@@ -2,11 +2,11 @@ import GenericForm, { random_token } from './generic_form';
import type { Field } from './generic_form';
export interface WebsocketClientFormProps {
data?: OneBotConfig['network']['websocketClients'][0]
onClose: () => void
data?: OneBotConfig['network']['websocketClients'][0];
onClose: () => void;
onSubmit: (
data: OneBotConfig['network']['websocketClients'][0]
) => Promise<void>
) => Promise<void>;
}
type WebsocketClientFormType = OneBotConfig['network']['websocketClients'];
@@ -26,6 +26,7 @@ const WebsocketClientForm: React.FC<WebsocketClientFormProps> = ({
debug: false,
heartInterval: 30000,
reconnectInterval: 30000,
verifyCertificate: true,
};
const fields: Field<'websocketClients'>[] = [
@@ -99,6 +100,13 @@ const WebsocketClientForm: React.FC<WebsocketClientFormProps> = ({
isRequired: true,
colSpan: 1,
},
{
name: 'verifyCertificate',
label: 'SSL证书验证',
type: 'switch',
description: '是否验证SSL证书(wss连接)。关闭后可连接自签名证书的服务器,但会降低安全性',
colSpan: 2,
},
];
return (
@@ -142,6 +142,8 @@ export default function WebLoginPage () {
useEffect(() => {
// 如果URL中有token,直接登录
if (token) {
// 不需要检查passkey,立即清除loading状态,避免登录失败后输入框被永久禁用
setIsPasskeyLoading(false);
onSubmit();
return;
}
+8 -12
View File
@@ -13,16 +13,12 @@ type HitokitoType =
| 'l'; /** 抖机灵 */
interface IHitokoto {
id: number
uuid: string
hitokoto: string
type: HitokitoType
from: string
from_who: string
creator: string
creator_uid: number
reviewer: number
commit_from: string
created_at: string
length: number
id: number;
uuid: string;
hitokoto: string;
type: HitokitoType;
from: string;
from_who: string;
created_at: string;
length: number;
}
@@ -42,6 +42,7 @@ interface WebsocketClientConfig extends AdapterConfig {
token: string;
debug: boolean;
heartInterval: number;
verifyCertificate?: boolean;
}
interface HttpSseServerConfig extends HttpServerConfig {
+3
View File
@@ -387,6 +387,9 @@ importers:
napcat-onebot:
specifier: workspace:*
version: link:../napcat-onebot
napcat-protobuf:
specifier: workspace:*
version: link:../napcat-protobuf
napcat-rpc:
specifier: workspace:*
version: link:../napcat-rpc