Merge pull request #224 from SnowLuma/dev

chore: promote dev → main (a3467a8)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-07-13 23:57:45 +00:00
commit 06106d2bd3
63 files changed
+2872 -452

No files matched your search

+23 -23
View File
@@ -109,42 +109,42 @@ jobs:
tag="${GITHUB_REF_NAME}"
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
if [[ -n "$previousTag" ]]; then
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
range="$previousTag..$tag"
comparison="[查看 ${previousTag} → ${tag} 的完整差异](https://github.com/${GITHUB_REPOSITORY}/compare/${previousTag}...${tag})"
else
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
range="$tag"
comparison=""
fi
changes="$(git log --no-merges --invert-grep --grep='^chore(release):' --pretty=format:"- %s ([%h](https://github.com/${GITHUB_REPOSITORY}/commit/%H))" "$range")"
[[ -z "$changes" ]] && changes="- No commit changes detected."
cat > release-notes.md <<EOF
# SnowLuma ${tag}
## 发布概览
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
> **跨平台正式支持:** Windows x64、Linux x64 与 Linux arm64 均可完整运行 SnowLuma,包含 QQ 接入、OneBot v11 与 WebUI 管理能力。
## 下载说明
命名约定:
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
## 选择下载
Windows:
- \`SnowLuma-${tag}-win-x64.zip\`
- \`SnowLuma-${tag}-win-x64-lite.zip\`
| 平台 | 完整版(内置 Node.js,推荐) | Lite(需 Node.js 22+) |
| --- | --- | --- |
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
| Linux arm64 | \`SnowLuma-${tag}-linux-arm64.tar.gz\` | \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\` |
Linux x64:
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
完整版适合直接解压运行;Lite 版不包含 Node.js,但其余运行时依赖和 WebUI 静态资源保持一致。
Linux arm64:
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
## 快速开始
1. 解压与你的系统架构匹配的压缩包。
2. Windows 运行 \`launcher.bat\`;Linux 运行 \`./launcher.sh\`。
3. 浏览器访问 http://localhost:5099,初始账号为 \`admin\`,密码见启动日志。
无人值守部署可同时设置 \`SNOWLUMA_ACCEPT_EULA=1\` 与 \`SNOWLUMA_ACCEPT_PRIVACY=1\` 完成协议确认。设置这些变量即表示运营者已阅读并同意发行包内的 EULA 与隐私政策;缺少任意一项时仍会显示同意页面。
## 本次更新
## 更新内容
${changes}
## 使用说明
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
${comparison}
EOF
- name: Create GitHub Release
+2 -1
View File
@@ -42,6 +42,8 @@ SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
无人值守部署可同时设置 `SNOWLUMA_ACCEPT_EULA=1` 与 `SNOWLUMA_ACCEPT_PRIVACY=1` 完成协议确认。两项必须同时设置;移除任意变量后会恢复按当前协议版本检查 WebUI 同意记录。设置这些变量即表示您已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
## 许可 / License
SnowLuma 采用 **源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**,见 [`LICENSE`](LICENSE)。**这不是 OSI 开源许可**:源码公开供查看、学习与非商业自托管,但**禁止任何商业使用**(出售、转售、付费托管 / 代搭 / 代运营等),公开发布修改版须事先书面授权。随附的原生附加组件(`snowluma-*.node` 等)为专有组件,不在本许可范围内。二进制发行包另受 [`EULA.md`](EULA.md) 约束;商业授权请联系 motricseven@foxmail.com。参与贡献请阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
@@ -57,4 +59,3 @@ SnowLuma is under a **source-available, non-commercial** license (see [`LICENSE`
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
</p>
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.12.1",
"version": "1.12.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.12.1",
"version": "1.12.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+95 -14
View File
@@ -8,8 +8,11 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { toHex } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
import type {
FriendCategoryInfo,
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
@@ -19,6 +22,8 @@ import type {
import type { DownloadRKeyInfo } from '../bridge';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.Contacts');
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
@@ -33,6 +38,23 @@ type FriendPropertySource = {
}>;
};
interface FriendRosterEntry {
friend: FriendInfo;
categoryId: number;
}
interface FriendCategoryMeta {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
}
interface FriendRoster {
entries: FriendRosterEntry[];
categories: FriendCategoryMeta[];
}
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
@@ -82,26 +104,85 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
private async fetchFriendRoster(): Promise<FriendRoster> {
const entries: FriendRosterEntry[] = [];
const categories = new Map<number, FriendCategoryMeta>();
const seenCookies = new Set<string>();
let cookie: Uint8Array | undefined;
for (;;) {
const resp = await FetchFriendListPage.invoke(this.ctx, { cookie });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
entries.push({
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
},
});
}
for (const raw of resp.categories ?? []) {
const categoryId = raw.categoryId ?? 0;
categories.set(categoryId, {
categoryId,
categoryName: raw.categoryName ?? '',
memberCount: raw.memberCount ?? 0,
sortId: raw.sortId ?? 0,
});
}
nextUin = resp.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
const next = resp.cookie;
if (!next?.length) break;
const key = toHex(next);
if (seenCookies.has(key)) {
throw new Error(`repeated friend-list cookie ${key}`);
}
seenCookies.add(key);
cookie = next;
}
const friends = entries.map(entry => entry.friend);
this.ctx.identity.rememberFriends(friends);
return friends;
return { entries, categories: [...categories.values()] };
}
async fetchFriendList(): Promise<FriendInfo[]> {
const roster = await this.fetchFriendRoster();
return roster.entries.map(entry => entry.friend);
}
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
const roster = await this.fetchFriendRoster();
const buckets = new Map(
roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]),
);
for (const entry of roster.entries) {
const bucket = buckets.get(entry.categoryId);
if (!bucket) {
throw new Error(
`friend roster references missing category ${entry.categoryId} `
+ `(${roster.entries.length} friends total)`,
);
}
bucket.push(entry.friend);
}
return roster.categories.map(category => {
const friends = buckets.get(category.categoryId)!;
if (friends.length !== category.memberCount) {
log.warn(
'friend category member count mismatch category=%d server=%d assembled=%d',
category.categoryId,
category.memberCount,
friends.length,
);
}
return { ...category, friends };
});
}
async fetchGroupList(): Promise<QQGroupInfo[]> {
+264 -39
View File
@@ -4,9 +4,12 @@ import type {
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type {
C2CReadedReportResponseItem,
C2CRecallRequest,
GroupReadedReportResponseItem,
GroupRecallRequest,
SsoReadedReportReq,
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
@@ -14,6 +17,7 @@ import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid } from './shared';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
@@ -27,9 +31,89 @@ import { resolveSelfUid } from './shared';
import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
const READ_REPORT_CMD = 'trpc.msg.msg_svc.MsgService.SsoReadedReport';
const READ_REPORT_BATCH_SIZE = 100;
const log = createLogger('Bridge.Message');
function decodeReadReportResponse(result: SendPacketResult, label: string): SsoReadedReportResp {
if (!result.success) {
throw new Error(result.errorMessage || `${label} transport failed`);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${label} response is empty`);
}
let response: SsoReadedReportResp;
try {
response = protobuf_decode<SsoReadedReportResp>(result.responseData);
} catch (error) {
throw new Error(`${label} response decode failed: ${error instanceof Error ? error.message : String(error)}`);
}
const resultCode = response.resultCode ?? 0;
if (resultCode !== 0) {
throw new Error(response.errorMessage || `${label} failed with result code ${resultCode}`);
}
return response;
}
interface C2CReadTarget {
userId: number;
uid: string;
}
interface ReadResponseItem {
resultCode?: number;
errorMessage?: string;
}
function uniqueSessionIds(ids: readonly number[], label: string): number[] {
const result: number[] = [];
const seen = new Set<number>();
for (const id of ids) {
if (!Number.isSafeInteger(id) || id <= 0) {
throw new Error(`invalid ${label} read target ${String(id)}`);
}
if (!seen.has(id)) {
seen.add(id);
result.push(id);
}
}
return result;
}
function requireReadResponseItem<T extends ReadResponseItem>(
items: readonly T[] | undefined,
index: number,
matches: (item: T) => boolean,
label: string,
): T {
const item = items?.find(matches) ?? items?.[index];
if (!item) throw new Error(`${label} response item is missing`);
const resultCode = item.resultCode ?? 0;
if (resultCode !== 0) {
throw new Error(item.errorMessage || `${label} failed with result code ${resultCode}`);
}
if (!matches(item)) throw new Error(`${label} response identity does not match the request`);
return item;
}
function readUnsignedSequence(value: bigint | null | undefined, label: string): bigint {
// Proton represents an omitted protobuf scalar as null; protobuf semantics
// define that as the numeric default (zero), not a decode failure.
if (value == null) return 0n;
if (typeof value !== 'bigint' || value < 0n) throw new Error(`${label} is invalid`);
return value;
}
function requirePositiveSequence(value: bigint | null | undefined, label: string): bigint {
const sequence = readUnsignedSequence(value, label);
if (sequence === 0n) throw new Error(`${label} is missing`);
return sequence;
}
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -454,48 +538,190 @@ export class MessageApi {
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
/**
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
* NT client's own "scrolled to bottom" behaviour so subsequent
* sync packets don't replay messages we've already processed.
*/
async markGroupRead(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<SsoReadedReportReq>({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
/** Mark the entire group conversation read, matching QQ NT's setMsgRead(peer). */
async markGroupRead(groupId: number): Promise<void> {
await this.markAllRead([groupId], []);
}
/** Mark the entire private conversation read, matching QQ NT's setMsgRead(peer). */
async markPrivateRead(userId: number): Promise<void> {
await this.markAllRead([], [userId]);
}
/**
* Push a c2c read-report. Same wire-cmd as the group variant but
* keyed by friend uid (resolved from uin via IdentityService).
* `lastReadTime` defaults to "now" — matches the QQ NT client
* which also uses wall-clock seconds rather than the read-message
* timestamp.
* Mark every supplied conversation read through SsoReadedReport.
*
* Message-head sequences are not valid C2C read sequences. The first packet
* therefore reports zero for every conversation and reads the server's
* current read/latest pair from the response without moving the marker
* backwards. A second packet advances only conversations that are behind.
* QQ NT caps each packet at 100 C2C plus 100 group entries and waits for the
* response before sending the next page; mirror that strictly here.
*/
async markPrivateRead(userId: number, sequence: number): Promise<void> {
const uid = await this.ctx.resolveUserUid(userId);
const request = protobuf_encode<SsoReadedReportReq>({
c2cList: [
{
uid,
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
async markAllRead(groupIds: readonly number[], privateUserIds: readonly number[]): Promise<void> {
const groups = uniqueSessionIds(groupIds, 'group');
const privateUsers = uniqueSessionIds(privateUserIds, 'private');
const c2cTargets: C2CReadTarget[] = [];
// Keep UID resolution sequential. A cache miss may itself use the network,
// so Promise.all here would reintroduce the burst this method is designed
// to avoid.
for (const userId of privateUsers) {
const uid = await this.ctx.resolveUserUid(userId);
if (!uid) throw new Error(`failed to resolve uid for private read target ${userId}`);
c2cTargets.push({ userId, uid });
}
const totalBatches = Math.max(
Math.ceil(groups.length / READ_REPORT_BATCH_SIZE),
Math.ceil(c2cTargets.length / READ_REPORT_BATCH_SIZE),
);
if (totalBatches === 0) return;
log.debug(
'mark-read start: groups=%d c2c=%d batches=%d',
groups.length,
c2cTargets.length,
totalBatches,
);
for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
const start = batchIndex * READ_REPORT_BATCH_SIZE;
await this.markReadBatch(
groups.slice(start, start + READ_REPORT_BATCH_SIZE),
c2cTargets.slice(start, start + READ_REPORT_BATCH_SIZE),
batchIndex + 1,
totalBatches,
);
}
log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length);
}
private async sendReadReport(request: SsoReadedReportReq, label: string): Promise<SsoReadedReportResp> {
log.debug(
'%s send: groups=%d c2c=%d',
label,
request.groupList?.length ?? 0,
request.c2cList?.length ?? 0,
);
const payload = protobuf_encode<SsoReadedReportReq>(request);
const result = await this.ctx.sendRawPacket(READ_REPORT_CMD, payload);
const response = decodeReadReportResponse(result, label);
log.debug(
'%s response: groups=%d c2c=%d',
label,
response.groupList?.length ?? 0,
response.c2cList?.length ?? 0,
);
return response;
}
private groupReadResponse(
response: SsoReadedReportResp,
groupId: number,
index: number,
label: string,
): GroupReadedReportResponseItem {
const groupUin = BigInt(groupId);
return requireReadResponseItem(
response.groupList,
index,
item => item.groupUin === groupUin,
`${label} group ${groupId}`,
);
}
private c2cReadResponse(
response: SsoReadedReportResp,
target: C2CReadTarget,
index: number,
label: string,
): C2CReadedReportResponseItem {
return requireReadResponseItem(
response.c2cList,
index,
item => item.uid === target.uid,
`${label} private user ${target.userId}`,
);
}
private async markReadBatch(
groupIds: readonly number[],
c2cTargets: readonly C2CReadTarget[],
batchIndex: number,
totalBatches: number,
): Promise<void> {
const batchLabel = `mark-read batch ${batchIndex}/${totalBatches}`;
const probe = await this.sendReadReport({
groupList: groupIds.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })),
c2cList: c2cTargets.map(target => ({ uid: target.uid, lastReadTime: 0n, lastReadSeq: 0n })),
}, `${batchLabel} probe`);
const groupList: NonNullable<SsoReadedReportReq['groupList']> = [];
for (let i = 0; i < groupIds.length; i++) {
const groupId = groupIds[i]!;
const item = this.groupReadResponse(probe, groupId, i, `${batchLabel} probe`);
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} read sequence`);
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} group ${groupId} latest sequence`);
if (latestSeq < readSeq) {
throw new Error(`${batchLabel} group ${groupId} latest sequence ${latestSeq} is before read sequence ${readSeq}`);
}
if (latestSeq > readSeq) groupList.push({ groupUin: BigInt(groupId), lastReadSeq: latestSeq });
}
const c2cList: NonNullable<SsoReadedReportReq['c2cList']> = [];
const c2cConfirmTargets: C2CReadTarget[] = [];
for (let i = 0; i < c2cTargets.length; i++) {
const target = c2cTargets[i]!;
const item = this.c2cReadResponse(probe, target, i, `${batchLabel} probe`);
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} private user ${target.userId} read sequence`);
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} private user ${target.userId} latest sequence`);
if (latestSeq < readSeq) {
throw new Error(
`${batchLabel} private user ${target.userId} latest sequence ${latestSeq} is before read sequence ${readSeq}`,
);
}
if (latestSeq > readSeq) {
const lastMsgTime = requirePositiveSequence(
item.lastMsgTime,
`${batchLabel} private user ${target.userId} last message time`,
);
c2cList.push({ uid: target.uid, lastReadTime: lastMsgTime, lastReadSeq: latestSeq });
c2cConfirmTargets.push(target);
}
}
if (groupList.length === 0 && c2cList.length === 0) {
log.debug('%s already current', batchLabel);
return;
}
const confirm = await this.sendReadReport({ groupList, c2cList }, `${batchLabel} confirm`);
for (let i = 0; i < groupList.length; i++) {
const requested = groupList[i]!;
const groupId = Number(requested.groupUin);
const item = this.groupReadResponse(confirm, groupId, i, `${batchLabel} confirm`);
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} confirmed read sequence`);
if (readSeq < (requested.lastReadSeq ?? 0n)) {
throw new Error(
`${batchLabel} group ${groupId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
);
}
}
for (let i = 0; i < c2cList.length; i++) {
const requested = c2cList[i]!;
const target = c2cConfirmTargets[i]!;
const item = this.c2cReadResponse(confirm, target, i, `${batchLabel} confirm`);
const readSeq = readUnsignedSequence(
item.readSeq,
`${batchLabel} private user ${target.userId} confirmed read sequence`,
);
if (readSeq < (requested.lastReadSeq ?? 0n)) {
throw new Error(
`${batchLabel} private user ${target.userId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
);
}
}
}
@@ -558,4 +784,3 @@ export class MessageApi {
}
}
}
+130 -54
View File
@@ -6,10 +6,15 @@ import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/p
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
type WebApiGroupNoticeCollection,
type WebApiGroupNoticeFeed,
type WebApiGroupNoticeRet,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { Bridge } from '../bridge';
@@ -42,6 +47,113 @@ export interface WebNoticeInfo {
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
/** Server response type. Regular notices are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
}
export interface SendNoticeOptions {
image?: string;
pinned?: number;
type?: number;
sendToNewMembers?: boolean;
isShowEditCard?: number;
tipWindowType?: number;
confirmRequired?: number;
}
function finiteNumber(value: unknown, field: string): number {
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
if (!Number.isFinite(parsed)) {
throw new Error(`invalid group notice response: ${field} must be a finite number`);
}
return parsed;
}
function collectionValues(
collection: WebApiGroupNoticeCollection | undefined,
field: 'feeds' | 'inst',
): WebApiGroupNoticeFeed[] {
if (collection === undefined) return [];
if (Array.isArray(collection)) return collection;
if (collection === null || typeof collection !== 'object') {
throw new Error(`invalid group notice response: ${field} must be an array or object`);
}
return Object.values(collection);
}
function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo {
if (!feed || typeof feed !== 'object') {
throw new Error('invalid group notice response: feed must be an object');
}
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
}
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
}
if (feed.settings === undefined) {
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
}
const image = (feed.msg.pics ?? []).map((pic, index) => {
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
}
return {
id: pic.id,
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
};
});
const responseType = feed.type === undefined
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
return {
notice_id: feed.fid,
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
message: {
text: feed.msg.text,
image,
images: image,
},
settings: feed.settings,
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
type: responseType,
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
};
}
/** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */
export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] {
if (ret.ec !== 0) {
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
}
const notices: WebNoticeInfo[] = [];
const indexByNoticeId = new Map<string, number>();
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
for (const feed of collectionValues(collection, field)) {
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
const existingIndex = indexByNoticeId.get(mapped.notice_id);
if (existingIndex === undefined) {
indexByNoticeId.set(mapped.notice_id, notices.length);
notices.push(mapped);
} else if (sendToNewMembers) {
// If QQ returns the same item in both collections, `inst` is the
// authoritative signal that it targets new members.
notices[existingIndex] = mapped;
}
}
};
append(ret.feeds, false, 'feeds');
append(ret.inst, true, 'inst');
return notices;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
@@ -243,12 +355,7 @@ export class WebApi {
async sendNotice(
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
options?: SendNoticeOptions,
): Promise<SetNoticeRetSuccess> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
@@ -266,29 +373,30 @@ export class WebApi {
const imageBuffer = Buffer.from(loaded.bytes);
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight,
{
pinned: options?.pinned,
type: options?.type,
sendToNewMembers: options?.sendToNewMembers,
isShowEditCard: options?.isShowEditCard,
tipWindowType: options?.tipWindowType,
confirmRequired: options?.confirmRequired,
picId,
imgWidth,
imgHeight,
},
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
if (ret.ec !== 0) {
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
}
return ret;
@@ -300,39 +408,7 @@ export class WebApi {
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: WebNoticeInfo[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
return mapGroupNoticeResponse(ret);
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
+50 -7
View File
@@ -18,6 +18,18 @@ const AGREEMENT_FILES = [
{ id: 'privacy' as const, file: 'PRIVACY.md' },
];
export const EULA_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_EULA';
export const PRIVACY_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_PRIVACY';
type ConsentEnvironment = Readonly<Record<string, string | undefined>>;
export interface EnvironmentConsent {
eulaAccepted: boolean;
privacyAccepted: boolean;
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
accepted: boolean;
}
export interface AgreementDoc {
id: 'eula' | 'privacy';
/** First markdown `# ` heading, for the tab/section title. */
@@ -41,15 +53,44 @@ export interface AgreementsPayload {
/** Content-hash version of the current agreement set. */
version: string;
/**
* True when the operator must (re-)accept: the agreements carry real text
* AND the stored consent version differs from the current one. A missing or
* unreadable agreement set fails OPEN (no gate) so a broken bundle can never
* lock the admin out of their own panel.
* True when the operator must (re-)accept: the agreements carry real text,
* environment consent is incomplete, AND the stored consent version differs
* from the current one. A missing or unreadable agreement set fails OPEN (no
* gate) so a broken bundle can never lock the admin out of their own panel.
*/
consentRequired: boolean;
documents: AgreementDoc[];
}
function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean {
if (raw === undefined || raw.trim() === '') return false;
const normalized = raw.trim().toLowerCase();
if (normalized === '1' || normalized === 'true') return true;
if (normalized === '0' || normalized === 'false') return false;
throw new Error(
`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`,
);
}
/**
* Resolve declarative consent for unattended deployments. Environment consent
* is intentionally ephemeral: removing either variable restores the normal
* versioned consent gate instead of silently writing a permanent record.
*/
export function resolveEnvironmentConsent(
env: ConsentEnvironment = process.env,
): EnvironmentConsent {
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
return {
eulaAccepted,
privacyAccepted,
accepted: eulaAccepted && privacyAccepted,
};
}
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
/**
@@ -85,7 +126,7 @@ export function parseAgreementMeta(text: string): {
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
const declaredVersion =
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.\-]*)/)?.[1]?.trim() ?? '';
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
const effectiveDate =
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
return { title, declaredVersion, effectiveDate };
@@ -169,8 +210,10 @@ export function recordConsent(version: string): ConsentRecord {
return record;
}
/** True when the agreements carry real text and the stored consent is stale. */
export function isConsentRequired(): boolean {
/** True when neither environment nor stored consent covers the current agreements. */
export function isConsentRequired(env: ConsentEnvironment = process.env): boolean {
if (resolveEnvironmentConsent(env).accepted) return false;
const { docs, version } = loadAgreements();
const hasContent = docs.some((d) => d.text.trim().length > 0);
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
+26 -2
View File
@@ -20,7 +20,15 @@ import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { getAgreementsPayload, isConsentRequired, loadAgreements, recordConsent } from './consent';
import {
EULA_ACCEPT_ENV,
getAgreementsPayload,
isConsentRequired,
loadAgreements,
PRIVACY_ACCEPT_ENV,
recordConsent,
resolveEnvironmentConsent,
} from './consent';
import { resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch } from './system-settings';
import { buildBackup, planRestore, validateBackup } from './backup';
@@ -419,8 +427,24 @@ export async function initWebUI(
// Memoized once at startup (agreements version is fixed per process; a text
// change ships with a redeploy that restarts us). Flipped to false the moment
// consent is recorded, so the middleware never touches disk per request.
const environmentConsent = resolveEnvironmentConsent();
let consentGatePending = isConsentRequired();
if (consentGatePending) log.info('awaiting EULA/PRIVACY consent before the panel unlocks');
if (environmentConsent.accepted) {
log.info(
'EULA/PRIVACY consent supplied by %s and %s (agreements version=%s)',
EULA_ACCEPT_ENV,
PRIVACY_ACCEPT_ENV,
loadAgreements().version,
);
} else if (environmentConsent.eulaAccepted || environmentConsent.privacyAccepted) {
log.warn(
'partial environment consent ignored; set both %s=1 and %s=1 to accept the agreements',
EULA_ACCEPT_ENV,
PRIVACY_ACCEPT_ENV,
);
} else if (consentGatePending) {
log.info('awaiting EULA/PRIVACY consent before the panel unlocks');
}
const app = new Hono();
+2
View File
@@ -27,6 +27,7 @@ export interface MockMessageApi {
recallPrivate: ReturnType<typeof vi.fn>;
markGroupRead: ReturnType<typeof vi.fn>;
markPrivateRead: ReturnType<typeof vi.fn>;
markAllRead: ReturnType<typeof vi.fn>;
}
export function mockMessageApi(): MockMessageApi {
@@ -38,6 +39,7 @@ export function mockMessageApi(): MockMessageApi {
recallPrivate: vi.fn(async () => undefined),
markGroupRead: vi.fn(async () => undefined),
markPrivateRead: vi.fn(async () => undefined),
markAllRead: vi.fn(async () => undefined),
};
}
@@ -0,0 +1,162 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type {
OidbBase,
OidbFriend,
OidbFriendCategory,
OidbSvcTrpcTcp0xFD4_1Response,
} from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { ContactsApi } from '../../src/bridge/apis/contacts';
function friend(
uin: number,
categoryId: number,
uid: string,
nickname: string,
remark = '',
): OidbFriend {
return {
uin,
uid,
customGroup: categoryId,
additional: [{
type: 1,
layer1: {
properties: [
{ code: 20002, value: nickname },
{ code: 103, value: remark },
],
},
}],
};
}
function category(
categoryId: number,
categoryName: string,
memberCount: number,
sortId: number,
): OidbFriendCategory {
return { categoryId, categoryName, memberCount, sortId };
}
function packet(body: OidbSvcTrpcTcp0xFD4_1Response): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }),
),
};
}
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
let index = 0;
const sendRawPacket = vi.fn(async (
_cmd: string,
_body: Uint8Array,
): Promise<SendPacketResult> => {
const page = pages[index++];
if (!page) throw new Error(`unexpected friend-list page ${index}`);
return packet(page);
});
const rememberFriends = vi.fn();
const api = new ContactsApi({
sendRawPacket,
identity: { rememberFriends },
} as any);
return { api, sendRawPacket, rememberFriends };
}
describe('apis/contacts / categorized friend roster', () => {
it('keeps fetchFriendList flat while traversing cookie pages', async () => {
const cookie = Uint8Array.from([0x01]);
const { api, sendRawPacket } = apiForPages([
{ cookie, friends: [friend(10001, 0, 'u1', 'Default')] },
{ friends: [friend(10002, 7, 'u2', 'Alice', 'A')] },
]);
await expect(api.fetchFriendList()).resolves.toEqual([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
});
it('groups a complete multi-page roster and preserves empty categories', async () => {
const cookie = Uint8Array.from([0xAA, 0xBB]);
const { api, sendRawPacket, rememberFriends } = apiForPages([
{
cookie,
friends: [friend(10001, 0, 'u1', 'Default')],
categories: [
category(0, '我的好友', 1, 0),
category(7, 'Work', 1, 1),
category(9, 'Empty', 0, 2),
],
},
{
friends: [friend(10002, 7, 'u2', 'Alice', 'A')],
categories: [category(7, 'Work', 1, 1)],
},
]);
await expect(api.fetchFriendCategories()).resolves.toEqual([
{
categoryId: 0,
categoryName: '我的好友',
memberCount: 1,
sortId: 0,
friends: [{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' }],
},
{
categoryId: 7,
categoryName: 'Work',
memberCount: 1,
sortId: 1,
friends: [{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' }],
},
{
categoryId: 9,
categoryName: 'Empty',
memberCount: 0,
sortId: 2,
friends: [],
},
]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
const secondRequest = protobuf_decode<OidbBase<OidbFriendListRequest>>(
sendRawPacket.mock.calls[1]![1],
);
expect(secondRequest.body?.cookie).toEqual(cookie);
expect(rememberFriends).toHaveBeenCalledOnce();
expect(rememberFriends).toHaveBeenCalledWith([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
]);
});
it('rejects a friend whose category metadata never arrives', async () => {
const { api } = apiForPages([{
friends: [friend(10001, 99, 'u1', 'Orphan')],
categories: [],
}]);
await expect(api.fetchFriendCategories())
.rejects.toThrow('missing category 99');
});
it('rejects a repeated non-empty pagination cookie', async () => {
const cookie = Uint8Array.from([0xAA]);
const { api } = apiForPages([{ cookie }, { cookie }]);
await expect(api.fetchFriendCategories())
.rejects.toThrow('repeated friend-list cookie aa');
});
});
@@ -5,6 +5,11 @@
// and #6 commit 6 absorbed setEssence into InteractionApi.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SsoReadedReportReq,
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -16,6 +21,16 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({
import { MessageApi } from '../../src/bridge/apis/message';
import { mockBridge } from './_helpers';
function readReportResult(response: SsoReadedReportResp) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoReadedReportResp>(response)),
};
}
describe('apis/message — recall + markRead', () => {
beforeEach(() => {
// No global mock state to reset — sendRawPacket is per-bridge.
@@ -51,16 +66,151 @@ describe('apis/message — recall + markRead', () => {
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
});
it('markGroupRead and markPrivateRead both hit SsoReadedReport', async () => {
const bridge = mockBridge();
const api = new MessageApi(bridge as any);
await api.markGroupRead(12345, 50);
await api.markPrivateRead(10001, 60);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const cmds = bridge.sendRawPacket.mock.calls.map((c: any) => c[0]);
expect(cmds).toEqual([
it('probes and confirms group plus private reads in the same packets', async () => {
const sendRawPacket = vi.fn()
.mockResolvedValueOnce(readReportResult({
groupList: [{ groupUin: 1081372778n, readSeq: 66569n, latestSeq: 66629n }],
c2cList: [{
uid: 'resolved-uid',
readSeq: 160n,
latestSeq: 171n,
lastMsgTime: 1783952859n,
}],
}))
.mockResolvedValueOnce(readReportResult({
groupList: [{ groupUin: 1081372778n, readSeq: 66629n, latestSeq: 66629n }],
c2cList: [{
uid: 'resolved-uid',
readSeq: 171n,
latestSeq: 171n,
lastMsgTime: 1783952859n,
}],
}));
const bridge = mockBridge({ sendRawPacket });
await new MessageApi(bridge as any).markAllRead([1081372778], [10001]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
expect(sendRawPacket.mock.calls.map((call: any) => call[0])).toEqual([
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
]);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const probeBytes = sendRawPacket.mock.calls[0]![1];
expect(Buffer.from(probeBytes).toString('hex')).toBe(
'0a0608eae0d18304120e120c7265736f6c7665642d756964',
);
const probe = protobuf_decode<SsoReadedReportReq>(probeBytes);
expect(probe).toEqual({
groupList: [{ groupUin: 1081372778n, lastReadSeq: null }],
c2cList: [{ uid: 'resolved-uid', lastReadTime: null, lastReadSeq: null }],
});
const confirm = protobuf_decode<SsoReadedReportReq>(sendRawPacket.mock.calls[1]![1]);
expect(confirm).toEqual({
groupList: [{ groupUin: 1081372778n, lastReadSeq: 66629n }],
c2cList: [{
uid: 'resolved-uid',
lastReadTime: 1783952859n,
lastReadSeq: 171n,
}],
});
});
it('does not send a confirm packet when every read marker is current', async () => {
const sendRawPacket = vi.fn(async () => readReportResult({
groupList: [{ groupUin: 12345n, readSeq: 50n, latestSeq: 50n }],
}));
const bridge = mockBridge({ sendRawPacket });
await new MessageApi(bridge as any).markGroupRead(12345);
expect(sendRawPacket).toHaveBeenCalledOnce();
});
it('markGroupRead rejects a transport success with no business response', async () => {
const bridge = mockBridge();
await expect(new MessageApi(bridge as any).markGroupRead(12345))
.rejects.toThrow(/response is empty/);
});
it('markGroupRead surfaces the per-group business error', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => readReportResult({
groupList: [{ resultCode: 100000010, errorMessage: 'send group msg failed, ret:2' }],
})),
});
await expect(new MessageApi(bridge as any).markGroupRead(1))
.rejects.toThrow(/send group msg failed, ret:2/);
});
it('rejects a top-level success when the private read marker did not advance', async () => {
const sendRawPacket = vi.fn()
.mockResolvedValueOnce(readReportResult({
c2cList: [{
uid: 'resolved-uid',
readSeq: 160n,
latestSeq: 171n,
lastMsgTime: 1783952859n,
}],
}))
.mockResolvedValueOnce(readReportResult({
c2cList: [{
uid: 'resolved-uid',
readSeq: 160n,
latestSeq: 171n,
lastMsgTime: 1783952859n,
}],
}));
const bridge = mockBridge({ sendRawPacket });
await expect(new MessageApi(bridge as any).markPrivateRead(10001))
.rejects.toThrow(/confirmed sequence 160 before requested 171/);
});
it('caps mixed read reports at 100 + 100 and confirms each page before probing the next', async () => {
const sendRawPacket = vi.fn(async (_cmd: string, body: Uint8Array) => {
const request = protobuf_decode<SsoReadedReportReq>(body);
return readReportResult({
groupList: request.groupList?.map(item => {
const requested = item.lastReadSeq ?? 0n;
return {
groupUin: item.groupUin,
readSeq: requested,
latestSeq: requested === 0n ? 1n : requested,
};
}),
c2cList: request.c2cList?.map(item => {
const requested = item.lastReadSeq ?? 0n;
return {
uid: item.uid,
readSeq: requested,
latestSeq: requested === 0n ? 1n : requested,
lastMsgTime: 1700000000n,
};
}),
});
});
const resolveUserUid = vi.fn(async (userId: number) => `uid-${userId}`);
const bridge = mockBridge({ sendRawPacket, resolveUserUid });
const groups = Array.from({ length: 101 }, (_, i) => 1000 + i);
const users = Array.from({ length: 101 }, (_, i) => 2000 + i);
await new MessageApi(bridge as any).markAllRead(groups, users);
expect(sendRawPacket).toHaveBeenCalledTimes(4);
const requests = sendRawPacket.mock.calls.map((call: any) =>
protobuf_decode<SsoReadedReportReq>(call[1]));
expect(requests.map(request => [request.groupList?.length, request.c2cList?.length])).toEqual([
[100, 100],
[100, 100],
[1, 1],
[1, 1],
]);
expect(requests[0]!.groupList![0]!.lastReadSeq).toBeNull();
expect(requests[1]!.groupList![0]!.lastReadSeq).toBe(1n);
expect(requests[2]!.groupList![0]!.lastReadSeq).toBeNull();
expect(requests[3]!.groupList![0]!.lastReadSeq).toBe(1n);
});
});
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import { mapGroupNoticeResponse } from '../src/bridge/apis/web';
import type { WebApiGroupNoticeFeed, WebApiGroupNoticeRet } from '@snowluma/protocol/web/group-notice';
function feed(fid: string, overrides: Partial<WebApiGroupNoticeFeed> = {}): WebApiGroupNoticeFeed {
return {
fid,
u: 10001,
pubt: 1_700_000_000,
msg: { text: `notice-${fid}` },
settings: {},
read_num: 2,
...overrides,
};
}
describe('mapGroupNoticeResponse', () => {
it('merges regular feeds and new-member inst entries with response metadata', () => {
const ret: WebApiGroupNoticeRet = {
ec: 0,
feeds: [feed('regular', {
type: '6',
pinned: '1',
msg: { text: 'regular', pics: [{ id: 'pic', w: '640', h: '360' }] },
})],
inst: { welcome: feed('welcome', { settings: { confirm_required: 1 } }) },
};
expect(mapGroupNoticeResponse(ret)).toEqual([
{
notice_id: 'regular',
sender_id: 10001,
publish_time: 1_700_000_000,
message: {
text: 'regular',
image: [{ id: 'pic', width: 640, height: 360 }],
images: [{ id: 'pic', width: 640, height: 360 }],
},
settings: {},
read_num: 2,
type: 6,
pinned: 1,
send_to_new_members: false,
},
{
notice_id: 'welcome',
sender_id: 10001,
publish_time: 1_700_000_000,
message: { text: 'notice-welcome', image: [], images: [] },
settings: { confirm_required: 1 },
read_num: 2,
type: 20,
pinned: 0,
send_to_new_members: true,
},
]);
});
it('deduplicates a feed repeated in inst and treats inst as authoritative', () => {
const duplicate = feed('same', { type: 20 });
const notices = mapGroupNoticeResponse({ ec: 0, feeds: [duplicate], inst: [duplicate] });
expect(notices).toHaveLength(1);
expect(notices[0]).toMatchObject({ notice_id: 'same', send_to_new_members: true, type: 20 });
});
it('recognizes a type-20 entry even if QQ places it in feeds', () => {
expect(mapGroupNoticeResponse({ ec: 0, feeds: [feed('welcome', { type: 20 })] })[0])
.toMatchObject({ send_to_new_members: true, type: 20 });
});
it('surfaces server failures and malformed response fields', () => {
expect(() => mapGroupNoticeResponse({ ec: 14, em: 'permission denied' })).toThrow('ec=14');
expect(() => mapGroupNoticeResponse({
ec: 0,
feeds: [feed('bad', { msg: { text: 'bad', pics: [{ id: 'x', w: 'wide', h: 20 }] } })],
})).toThrow('image 0.w');
});
});
+48
View File
@@ -4,9 +4,14 @@ import os from 'os';
import path from 'path';
import {
computeAgreementsVersion,
EULA_ACCEPT_ENV,
isConsentRequired,
loadAgreements,
parseAgreementMeta,
PRIVACY_ACCEPT_ENV,
recordConsent,
loadConsentRecord,
resolveEnvironmentConsent,
} from '@/webui/consent';
describe('computeAgreementsVersion', () => {
@@ -66,6 +71,35 @@ describe('parseAgreementMeta', () => {
});
});
describe('environment consent', () => {
it('requires explicit acceptance of both EULA and PRIVACY', () => {
expect(resolveEnvironmentConsent({})).toEqual({
eulaAccepted: false,
privacyAccepted: false,
accepted: false,
});
expect(resolveEnvironmentConsent({ [EULA_ACCEPT_ENV]: '1' })).toEqual({
eulaAccepted: true,
privacyAccepted: false,
accepted: false,
});
});
it('accepts trimmed, case-insensitive true values', () => {
expect(resolveEnvironmentConsent({
[EULA_ACCEPT_ENV]: ' true ',
[PRIVACY_ACCEPT_ENV]: 'TRUE',
}).accepted).toBe(true);
});
it('fails fast on an invalid configured value', () => {
expect(() => resolveEnvironmentConsent({
[EULA_ACCEPT_ENV]: 'yes',
[PRIVACY_ACCEPT_ENV]: '1',
})).toThrow(`${EULA_ACCEPT_ENV} must be one of: 1, true, 0, false`);
});
});
describe('consent persistence', () => {
let tmp: string;
let cwd: string;
@@ -100,6 +134,20 @@ describe('consent persistence', () => {
expect(stored?.version !== 'old-version').toBe(false);
});
it('environment consent unlocks without writing a permanent consent record', () => {
expect(isConsentRequired({
[EULA_ACCEPT_ENV]: '1',
[PRIVACY_ACCEPT_ENV]: 'true',
})).toBe(false);
expect(loadConsentRecord()).toBeNull();
expect(isConsentRequired({ [EULA_ACCEPT_ENV]: '1' })).toBe(true);
});
it('stored consent still covers the current agreement version', () => {
recordConsent(loadAgreements().version);
expect(isConsentRequired({})).toBe(false);
});
it('ignores a malformed consent.json (treated as no consent)', () => {
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(path.join('config', 'consent.json'), '{ not json');
+2 -2
View File
@@ -41,8 +41,8 @@ const nativeSrc = toPosix(nativeDir);
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
const [targetPlatform, targetArch] = targetTriple.split('-');
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
// so its launcher/shell script differ per target.
// Runtime scaffolding files copied into dist/. Windows and Linux use different
// launchers, while both targets ship their matching QQ integration binaries.
const runtimeDistFiles = ['package.json',
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
];
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.12.1",
"version": "1.12.2",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+241 -17
View File
@@ -62,6 +62,7 @@
"name": "_get_group_notice",
"aliases": [],
"summary": "获取群公告",
"returns": "普通公告与新成员公告的合并数组;send_to_new_members 标识后者",
"readOnly": true,
"params": [
{
@@ -155,7 +156,7 @@
{
"name": "_mark_all_as_read",
"aliases": [],
"summary": "标记全部已读(no-op,待 RE 全读 cmd)",
"summary": "标记全部已读",
"readOnly": false,
"params": [],
"invariants": [],
@@ -169,7 +170,7 @@
{
"name": "_send_group_notice",
"aliases": [],
"summary": "发送群公告",
"summary": "发送群公告(支持置顶、弹窗、新成员、群昵称引导与确认)",
"readOnly": false,
"params": [
{
@@ -190,7 +191,8 @@
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "公告正文"
},
{
"name": "image",
@@ -200,28 +202,80 @@
"type": "string"
},
"default": "",
"role": "image"
"role": "image",
"desc": "可选公告图片(本地路径、URL 或 base64)"
},
{
"name": "pinned",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 0,
"desc": "是否置顶:1=置顶,0=不置顶"
},
{
"name": "type",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer"
},
"desc": "发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members"
},
{
"name": "send_to_new_members",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"desc": "是否在成员新加入群时发送(与 type=20 等价)"
},
{
"name": "is_show_edit_card",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "是否引导群成员修改群昵称:1=是,0=否"
},
{
"name": "tip_window_type",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)"
},
{
"name": "confirm_required",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "是否需要群成员确认收到:1=是,0=否"
}
],
"invariants": [],
"invariants": [
"type must be 1 (regular) or 20 (new members)",
"send_to_new_members conflicts with type"
],
"inputSchema": {
"type": "object",
"properties": {
@@ -233,16 +287,51 @@
},
"content": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "公告正文"
},
"image": {
"type": "string",
"description": "可选公告图片(本地路径、URL 或 base64)",
"default": "",
"x-role": "image"
},
"pinned": {},
"type": {},
"confirm_required": {}
"pinned": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否置顶:1=置顶,0=不置顶",
"default": 0
},
"type": {
"type": "integer",
"description": "发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members"
},
"send_to_new_members": {
"type": "boolean",
"description": "是否在成员新加入群时发送(与 type=20 等价)"
},
"is_show_edit_card": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否引导群成员修改群昵称:1=是,0=否",
"default": 1
},
"tip_window_type": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)",
"default": 1
},
"confirm_required": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否需要群成员确认收到:1=是,0=否",
"default": 1
}
},
"required": [
"group_id",
@@ -3019,6 +3108,60 @@
"name": "get_friends_with_category",
"aliases": [],
"summary": "获取分组好友列表",
"returns": "好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。",
"returnsSchema": {
"type": "array",
"description": "带分组的好友列表",
"items": {
"type": "object",
"properties": {
"categoryId": {
"type": "integer",
"description": "分组 ID"
},
"categoryName": {
"type": "string",
"description": "分组名称"
},
"categoryMbCount": {
"type": "integer",
"description": "服务端报告的分组好友数"
},
"buddyList": {
"type": "array",
"description": "该分组内的好友",
"items": {
"type": "object",
"properties": {
"user_id": {
"type": "integer",
"description": "QQ 号"
},
"nickname": {
"type": "string",
"description": "昵称"
},
"remark": {
"type": "string",
"description": "好友备注"
}
},
"required": [
"user_id",
"nickname",
"remark"
]
}
}
},
"required": [
"categoryId",
"categoryName",
"categoryMbCount",
"buddyList"
]
}
},
"readOnly": true,
"params": [],
"invariants": [],
@@ -4561,12 +4704,93 @@
"name": "get_group_system_msg",
"aliases": [],
"summary": "获取群系统消息",
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
"returnsSchema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"group_id": {
"type": "integer",
"description": "群号"
},
"group_name": {
"type": "string",
"description": "群名称"
},
"request_id": {
"type": "integer",
"description": "请求序列号"
},
"requester_uin": {
"type": "integer",
"description": "申请人 QQ 号"
},
"requester_nick": {
"type": "string",
"description": "申请人昵称"
},
"message": {
"type": "string",
"description": "验证留言"
},
"checked": {
"type": "boolean",
"description": "是否已处理"
},
"flag": {
"type": "string",
"description": "处理请求使用的规范 flag"
}
},
"required": [
"group_id",
"group_name",
"request_id",
"requester_uin",
"requester_nick",
"message",
"checked",
"flag"
]
}
},
"readOnly": true,
"params": [],
"params": [
{
"name": "group_id",
"type": "uint",
"required": false,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
}
},
{
"name": "only_pending",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"x-role": "group_id"
},
"only_pending": {
"type": "boolean",
"default": false
}
},
"additionalProperties": true
},
"category": "群信息"
+241 -17
View File
@@ -65,6 +65,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "_get_group_notice",
"aliases": [],
"summary": "获取群公告",
"returns": "普通公告与新成员公告的合并数组;send_to_new_members 标识后者",
"readOnly": true,
"params": [
{
@@ -158,7 +159,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "_mark_all_as_read",
"aliases": [],
"summary": "标记全部已读(no-op,待 RE 全读 cmd)",
"summary": "标记全部已读",
"readOnly": false,
"params": [],
"invariants": [],
@@ -172,7 +173,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "_send_group_notice",
"aliases": [],
"summary": "发送群公告",
"summary": "发送群公告(支持置顶、弹窗、新成员、群昵称引导与确认)",
"readOnly": false,
"params": [
{
@@ -193,7 +194,8 @@ export const ACTIONS: CatalogAction[] = [
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "公告正文"
},
{
"name": "image",
@@ -203,28 +205,80 @@ export const ACTIONS: CatalogAction[] = [
"type": "string"
},
"default": "",
"role": "image"
"role": "image",
"desc": "可选公告图片(本地路径、URL 或 base64)"
},
{
"name": "pinned",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 0,
"desc": "是否置顶:1=置顶,0=不置顶"
},
{
"name": "type",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer"
},
"desc": "发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members"
},
{
"name": "send_to_new_members",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"desc": "是否在成员新加入群时发送(与 type=20 等价)"
},
{
"name": "is_show_edit_card",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "是否引导群成员修改群昵称:1=是,0=否"
},
{
"name": "tip_window_type",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)"
},
{
"name": "confirm_required",
"type": "raw",
"type": "int",
"required": false,
"schema": {}
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 1
},
"default": 1,
"desc": "是否需要群成员确认收到:1=是,0=否"
}
],
"invariants": [],
"invariants": [
"type must be 1 (regular) or 20 (new members)",
"send_to_new_members conflicts with type"
],
"inputSchema": {
"type": "object",
"properties": {
@@ -236,16 +290,51 @@ export const ACTIONS: CatalogAction[] = [
},
"content": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "公告正文"
},
"image": {
"type": "string",
"description": "可选公告图片(本地路径、URL 或 base64)",
"default": "",
"x-role": "image"
},
"pinned": {},
"type": {},
"confirm_required": {}
"pinned": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否置顶:1=置顶,0=不置顶",
"default": 0
},
"type": {
"type": "integer",
"description": "发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members"
},
"send_to_new_members": {
"type": "boolean",
"description": "是否在成员新加入群时发送(与 type=20 等价)"
},
"is_show_edit_card": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否引导群成员修改群昵称:1=是,0=否",
"default": 1
},
"tip_window_type": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)",
"default": 1
},
"confirm_required": {
"type": "integer",
"minimum": 0,
"maximum": 1,
"description": "是否需要群成员确认收到:1=是,0=否",
"default": 1
}
},
"required": [
"group_id",
@@ -3022,6 +3111,60 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_friends_with_category",
"aliases": [],
"summary": "获取分组好友列表",
"returns": "好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。",
"returnsSchema": {
"type": "array",
"description": "带分组的好友列表",
"items": {
"type": "object",
"properties": {
"categoryId": {
"type": "integer",
"description": "分组 ID"
},
"categoryName": {
"type": "string",
"description": "分组名称"
},
"categoryMbCount": {
"type": "integer",
"description": "服务端报告的分组好友数"
},
"buddyList": {
"type": "array",
"description": "该分组内的好友",
"items": {
"type": "object",
"properties": {
"user_id": {
"type": "integer",
"description": "QQ 号"
},
"nickname": {
"type": "string",
"description": "昵称"
},
"remark": {
"type": "string",
"description": "好友备注"
}
},
"required": [
"user_id",
"nickname",
"remark"
]
}
}
},
"required": [
"categoryId",
"categoryName",
"categoryMbCount",
"buddyList"
]
}
},
"readOnly": true,
"params": [],
"invariants": [],
@@ -4564,12 +4707,93 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_group_system_msg",
"aliases": [],
"summary": "获取群系统消息",
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
"returnsSchema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"group_id": {
"type": "integer",
"description": "群号"
},
"group_name": {
"type": "string",
"description": "群名称"
},
"request_id": {
"type": "integer",
"description": "请求序列号"
},
"requester_uin": {
"type": "integer",
"description": "申请人 QQ 号"
},
"requester_nick": {
"type": "string",
"description": "申请人昵称"
},
"message": {
"type": "string",
"description": "验证留言"
},
"checked": {
"type": "boolean",
"description": "是否已处理"
},
"flag": {
"type": "string",
"description": "处理请求使用的规范 flag"
}
},
"required": [
"group_id",
"group_name",
"request_id",
"requester_uin",
"requester_nick",
"message",
"checked",
"flag"
]
}
},
"readOnly": true,
"params": [],
"params": [
{
"name": "group_id",
"type": "uint",
"required": false,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
}
},
{
"name": "only_pending",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"x-role": "group_id"
},
"only_pending": {
"type": "boolean",
"default": false
}
},
"additionalProperties": true
},
"category": "群信息"
+6 -1
View File
@@ -598,6 +598,10 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
fs.writeFileSync(inputFile, 'x');
const requests: Array<Record<string, any>> = [];
const signals: AbortSignal[] = [];
let markUploadRequestStarted!: () => void;
const uploadRequestStarted = new Promise<void>((resolve) => {
markUploadRequestStarted = resolve;
});
const fakeFetch = (async (_url: unknown, init: RequestInit) => {
const request = JSON.parse(String(init.body)) as Record<string, any>;
requests.push(request);
@@ -606,12 +610,13 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
const reset = { status: 'failed', retcode: 100, wording: 'Stream reset completed', data: { type: 'error' } };
return new Response(`${JSON.stringify(reset)}\r\n\r\n`, { status: 200 });
}
markUploadRequestStarted();
return new Response(new ReadableStream<Uint8Array>({ start() {} }), { status: 200 });
}) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root, timeoutMs: 1_000 });
const controller = new AbortController();
const pending = client.callStream('upload_file_stream', {}, { inputFile, signal: controller.signal });
for (let i = 0; i < 50 && requests.length === 0; i++) await new Promise<void>((resolve) => setImmediate(resolve));
await uploadRequestStarted;
controller.abort(new Error('cancel automatic upload'));
const outcome = await Promise.race([
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
+69 -22
View File
@@ -370,7 +370,7 @@ export const actions = [
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence);
await ctx.bridge.apis.message.markGroupRead(meta.targetId);
return okResponse();
},
}),
@@ -392,7 +392,7 @@ export const actions = [
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
}
await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence);
await ctx.bridge.apis.message.markPrivateRead(meta.targetId);
return okResponse();
},
}),
@@ -413,9 +413,9 @@ export const actions = [
}
if (meta.isGroup) {
await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence);
await ctx.bridge.apis.message.markGroupRead(meta.targetId);
} else {
await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence);
await ctx.bridge.apis.message.markPrivateRead(meta.targetId);
}
return okResponse();
},
@@ -424,20 +424,33 @@ export const actions = [
// 群公告
groupAction({
name: '_send_group_notice',
summary: '发送群公告',
summary: '发送群公告(支持置顶、弹窗、新成员、群昵称引导与确认)',
params: {
content: f.string({ allowEmpty: false }),
image: f.string().default('').role('image'),
pinned: f.raw(),
type: f.raw(),
confirm_required: f.raw(),
content: f.string({ allowEmpty: false }).describe('公告正文'),
image: f.string().default('').role('image').describe('可选公告图片(本地路径、URL 或 base64)'),
pinned: f.int({ min: 0, max: 1 }).default(0).describe('是否置顶:1=置顶,0=不置顶'),
type: f.int().optional().describe('发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members'),
send_to_new_members: f.bool().optional().describe('是否在成员新加入群时发送(与 type=20 等价)'),
is_show_edit_card: f.int({ min: 0, max: 1 }).default(1).describe('是否引导群成员修改群昵称:1=是,0=否'),
tip_window_type: f.int({ min: 0, max: 1 }).default(1).describe('弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)'),
confirm_required: f.int({ min: 0, max: 1 }).default(1).describe('是否需要群成员确认收到:1=是,0=否'),
},
rules: (r) => [
r.rule('type must be 1 (regular) or 20 (new members)', (p) => p.type === undefined || p.type === 1 || p.type === 20),
r.rule(
'send_to_new_members conflicts with type',
(p) => p.send_to_new_members === undefined || p.type === undefined || p.type === (p.send_to_new_members ? 20 : 1),
),
],
run: async (p, ctx) => {
const options = {
image: p.image || undefined,
pinned: p.pinned !== undefined ? Number(p.pinned) : 0,
type: p.type !== undefined ? Number(p.type) : 1,
confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1,
pinned: p.pinned,
type: p.type,
sendToNewMembers: p.send_to_new_members,
isShowEditCard: p.is_show_edit_card,
tipWindowType: p.tip_window_type,
confirmRequired: p.confirm_required,
};
await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options);
@@ -448,6 +461,7 @@ export const actions = [
groupAction({
name: '_get_group_notice',
summary: '获取群公告',
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者',
readOnly: true,
run: async (p, ctx) => {
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
@@ -690,14 +704,13 @@ export const actions = [
},
}),
// _mark_all_as_read — no-op。NapCat 靠单次内核 IPC markAllMsgAsRead() 实现,
// SnowLuma 无等价单包 SSO cmd;遍历所有会话逐个发已读报告是风控高危群发,
// 故暂不真正执行(留待 RE 出"一键全读"cmd)。返回 ok 以兼容启动时盲调的客户端。
defineAction({
name: '_mark_all_as_read',
summary: '标记全部已读(no-op,待 RE 全读 cmd)',
summary: '标记全部已读',
params: {},
run: async () => {
run: async (_p, ctx) => {
const sessions = ctx.listReadSessions();
await ctx.bridge.apis.message.markAllRead(sessions.groupIds, sessions.privateUserIds);
return okResponse();
},
}),
@@ -1122,12 +1135,46 @@ export const actions = [
name: 'get_friends_with_category',
summary: '获取分组好友列表',
readOnly: true,
returns: '好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。',
returnsSchema: {
type: 'array',
description: '带分组的好友列表',
items: {
type: 'object',
properties: {
categoryId: { type: 'integer', description: '分组 ID' },
categoryName: { type: 'string', description: '分组名称' },
categoryMbCount: { type: 'integer', description: '服务端报告的分组好友数' },
buddyList: {
type: 'array',
description: '该分组内的好友',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
},
},
required: ['categoryId', 'categoryName', 'categoryMbCount', 'buddyList'],
},
},
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
const categories = await ctx.bridge.apis.contacts.fetchFriendCategories();
return okResponse(categories.map(category => ({
categoryId: category.categoryId,
categoryName: category.categoryName,
categoryMbCount: category.memberCount,
buddyList: category.friends.map(friend => ({
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
})),
})));
},
}),
+30 -4
View File
@@ -183,13 +183,39 @@ export const actions = [
name: 'get_group_system_msg',
summary: '获取群系统消息',
readOnly: true,
params: {},
run: async (_p, ctx) => {
returns: '群系统消息数组,可按群号或未处理状态过滤。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名称' },
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
},
required: [
'group_id', 'group_name', 'request_id', 'requester_uin',
'requester_nick', 'message', 'checked', 'flag',
],
},
},
params: {
group_id: f.groupId().optional(),
only_pending: f.bool().default(false),
},
run: async (p, ctx) => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
return okResponse(await ctx.handleGetGroupSystemMsg({
groupId: p.group_id,
onlyPending: p.only_pending,
}));
}
return okResponse([]);
},
}),
];
+4 -1
View File
@@ -8,7 +8,9 @@ import {
type CompiledActionKind,
type CompiledActionRegistry,
} from './actions';
import type { GroupSystemMessageQuery } from './modules/contact-actions';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { ReadSessionTargets } from './message-store';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { RETCODE, failedResponse, okResponse } from './types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming';
@@ -37,6 +39,7 @@ export interface ApiActionContext {
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
listReadSessions: () => ReadSessionTargets;
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
@@ -54,7 +57,7 @@ export interface ApiActionContext {
deleteEssenceMsg: (messageId: number) => Promise<void>;
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
handleGetGroupSystemMsg: (query: GroupSystemMessageQuery) => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>;
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
@@ -292,9 +292,18 @@ export const ELEMENT_CODECS = {
return { type: 'json', data: { data: element.text ?? '' } };
},
async fromSegment(data) {
const text = data.data;
if (typeof text !== 'string' || !text.trim()) {
throw new MessageElementValidationError(
'INVALID_FIELD',
'message segment "json" field "data" must be a non-empty JSON string',
'json',
'data',
);
}
return {
type: 'json',
text: String(data.data ?? ''),
text,
};
},
},
+4 -2
View File
@@ -66,6 +66,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
listReadSessions: () => messageStore.listReadSessions(
bridge.identity.groups.map(group => group.groupId),
),
canSendImage: () => true,
canSendRecord: () => true,
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
@@ -81,7 +84,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
getGroupMsgHistory: (groupId, messageId, count) => getGroupHistory(ref, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendHistory(ref, userId, messageId, count),
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
handleGetGroupSystemMsg: (query) => getGroupSystemMessages(bridge, query),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
@@ -125,4 +128,3 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
}
export type { Bridge, WebHonorType };
+46
View File
@@ -2,6 +2,11 @@ import { DatabaseSync, type StatementSync } from 'node:sqlite';
import type { JsonObject, MessageMeta } from './types';
import { openSqliteDb } from './sqlite-open';
export interface ReadSessionTargets {
groupIds: number[];
privateUserIds: number[];
}
export class MessageStore {
private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync;
@@ -12,6 +17,7 @@ export class MessageStore {
private readonly stmtResolveReplyPrivate: StatementSync;
private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsLatest: StatementSync;
private readonly stmtListIncomingC2CSessions: StatementSync;
constructor(dbPath: string) {
// Replace .json extension with .db if present
@@ -85,6 +91,18 @@ export class MessageStore {
ORDER BY sequence DESC
LIMIT ?`,
);
this.stmtListIncomingC2CSessions = this.db.prepare(
`SELECT session_id
FROM messages
WHERE is_group = 0
AND data IS NOT NULL
AND json_extract(data, '$.post_type') = 'message'
AND json_extract(data, '$.message_type') = 'private'
AND json_extract(data, '$.sub_type') = 'friend'
GROUP BY session_id
ORDER BY session_id ASC`,
);
}
close(): void {
@@ -209,7 +227,35 @@ export class MessageStore {
return result;
}
/**
* Build read-report targets from current groups plus genuine incoming C2C
* sessions. `is_group = 0` alone is insufficient: group temp sessions use
* the same storage lane, and sent-message echoes may be keyed by self UIN.
* Only an incoming `sub_type=friend` event can represent unread C2C state.
*/
listReadSessions(currentGroupIds: readonly number[]): ReadSessionTargets {
const groupIds: number[] = [];
const seenGroups = new Set<number>();
for (const groupId of currentGroupIds) {
if (!Number.isSafeInteger(groupId) || groupId <= 0) {
throw new Error(`current group list contains invalid group id ${String(groupId)}`);
}
if (!seenGroups.has(groupId)) {
seenGroups.add(groupId);
groupIds.push(groupId);
}
}
const rows = this.stmtListIncomingC2CSessions.all() as Array<{ session_id: number }>;
const privateUserIds: number[] = [];
for (const row of rows) {
if (!Number.isSafeInteger(row.session_id) || row.session_id <= 0) {
throw new Error(`messages database contains invalid session id ${String(row.session_id)}`);
}
privateUserIds.push(row.session_id);
}
return { groupIds, privateUserIds };
}
private initSchema(): void {
this.db.exec(`
+76 -15
View File
@@ -1,9 +1,21 @@
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { IdentityService } from '@snowluma/protocol/identity-service';
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
import {
formatGroupRequestFlag,
type GroupRequestInfo,
type UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
const REQUESTER_PROFILE_CONCURRENCY = 4;
export interface GroupSystemMessageQuery {
groupId?: number;
onlyPending?: boolean;
}
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.bridge.identity.nickname || ref.uin;
@@ -230,21 +242,70 @@ export async function getStrangerInfo(
}
}
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const reqs = await bridge.apis.contacts.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId,
group_name: r.groupName,
request_id: r.sequence,
requester_uin: r.targetUin,
requester_nick: r.targetName,
message: r.comment,
flag: formatGroupRequestFlag(r),
}));
} catch {
return [];
async function resolveRequesterUins(
bridge: BridgeInterface,
requests: readonly GroupRequestInfo[],
): Promise<Map<string, number>> {
const resolved = new Map<string, number>();
const unresolved = new Set<string>();
for (const request of requests) {
const uid = request.targetUid;
if (!uid || resolved.has(uid)) continue;
if (request.targetUin > 0) {
resolved.set(uid, request.targetUin);
unresolved.delete(uid);
continue;
}
if (unresolved.has(uid)) continue;
const cached = bridge.identity.findUinByUid(uid, request.groupId)
?? bridge.identity.findUinByUid(uid);
if (cached && cached > 0) resolved.set(uid, cached);
else unresolved.add(uid);
}
const profiles = await mapWithConcurrency(
[...unresolved],
REQUESTER_PROFILE_CONCURRENCY,
async (uid) => {
let profile: UserProfileInfo;
try {
profile = await bridge.apis.contacts.fetchUserProfileByUid(uid);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`failed to resolve requester UIN for UID ${uid}: ${message}`, { cause: error });
}
if (!Number.isSafeInteger(profile.uin) || profile.uin <= 0) {
throw new Error(`failed to resolve requester UIN for UID ${uid}`);
}
return [uid, profile.uin] as const;
},
);
for (const [uid, uin] of profiles) resolved.set(uid, uin);
return resolved;
}
export async function getGroupSystemMessages(
bridge: BridgeInterface,
query: GroupSystemMessageQuery = {},
): Promise<JsonObject[]> {
const requests = (await bridge.apis.contacts.fetchGroupRequests()).filter((request) => {
if (query.groupId !== undefined && request.groupId !== query.groupId) return false;
if (query.onlyPending && request.state !== 1) return false;
return true;
});
const requesterUins = await resolveRequesterUins(bridge, requests);
return requests.map((request) => ({
group_id: request.groupId,
group_name: request.groupName,
request_id: request.sequence,
requester_uin: requesterUins.get(request.targetUid) ?? request.targetUin,
requester_nick: request.targetName,
message: request.comment,
checked: request.state !== 1,
flag: formatGroupRequestFlag(request),
}));
}
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
+20 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { defineAction, defineStreamAction, type RegisteredActionSpec } from '../src/action-kit';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import {
@@ -129,6 +129,25 @@ describe('compiled production Action registry', () => {
.map((entry) => [entry.name, entry.kind]),
);
});
it('validates and forwards get_group_system_msg filters', async () => {
const handleGetGroupSystemMsg = vi.fn(async () => []);
const handler = new ApiHandler({ handleGetGroupSystemMsg } as unknown as ApiActionContext);
const response = await handler.handle('get_group_system_msg', {
group_id: '100000002',
only_pending: true,
});
expect(response.status).toBe('ok');
expect(handleGetGroupSystemMsg).toHaveBeenCalledWith({
groupId: 100000002,
onlyPending: true,
});
const doc = ACTION_REGISTRY.resolve('get_group_system_msg');
if (!doc || doc.kind === 'raw') throw new Error('get_group_system_msg action missing');
expect(doc.action.doc.params.map((param) => param.name)).toEqual(['group_id', 'only_pending']);
});
});
describe('ApiHandler constructor-time registry transaction', () => {
+100 -1
View File
@@ -34,7 +34,8 @@ import type { OneBotInstanceContext } from '../src/instance-context';
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
fetchUserProfileByUid: 'contacts', fetchGroupRequests: 'contacts',
fetchDownloadRKeys: 'contacts',
fetchGroupDetail: 'contacts',
};
@@ -393,7 +394,105 @@ describe('onebot/contact-actions / getGroupSystemMessages', () => {
expect(result[0]).toMatchObject({
request_id: 123456,
group_id: 999,
checked: false,
flag: 'slreq:1:123456:999:22:1',
});
});
it('filters by group and pending state before resolving requester identities', async () => {
const fetchUserProfileByUid = vi.fn(async (uid: string) =>
makeProfile(uid === 'u_pending' ? 101 : 202, uid));
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
makeGroupRequest({ groupId: 100, sequence: 1, state: 1, targetUid: 'u_pending', targetUin: 0 }),
makeGroupRequest({ groupId: 100, sequence: 2, state: 2, targetUid: 'u_checked', targetUin: 0 }),
makeGroupRequest({ groupId: 200, sequence: 3, state: 1, targetUid: 'u_other_group', targetUin: 0 }),
]),
fetchUserProfileByUid,
identity: fakeIdentity({ findUinByUid: () => null }),
});
const result = await getGroupSystemMessages(bridge, { groupId: 100, onlyPending: true });
expect(result).toEqual([expect.objectContaining({
group_id: 100,
request_id: 1,
requester_uin: 101,
checked: false,
})]);
expect(fetchUserProfileByUid).toHaveBeenCalledOnce();
expect(fetchUserProfileByUid).toHaveBeenCalledWith('u_pending');
});
it('deduplicates requester profile lookups and limits QQ query concurrency', async () => {
let inFlight = 0;
let peak = 0;
const fetchUserProfileByUid = vi.fn(async (uid: string) => {
inFlight++;
peak = Math.max(peak, inFlight);
await new Promise<void>((resolve) => setTimeout(resolve, 0));
inFlight--;
return makeProfile(1_000 + Number(uid.slice(2)), uid);
});
const requests = Array.from({ length: 6 }, (_, index) => makeGroupRequest({
sequence: index + 1,
targetUid: `u_${index + 1}`,
targetUin: 0,
}));
requests.push(makeGroupRequest({ sequence: 7, targetUid: 'u_1', targetUin: 0 }));
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => requests),
fetchUserProfileByUid,
identity: fakeIdentity({ findUinByUid: () => null }),
});
const result = await getGroupSystemMessages(bridge);
expect(fetchUserProfileByUid).toHaveBeenCalledTimes(6);
expect(peak).toBeLessThanOrEqual(4);
expect(result.map((item) => item.requester_uin)).toEqual([
1001, 1002, 1003, 1004, 1005, 1006, 1001,
]);
});
it('uses a known UIN from a duplicate request without querying QQ', async () => {
const fetchUserProfileByUid = vi.fn(async () => {
throw new Error('profile lookup must not run');
});
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
makeGroupRequest({ sequence: 1, targetUid: 'u_known', targetUin: 0 }),
makeGroupRequest({ sequence: 2, targetUid: 'u_known', targetUin: 4242 }),
]),
fetchUserProfileByUid,
identity: fakeIdentity({ findUinByUid: () => null }),
});
const result = await getGroupSystemMessages(bridge);
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
expect(result.map((item) => item.requester_uin)).toEqual([4242, 4242]);
});
it('propagates inbox failures instead of disguising them as an empty list', async () => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => { throw new Error('OIDB unavailable'); }),
});
await expect(getGroupSystemMessages(bridge)).rejects.toThrow('OIDB unavailable');
});
it('identifies the requester UID when profile resolution fails', async () => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
makeGroupRequest({ targetUid: 'u_missing', targetUin: 0 }),
]),
fetchUserProfileByUid: vi.fn(async () => { throw new Error('profile OIDB unavailable'); }),
identity: fakeIdentity({ findUinByUid: () => null }),
});
await expect(getGroupSystemMessages(bridge)).rejects.toThrow(
'failed to resolve requester UIN for UID u_missing: profile OIDB unavailable',
);
});
});
+143 -7
View File
@@ -35,6 +35,7 @@ function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
// drops the redundant `Group`/`File` prefix.
const APIS_ROUTING: Record<string, [string, string]> = {
fetchFriendList: ['contacts', 'fetchFriendList'],
fetchFriendCategories: ['contacts', 'fetchFriendCategories'],
fetchGroupList: ['contacts', 'fetchGroupList'],
fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'],
fetchUserProfile: ['contacts', 'fetchUserProfile'],
@@ -100,6 +101,7 @@ function fakeCtx(bridge: BridgeInterface, overrides: Partial<ApiActionContext> =
bridge,
getMessageMeta: () => null,
getMessage: () => null,
listReadSessions: () => ({ groupIds: [], privateUserIds: [] }),
getLoginInfo: () => ({ userId: 1, nickname: '' }),
isOnline: () => true,
canSendImage: () => true,
@@ -119,6 +121,108 @@ function makeHandler(ctx: ApiActionContext): ApiHandler {
return new ApiHandler(ctx);
}
describe('extended-actions / group notice options', () => {
it('coerces and forwards every supported announcement option', async () => {
const sendNotice = vi.fn(async () => ({ ec: 0 }));
const bridge = fakeBridge({ apis: { web: { sendNotice } } });
const response = await makeHandler(fakeCtx(bridge)).handle('_send_group_notice', {
group_id: '941657197',
content: 'announcement option test',
pinned: '1',
type: '20',
send_to_new_members: 'true',
is_show_edit_card: '0',
tip_window_type: '0',
confirm_required: '0',
});
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
expect(sendNotice).toHaveBeenCalledWith(941657197, 'announcement option test', {
image: undefined,
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 0,
confirmRequired: 0,
});
});
it('rejects a semantic/raw target conflict without calling the bridge', async () => {
const sendNotice = vi.fn();
const bridge = fakeBridge({ apis: { web: { sendNotice } } });
const response = await makeHandler(fakeCtx(bridge)).handle('_send_group_notice', {
group_id: 941657197,
content: 'conflict',
type: 1,
send_to_new_members: true,
});
expect(response).toMatchObject({
status: 'failed',
retcode: 1400,
wording: 'send_to_new_members conflicts with type',
});
expect(sendNotice).not.toHaveBeenCalled();
});
it('rejects an unverified publish type without calling the bridge', async () => {
const sendNotice = vi.fn();
const bridge = fakeBridge({ apis: { web: { sendNotice } } });
const response = await makeHandler(fakeCtx(bridge)).handle('_send_group_notice', {
group_id: 941657197,
content: 'unsupported',
type: 6,
});
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
expect(sendNotice).not.toHaveBeenCalled();
});
});
describe('extended-actions / get_friends_with_category', () => {
it('returns the exact categorized friend contract', async () => {
const fetchFriendCategories = vi.fn(async () => [{
categoryId: 7,
categoryName: 'Work',
memberCount: 1,
sortId: 3,
friends: [{ uin: 10001, uid: 'u1', nickname: 'Alice', remark: 'A' }],
}]);
const bridge = fakeBridge({ fetchFriendCategories });
const response = await makeHandler(fakeCtx(bridge))
.handle('get_friends_with_category', {});
expect(fetchFriendCategories).toHaveBeenCalledOnce();
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
expect(response.data).toEqual([{
categoryId: 7,
categoryName: 'Work',
categoryMbCount: 1,
buddyList: [{ user_id: 10001, nickname: 'Alice', remark: 'A' }],
}]);
});
it('surfaces categorized fetch failures', async () => {
const bridge = fakeBridge({
fetchFriendCategories: vi.fn(async () => {
throw new Error('repeated friend-list cookie aa');
}),
});
const response = await makeHandler(fakeCtx(bridge))
.handle('get_friends_with_category', {});
expect(response).toMatchObject({
status: 'failed',
retcode: 100,
wording: 'repeated friend-list cookie aa',
});
});
});
// ─── Tier 1: send_packet / .send_packet ───
describe('extended-actions / send_packet', () => {
@@ -248,6 +352,34 @@ describe('extended-actions / history accepts negative message_id', () => {
});
});
describe('extended-actions / mark conversation read', () => {
it('uses a group message only to identify the conversation', async () => {
const markGroupRead = vi.fn(async () => undefined);
const bridge = fakeBridge({ apis: { message: { markGroupRead } } });
const ctx = fakeCtx(bridge, {
getMessageMeta: () => fakeMeta({ targetId: 12345, sequence: 42708 }),
});
const res = await makeHandler(ctx).handle('mark_group_msg_as_read', { message_id: 1 });
expect(markGroupRead).toHaveBeenCalledWith(12345);
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
});
it('routes a private message to the C2C read implementation without forwarding its header sequence', async () => {
const markPrivateRead = vi.fn(async () => undefined);
const bridge = fakeBridge({ apis: { message: { markPrivateRead } } });
const ctx = fakeCtx(bridge, {
getMessageMeta: () => fakeMeta({ isGroup: false, targetId: 1787882683, sequence: 42708 }),
});
const res = await makeHandler(ctx).handle('mark_private_msg_as_read', { message_id: 1 });
expect(markPrivateRead).toHaveBeenCalledWith(1787882683);
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
});
});
// ─── Tier 1: nc_get_packet_status / nc_get_rkey ───
describe('extended-actions / nc_get_packet_status', () => {
@@ -822,10 +954,8 @@ describe('extended-actions / ocr_image', () => {
});
});
// ─── TierB Phase 1: compat stubs (model_show / online_clients / mark_all_as_read) ───
// These are kernel-only in NapCat (mock/no-op), so SnowLuma ships honest
// compat shapes rather than RE-ing a wire that doesn't exist. We pin the
// response *shape* of each. NOTE two deliberate divergences from NapCat:
// ─── TierB Phase 1: compatibility actions ───
// NOTE two deliberate divergences from NapCat:
// • _get_model_show reuses NapCat's array/variants shape but ECHOES the
// requested model instead of NapCat's hardcoded 'napcat'.
// • get_online_clients returns the OneBot-v11/go-cqhttp { clients: [] }
@@ -862,9 +992,15 @@ describe('extended-actions / TierB compat stubs', () => {
expect(res.data).toMatchObject({ clients: [] });
});
it('_mark_all_as_read is an accepted no-op', async () => {
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_mark_all_as_read', {});
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
it('_mark_all_as_read passes every observed session to the batched SSO implementation', async () => {
const markAllRead = vi.fn(async () => undefined);
const bridge = fakeBridge({ apis: { message: { markAllRead } } });
const res = await makeHandler(fakeCtx(bridge, {
listReadSessions: () => ({ groupIds: [101, 102], privateUserIds: [201] }),
})).handle('_mark_all_as_read', {});
expect(markAllRead).toHaveBeenCalledWith([101, 102], [201]);
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: null });
});
});
@@ -6,10 +6,12 @@
// - formatEvent prints something readable in the [Event] log
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
import type { GroupReactNotify } from '@snowluma/proto-defs/notify';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { decodeEvent0x2DC } from '@snowluma/protocol/msg-push/decoders/event-0x2dc';
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { buildContext, type MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/protocol/events';
import { convertGroupMsgEmojiLike } from '../src/event-converter/to-notice';
@@ -35,6 +37,64 @@ function buildReactContent(notify: Record<string, unknown>): Uint8Array {
return out;
}
function encodeVarint(value: bigint): number[] {
const out: number[] = [];
let remaining = value;
do {
let byte = Number(remaining & 0x7fn);
remaining >>= 7n;
if (remaining !== 0n) byte |= 0x80;
out.push(byte);
} while (remaining !== 0n);
return out;
}
function encodeSignedInt32Varint(value: number): number[] {
return encodeVarint(BigInt.asUintN(64, BigInt(value | 0)));
}
function varintField(fieldNumber: number, value: number[] | bigint): number[] {
const bytes = Array.isArray(value) ? value : encodeVarint(value);
return [...encodeVarint(BigInt(fieldNumber << 3)), ...bytes];
}
function messageField(fieldNumber: number, payload: number[] | Uint8Array): number[] {
const bytes = Array.from(payload);
return [
...encodeVarint(BigInt((fieldNumber << 3) | 2)),
...encodeVarint(BigInt(bytes.length)),
...bytes,
];
}
function buildPushPacket(
content: Uint8Array,
options: { sequence: number[] | bigint; msgId: number[] | bigint },
): PacketInfo {
const contentHead = [
...varintField(1, 732n),
...varintField(2, 16n),
...varintField(4, options.msgId),
...varintField(5, options.sequence),
...varintField(6, 1735000000n),
];
const body = messageField(2, content);
const message = [
...messageField(2, contentHead),
...messageField(3, body),
];
return {
pid: 1,
uin: SELF_UIN,
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: Uint8Array.from(messageField(1, message)),
};
}
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
return {
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
@@ -49,6 +109,46 @@ function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext
}
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
it('decodes a full PushMsg whose envelope sequence uses a sign-extended 10-byte varint', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 4242n },
groupReactionDataContent: {
code: '76', count: 1, operatorUid: 'u_operator_xxx', type: 1,
},
},
},
},
});
const packet = buildPushPacket(content, {
msgId: 123n,
sequence: encodeSignedInt32Varint(-2),
});
const [event] = parseMsgPush(packet, makeIdentity()) as GroupMsgEmojiLikeEvent[];
expect(event).toMatchObject({
kind: 'group_msg_emoji_like',
groupId: GROUP_ID,
msgSeq: 4242,
emojiId: '76',
});
});
it('accepts a sign-extended negative ContentHead field 4 without losing its low 32 bits', () => {
const packet = buildPushPacket(new Uint8Array(0), {
msgId: encodeSignedInt32Varint(-1),
sequence: 7n,
});
const ctx = buildContext(packet, makeIdentity());
expect(ctx?.head.msgId).toBe(0xffffffff);
expect(ctx?.head.sequence).toBe(7);
});
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
@@ -70,4 +70,28 @@ describe('outbound message validation at the Action boundary', () => {
});
expect(bridgeSend).not.toHaveBeenCalled();
});
it('reports the public data field when a JSON segment uses data.text', async () => {
const bridgeSend = vi.fn();
const ref = instanceContext(bridgeSend);
const api = new ApiHandler({
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
} as ApiActionContext);
const response = await api.handle('send_group_msg', {
group_id: 12345,
message: [{
type: 'json',
data: { text: '{"app":"com.tencent.contact.lua"}' },
}],
});
expect(response).toMatchObject({
status: 'failed',
retcode: 1400,
wording: 'message segment "json" field "data" must be a non-empty JSON string',
});
expect(bridgeSend).not.toHaveBeenCalled();
});
});
@@ -187,4 +187,28 @@ describe('MessageStore', () => {
expect(retrieved).toBeNull();
});
});
describe('listReadSessions', () => {
it('uses current groups and only genuine incoming friend sessions', () => {
const event = (postType: string, subType: string) => ({
time: 1700000000,
post_type: postType,
message_type: 'private',
sub_type: subType,
});
store.storeEvent(1001, false, 40001, 1, PRIVATE_MESSAGE_EVENT, event('message', 'friend'));
store.storeEvent(1002, false, 40001, 2, PRIVATE_MESSAGE_EVENT, event('message', 'friend'));
store.storeEvent(1003, false, 40002, 3, PRIVATE_MESSAGE_EVENT, event('message', 'group'));
store.storeEvent(1004, false, 40003, 4, PRIVATE_MESSAGE_EVENT, event('message_sent', 'friend'));
expect(store.listReadSessions([30002, 30001, 30002])).toEqual({
groupIds: [30002, 30001],
privateUserIds: [40001],
});
});
it('fails on a corrupt current group target', () => {
expect(() => store.listReadSessions([0])).toThrow('invalid group id 0');
});
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
+28 -5
View File
@@ -215,13 +215,10 @@ export interface OidbFriendListBodyItem {
type?: pb<1, uint_32>;
number?: pb<2, OidbFriendListNumber>;
}
export interface OidbFriendListNextUin {
uin?: pb<1, uint_32>;
}
export interface OidbFriendListRequest {
friendCount?: pb<2, uint_32>;
field4?: pb<4, uint_32>;
nextUin?: pb<5, OidbFriendListNextUin>;
cookie?: pb<5, bytes>;
field6?: pb<6, uint_32>;
field7?: pb<7, uint_32>;
body?: pb_repeated<10001, OidbFriendListBodyItem>;
@@ -405,6 +402,33 @@ export interface SsoReadedReportReq {
groupList?: pb_repeated<1, GroupReadedReportItem>;
c2cList?: pb_repeated<2, C2CReadedReportItem>;
}
// SsoReadedReport deliberately uses different tags in its response. In
// particular, field 3 is the repeated GROUP RESPONSE, not a request field.
// Both response item types expose the server's current read sequence and its
// latest message sequence. A read report is complete only after readSeq catches
// up with latestSeq; a top-level success alone does not prove that happened.
export interface GroupReadedReportResponseItem {
resultCode?: pb<1, uint_32>;
errorMessage?: pb<2, string>;
groupUin?: pb<3, uint_64>;
readSeq?: pb<4, uint_64>;
latestSeq?: pb<5, uint_64>;
}
export interface C2CReadedReportResponseItem {
resultCode?: pb<1, uint_32>;
errorMessage?: pb<2, string>;
targetUin?: pb<3, uint_64>;
uid?: pb<4, string>;
readSeq?: pb<5, uint_64>;
latestSeq?: pb<6, uint_64>;
lastMsgTime?: pb<7, uint_64>;
}
export interface SsoReadedReportResp {
resultCode?: pb<1, uint_32>;
errorMessage?: pb<2, string>;
groupList?: pb_repeated<3, GroupReadedReportResponseItem>;
c2cList?: pb_repeated<4, C2CReadedReportResponseItem>;
}
export interface OidbClientKeyReq {}
export interface OidbClientKeyResp {
keyIndex?: pb<2, uint_32>;
@@ -912,4 +936,3 @@ export interface Oidb0xcdeRespBodyInfo {
export interface Oidb0xcdeResp {
info?: pb<2, Oidb0xcdeRespBodyInfo>;
}
+13 -9
View File
@@ -1,4 +1,4 @@
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes, bool } from '@snowluma/proton';
export interface OidbProperty {
key?: pb<1, string>;
@@ -51,17 +51,21 @@ export interface OidbFriend {
additional?: pb_repeated<10001, OidbFriendAdditional>;
}
export interface OidbSvcTrpcTcp0xFD4_1ResponseUin {
uin?: pb<1, uint_32>;
export interface OidbFriendCategory {
categoryId?: pb<1, uint_32>;
categoryName?: pb<2, string>;
memberCount?: pb<3, uint_32>;
sortId?: pb<4, uint_32>;
}
export interface OidbSvcTrpcTcp0xFD4_1Response {
next?: pb<2, OidbSvcTrpcTcp0xFD4_1ResponseUin>;
displayFriendCount?: pb<3, uint_32>;
timestamp?: pb<6, uint_32>;
selfUin?: pb<7, uint_32>;
friends?: pb_repeated<101, OidbFriend>;
groups?: pb_repeated<102, OidbFriendProperty>;
cookie?: pb<2, bytes>;
isEnd?: pb<3, bool>;
timestamp?: pb<6, uint_64>;
selfUin?: pb<7, uint_64>;
smallSeq?: pb<8, uint_32>;
friends?: pb_repeated<101, OidbFriend>;
categories?: pb_repeated<102, OidbFriendCategory>;
}
// Oidb.0xFE5_2 Group list
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
+3
View File
@@ -228,6 +228,9 @@ export interface QQEvent {
export interface FriendMessage extends QQEvent {
kind: 'friend_message';
senderUin: number;
/** Stable QQ UID carried by ResponseHead. Kept internally so the identity
* index can preserve the exact C2C peer instead of re-resolving its UIN. */
senderUid?: string;
senderNick: string;
msgSeq: number;
msgId: number;
@@ -38,6 +38,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
senderUid: ctx.fromUid,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
@@ -1,8 +1,8 @@
// 0xFD4_1 — single-page friend-roster fetch.
//
// QQ paginates the friend list with a wire-level cursor (`nextUin`).
// QQ paginates the friend list with an opaque wire-level cookie.
// This namespace handles ONE round-trip — the facade drives the
// while-loop until the server stops emitting a next cursor and
// while-loop until the server stops emitting a cookie and
// concatenates results into the public FriendInfo[] shape.
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
@@ -15,9 +15,8 @@ export namespace FetchFriendListPage {
export const subCommand = 1;
export interface Params {
/** Cursor: `null` for the first page, otherwise the previous
* page's `nextUin`. */
nextUin: number | null;
/** Opaque cookie returned by the previous page. Omit on page one. */
cookie?: Uint8Array;
}
export type Deps = OidbSender;
@@ -35,8 +34,8 @@ export namespace FetchFriendListPage {
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (p.nextUin !== null) {
body.nextUin = { uin: p.nextUin };
if (p.cookie?.length) {
body.cookie = p.cookie;
}
return body;
};
+10
View File
@@ -369,6 +369,16 @@ export class IncomingPacketPipeline {
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'friend_message':
// The message already carries the authoritative UID/UIN pair. Keep it
// at the receive boundary so later C2C operations never have to infer
// a peer UID from a stale message row or a fallible profile lookup.
this.deps.identity.rememberRequestIdentity({
uid: event.senderUid,
uin: event.senderUin,
source: 'friend_message',
});
break;
case 'group_message': {
// [#1] Self-heal a member's cached group card from message traffic. The
// member cache only refreshes via a member-list refetch, which nothing
+8
View File
@@ -21,6 +21,14 @@ export interface FriendInfo {
remark: string;
}
export interface FriendCategoryInfo {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
friends: FriendInfo[];
}
export interface GroupMemberInfo {
uin: number;
uid: string;
+254 -147
View File
@@ -13,28 +13,65 @@ export interface SetNoticeRetSuccess {
export interface UploadImageRetSuccess {
ec?: number;
em?: string;
id?: string;
[key: string]: JsonValue | undefined;
}
export const GROUP_NOTICE_TYPE_NORMAL = 1;
export const GROUP_NOTICE_TYPE_NEW_MEMBERS = 20;
export interface SetGroupNoticeOptions {
pinned?: number;
/** Raw publish type kept for OneBot compatibility: 1=regular, 20=new members. */
type?: number;
/** Semantic alias for selecting the new-member announcement endpoint. */
sendToNewMembers?: boolean;
isShowEditCard?: number;
/** QQ uses inverted semantics here: 0=show popup, 1=do not show popup. */
tipWindowType?: number;
confirmRequired?: number;
picId?: string;
imgWidth?: number;
imgHeight?: number;
}
export interface ResolvedGroupNoticeOptions {
pinned: 0 | 1;
type: typeof GROUP_NOTICE_TYPE_NORMAL | typeof GROUP_NOTICE_TYPE_NEW_MEMBERS;
sendToNewMembers: boolean;
isShowEditCard: 0 | 1;
tipWindowType: 0 | 1;
confirmRequired: 0 | 1;
picId: string;
imgWidth: number;
imgHeight: number;
}
export interface WebApiGroupNoticeFeed {
fid: string;
u: number;
pubt: number;
type?: number | string;
pinned?: number | string;
msg: {
text: string;
pics?: Array<{ id: string; w: number; h: number }>;
pics?: Array<{ id: string; w: number | string; h: number | string }>;
};
settings: JsonValue;
read_num: number;
[key: string]: JsonValue;
[key: string]: JsonValue | undefined;
}
export type WebApiGroupNoticeCollection = WebApiGroupNoticeFeed[] | Record<string, WebApiGroupNoticeFeed>;
export interface WebApiGroupNoticeRet {
ec: number;
em?: string;
feeds?: Record<string, WebApiGroupNoticeFeed>;
[key: string]: JsonValue | Record<string, WebApiGroupNoticeFeed> | undefined;
feeds?: WebApiGroupNoticeCollection;
/** Announcements shown to members when they newly join the group. */
inst?: WebApiGroupNoticeCollection;
[key: string]: JsonValue | WebApiGroupNoticeCollection | undefined;
}
export function calculateBkn(key: string): string {
@@ -46,6 +83,100 @@ export function calculateBkn(key: string): string {
return (hash & 0x7FFFFFFF).toString();
}
function binaryOption(name: string, value: number | undefined, fallback: 0 | 1): 0 | 1 {
const resolved = value ?? fallback;
if (resolved !== 0 && resolved !== 1) {
throw new RangeError(`${name} must be 0 or 1, received ${resolved}`);
}
return resolved;
}
/**
* Resolve the public compatibility fields into the exact QQ request mode.
* Kept pure so both runtime callers and tests share one conflict check.
*/
export function resolveGroupNoticeOptions(options: SetGroupNoticeOptions = {}): ResolvedGroupNoticeOptions {
if (options.sendToNewMembers !== undefined && typeof options.sendToNewMembers !== 'boolean') {
throw new TypeError(`sendToNewMembers must be a boolean, received ${typeof options.sendToNewMembers}`);
}
if (
options.type !== undefined &&
options.type !== GROUP_NOTICE_TYPE_NORMAL &&
options.type !== GROUP_NOTICE_TYPE_NEW_MEMBERS
) {
throw new RangeError(
`type must be ${GROUP_NOTICE_TYPE_NORMAL} (regular) or ${GROUP_NOTICE_TYPE_NEW_MEMBERS} (new members), received ${options.type}`,
);
}
const semanticType = options.sendToNewMembers === undefined
? undefined
: options.sendToNewMembers
? GROUP_NOTICE_TYPE_NEW_MEMBERS
: GROUP_NOTICE_TYPE_NORMAL;
if (options.type !== undefined && semanticType !== undefined && options.type !== semanticType) {
throw new Error(
`sendToNewMembers=${options.sendToNewMembers} conflicts with type=${options.type}`,
);
}
const type = options.type ?? semanticType ?? GROUP_NOTICE_TYPE_NORMAL;
const imgWidth = options.imgWidth ?? 540;
const imgHeight = options.imgHeight ?? 300;
if (!Number.isFinite(imgWidth) || imgWidth <= 0 || !Number.isFinite(imgHeight) || imgHeight <= 0) {
throw new RangeError(`group notice image dimensions must be positive finite numbers, received ${imgWidth}x${imgHeight}`);
}
return {
pinned: binaryOption('pinned', options.pinned, 0),
type,
sendToNewMembers: type === GROUP_NOTICE_TYPE_NEW_MEMBERS,
// Preserve SnowLuma's established defaults for existing callers.
isShowEditCard: binaryOption('isShowEditCard', options.isShowEditCard, 1),
tipWindowType: binaryOption('tipWindowType', options.tipWindowType, 1),
confirmRequired: binaryOption('confirmRequired', options.confirmRequired, 1),
picId: options.picId ?? '',
imgWidth,
imgHeight,
};
}
/** Parse QQ's HTML-escaped JSON metadata returned by the image upload CGI. */
export function parseGroupNoticeImageUploadResponse(data: string): { id: string; width: number; height: number } {
let result: UploadImageRetSuccess;
try {
result = JSON.parse(data) as UploadImageRetSuccess;
} catch (cause) {
throw new Error('group notice image upload returned invalid JSON', { cause });
}
if (result.ec !== 0 || !result.id) {
throw new Error(`group notice image upload failed: ec=${result.ec ?? 'missing'} em=${result.em ?? 'missing'}`);
}
let idObj: { id?: unknown; w?: unknown; h?: unknown };
try {
idObj = JSON.parse(result.id.replace(/&quot;/g, '"')) as { id?: unknown; w?: unknown; h?: unknown };
} catch (cause) {
throw new Error('group notice image upload returned invalid image metadata JSON', { cause });
}
const width = Number(idObj.w);
const height = Number(idObj.h);
if (
typeof idObj.id !== 'string' ||
idObj.id.length === 0 ||
!Number.isFinite(width) ||
width <= 0 ||
!Number.isFinite(height) ||
height <= 0
) {
throw new Error('group notice image upload returned malformed image metadata');
}
return { id: idObj.id, width, height };
}
/**
* 发送群公告 Web API
*/
@@ -53,70 +184,64 @@ export async function setGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
content: string,
pinned: number = 0,
type: number = 1,
isShowEditCard: number = 1,
tipWindowType: number = 1,
confirmRequired: number = 1,
picId: string = '',
imgWidth: number = 540,
imgHeight: number = 300
): Promise<SetNoticeRetSuccess | undefined> {
try {
// 分别获取 skey 和 p_skey
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
options: SetGroupNoticeOptions = {},
): Promise<SetNoticeRetSuccess> {
const resolved = resolveGroupNoticeOptions(options);
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
//
// console.log(skey)
// console.log(pskey)
//
// console.log(urlBkn);
// console.log(bodyBkn)
// QQ validates these independently: the body token comes from skey while
// the URL token comes from p_skey (falling back to skey when absent).
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
const settings = JSON.stringify({
is_show_edit_card: isShowEditCard,
tip_window_type: tipWindowType,
confirm_required: confirmRequired,
});
const settings = JSON.stringify({
is_show_edit_card: resolved.isShowEditCard,
tip_window_type: resolved.tipWindowType,
confirm_required: resolved.confirmRequired,
});
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: pinned.toString(),
type: type.toString(),
settings,
};
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: resolved.pinned.toString(),
type: resolved.type.toString(),
settings,
};
if (picId !== '') {
bodyParams.pic = picId;
bodyParams.imgWidth = imgWidth.toString();
bodyParams.imgHeight = imgHeight.toString();
}
// 注意这里:URL 必须使用 skey 算出来的 bkn
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
if (resolved.picId !== '') {
bodyParams.pic = resolved.picId;
bodyParams.imgWidth = resolved.imgWidth.toString();
bodyParams.imgHeight = resolved.imgHeight.toString();
}
const endpoint = resolved.sendToNewMembers ? 'add_qun_instruction' : 'add_qun_notice';
const url = `https://web.qun.qq.com/cgi-bin/announce/${endpoint}?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
log.debug(
'group-notice publish: group=%s target=%s pinned=%d edit-card=%d popup=%s confirm=%d image=%s',
groupCode,
resolved.sendToNewMembers ? 'new-members' : 'regular',
resolved.pinned,
resolved.isShowEditCard,
resolved.tipWindowType === 0 ? 'on' : 'off',
resolved.confirmRequired,
resolved.picId ? 'yes' : 'no',
);
return RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
},
true,
false,
);
}
/**
@@ -127,44 +252,37 @@ export async function getGroupNoticeWebAPI(
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet | undefined> {
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
): Promise<WebApiGroupNoticeRet> {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
ft: '23',
s: start.toString(), // 分页游标
n: count.toString(), // 获取数量
i: '1',
ni: '1'
}).toString();
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn,
ft: '23',
s: start.toString(),
n: count.toString(),
i: '1',
ni: '1',
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
},
true,
false
);
// console.log(JSON.stringify(ret, null, 2));
return ret?.ec === 0 ? ret : undefined;
} catch (e) {
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
return RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148',
},
true,
false,
);
}
/**
* 上传群公告图片 Web API
@@ -172,63 +290,52 @@ export async function getGroupNoticeWebAPI(
export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>,
imageBuffer: Buffer
): Promise<{ id: string; width: number; height: number } | undefined> {
try {
const bkn = calculateBkn(cookieObject['skey']);
const boundary = `-----------------------------${Date.now()}`;
): Promise<{ id: string; width: number; height: number }> {
const bkn = calculateBkn(cookieObject['skey'] || '');
const boundary = `-----------------------------${Date.now()}`;
const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const body = Buffer.concat(parts);
const body = Buffer.concat(parts);
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
'Cookie': cookieToString(cookieObject),
},
};
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
'Cookie': cookieToString(cookieObject),
},
};
return new Promise((resolve) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
const result = JSON.parse(data) as UploadImageRetSuccess;
if (result.ec === 0 && result.id) {
const unescapedIdStr = result.id.replace(/&quot;/g, '"');
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
reject(new Error(`group notice image upload returned HTTP ${res.statusCode ?? 'unknown'}`));
return;
}
const idObj = JSON.parse(unescapedIdStr);
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
} else {
resolve(undefined);
}
} catch {
resolve(undefined);
}
});
try {
resolve(parseGroupNoticeImageUploadResponse(data));
} catch (error) {
reject(error instanceof Error ? error : new Error(String(error)));
}
});
req.on('error', (err) => {
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
resolve(undefined);
});
req.write(body);
req.end();
});
} catch (e) {
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
req.on('error', (error) => reject(new Error(`group notice image upload transport error: ${error.message}`, { cause: error })));
req.write(body);
req.end();
});
}
/**
@@ -43,7 +43,9 @@ describe('parseMsgPush — empty message drop (#102)', () => {
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
}), identity);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ kind: 'friend_message', elements: [{ type: 'text', text: 'hi' }] });
expect(out[0]).toMatchObject({
kind: 'friend_message', senderUid: 'u_x', elements: [{ type: 'text', text: 'hi' }],
});
});
it('drops a C2C control push by (msgType, c2cCmd) even when it carries content', () => {
@@ -1,11 +1,32 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import {
protobuf_decode,
protobuf_encode,
type bool,
type bytes,
type pb,
type pb_repeated,
type uint_32,
} from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
interface TestFriendCategory {
categoryId?: pb<1, uint_32>;
categoryName?: pb<2, string>;
memberCount?: pb<3, uint_32>;
sortId?: pb<4, uint_32>;
}
interface TestFriendListResponse {
cookie?: pb<2, bytes>;
isEnd?: pb<3, bool>;
categories?: pb_repeated<102, TestFriendCategory>;
}
function makeSender(body?: OidbSvcTrpcTcp0xFD4_1Response) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }))
@@ -21,20 +42,22 @@ describe('FetchFriendListPage namespace', () => {
});
describe('serialize', () => {
it('omits nextUin on the first page', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.nextUin).toBeUndefined();
it('omits the cookie on the first page', () => {
const out = FetchFriendListPage.serialize({} as any, {} as any) as any;
expect(out.cookie).toBeUndefined();
expect(out.friendCount).toBe(300);
expect(out.field4).toBe(0);
});
it('includes nextUin sub-message on follow-up pages', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: 10001 }) as any;
expect(out.nextUin).toEqual({ uin: 10001 });
it('replays the opaque response cookie in request tag 5', () => {
const cookie = Uint8Array.from([0x08, 0x96, 0x01, 0xFF]);
const out = FetchFriendListPage.serialize({} as any, { cookie } as any) as any;
expect(out.cookie).toEqual(cookie);
expect(out.nextUin).toBeUndefined();
});
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
const out = FetchFriendListPage.serialize({} as any, {}) as any;
expect(out.body).toEqual([
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
@@ -45,24 +68,47 @@ describe('FetchFriendListPage namespace', () => {
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfd4_1', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: null });
await FetchFriendListPage.invoke(sender, {});
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfd4_1');
});
it('returns the wire body verbatim (facade does the FriendInfo mapping)', async () => {
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }], next: { uin: 0 } };
it('returns the wire body verbatim (facade does the roster mapping)', async () => {
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }] };
const sender = makeSender(body as any);
const out = await FetchFriendListPage.invoke(sender, { nextUin: null });
const out = await FetchFriendListPage.invoke(sender, {} as any);
expect(out.friends).toBeDefined();
expect(out.next?.uin ?? 0).toBe(0);
});
it('encodes envelope body correctly', async () => {
it('encodes a follow-up cookie in the envelope body', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: 10001 });
const cookie = Uint8Array.from([0xAA, 0xBB]);
await FetchFriendListPage.invoke(sender, { cookie } as any);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendListRequest>>(bytes);
expect(env.body?.nextUin).toEqual({ uin: 10001 });
expect((env.body as any)?.cookie).toEqual(cookie);
});
it('decodes category metadata and the opaque response cookie', () => {
const bytes = protobuf_encode<OidbBase<TestFriendListResponse>>({
body: {
cookie: Uint8Array.from([0xAA, 0xBB]),
isEnd: false,
categories: [{
categoryId: 7,
categoryName: 'Work',
memberCount: 2,
sortId: 3,
}],
},
});
const body = FetchFriendListPage.decode(bytes).body as any;
expect(body.cookie).toEqual(Uint8Array.from([0xAA, 0xBB]));
expect(body.categories).toEqual([{
categoryId: 7,
categoryName: 'Work',
memberCount: 2,
sortId: 3,
}]);
});
});
});
@@ -39,7 +39,7 @@ function makePipeline(opts: {
events.onAny((event) => { captured.push(event as QQEventVariant); });
return {
pipeline, events, captured,
identity, pipeline, events, captured,
resolveStrangerProfile, resolveGroupJoinRequest, resolveGroupInviteCardSequence,
};
}
@@ -367,6 +367,28 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
});
});
describe('IncomingPacketPipeline / friend message identity', () => {
it('preserves the exact UID/UIN pair carried by an incoming C2C message', () => {
const { identity, pipeline } = makePipeline();
pipeline.registerCmd('test.cmd', () => [{
kind: 'friend_message',
time: 1700000000,
selfUin: 10001,
senderUin: 22222,
senderUid: 'u_peer_exact',
senderNick: 'peer',
msgSeq: 1,
msgId: 2,
elements: [{ type: 'text', text: 'hi' }],
}]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
expect(identity.findUidByUin(22222)).toBe('u_peer_exact');
expect(identity.findUinByUid('u_peer_exact')).toBe(22222);
});
});
describe('IncomingPacketPipeline / #1 group card self-heal', () => {
function makeGroupMsgPipeline() {
const identity = IdentityService.memory('10001');
@@ -0,0 +1,143 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
GROUP_NOTICE_TYPE_NEW_MEMBERS,
calculateBkn,
getGroupNoticeWebAPI,
parseGroupNoticeImageUploadResponse,
resolveGroupNoticeOptions,
setGroupNoticeWebAPI,
type WebApiGroupNoticeRet,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
describe('group-notice / publish HTTP layer', () => {
afterEach(() => vi.restoreAllMocks());
const cookies = { skey: 'BODY_KEY', p_skey: 'URL_KEY', uin: 'o10000' };
it('publishes a regular announcement with the exact options and image metadata', async () => {
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
await setGroupNoticeWebAPI(cookies, '12345', 'regular notice', {
pinned: 1,
isShowEditCard: 0,
tipWindowType: 0,
confirmRequired: 0,
picId: 'pic-id',
imgWidth: 640,
imgHeight: 360,
});
const [url, method, rawBody, headers, isJsonRet, isArgJson] = request.mock.calls[0]!;
expect(url).toBe(`https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${calculateBkn('URL_KEY')}`);
expect(method).toBe('POST');
const body = new URLSearchParams(rawBody as string);
expect(Object.fromEntries(body)).toMatchObject({
qid: '12345',
bkn: calculateBkn('BODY_KEY'),
text: 'regular notice',
pinned: '1',
type: '1',
pic: 'pic-id',
imgWidth: '640',
imgHeight: '360',
});
expect(JSON.parse(body.get('settings')!)).toEqual({
is_show_edit_card: 0,
tip_window_type: 0,
confirm_required: 0,
});
expect(headers).toMatchObject({ 'Content-Type': 'application/x-www-form-urlencoded' });
expect(isJsonRet).toBe(true);
expect(isArgJson).toBe(false);
});
it('routes semantic new-member announcements to the instruction endpoint with type 20', async () => {
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { sendToNewMembers: true });
const [url, , rawBody] = request.mock.calls[0]!;
expect(url).toContain('/cgi-bin/announce/add_qun_instruction?');
expect(new URLSearchParams(rawBody as string).get('type')).toBe(String(GROUP_NOTICE_TYPE_NEW_MEMBERS));
});
it('keeps raw type=20 compatibility while selecting the correct endpoint', async () => {
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { type: 20 });
expect(request.mock.calls[0]![0]).toContain('/cgi-bin/announce/add_qun_instruction?');
});
it('fails before I/O when raw type and semantic target conflict', async () => {
const request = vi.spyOn(RequestUtil, 'HttpGetJson');
await expect(setGroupNoticeWebAPI(cookies, '12345', 'bad', {
type: 1,
sendToNewMembers: true,
})).rejects.toThrow('conflicts');
expect(request).not.toHaveBeenCalled();
});
it('rejects unsupported raw types and non-binary options', () => {
expect(() => resolveGroupNoticeOptions({ type: 6 })).toThrow('type must be 1');
expect(() => resolveGroupNoticeOptions({ pinned: 2 })).toThrow('pinned must be 0 or 1');
expect(() => resolveGroupNoticeOptions({ tipWindowType: -1 })).toThrow('tipWindowType must be 0 or 1');
});
it('preserves the established regular-announcement defaults', () => {
expect(resolveGroupNoticeOptions()).toMatchObject({
pinned: 0,
type: 1,
sendToNewMembers: false,
isShowEditCard: 1,
tipWindowType: 1,
confirmRequired: 1,
});
});
it('propagates transport failures instead of returning undefined', async () => {
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('Unexpected status code: 403'));
await expect(setGroupNoticeWebAPI(cookies, '12345', 'notice')).rejects.toThrow('403');
});
});
describe('group-notice / image upload response', () => {
it('parses HTML-escaped image metadata', () => {
expect(parseGroupNoticeImageUploadResponse(JSON.stringify({
ec: 0,
id: '{&quot;id&quot;:&quot;pic-1&quot;,&quot;w&quot;:&quot;640&quot;,&quot;h&quot;:&quot;360&quot;}',
}))).toEqual({ id: 'pic-1', width: 640, height: 360 });
});
it('surfaces server and malformed-response failures', () => {
expect(() => parseGroupNoticeImageUploadResponse(JSON.stringify({ ec: 14, em: 'denied' }))).toThrow('ec=14 em=denied');
expect(() => parseGroupNoticeImageUploadResponse('not json')).toThrow('invalid JSON');
expect(() => parseGroupNoticeImageUploadResponse(JSON.stringify({ ec: 0, id: '{"id":"pic","w":0,"h":10}' })))
.toThrow('malformed image metadata');
});
});
describe('group-notice / list HTTP layer', () => {
afterEach(() => vi.restoreAllMocks());
it('requests both regular and new-member collections and preserves server errors', async () => {
const response: WebApiGroupNoticeRet = { ec: 14, em: 'permission denied' };
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(response as never);
await expect(getGroupNoticeWebAPI({ skey: 'SK', p_skey: 'PSK' }, '9876')).resolves.toBe(response);
const [url, method, rawBody] = request.mock.calls[0]!;
expect(url).toContain('/cgi-bin/announce/list_announce?');
expect(method).toBe('POST');
const body = new URLSearchParams(rawBody as string);
expect(body.get('i')).toBe('1');
expect(body.get('ni')).toBe('1');
});
it('propagates transport failures instead of hiding them as an empty list', async () => {
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('socket closed'));
await expect(getGroupNoticeWebAPI({ skey: 'SK' }, '9876')).rejects.toThrow('socket closed');
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+9 -3
View File
@@ -22,6 +22,13 @@ function varintDec64(varName: string, ind: string): string {
].join('\n');
}
function varintDec32Value(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
@@ -153,15 +160,14 @@ function decodeField(field: ProtobufField, index: number): string {
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits. uint32/sint32/tag/length values must remain on the stricter
// five-byte reader.
// 32 bits.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec('_val', I));
L.push(varintDec32Value('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
+7
View File
@@ -117,6 +117,13 @@ function __readVarint64(data, offset, end) {
}
throw new Error('protobuf uint64 varint overflow');
}
function __readVarint32Value(data, offset, end) {
const [value, next] = __readVarint64(data, offset, end);
if (value > 0xffffffffn && value < 0xffffffff80000000n) {
throw new Error('protobuf uint32 field varint overflow');
}
return [Number(BigInt.asUintN(32, value)), next];
}
function __skipVarint(data, offset, end) {
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated varint');
@@ -169,6 +169,28 @@ interface Int32Msg {
])).value).toBe(-1);
});
it('accepts sign-extended 10-byte values for uint_32 fields without accepting real overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(dec(Uint8Array.from([
0x08,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(0xfffffffe);
// 2^32 is neither uint32 nor a sign-extended negative int32, so accepting
// ten-byte compatibility must not turn genuine overflow into truncation.
expect(() => dec(Uint8Array.from([
0x08,
0x80, 0x80, 0x80, 0x80, 0x10,
]))).toThrow(/uint32 field varint overflow/);
});
it('rejects malformed length-delimited fields without leaving parent bounds', () => {
const schema = `interface BytesMsg { data: pb<1, bytes>; }`;
const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts'));
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.1",
"version": "1.12.2",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+10 -3
View File
@@ -326,9 +326,13 @@ export abstract class SnowLumaApiClient {
sendGroupNotice(groupId: number, content: string, options: RequestOptions & {
image?: string;
pinned?: number;
type?: number;
confirmRequired?: number;
pinned?: 0 | 1;
type?: 1 | 20;
sendToNewMembers?: boolean;
isShowEditCard?: 0 | 1;
/** QQ's raw inverted field: 0=show popup, 1=do not show popup. */
tipWindowType?: 0 | 1;
confirmRequired?: 0 | 1;
} = {}) {
return this.call('_send_group_notice', {
group_id: groupId,
@@ -336,6 +340,9 @@ export abstract class SnowLumaApiClient {
image: options.image,
pinned: options.pinned,
type: options.type,
send_to_new_members: options.sendToNewMembers,
is_show_edit_card: options.isShowEditCard,
tip_window_type: options.tipWindowType,
confirm_required: options.confirmRequired,
}, options);
}
+4 -2
View File
@@ -77,11 +77,13 @@ import type {
DownloadFileResult,
EmptyData,
ForwardMessageResult,
FriendCategoryResult,
FriendMessageHistory,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
GroupMessageHistory,
GroupNoticeInfo,
LoginInfo,
MediaInfo,
OnlineClientsInfo,
@@ -162,7 +164,7 @@ export interface SnowLumaActionMap {
ocr_image: { params: JsonObject; data: JsonValue };
'.ocr_image': { params: JsonObject; data: JsonValue };
_send_group_notice: { params: GroupNoticeParams; data: EmptyData };
_get_group_notice: { params: GroupIdParams; data: JsonArray };
_get_group_notice: { params: GroupIdParams; data: GroupNoticeInfo[] };
_del_group_notice: { params: JsonObject; data: EmptyData };
upload_forward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
upload_foward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
@@ -196,7 +198,7 @@ export interface SnowLumaActionMap {
fetch_custom_face: { params: FetchCustomFaceParams; data: string[] };
get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject };
fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: JsonObject[] };
get_friends_with_category: { params: JsonObject; data: FriendCategoryResult[] };
get_online_clients: { params: JsonObject; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
_set_model_show: { params: JsonObject; data: EmptyData };
+8 -3
View File
@@ -217,9 +217,14 @@ export interface MarkMsgAsReadParams extends JsonObject {
export interface GroupNoticeParams extends GroupIdParams {
content: string;
image?: string;
pinned?: number;
type?: number;
confirm_required?: number;
pinned?: 0 | 1;
/** Compatibility field: 1=regular announcement, 20=new-member announcement. */
type?: 1 | 20;
send_to_new_members?: boolean;
is_show_edit_card?: 0 | 1;
/** QQ's raw inverted field: 0=show popup, 1=do not show popup. */
tip_window_type?: 0 | 1;
confirm_required?: 0 | 1;
}
export interface ForwardPreviewParams {
+31 -1
View File
@@ -1,4 +1,4 @@
import type { JsonArray, JsonObject } from './json';
import type { JsonArray, JsonObject, JsonValue } from './json';
export interface SendMessageResult {
message_id: number;
@@ -60,6 +60,36 @@ export interface FriendMessageHistory {
messages: JsonObject[];
}
export interface GroupNoticeInfo {
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
};
settings: JsonValue;
read_num: number;
/** Server response type; regular announcements are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
}
export interface CategorizedFriend {
user_id: number;
nickname: string;
remark: string;
}
export interface FriendCategoryResult {
categoryId: number;
categoryName: string;
categoryMbCount: number;
buddyList: CategorizedFriend[];
}
export interface MediaInfo extends JsonObject {}
export interface CookieInfo {
+33
View File
@@ -7,6 +7,39 @@ import {
} from '../src';
describe('SnowLumaHttpClient', () => {
it('maps group-announcement options to their OneBot field names', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await client.sendGroupNotice(941657197, 'welcome', {
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 0,
confirmRequired: 0,
});
const init = fetchImpl.mock.calls[0]![1] as RequestInit;
expect(JSON.parse(init.body as string)).toEqual({
action: '_send_group_notice',
params: {
group_id: 941657197,
content: 'welcome',
pinned: 1,
type: 20,
send_to_new_members: true,
is_show_edit_card: 0,
tip_window_type: 0,
confirm_required: 0,
},
});
});
it('throws SnowLumaAuthError for auth retcodes', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'failed',
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.1",
"version": "1.12.2",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.12.1",
"version": "1.12.2",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.12.1",
"version": "1.12.2",
"type": "module",
"scripts": {
"dev": "vite",