Compare commits

..

9 Commits
v2.4.1 ... dev

Author SHA1 Message Date
DrSmoothl
744f25fd9b fix(protocol): integrate styled group card normalization
Keep the full control-character range limited to decoded styled-card text. Preserve member-level error isolation and cover whitespace, Unicode text, cached output, and restart behavior.

Refs #680
2026-11-09 14:57:41 +08:00
DrSmoothl
22bde5d949 fix(contacts): keep member lists available with unreadable cards
Preserve known member cards across refreshes and restarts, and report decoding failures without dropping the roster.

Refs #680
2026-11-09 14:57:11 +08:00
Auceptin
ca61e6039f fix(protocol): strip control characters from styled group card text (#680) (#681) 2026-11-09 13:59:58 +08:00
DrSmoothl
9df7b7524b fix(onebot): preserve voice transcription metadata
Refs #607
2026-11-08 17:33:46 +08:00
DrSmoothl
0cb5daed5e chore(runtime): add macOS ARM64 native artifact 2026-11-08 02:12:26 +08:00
DrSmoothl
f2ea3354f8 chore(release): v2.4.2 2026-11-07 19:49:06 +08:00
DrSmoothl
efcbf988b2 fix(runtime): improve ARM64 compatibility 2026-11-07 19:38:35 +08:00
DrSmoothl
a341fa4b15 docs(readme): add Docker pulls badge 2026-11-07 17:22:46 +08:00
DrSmoothl
8bea681aa2 fix(core): handle group file storage limits
Retry eligible storage failures as temporary files and preserve their storage type for later use. Reject incompatible mixed content before chat publication.

Refs #644
2026-11-07 15:14:55 +08:00
60 changed files with 1677 additions and 194 deletions

View File

@@ -10,6 +10,7 @@ OneBot v11 · WebUI · SDK · MCP
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
<a href="https://hub.docker.com/r/motricseven7/snowluma"><img alt="Docker 拉取次数" src="https://img.shields.io/docker/pulls/motricseven7/snowluma?style=flat-square&label=docker%20pulls"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.4.1",
"version": "2.4.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.4.1",
"version": "2.4.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).",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.4.1",
"version": "2.4.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).",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "2.4.1",
"version": "2.4.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -523,8 +523,7 @@ export class ContactsApi {
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
}
this.ctx.identity.rememberGroupMembers(groupId, members);
return members;
return this.ctx.identity.rememberGroupMembers(groupId, members);
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {

View File

@@ -35,6 +35,9 @@ export interface PttTransInput {
duration: number;
size: number;
format: number;
/** Omitted by older callers for legacy voice media. */
isNtv2?: boolean;
storeRegion?: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
}
@@ -390,6 +393,8 @@ export class ExtrasApi {
md5,
},
};
req.isNtv2 = input.isNtv2 ? 1 : 0;
req.storeRegion = input.isNtv2 ? (input.storeRegion ?? 0) : 0;
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
@@ -406,9 +411,11 @@ export class ExtrasApi {
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
'ptt translate errCode=%d isGroup=%s ntv2=%d region=%d md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode,
input.isGroup,
req.isNtv2,
req.storeRegion,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format,
input.uuid ? 'set' : 'EMPTY',

View File

@@ -406,6 +406,7 @@ export class ForwardApi {
name: string,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElementOf<'file'>> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(
@@ -415,6 +416,7 @@ export class ForwardApi {
'/',
true,
false,
{ allowTemporary },
);
if (!uploaded.fileId) {
@@ -482,6 +484,7 @@ export class ForwardApi {
element: MessageElement,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElement> {
if (element.type !== 'file') {
return element;
@@ -495,6 +498,7 @@ export class ForwardApi {
fileNameForUpload(element),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -506,6 +510,14 @@ export class ForwardApi {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'temporary group files require only file or image segments in the same forward node',
'file',
);
}
return element;
}
@@ -515,6 +527,7 @@ export class ForwardApi {
fileNameForUpload(element, cached),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -532,9 +545,12 @@ export class ForwardApi {
): Promise<ForwardNodePayload[]> {
return Promise.all(
nodes.map(async (node) => {
const allowTemporary = node.elements.every(
(element) => element.type === 'file' || element.type === 'image',
);
const elements = await Promise.all(
node.elements.map((element) =>
this.prepareForwardFileElement(element, groupId, userId),
this.prepareForwardFileElement(element, groupId, userId, allowTemporary),
),
);
return cloneNodeWithElements(node, elements);

View File

@@ -76,6 +76,16 @@ export interface UploadFileResult {
fileHash?: string | null;
}
export interface GroupFileUploadResult {
fileId: string;
busId: number;
}
export interface GroupFileUploadOptions {
/** False when the enclosing message contains content a temporary file cannot carry. */
allowTemporary?: boolean;
}
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
@@ -136,6 +146,7 @@ async function assertUnchanged(
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
busId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
@@ -150,7 +161,7 @@ function buildGroupFileUploadExt(
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
busId,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
@@ -255,12 +266,23 @@ export class GroupFileApi {
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
publish(groupId: number, fileId: string, busId?: number): Promise<void> {
if (!fileId) {
throw new Error('publish requires fileId');
}
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
return PublishGroupFile.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
private cachedBusId(groupId: number, fileId: string): number {
const cached = this.ctx.recallUploadedFile(fileId);
return cached?.scope === 'group' && cached.groupId === groupId
? (cached.busId ?? 102)
: 102;
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
@@ -290,7 +312,8 @@ export class GroupFileApi {
folderId = '/',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
options: GroupFileUploadOptions = {},
): Promise<GroupFileUploadResult> {
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
@@ -307,14 +330,36 @@ export class GroupFileApi {
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
const params: UploadGroupFileRequest.Params = {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
busId: 102,
};
let upload = await UploadGroupFileRequest.invoke(this.ctx, params);
// These are the storage-limit responses for which QQ switches to
// temporary storage. Never retry transport, permission or arbitrary
// service errors, and never retry the temporary request itself.
if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) {
if (options.allowTemporary === false) {
throw new Error(
`temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`,
);
}
log.warn(
'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file',
groupId,
upload.retCode,
);
params.busId = 104;
upload = await UploadGroupFileRequest.invoke(this.ctx, params);
}
ensureRetCodeZero(
'group file upload',
upload.retCode,
@@ -322,6 +367,18 @@ export class GroupFileApi {
upload.clientWording,
);
const busId = upload.busId || params.busId;
if (busId !== 102 && busId !== 104) {
throw new Error(`group file upload returned unsupported storage type: ${busId}`);
}
if (busId === 104 && options.allowTemporary === false) {
throw new Error(
'temporary group files require only file or image segments; remove text and other content before retrying',
);
}
const fileId =
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
@@ -329,23 +386,6 @@ export class GroupFileApi {
throw new Error('group file upload response missing file_id');
}
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
@@ -366,6 +406,7 @@ export class GroupFileApi {
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
busId,
fileName,
staged.fileSize,
hashes.md5,
@@ -386,6 +427,20 @@ export class GroupFileApi {
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
}
// Retain the storage type for later file_id publication and download.
// A failed byte transfer must not leave a usable-looking cache entry.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
busId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
@@ -398,7 +453,7 @@ export class GroupFileApi {
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
await this.publish(groupId, fileId, busId);
} catch (err) {
// Keep the completed upload identifiable, but a requested chat
// publication must not be reported as a successful send.
@@ -409,7 +464,7 @@ export class GroupFileApi {
}
}
return { fileId };
return { fileId, busId };
} finally {
await staged.cleanup();
}
@@ -711,8 +766,12 @@ export class GroupFileApi {
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
async getUrl(groupId: number, fileId: string, busId?: number): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {

View File

@@ -17,6 +17,8 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import { buildApiHub, type ApiHub } from './apis';
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
import type { UploadedFileMeta } from './bridge-context';
export type { UploadedFileMeta } from './bridge-context';
const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
@@ -594,23 +596,6 @@ export interface SendMessageReceipt {
timestamp: number;
}
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;

View File

@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { GroupMemberInfo } from '@snowluma/protocol/qq-info';
import type {
OidbBase,
OidbEmpty,
@@ -652,7 +653,9 @@ describe('apis/contacts / categorized friend roster', () => {
describe('apis/contacts / robot group-member classification', () => {
it('loads QQ robot ranges once and marks every fetched member', async () => {
const rememberGroupMembers = vi.fn();
const rememberGroupMembers = vi.fn(
(_groupId: number, members: GroupMemberInfo[]) => members,
);
const sendRawPacket = vi.fn(
async (cmd: string, _data: Uint8Array): Promise<SendPacketResult> => {
if (cmd === 'OidbSvcTrpcTcp.0x496_0') {
@@ -735,7 +738,9 @@ describe('apis/contacts / robot group-member classification', () => {
throw new Error(`unexpected command: ${cmd}`);
},
);
const rememberGroupMembers = vi.fn();
const rememberGroupMembers = vi.fn(
(_groupId: number, members: GroupMemberInfo[]) => members,
);
const api = new ContactsApi({
sendRawPacket,
identity: { uin: '10001', rememberGroupMembers },

View File

@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
}
describe('actions/forward — file segment inside forward node', () => {
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge({
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
});
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', fileId: 'temp' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge();
bridge.apis.groupFile.upload.mockRejectedValueOnce(
new Error('temporary group files require only file or image segments'),
);
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files/);
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
12345,
'base64://AQID',
'note.txt',
'/',
true,
false,
{ allowTemporary: false },
);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('rejects a recursive window shake before identity resolution or upload', async () => {
buildSendElemsMock.mockClear();
const resolveUserUid = vi.fn();
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
12345,
);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
allowTemporary: true,
});
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
'/',
true,
false,
{ allowTemporary: true },
);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([

View File

@@ -1,10 +1,12 @@
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileUploadResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
};
}
function uploadResponse(upload: OidbGroupFileUploadResp) {
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=999/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([-403, -9801, -98090])(
'retries capacity error %s as a temporary group file',
async (retCode) => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
)
.mockResolvedValueOnce(
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
);
const api = new GroupFileApi(bridge as any);
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const requests = bridge.sendRawPacket.mock.calls
.slice(0, 2)
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(publish.body?.body?.info).toMatchObject({
fileId: 'temporary-file',
busiType: 104,
});
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
expect.objectContaining({ busId: 104, groupId: 12345 }),
);
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({
fileId: 'temporary-file',
busId: 104,
uploadIp: '127.0.0.1',
uploadPort: 8080,
fileKey: new Uint8Array([7]),
checkKey: new Uint8Array([8]),
}),
);
bridge.recallUploadedFile.mockImplementation(
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
);
const api = new GroupFileApi(bridge as any);
await api.upload(12345, '/path/file.bin');
const ext = protobuf_decode<FileUploadExt>(
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
);
expect(ext.entry?.busiBuff?.busId).toBe(104);
await api.publish(12345, 'temporary-file');
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
).toBe(104);
}
});
it('stops after a failed temporary attempt and releases the staged file', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=-9801/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
expect(staged.cleanup).toHaveBeenCalledOnce();
});
it('retains temporary mode when the successful retry omits its storage type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
const api = new GroupFileApi(bridge as any);
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
fileId: 'temp',
busId: 104,
});
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
});
it('rejects an unknown server storage type before bytes or publication', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/unsupported storage type: 777/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([
{ scope: 'group', groupId: 12345, expected: 104 },
{ scope: 'group', groupId: 54321, expected: 102 },
{ scope: 'private', groupId: undefined, expected: 102 },
] as const)(
'scopes cached storage to the target group for download and reuse (%j)',
async ({ scope, groupId, expected }) => {
const bridge = mockBridge();
bridge.recallUploadedFile.mockReturnValue({
fileId: 'temp',
scope,
groupId,
busId: 104,
});
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
downloadDns: 'download.example.com',
downloadUrl: new Uint8Array([1]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
await api.getUrl(12345, 'temp');
await api.publish(12345, 'temp');
const requests = bridge.sendRawPacket.mock.calls;
expect(
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
).toBe(expected);
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
?.busiType,
).toBe(expected);
},
);
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
async (response) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
await expect(
new GroupFileApi(bridge as any).upload(
12345,
'/path/file.bin',
'',
'/',
true,
false,
{ allowTemporary: false },
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
@@ -341,11 +519,12 @@ describe('apis/group-file', () => {
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();

View File

@@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
@@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
});
describe('element-builder / file element is no longer carried in elems[]', () => {
it.each([12345, 54321])(
'preserves temporary storage only in a matching group forward (%s)',
async (cachedGroupId) => {
const bridge = {
recallUploadedFile: vi.fn(() => ({
scope: 'group',
groupId: cachedGroupId,
busId: 104,
fileName: 'doc.pdf',
fileSize: 3,
})),
} as any;
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
bridge,
groupId: 12345,
forwardFake: true,
});
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
},
);
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire

View File

@@ -39,11 +39,12 @@ describe('ptt-upload', () => {
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
msgInfo: { msgInfoBody: [{ index: node }] },
} as any);
const element = { ...FINGERPRINT };
const element = { ...FINGERPRINT, isNtv2: false };
await uploadPttMsgInfo({} as any, true, 12345, element);
expect(element).toMatchObject({
fileId: 'uploaded-resource',
mediaNode: node,
isNtv2: true,
md5Hex: 'aa',
sha1Hex: 'bb',
});

View File

@@ -227,11 +227,13 @@ describe('IdentityService', () => {
}
});
it('migrates legacy member caches without inventing a robot classification', async () => {
const dbPath = tempDbPath('migrate-robot');
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const legacy = new DatabaseSync(dbPath);
legacy.exec(`
it.each([false, true])(
'migrates legacy member cards and retries after failure=%s',
async (failMigration) => {
const dbPath = tempDbPath('migrate-robot');
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const legacy = new DatabaseSync(dbPath);
legacy.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid TEXT UNIQUE,
@@ -264,6 +266,7 @@ describe('IdentityService', () => {
join_time INTEGER NOT NULL DEFAULT 0,
last_sent_time INTEGER NOT NULL DEFAULT 0,
shut_up_time INTEGER NOT NULL DEFAULT 0,
${failMigration ? 'is_robot INTEGER,' : ''}
active INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL,
UNIQUE(group_id, uid),
@@ -274,19 +277,96 @@ describe('IdentityService', () => {
INSERT INTO group_members (group_id, uid, uin, nickname, updated_at)
VALUES (${GROUP_ID}, 'u_legacy', 33333, 'legacy-member', 1);
`);
legacy.close();
legacy.close();
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
await identity.close();
if (failMigration) {
const originalExec = SqliteDatabase.prototype.exec;
const fault = vi
.spyOn(SqliteDatabase.prototype, 'exec')
.mockImplementation(function (this: SqliteDatabase, sql) {
if (sql.includes('ADD COLUMN card_known')) {
return Promise.reject(new Error('injected card migration failure'));
}
const migrated = new DatabaseSync(dbPath);
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
name: string;
}>;
expect(columns.map((column) => column.name)).toContain('is_robot');
migrated.close();
return originalExec.call(this, sql);
});
const failed = new IdentityService(SELF_UIN, dbPath);
try {
await expect(failed.initialization).rejects.toThrow(
'injected card migration failure',
);
await expect(failed.close()).rejects.toThrow('injected card migration failure');
} finally {
fault.mockRestore();
await failed.close();
}
}
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
await identity.close();
const migrated = new DatabaseSync(dbPath);
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
name: string;
}>;
expect(columns.map((column) => column.name)).toContain('is_robot');
expect(columns.map((column) => column.name)).toContain('card_known');
migrated.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
await reopened.close();
},
);
it('preserves valid cards when an unreadable roster arrives during initialization', async () => {
const dbPath = tempDbPath('pending-card-roster');
const member = makeMember(33333, 'u_member', 'valid card');
const seed = new IdentityService(SELF_UIN, dbPath);
seed.rememberGroups([makeGroup()]);
seed.rememberGroupMembers(GROUP_ID, [member]);
await seed.close();
let release!: () => void;
const loading = new Promise<void>((resolve) => {
release = resolve;
});
const identity = new IdentityService(SELF_UIN, dbPath, loading);
const unreadable = { ...member, card: undefined, role: 'admin' };
identity.rememberGroupMembers(GROUP_ID, [unreadable]);
release();
try {
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
card: 'valid card',
role: 'admin',
});
identity.updateGroupMember(GROUP_ID, { ...unreadable, level: 9 });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
card: 'valid card',
level: 9,
});
} finally {
await identity.close();
}
const reopened = new IdentityService(SELF_UIN, dbPath);
try {
await reopened.initialization;
expect(reopened.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
card: 'valid card',
role: 'admin',
level: 9,
});
} finally {
await reopened.close();
}
});
it('keeps updateGroupMember changes after reopening the persistent cache', async () => {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "2.4.1",
"version": "2.4.2",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -49,3 +49,23 @@ The exported `FriendInfo`, `StrangerInfo`, `PublicProfileFields` and
`ProfilePrivilege` types describe these fields. Returned availability depends
on QQ and the account's access; requesting enrichment does not guarantee every
field is present.
## Group member cards
Styled cards are decoded before their text is normalized. Within successfully
decoded UTF-8 text, SnowLuma removes C0 control characters (`U+0000`–`U+001F`)
except tab, line feed and carriage return, and removes DEL (`U+007F`). Spaces,
Unicode formatting characters and emoji sequences are preserved. Raw plain text
and explicitly literal display names retain strict control-character validation;
invalid UTF-8 is rejected in both formats.
`get_group_member_list` and `get_group_member_info` keep returning member data
when an individual group card cannot be decoded. The last valid card for that
member in the same group and account is retained; if none is known, the OneBot
`card` field is an empty string. An explicitly empty card from QQ clears a
previous value.
Unreadable cards are logged with the group, member, byte length and decoding
reason. The persistent cache distinguishes an unknown card from a confirmed
empty one, so later roster refreshes can recover it after restart. The existing
60-second roster cache and `no_cache: true` refresh option still apply.

View File

@@ -0,0 +1,26 @@
# 群文件发送与临时存储
`upload_group_file` 和 `send_group_msg` 中的文件段默认使用群永久文件空间。
当服务器明确返回容量或文件数量限制时,SnowLuma 会尝试一次临时存储,并在日志中记录这次切换。
临时申请、文件传输或聊天发布失败仍会报错;权限不足、连接失败等其他错误不会触发切换。
临时文件可能过期,不能作为永久保存的替代。
## 消息内容限制
进入临时文件路径时,一条消息只能包含文件或图片段。
含文字、提及、表情等其他内容的混合消息会被拒绝,需要调用方拆成独立消息后再发送。
合并转发按每个节点的内容检查同一规则。
SnowLuma 会在发布聊天消息前检查附件;发现不允许的组合时,不会先发文字、再丢掉附件或文字。
检查之前已完成的其他附件上传不会自动删除。上传成功后如果聊天发布失败,错误仍会保留文件标识。
这不是跨多条消息的事务:开始发布后出现的网络或服务端错误仍可能使前面的消息已经送达。
普通图片加文字仍通过图片消息通道发送,不会因为群永久文件空间不足而转成群文件。
永久文件与文字的现有分开发送方式保持兼容。超大视频按原有规则转成文件后,也适用临时文件的内容限制。
## 文件复用与下载
运行期间上传过的群文件会按账号、群和文件标识保留其存储类型。
同一群中用 `file_id` 再次发送、获取下载链接或生成合并转发时,会使用该存储类型。
`get_group_file_url` 显式传入的 `busid` 仍优先;未提供有效值时,使用当前会话记住的类型,否则沿用永久文件默认值。
上传记录不是持久化目录;重启后获取临时文件链接,应从群文件列表取得对应的 `busid` 并传入。

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "2.4.1",
"version": "2.4.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>'`.",

View File

@@ -4,17 +4,17 @@ import { RETCODE, failedResponse, okResponse } from '../types';
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
// so whatever value a client tacks on is silently ignored. Mirror that here:
// accept any value, coerce when it's a usable non-negative integer, else fall
// back to the canonical 102. Restores the legacy `asNumber(busid) || 102`
// back to the uploaded file's known storage type (otherwise 102). Retains the
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
// non-numeric busid was rejected with `expected an integer`). See issue #147.
function busidOr102(raw: unknown): number {
function optionalBusId(raw: unknown): number | undefined {
const n =
typeof raw === 'number' && Number.isFinite(raw)
? Math.trunc(raw)
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
? Math.trunc(Number(raw))
: NaN;
return Number.isInteger(n) && n >= 0 ? n : 102;
return Number.isInteger(n) && n >= 0 ? n : undefined;
}
export const actions = [
@@ -159,7 +159,7 @@ export const actions = [
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
// busid is accepted but tolerant (see optionalBusId): NapCat/LLBot ignore it,
// so a present null/empty/non-numeric value must not 400 the request (#147).
params: { file_id: f.fileId(), busid: f.raw() },
run: async (p, ctx) => {
@@ -167,7 +167,7 @@ export const actions = [
url: await ctx.bridge.apis.groupFile.getUrl(
p.group_id,
p.file_id,
busidOr102(p.busid),
optionalBusId(p.busid),
),
});
},

View File

@@ -52,6 +52,7 @@ export class MediaIndexer {
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
voiceFormat: element.voiceFormat,
isNtv2: element.isNtv2,
});
return;
}

View File

@@ -35,6 +35,7 @@ export interface CachedRecord {
md5Hex?: string;
sha1Hex?: string;
voiceFormat?: number;
isNtv2?: boolean;
}
export interface CachedVideo {

View File

@@ -78,6 +78,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
picFormat,
duration,
voiceFormat,
isNtv2,
videoFormat,
fileHash,
mediaNode,
@@ -100,6 +101,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
picFormat,
duration,
voiceFormat,
isNtv2,
videoFormat,
fileHash,
mediaNode,
@@ -207,7 +209,13 @@ function mergeKnownMediaFields(old: object, next: object): Record<string, unknow
for (const [key, value] of Object.entries(next)) {
// Zero dimensions, sizes and durations are incomplete observations, not
// evidence that known properties of the same resource have changed.
if (value === undefined || value === null || value === '' || value === 0) {
// Storage region zero is a valid destination and must replace old values.
if (
value === undefined ||
value === null ||
value === '' ||
(value === 0 && key !== 'storeId')
) {
continue;
}

View File

@@ -761,16 +761,13 @@ function formatGroupMember(
);
}
if (member.card === undefined) {
throw new Error(`group member card unavailable: group=${groupId} member=${member.uin}`);
}
const qage = accountAge(profile?.regTime);
return {
group_id: groupId,
user_id: member.uin,
nickname: member.nickname,
card: member.card,
// OneBot requires a string; keep the unknown state in the identity store.
card: member.card ?? '',
is_robot: member.isRobot,
sex: 'unknown',
age: 0,

View File

@@ -222,10 +222,17 @@ export async function fetchPttText(
const senderUin = Number(event.user_id) || 0;
// c2c: receiver is self (inbound voice); group: the group uin.
const peerUin = isGroup ? Number(event.group_id) || cached.sessionId : selfId;
// Before the explicit marker was persisted, only NT records carried a
// storage region. Legacy records also have mediaNode, but no storeId.
// Old decoded NT records can store null for the default region as well.
const isNtv2 = cached.isNtv2 ?? cached.mediaNode?.storeId !== undefined;
const storeRegion = isNtv2 ? (cached.mediaNode?.storeId ?? 0) : 0;
const text = await requestPttTransText(pttTransKey(selfId, messageId), 20_000, () =>
bridge.apis.extras.translatePttToText({
isGroup,
isNtv2,
storeRegion,
msgId: messageId,
senderUin,
peerUin,

View File

@@ -1409,9 +1409,8 @@ export async function sendGroupMessage(
throw new Error('message is empty');
}
// Two sub-paths for group file segments:
// a) has url/path but no file_id → upload() which internally calls publish()
// b) has file_id from a prior upload_group_file → publish() only
// Prepare all file uploads before publishing any part of the message.
// Whether storage is temporary is only known after the upload preflight.
let allFileElements = elements.filter((e) => e.type === 'file');
let nonFileElements = elements.filter((e) => e.type !== 'file');
@@ -1426,6 +1425,73 @@ export async function sendGroupMessage(
}
}
let allowTemporary = nonFileElements.every((element) => element.type === 'image');
const assertStorageAllowed = (busId: number | undefined) => {
if (busId === 104 && !allowTemporary) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'temporary group files require only file or image segments; remove text and other content before retrying',
'file',
);
}
};
const preparedFiles: Array<{
element: MessageElementOf<'file'>;
fileId: string;
busId?: number;
}> = [];
const prepareFiles = async (files: Array<MessageElementOf<'file'>>) => {
// Check known temporary ids first, even if preceded by a new upload.
const candidates = files.map((element) => {
const cached = element.fileId
? ref.bridge.recallUploadedFile(element.fileId)
: undefined;
const busId =
cached?.scope === 'group' && cached.groupId === groupId ? cached.busId : undefined;
assertStorageAllowed(busId);
return { element, fileId: element.fileId, busId };
});
for (const candidate of candidates) {
const { element } = candidate;
if (!candidate.fileId) {
if (!element.url) {
throw new MessageElementValidationError(
'MISSING_FIELD',
'group file segment requires file_id or url',
'file',
);
}
const name = element.fileName || guessFileNameFromUrl(element.url) || 'file';
const uploaded = await ref.bridge.apis.groupFile.upload(
groupId,
element.url,
name,
'/',
true,
false,
{ allowTemporary },
);
candidate.fileId = uploaded.fileId;
candidate.busId = uploaded.busId;
assertStorageAllowed(candidate.busId);
}
if (!candidate.fileId) {
throw new Error('group file auto-upload returned no file_id');
}
preparedFiles.push({ element, fileId: candidate.fileId, busId: candidate.busId });
}
};
await prepareFiles(allFileElements);
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
@@ -1447,8 +1513,9 @@ export async function sendGroupMessage(
err instanceof Error ? err.message : String(err),
);
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
allFileElements = [...allFileElements, ...fileEls];
nonFileElements = remaining;
allowTemporary = remaining.every((element) => element.type === 'image');
await prepareFiles(fileEls);
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
@@ -1457,34 +1524,14 @@ export async function sendGroupMessage(
}
}
for (const fileEl of allFileElements) {
let fileId: string;
if (fileEl.url && !fileEl.fileId) {
// upload() already calls publish() internally — do NOT call publish() again.
const name = fileEl.fileName || guessFileNameFromUrl(fileEl.url) || 'file';
const result = await ref.bridge.apis.groupFile.upload(
groupId,
fileEl.url,
name,
'/',
true,
for (const { element: fileEl, fileId, busId } of preparedFiles) {
try {
await ref.bridge.apis.groupFile.publish(groupId, fileId, busId);
} catch (err) {
throw new Error(
`group file chat post failed (fileId=${fileId}): ${err instanceof Error ? err.message : String(err)}`,
{ cause: err },
);
fileId = result.fileId ?? '';
if (!fileId) {
throw new Error('group file auto-upload returned no file_id');
}
} else if (fileEl.fileId) {
fileId = fileEl.fileId;
await ref.bridge.apis.groupFile.publish(groupId, fileId);
} else {
throw new MessageElementValidationError(
'MISSING_FIELD',
'group file segment requires file_id or url',
'file',
);
continue;
}
logSentMessage(true, groupId, [fileEl]);

View File

@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import type { ApiActionContext } from '../src/api-handler';
import { actions } from '../src/actions/group-file';
describe('get_group_file_url storage selection', () => {
it.each([
{ busid: undefined, expected: undefined },
{ busid: null, expected: undefined },
{ busid: '', expected: undefined },
{ busid: 'invalid', expected: undefined },
{ busid: -1, expected: undefined },
{ busid: 102, expected: 102 },
{ busid: '104', expected: 104 },
{ busid: 0, expected: 0 },
])(
'passes an explicit valid type, otherwise lets the file cache select it (%j)',
async ({ busid, expected }) => {
const getUrl = vi.fn(async () => 'https://download.example.com/file');
const ctx = {
bridge: { apis: { groupFile: { getUrl } } },
} as unknown as ApiActionContext;
const action = actions.find((entry) => entry.names[0] === 'get_group_file_url')!;
const result = await action.toHandler(ctx)({ group_id: 12345, file_id: 'temp', busid });
expect(result).toMatchObject({ status: 'ok' });
expect(getUrl).toHaveBeenCalledExactlyOnceWith(12345, 'temp', expected);
},
);
});

View File

@@ -0,0 +1,253 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Bridge } from '@snowluma/core/bridge';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
OidbBase,
OidbRobotUinRangeResponse,
OidbSvcTrpcTcp0xFE7_3Response,
} from '@snowluma/proto-defs/oidb';
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { getGroupMemberInfo, getGroupMemberList } from '../src/modules/contact-actions';
const groupId = 680;
const cleanups: Array<() => void | Promise<void>> = [];
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) {
await cleanup();
}
vi.restoreAllMocks();
});
function member(uin: number, card: string): GroupMemberInfo {
return {
uin,
uid: `u_${uin}`,
nickname: `old-${uin}`,
card,
isRobot: false,
role: 'member',
level: 1,
title: '',
joinTime: 10,
lastSentTime: 20,
shutUpTime: 0,
};
}
function group(id = groupId): QQGroupInfo {
return {
groupId: id,
groupName: 'test group',
remark: '',
memberCount: 0,
memberMax: 100,
members: new Map(),
};
}
function packet(responseData: Uint8Array): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(responseData),
};
}
async function openBridge(dbPath: string) {
const identity = new IdentityService('10001', dbPath);
const bridge = new Bridge(identity);
cleanups.push(() => bridge.dispose());
await identity.initialization;
// Profile enrichment is independent of the roster and card decoding.
vi.spyOn(bridge.apis.contacts, 'fetchUserProfile').mockImplementation(async (uin) => ({
uin,
uid: `u_${uin}`,
nickname: 'profile',
remark: '',
qid: '',
sex: 'unknown',
age: 0,
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
}));
return bridge;
}
function sendPages(bridge: Bridge, pages: OidbSvcTrpcTcp0xFE7_3Response[]) {
const tokens: string[] = [];
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (command, bytes) => {
if (command === 'OidbSvcTrpcTcp.0x496_0') {
return packet(
protobuf_encode<OidbBase<OidbRobotUinRangeResponse>>({
body: { robotConfig: { version: 1, ranges: [{ minUin: 66n, maxUin: 66n }] } },
}),
);
}
if (command !== 'OidbSvcTrpcTcp.0xfe7_3') {
throw new Error(`unexpected command: ${command}`);
}
const request = protobuf_decode<OidbBase<OidbGroupMemberListRequest>>(bytes);
expect(request.body?.groupUin).toBe(groupId);
tokens.push(request.body?.token ?? '');
const page = pages[tokens.length - 1];
if (!page) {
throw new Error('roster unavailable');
}
return packet(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>({ body: page }));
});
return { send, tokens };
}
describe('group card failures through roster, cache and OneBot output', () => {
it.each([false, true])(
'returns every page and preserves valid cards with no_cache=%s',
async (noCache) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'group-card-'));
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
const dbPath = path.join(directory, 'identity.db');
const bridge = await openBridge(dbPath);
bridge.identity.rememberGroups([group(), group(681)]);
bridge.identity.rememberGroupMembers(groupId, [
member(11, 'last valid card'),
member(44, 'removed card'),
member(55, ''),
]);
bridge.identity.rememberGroupMembers(681, [member(22, 'another group card')]);
const damaged = Buffer.from('616207', 'hex');
const firstPage: OidbSvcTrpcTcp0xFE7_3Response = {
token: 'page-2',
members: [11, 22, 33, 44, 55].map((uin) => ({
uin: { uin, uid: `u_${uin}` },
memberName: `fresh-${uin}`,
permission: 2,
memberCard: {
memberCard:
uin === 33
? Buffer.from('fresh card')
: uin === 44
? Buffer.alloc(0)
: damaged,
},
})),
};
const transport = sendPages(bridge, [
firstPage,
{
members: [
{ uin: { uin: 66, uid: 'u_66' } },
{
uin: { uin: 77, uid: 'u_77' },
memberName: 'styled member',
memberCard: {
memberCard: Buffer.from(
'0a090a0724c7bfc480440e0a071205202014c6951000',
'hex',
),
},
},
],
},
]);
const output = await getGroupMemberList(bridge, groupId, noCache);
expect(output.map((entry) => [entry.user_id, entry.card])).toEqual([
[11, 'last valid card'],
[22, ''],
[33, 'fresh card'],
[44, ''],
[55, ''],
[66, ''],
[77, ' ƕ'],
]);
expect(output[0]).toMatchObject({ nickname: 'fresh-11', role: 'admin' });
expect(output[5]).toMatchObject({ is_robot: true });
expect(transport.tokens).toEqual(['', 'page-2']);
expect(bridge.identity.findGroupMember(groupId, 22)?.card).toBeUndefined();
expect(bridge.identity.findGroupMember(681, 22)?.card).toBe('another group card');
expect(await getGroupMemberList(bridge, groupId)).toEqual(output);
expect(await getGroupMemberInfo(bridge, groupId, 22)).toMatchObject({
user_id: 22,
card: '',
role: 'admin',
});
expect(await getGroupMemberInfo(bridge, groupId, 11)).toMatchObject({
card: 'last valid card',
});
expect(await getGroupMemberInfo(bridge, groupId, 77)).toMatchObject({
card: ' ƕ',
});
expect(transport.tokens).toEqual(['', 'page-2']);
await bridge.dispose();
const restarted = await openBridge(dbPath);
const offline = sendPages(restarted, []);
expect(restarted.identity.findGroupMember(groupId, 22)?.card).toBeUndefined();
expect(restarted.identity.findGroupMember(groupId, 55)?.card).toBe('');
const cachedOutput = await getGroupMemberList(restarted, groupId);
expect(cachedOutput).toHaveLength(output.length);
expect(cachedOutput).toEqual(expect.arrayContaining(output));
expect(offline.tokens).toEqual(['']);
sendPages(restarted, [
{
members: [
{
uin: { uin: 22, uid: 'u_22' },
memberName: 'recovered',
memberCard: { memberCard: Buffer.from('decoded card') },
},
],
},
]);
expect(await getGroupMemberInfo(restarted, groupId, 22, true)).toMatchObject({
nickname: 'recovered',
card: 'decoded card',
});
await restarted.dispose();
const recovered = await openBridge(dbPath);
expect(recovered.identity.findGroupMember(groupId, 22)?.card).toBe('decoded card');
},
);
it('still rejects a forced refresh when a later page fails and keeps the previous roster', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
cleanups.push(() => bridge.dispose());
bridge.identity.rememberGroups([group()]);
bridge.identity.rememberGroupMembers(groupId, [member(11, 'existing')]);
sendPages(bridge, [
{
token: 'missing-page',
members: [
{
uin: { uin: 22 },
memberCard: { memberCard: Buffer.from('616207', 'hex') },
},
],
},
]);
await expect(getGroupMemberList(bridge, groupId, true)).rejects.toThrow(
'roster unavailable',
);
expect(bridge.identity.findGroupMember(groupId, 11)?.card).toBe('existing');
expect(bridge.identity.findGroupMember(groupId, 22)).toBeNull();
});
});

View File

@@ -1141,6 +1141,8 @@ describe('buildApiContext media', () => {
duration: 2,
size: 16,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});

View File

@@ -428,6 +428,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -461,6 +463,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -494,6 +498,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -526,6 +532,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});
@@ -564,6 +572,8 @@ describe('fetchPttText', () => {
duration: 0,
size: 0,
format: 0,
isNtv2: false,
storeRegion: 0,
});
});
@@ -591,6 +601,8 @@ describe('fetchPttText', () => {
duration: 7,
size: 4096,
format: 1,
isNtv2: false,
storeRegion: 0,
});
});

View File

@@ -0,0 +1,292 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { pb, uint_32 } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { MessageBody } from '@snowluma/proto-defs/message';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { ExtrasApi } from '../../core/src/bridge/apis/extras';
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
import { elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
import { MediaIndexer } from '../src/media-indexer';
import { MediaStore } from '../src/media-store';
import { migrateLegacyMedia } from '../src/media-store-migration';
import { MessageStore } from '../src/message-store';
import { fetchPttText } from '../src/modules/media-actions';
// Decode the routing fields independently of the production request schema.
interface TranscriptionRouting {
isNtv2?: pb<5, uint_32>;
storeRegion?: pb<6, uint_32>;
}
const selfId = 10001;
const peerId = 20002;
const groupId = 30003;
const messageId = -607;
const md5 = '00112233445566778899aabbccddeeff';
const cleanups: Array<() => void | Promise<void>> = [];
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) {
await cleanup();
}
});
function location() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ptt-transcription-'));
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
return {
dbPath: path.join(directory, 'messages.db'),
legacyPath: path.join(directory, 'media.db'),
};
}
async function openStores(dbPath: string) {
const messages = new MessageStore(dbPath);
await messages.initialization;
const media = new MediaStore(dbPath, 1);
let closed = false;
const close = async () => {
if (closed) {
return;
}
closed = true;
await media.close();
await messages.close();
};
cleanups.push(close);
await media.initialization;
const indexer = new MediaIndexer(media);
const converter: ConverterContext = {
selfId,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args),
};
return { messages, media, converter, close };
}
function voice(isGroup: boolean, ntv2: boolean, storeId?: number) {
const body: MessageBody = {
richText: ntv2
? {
elems: [
{
commonElem: {
serviceType: 48,
businessType: isGroup ? 12 : 22,
pbElem: protobuf_encode<MsgInfo>({
msgInfoBody: [
{
index: {
fileUuid: 'voice-resource',
storeId,
info: {
fileName: 'voice.silk',
fileSize: 4003,
fileHash: md5,
time: 2,
type: { type: 3, voiceFormat: 1 },
},
},
},
],
}),
},
},
],
}
: {
ptt: {
fileName: 'voice.silk',
fileUuid: Buffer.from('voice-resource'),
fileMd5: Buffer.from(md5, 'hex'),
fileSize: 4003,
time: 2,
format: 1,
},
},
};
const elements = decodeRichBody(
protobuf_decode<MessageBody>(protobuf_encode<MessageBody>(body)),
isGroup,
);
expect(elements).toHaveLength(1);
return elements;
}
async function saveVoice(
stores: Awaited<ReturnType<typeof openStores>>,
isGroup: boolean,
elements: ReturnType<typeof voice>,
withSnapshot = true,
) {
const segments = await elementsToOneBotSegments(
stores.converter,
elements,
isGroup,
isGroup ? groupId : peerId,
);
await stores.messages.storeEvent(
messageId,
isGroup,
isGroup ? groupId : peerId,
42,
isGroup ? 'GroupMessage' : 'PrivateMessage',
{
message_id: messageId,
message_type: isGroup ? 'group' : 'private',
user_id: peerId,
...(isGroup ? { group_id: groupId } : {}),
message: withSnapshot ? segments : JSON.parse(JSON.stringify(segments)),
},
);
}
function transport(isGroup: boolean, errCode = 0) {
const sendRawPacket = vi.fn(async (_cmd: string, _bytes: Uint8Array) => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: protobuf_encode<PttTransResp>(
isGroup
? { type: 1, groupResult: { errCode, text: errCode ? '' : '测试转写结果' } }
: { type: 2, c2cResult: { errCode, text: errCode ? '' : '测试转写结果' } },
),
}));
const extras = new ExtrasApi({ sendRawPacket } as unknown as ConstructorParameters<
typeof ExtrasApi
>[0]);
const bridge = { apis: { extras } } as unknown as BridgeInterface;
return { sendRawPacket, bridge };
}
async function checkRequest(
stores: Awaited<ReturnType<typeof openStores>>,
isGroup: boolean,
ntv2: boolean,
storeRegion = 0,
) {
const { sendRawPacket, bridge } = transport(isGroup);
await expect(
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
).resolves.toEqual({ text: '测试转写结果' });
expect(sendRawPacket).toHaveBeenCalledTimes(1);
const [cmd, bytes] = sendRawPacket.mock.calls[0]!;
expect(cmd).toBe(isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq');
const routing = protobuf_decode<TranscriptionRouting>(bytes);
expect(routing.isNtv2 ?? 0).toBe(ntv2 ? 1 : 0);
expect(routing.storeRegion ?? 0).toBe(storeRegion);
const request = protobuf_decode<PttTransReq>(bytes);
expect(isGroup ? request.groupItem : request.c2cItem).toMatchObject({
msgId: BigInt.asUintN(64, BigInt(messageId)),
senderUin: BigInt(peerId),
uuid: 'voice-resource',
md5,
duration: 2,
size: 4003,
format: 1,
...(isGroup ? { groupUin: BigInt(groupId) } : { receiverUin: BigInt(selfId) }),
});
}
describe.each([false, true])('voice transcription (isGroup=%s)', (isGroup) => {
it.each([
{ name: 'NT voice', ntv2: true, storeId: 1 },
{ name: 'NT voice in region zero', ntv2: true, storeId: 0 },
{ name: 'NT voice without a region', ntv2: true, storeId: undefined },
{ name: 'legacy voice', ntv2: false, storeId: undefined },
])('preserves $name routing through storage and reopening', async ({ ntv2, storeId }) => {
const { dbPath } = location();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, ntv2, storeId));
await checkRequest(stores, isGroup, ntv2, storeId);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, ntv2, storeId);
expect((await stores.messages.findMedia(messageId))?.[0]).toMatchObject({ isNtv2: ntv2 });
expect(await stores.media.findRecord('voice.silk')).toMatchObject({ isNtv2: ntv2 });
const event = await stores.messages.findEvent(messageId);
expect(event?.message_id).toBe(messageId);
expect(JSON.stringify(event)).not.toMatch(/isNtv2|storeId|storeRegion/);
});
it.each([true, false])('reads pre-marker snapshots (ntv2=%s)', async (ntv2) => {
const { dbPath } = location();
let stores = await openStores(dbPath);
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
await saveVoice(stores, isGroup, elements);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
});
it('recognizes pre-marker NT snapshots with a null default region', async () => {
const { dbPath } = location();
let stores = await openStores(dbPath);
const elements = voice(isGroup, true);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
Reflect.set(elements[0]!.mediaNode!, 'storeId', null);
await saveVoice(stores, isGroup, elements);
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, true);
});
it('retains an explicit zero region when updating the same voice', async () => {
const { dbPath } = location();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
await saveVoice(stores, isGroup, voice(isGroup, true, 0));
await stores.close();
stores = await openStores(dbPath);
await checkRequest(stores, isGroup, true, 0);
});
it.each([true, false])(
'reads migrated media without a message snapshot (ntv2=%s)',
async (ntv2) => {
const { dbPath, legacyPath } = location();
const old = await openStores(legacyPath);
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
Reflect.deleteProperty(elements[0]!, 'isNtv2');
await saveVoice(old, isGroup, elements);
await old.close();
let stores = await openStores(dbPath);
await saveVoice(stores, isGroup, elements, false);
await stores.close();
await migrateLegacyMedia(dbPath);
stores = await openStores(dbPath);
// A same-named current entry must not replace the migrated source.
await elementsToOneBotSegments(
stores.converter,
voice(isGroup, true, 9),
isGroup,
peerId,
);
expect(await stores.messages.findMedia(messageId)).toBeNull();
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
},
);
it('preserves the server failure without retrying', async () => {
const { dbPath } = location();
const stores = await openStores(dbPath);
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
const { sendRawPacket, bridge } = transport(isGroup, 9);
await expect(
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
).rejects.toThrow('ptt translate failed: error=9');
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
});

View File

@@ -22,15 +22,22 @@ import { MessageStore } from '../src/message-store';
import { sendGroupMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
get(target, prop) {
if (prop in target) {
return (target as any)[prop];
}
return new Proxy(
{
identity: { nickname: 'SnowLuma' },
recallUploadedFile: vi.fn(),
...overrides,
} as BridgeInterface,
{
get(target, prop) {
if (prop in target) {
return (target as any)[prop];
}
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
},
});
);
}
function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
@@ -345,10 +352,214 @@ describe('send_group_msg with {type:"file"} segment', () => {
expect(upload).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
it('rejects text + image + temporary file before any chat publication', async () => {
const sendGroup = vi.fn(async () => goodReceipt);
const publish = vi.fn();
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
const ctx = makeCtx(
fakeBridge({
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
}),
);
await expect(
sendGroupMessage(
ctx,
12345,
[
{ type: 'text', data: { text: 'caption' } },
{ type: 'image', data: { file: 'base64://AQID' } },
{ type: 'file', data: { file: '/tmp/report.pdf' } },
],
false,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(sendGroup).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
});
it('rejects cached temporary file + text before publishing an earlier permanent file', async () => {
const sendGroup = vi.fn(async () => goodReceipt);
const publish = vi.fn();
const ctx = makeCtx(
fakeBridge({
apis: { message: { sendGroup }, groupFile: { publish } } as any,
recallUploadedFile: vi.fn((id) =>
id === 'temp'
? {
fileId: id,
scope: 'group',
groupId: 12345,
busId: 104,
}
: undefined,
),
} as any),
);
await expect(
sendGroupMessage(
ctx,
12345,
[
{ type: 'file', data: { file_id: 'permanent' } },
{ type: 'text', data: { text: 'caption' } },
{ type: 'file', data: { file_id: 'temp' } },
],
false,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(sendGroup).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
});
it.each([false, true])(
'allows temporary files with only file/image content (image=%s)',
async (withImage) => {
const sendGroup = vi.fn(async () => goodReceipt);
const publish = vi.fn();
const upload = vi.fn(async () => {
expect(sendGroup).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
return { fileId: 'temp', busId: 104 };
});
const ctx = makeCtx(
fakeBridge({
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
}),
);
const message = [
{ type: 'file', data: { file: '/tmp/report.pdf' } },
...(withImage ? [{ type: 'image', data: { file: 'base64://AQID' } }] : []),
];
await sendGroupMessage(ctx, 12345, message, false);
expect(upload).toHaveBeenCalledWith(
12345,
'/tmp/report.pdf',
'report.pdf',
'/',
true,
false,
{ allowTemporary: true },
);
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
expect(sendGroup).toHaveBeenCalledTimes(withImage ? 1 : 0);
},
);
it('preserves ordinary image + text without entering the group-file path', async () => {
const sendGroup = vi.fn(async () => goodReceipt);
const upload = vi.fn();
const publish = vi.fn();
const ctx = makeCtx(
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
);
await sendGroupMessage(
ctx,
12345,
[
{ type: 'image', data: { file: 'base64://AQID' } },
{ type: 'text', data: { text: 'caption' } },
],
false,
);
expect(sendGroup).toHaveBeenCalledOnce();
expect(sendGroup.mock.calls[0]).toMatchObject([
12345,
[
{ type: 'image', url: 'base64://AQID' },
{ type: 'text', text: 'caption' },
],
]);
expect(upload).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
});
it('keeps permanent file + text sends, but checks uploads before sending the text', async () => {
const sendGroup = vi.fn(async () => goodReceipt);
const publish = vi.fn();
const upload = vi.fn(async () => {
expect(sendGroup).not.toHaveBeenCalled();
return { fileId: 'permanent', busId: 102 };
});
const ctx = makeCtx(
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
);
await sendGroupMessage(
ctx,
12345,
[
{ type: 'text', data: { text: 'caption' } },
{ type: 'file', data: { file: '/tmp/report.pdf' } },
],
false,
);
expect(upload).toHaveBeenCalledWith(
12345,
'/tmp/report.pdf',
'report.pdf',
'/',
true,
false,
{ allowTemporary: false },
);
expect(sendGroup).toHaveBeenCalledOnce();
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'permanent', 102);
});
it('does not publish the first file or text if a later upload fails', async () => {
const sendGroup = vi.fn();
const publish = vi.fn();
const upload = vi
.fn()
.mockResolvedValueOnce({ fileId: 'first', busId: 102 })
.mockRejectedValueOnce(
new Error('temporary group files require only file or image segments'),
);
const ctx = makeCtx(
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
);
await expect(
sendGroupMessage(
ctx,
12345,
[
{ type: 'text', data: { text: 'caption' } },
{ type: 'file', data: { file: '/tmp/one.pdf' } },
{ type: 'file', data: { file: '/tmp/two.pdf' } },
],
false,
),
).rejects.toThrow(/temporary group files/);
expect(sendGroup).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
});
it('reports a failed file publication with its identity and never retries the send', async () => {
const cause = new Error('chat post rejected');
const publish = vi.fn().mockRejectedValueOnce(cause);
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
const ctx = makeCtx(
fakeBridge({
apis: { message: { sendGroup: vi.fn() }, groupFile: { upload, publish } } as any,
}),
);
await expect(
sendGroupMessage(
ctx,
12345,
[{ type: 'file', data: { file: '/tmp/report.pdf' } }],
false,
),
).rejects.toMatchObject({
message: 'group file chat post failed (fileId=temp): chat post rejected',
cause,
});
expect(upload).toHaveBeenCalledOnce();
expect(publish).toHaveBeenCalledOnce();
});
it('uploads a file source without publishing, then publishes it exactly once', async () => {
// Happy path for inline file sending: the bot passes a local path
// directly. upload() internally calls publish(), so we must NOT
// call publish() a second time.
// directly. Delay chat publication until all uploads are checked.
const upload = vi.fn(
async (
_gid: number,
@@ -387,8 +598,16 @@ describe('send_group_msg with {type:"file"} segment', () => {
expect(name).toBe('audio.wav');
expect(folder).toBe('/');
expect(doUpload).toBe(true);
// publish must NOT be called — upload() already handles it internally
expect(publish).not.toHaveBeenCalled();
expect(upload).toHaveBeenCalledWith(
12345,
'/tmp/audio.wav',
'audio.wav',
'/',
true,
false,
{ allowTemporary: true },
);
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
});
it('percent-decodes a file:// URL basename when name is omitted (#354)', async () => {

View File

@@ -95,8 +95,7 @@ describe('send_group_msg large-video fallback', () => {
expect(gid).toBe(12345);
expect(src).toBe('http://example.com/big.mp4');
expect(name).toBe('video.mp4');
// upload() publishes internally — no second publish().
expect(publish).not.toHaveBeenCalled();
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
});
it('rethrows (no fallback) when a remote video fails with a non-size error', async () => {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "2.4.1",
"version": "2.4.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).",

View File

@@ -4,14 +4,6 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton';
* Voice-to-text (语音转文字) request/response protobufs for the
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
*
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
* build the request, `OnTranslateResp` decodes the response). The wire shape
* here is RE-derived and NOT yet verified against a live server: the numeric
* field tags are read straight from the encoder, but the length-delimited
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: the response can carry completed text inline. Otherwise, the caller
* waits for an asynchronous result correlated with the original message ID.
*/
@@ -55,6 +47,9 @@ export interface PttTransReq {
type?: pb<1, uint_32>;
groupItem?: pb<2, GroupPttTransItem>;
c2cItem?: pb<3, C2CPttTransItem>;
/** 1 for NT media, 0 for legacy media; not the audio codec. */
isNtv2?: pb<5, uint_32>;
storeRegion?: pb<6, uint_32>;
}
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "2.4.1",
"version": "2.4.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>'`.",

View File

@@ -31,6 +31,8 @@ export interface UploadedFileMeta {
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Server-selected group storage type: 102 permanent, 104 temporary. */
busId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;

View File

@@ -607,6 +607,8 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle
}
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
const busId =
cached?.scope === 'group' && cached.groupId === ctx?.groupId ? (cached.busId ?? 102) : 102;
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
const fileName = element.fileName ?? cached?.fileName ?? '';
const md5 = element.md5Hex
@@ -618,13 +620,13 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
// busId=102 + the file_id + name + size + sha1/md5 hashes.
// the storage type + file_id + name + size + sha1/md5 hashes.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
busId,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,

View File

@@ -215,6 +215,7 @@ export const ELEMENT_MANIFEST = {
'md5Hex',
'sha1Hex',
'voiceFormat',
'isNtv2',
'noByteFallback',
'mediaNode',
]),
@@ -353,7 +354,7 @@ const NUMBER_FIELDS: ReadonlySet<string> = new Set([
'videoFormat',
'voiceFormat',
]);
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large']);
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large', 'isNtv2']);
function throwValidation(
code: MessageElementValidationCode,

View File

@@ -145,6 +145,8 @@ export interface RecordElement extends FingerprintFields {
url?: string;
duration?: number;
voiceFormat?: number;
/** Media protocol generation; independent of the audio codec. */
isNtv2?: boolean;
mediaNode?: MediaNode;
}

View File

@@ -4,21 +4,24 @@ import { protobuf_decode } from '@snowluma/proton';
const log = createLogger('Protocol.GroupMemberCard');
const utf8 = new TextDecoder('utf-8', { fatal: true });
// eslint-disable-next-line no-control-regex -- C0 controls except tab/LF/CR, plus DEL.
const cardControls = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
/** Keep ordinary text whitespace, but never publish binary framing as a name. */
export function isBinaryCardText(text: string): boolean {
// eslint-disable-next-line no-control-regex -- These are the binary framing bytes we must detect.
return /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(text);
return text.search(cardControls) !== -1;
}
function displayText(bytes: Uint8Array): string {
let text: string;
function utf8Text(bytes: Uint8Array): string {
try {
text = utf8.decode(bytes);
return utf8.decode(bytes);
} catch (cause) {
throw new Error('group card contains invalid UTF-8', { cause });
}
}
function displayText(bytes: Uint8Array): string {
const text = utf8Text(bytes);
if (isBinaryCardText(text)) {
throw new Error('group card text contains binary control characters');
@@ -55,7 +58,9 @@ export function decodeGroupMemberCard(bytes?: Uint8Array): string {
const text = parts.flatMap((part) =>
part.control == null && part.text != null ? [part.text] : [],
);
return displayText(Buffer.concat(text));
// Structured text can contain display controls (#680). Normalize the whole
// control set after strict UTF-8 decoding, preserving whitespace and Unicode formatting.
return utf8Text(Buffer.concat(text)).replace(cardControls, '');
}
/** A malformed optional display name must not discard the message itself. */

View File

@@ -310,6 +310,7 @@ export async function uploadPtt(
fileName: ptt.fileName,
duration: ptt.duration,
voiceFormat: ptt.voiceFormat,
isNtv2: true,
fileId: mediaNode?.fileUuid,
mediaNode,
});

View File

@@ -391,7 +391,7 @@ export class IdentityService {
}
this.assertPersistenceCapacity('group member update');
const observed = { ...member };
const observed = this.retainGroupMemberCard(groupId, member);
const persisted: MemberInput = { groupId, ...observed, active: true };
g.members.set(observed.uin, observed);
this.rememberUidUin(observed.uid, observed.uin);
@@ -780,7 +780,8 @@ export class IdentityService {
});
}
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
/** Returns the refreshed roster with previously known cards retained when unreadable. */
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): GroupMemberInfo[] {
this.beginObservation('group members');
if (!this.loaded_) {
@@ -790,7 +791,7 @@ export class IdentityService {
});
}
const observed = members.map((member) => ({ ...member }));
const observed = members.map((member) => this.retainGroupMemberCard(groupId, member));
const persisted = observed.map((member): MemberInput => ({
groupId,
...member,
@@ -816,6 +817,7 @@ export class IdentityService {
}
}),
);
return observed;
}
rememberUserProfile(info: UserProfileInfo): void {
@@ -1120,6 +1122,16 @@ export class IdentityService {
}
}
private retainGroupMemberCard(groupId: number, member: GroupMemberInfo): GroupMemberInfo {
const previous = this.findGroupMember(groupId, member.uin)?.card;
return {
...member,
card:
member.card ??
(previous !== undefined && !isBinaryCardText(previous) ? previous : undefined),
};
}
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
@@ -1182,6 +1194,7 @@ export class IdentityService {
uin INTEGER,
nickname TEXT NOT NULL DEFAULT '',
card TEXT NOT NULL DEFAULT '',
card_known INTEGER NOT NULL DEFAULT 1,
role TEXT NOT NULL DEFAULT 'member',
level INTEGER NOT NULL DEFAULT 0,
title TEXT NOT NULL DEFAULT '',
@@ -1208,12 +1221,17 @@ export class IdentityService {
'PRAGMA table_info(group_members)',
).all()) as Array<{ name: string }>;
if (columns.some((column) => column.name === 'is_robot')) {
return;
if (!columns.some((column) => column.name === 'is_robot')) {
await this.db!.exec('ALTER TABLE group_members ADD COLUMN is_robot INTEGER');
this.log.info('identity schema migrated: added group_members.is_robot');
}
await this.db!.exec('ALTER TABLE group_members ADD COLUMN is_robot INTEGER');
this.log.info('identity schema migrated: added group_members.is_robot');
if (!columns.some((column) => column.name === 'card_known')) {
await this.db!.exec(
'ALTER TABLE group_members ADD COLUMN card_known INTEGER NOT NULL DEFAULT 1',
);
this.log.info('identity schema migrated: added group_members.card_known');
}
}
private async loadSnapshot(): Promise<void> {
@@ -1309,7 +1327,7 @@ export class IdentityService {
const select = this.db!.prepare(
`SELECT group_id, uid, uin, nickname,
CASE WHEN instr(card, char(0)) = 0 THEN card END AS card, role, level, title,
CASE WHEN card_known = 1 AND instr(card, char(0)) = 0 THEN card END AS card, role, level, title,
join_time, last_sent_time, shut_up_time, is_robot
FROM group_members
WHERE group_id = ? AND active = 1`,
@@ -1491,7 +1509,8 @@ export class IdentityService {
await this.db!.prepare(
`UPDATE group_members
SET uid = ?, uin = ?, nickname = ?, card = COALESCE(?, card), role = ?, level = ?, title = ?,
join_time = ?, last_sent_time = ?, shut_up_time = ?, is_robot = ?, active = ?, updated_at = ?
join_time = ?, last_sent_time = ?, shut_up_time = ?, is_robot = ?, active = ?, updated_at = ?,
card_known = CASE WHEN ? IS NULL THEN card_known ELSE 1 END
WHERE id = ?`,
).run(
merged.uid,
@@ -1507,6 +1526,7 @@ export class IdentityService {
merged.isRobot,
merged.active,
merged.updatedAt,
input.card ?? null,
primary.id,
);
return;
@@ -1515,8 +1535,8 @@ export class IdentityService {
await this.db!.prepare(
`INSERT INTO group_members
(group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, is_robot, active, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
join_time, last_sent_time, shut_up_time, is_robot, active, updated_at, card_known)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
input.groupId,
merged.uid,
@@ -1532,6 +1552,7 @@ export class IdentityService {
merged.isRobot,
merged.active,
merged.updatedAt,
input.card === undefined ? 0 : 1,
);
}

View File

@@ -599,7 +599,7 @@ function assignValidFingerprints(
function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode'] {
return {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
storeId: idx.storeId ?? 0,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
@@ -1153,6 +1153,7 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
voiceFormat: fi.type?.voiceFormat ?? 0,
isNtv2: true,
mediaNode: buildMediaNode(idx, fi),
};
assignValidFingerprints(
@@ -1579,6 +1580,7 @@ function extractRichtextExtras(
duration: p.time ?? 0,
fileHash: md5Hex ?? '',
voiceFormat: p.format ?? 0,
isNtv2: false,
};
assignValidFingerprints(me, md5Hex, undefined, 'ptt');

View File

@@ -6,6 +6,7 @@
// state that's per-Bridge (and is what stops Tencent risk-control
// from banning the account on busy clients — see #42).
import { createLogger } from '@snowluma/common/logger';
import type { OidbBase, OidbSvcTrpcTcp0xFE7_3Response } from '@snowluma/proto-defs/oidb';
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
@@ -13,6 +14,8 @@ import { decodeGroupMemberCard } from '../../group-member-card';
import type { GroupMemberInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
const log = createLogger('Protocol.GroupMemberCard');
export interface GroupMemberListPage {
members: GroupMemberInfo[];
token: string;
@@ -80,20 +83,39 @@ export namespace FetchGroupMemberListPage {
export const deserialize = (
_ctx: Deps,
body: OidbSvcTrpcTcp0xFE7_3Response,
groupId = body.groupUin ?? 0,
): GroupMemberListPage => ({
members: (body.members ?? []).map((raw) => ({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: decodeGroupMemberCard(raw.memberCard?.memberCard),
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
})),
members: (body.members ?? []).map((raw) => {
const uin = raw.uin?.uin ?? 0;
const bytes = raw.memberCard?.memberCard;
let card: string | undefined;
try {
card = decodeGroupMemberCard(bytes);
} catch (error) {
log.warn(
'unreadable group member card: group=%d member=%d bytes=%d reason=%s',
groupId,
uin,
bytes?.length ?? 0,
error instanceof Error ? error.message : String(error),
);
}
return {
uin,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card,
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
};
}),
token: body.token ?? '',
});
@@ -104,5 +126,12 @@ export namespace FetchGroupMemberListPage {
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupMemberListPage> =>
invokeOidb(deps, FetchGroupMemberListPage, params);
invokeOidb(
deps,
{
...FetchGroupMemberListPage,
deserialize: (ctx, body) => deserialize(ctx, body, params.groupId),
},
params,
);
}

View File

@@ -21,6 +21,7 @@ export namespace PublishGroupFile {
export interface Params {
groupId: number;
fileId: string;
busId?: number;
}
export type Deps = OidbSender;
@@ -29,7 +30,7 @@ export namespace PublishGroupFile {
groupUin: p.groupId,
type: 2,
info: {
busiType: 102,
busiType: p.busId ?? 102,
fileId: p.fileId,
field3: Math.floor(Math.random() * 0x7fffffff) >>> 0,
field5: true,

View File

@@ -33,6 +33,7 @@ export namespace UploadGroupFileRequest {
fileSize: number;
fileSha1: Uint8Array;
fileMd5: Uint8Array;
busId?: 102 | 104;
}
export type Deps = OidbSender;
@@ -41,7 +42,7 @@ export namespace UploadGroupFileRequest {
file: {
groupUin: p.groupId,
appId: 4,
busId: 102,
busId: p.busId ?? 102,
entrance: 6,
targetDirectory: p.folderId,
fileName: p.fileName,

View File

@@ -99,7 +99,7 @@ export interface GroupMemberInfo {
uin: number;
uid: string;
nickname: string;
/** Empty when unset; undefined until an unreadable card is refreshed. */
/** Empty when unset; undefined when unreadable and no previously valid card is known. */
card?: string;
/** Undefined until QQ's server-provided robot ranges classify this member. */
isRobot?: boolean;

View File

@@ -81,7 +81,12 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)
return 'cd'.repeat(20);
}
if (field === 'flash' || field === 'noByteFallback' || field === 'large') {
if (
field === 'flash' ||
field === 'noByteFallback' ||
field === 'large' ||
field === 'isNtv2'
) {
return true;
}

View File

@@ -1,15 +1,27 @@
import { describe, expect, it } from 'vitest';
import type { PushMsg } from '@snowluma/proto-defs/message';
import { subscribeLogs } from '@snowluma/common/logger';
import type { PushMsg, RichGroupCard } from '@snowluma/proto-defs/message';
import type { OidbBase, OidbSvcTrpcTcp0xFE7_3Response } from '@snowluma/proto-defs/oidb';
import { protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '../src/identity-service';
import type { GroupMemberInfo } from '../src/qq-info';
import { MSG_PUSH_CMD, parseMsgPushOrThrow } from '../src/msg-push';
import { FetchGroupMemberListPage } from '../src/oidb-services/contacts/fetch-group-member-list-page';
import { decodeGroupMemberCard, isBinaryCardText } from '../src/group-member-card';
const groupId = 42;
const uin = 123;
const hex = (s: string) => Buffer.from(s, 'hex');
const controlCodes = [
...Array.from({ length: 0x20 }, (_, code) => code).filter(
(code) => ![9, 10, 13].includes(code),
),
0x7f,
];
function styledCard(text: Uint8Array): Uint8Array {
return protobuf_encode<RichGroupCard>({ parts: [{ text }] });
}
async function fetchMember(card: Uint8Array) {
const responseData = Buffer.from(
@@ -99,6 +111,8 @@ describe('group member card wire formats', () => {
// Reordered outer fields, multiple text parts and a control part containing a text field.
['甲乙', hex('10000a051203e794b20a080a01ff1203e581870a070a001203e581870a051203e4b999')],
['🌙', hex('0a041202f09f0a0412028c99')], // A UTF-8 code point split between text parts.
// #680: QQ hides the 0x14 embedded in the text part and shows " ƕ".
[' ƕ', hex('0a090a0724c7bfc480440e0a071205202014c6951000')],
[' 普通🌙 ', Buffer.from(' 普通🌙 ')],
] as const)(
'decodes %s in the roster and in pushes with or without a cached member',
@@ -115,6 +129,43 @@ describe('group member card wire formats', () => {
},
);
it.each(controlCodes.map((code) => [code.toString(16).padStart(2, '0'), code] as const))(
'cleans 0x%s only in decoded card text and keeps raw text strict',
async (_label, code) => {
const raw = Buffer.from(` 甲${String.fromCodePoint(code)}乙🌙 `);
const card = styledCard(raw);
const member = await fetchMember(card);
expect(member.card).toBe(' 甲乙🌙 ');
expect(push(withCachedMember({ ...member, card: 'outdated' }), card)).toMatchObject({
senderNick: 'nickname',
senderCard: ' 甲乙🌙 ',
});
expect(() => decodeGroupMemberCard(raw)).toThrow('control characters');
// Detection also serves repeated cache reads; it must not depend on regex state.
expect(isBinaryCardText(raw.toString())).toBe(true);
expect(isBinaryCardText(raw.toString())).toBe(true);
expect(isBinaryCardText(member.card!)).toBe(false);
},
);
it('preserves whitespace, Unicode formatting and combining characters', async () => {
const text = ' \t甲\n乙\r 👩\u200d💻 ❤️\u200b\u2060 e\u0301 \u0085 ';
const member = await fetchMember(styledCard(Buffer.from(text)));
expect(member.card).toBe(text);
expect(decodeGroupMemberCard(Buffer.from(text))).toBe(text);
expect(isBinaryCardText(text)).toBe(false);
});
it('treats decoded text containing only non-display controls as an empty card', async () => {
const card = styledCard(Buffer.from(controlCodes));
const member = await fetchMember(card);
expect(member.card).toBe('');
expect(push(withCachedMember({ ...member, card: 'outdated' }), card)).toMatchObject({
senderNick: 'nickname',
senderCard: '',
});
});
it('treats a control-only card as empty even when a previous card was cached', async () => {
const control = hex('0a030a01ff1000');
const member = await fetchMember(control);
@@ -134,9 +185,39 @@ describe('group member card wire formats', () => {
});
});
it('rejects unreadable roster data and still delivers a message with damaged metadata', async () => {
it.each(['0a051202ff00', '616207', '0a031201ff', '0a0512036114ff'])(
'keeps a member with unreadable card %s and logs its context',
async (encoded) => {
const damaged = hex(encoded);
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
expect(() => decodeGroupMemberCard(damaged)).toThrow('group card');
expect(await fetchMember(damaged)).toMatchObject({
uin,
nickname: 'nickname',
card: undefined,
});
expect(warnings).toEqual([
expect.stringMatching(
new RegExp(`group=42 member=123 bytes=${damaged.length} reason=group card`),
),
]);
expect(warnings[0]).not.toContain(encoded);
expect(warnings[0]).not.toContain('nickname');
} finally {
unsubscribe();
}
},
);
it('still delivers a message with damaged metadata', async () => {
const damaged = hex('0a051202ff00');
await expect(fetchMember(damaged)).rejects.toThrow('group card');
const identity = withCachedMember(await fetchMember(Buffer.from('existing card')));
expect(push(identity, damaged)).toMatchObject({
senderNick: 'nickname',
@@ -144,4 +225,13 @@ describe('group member card wire formats', () => {
elements: [{ type: 'text', text: 'hello' }],
});
});
it('keeps literal display names strict when they contain a styled-card control character', async () => {
const identity = withCachedMember(await fetchMember(Buffer.from('existing card')));
expect(push(identity, Buffer.from('literal\x14name'), 2)).toMatchObject({
senderNick: 'nickname',
senderCard: 'existing card',
elements: [{ type: 'text', text: 'hello' }],
});
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "2.4.1",
"version": "2.4.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 with edge-case fixes applied.",

Binary file not shown.

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "2.4.1",
"version": "2.4.2",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.4.1",
"version": "2.4.2",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/sqlite",
"version": "2.4.1",
"version": "2.4.2",
"private": true,
"type": "module",
"description": "SnowLuma asynchronous SQLite facade, native loader and release assets.",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.4.1",
"version": "2.4.2",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "2.4.1",
"version": "2.4.2",
"private": true,
"type": "module",
"main": "./src/index.ts",

View File

@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "2.4.1",
"version": "2.4.2",
"type": "module",
"scripts": {
"dev": "vite",